﻿(function($) {

	$.fn.prompt = function(textContainer, labelContainer) {
		return $(this).each(function() {

			var root = $(this);
			var input = root.find(textContainer);
			var label = root.find(labelContainer);
			var prompt =
                $("<span />")
                 .addClass("prompt")
                 .insertAfter(label);
			label.show().appendTo(prompt);

			var pos = input.position();
			prompt.css('left', pos.left).css('top', pos.top);
			input.bind('click focus', function() {
				prompt.hide();
				if ($(this).val() == label.text()) $(this).val('');

			}).bind('blur', function() {
				if ($(this).val() == label.text() || $(this).val() == '') {
					prompt.show();
					$(this).val('');
				}
			});
			prompt.click(function() {
				$(this).hide();
				input.focus();
			});

			$(function() {
				if (input.val() != '') prompt.hide();
			});

		});
	};

	$.fn.mbox_init = function(selector, closingSelector, submitter, onOpen) {
		var mbox = $(this);
		mbox.find("script").remove();
		var close = mbox.find('.close');
		var root = $('body');
		mbox.addClass('mbox');
		/* If no form with id form found, cannot use the submit based popup */
		if (submitter) {
			var root = $(document).find('Form');
			if (!root || !selector) return;
		}
		close.show();
		mbox.hide();
		mbox.draggable({ cursor: 'pointer', containment: 'document', handle: '.header' });
		/* Default link for closing the popup */

		mbox.click(function(e) {
			var target = $(e.target);
			if (target.is('.close') || target.is(closingSelector)) {
				mbox.hide();
				e.stopPropagation();
				e.preventDefault();
			}
		});

		/* Elements which should open the popup */

		$("body").click(function(e) {
			if ($(e.target).is(selector)) {
				var x = e.pageX - mbox.width() / 2;
				var y = e.pageY - mbox.height() - 35;
				mbox.css('top', y + "px").css('left', x + "px").css('position', 'absolute').css('z-index', '999');

				mbox.show();
				root.append(mbox);
				e.stopPropagation();
				e.preventDefault();

				if (onOpen)
					onOpen();
			}
		});
	};

	$.fn.submitNewsletter = function(extraElements, linkSelector, url, urlParams, language) {
		return $(this).each(function() {
			var root = $(this);
			var link = $(linkSelector);
			var uri = url;
			var lang = language;
			var uriparams = urlParams;

			link.click(function() {
				if (!root.val()) {
					root.parent().addClass('error');
				} else {
					var params = $.param($(uriparams));
					$.post(uri, params, function(data) {
						var temp = $(data);
						if (temp.find('.FormSuccess').length) {
							if (window.snoobi) snoobi.trackPageView('/virtual/yhteydenotot/uutiskirje/' + lang, 'Yhteydenotot - Uutiskirje - ' + lang, 'Generoidut klikkaukset');
							var box = temp.find('#Newsletter');

							if (box.length) {
								box.appendTo($('#Form')).hide();
								box.css({
									top: link.offset().top - box.outerHeight() - 20,
									left: link.offset().left - 50,
									position: 'absolute'
								}).show();

								box.find('.close').click(function(e) {
									root.val("");
									root.parent().find('.prompt').show();
									e.preventDefault();
									box.remove();
								});
							}
						}
					});
				}
			});

			root.keydown(function() {
				if (root.val()) {
					root.parent().removeClass('error');
				}
			});
		});
	};

	$.fn.atajacksBox = function(extraElements, linkSelector, url, urlParams) {
		return $(this).each(function() {
			var box = $(this);
			var resetting = false;

			box.mbox_init(linkSelector || '.mbox-init', '.cancel', true, function() {
				if (typeof url != 'undefined') {
					jQuery.atajacks({ elements: box.add(extraElements), url: url, success: function() {
						var params = $.param($(urlParams));
						params.length ? url += ((url.match('\\?')) ? "&" : "?") + params : '';

						box.atajacksForm({ elements: box.add(extraElements), url: url, success: success });

						var window = $(window);
						var boxY = parseInt(box.css('top'));
						var yMax = window.height() - boxY - box.height();
						if (yMax < 100) {
							box.css('top', boxY - box.height());
						}
						if (boxY <= 50) {
							box.css('top', '200px');
						}
					}
					});

				}
				if (resetting)
					reset();
			});

			function reset() {
				resetting = false;
				box.stop(true, true);
				box.css({ opacity: 1.0 });
				box.find('.success').remove();
				box.find('.content').css({ display: "" });
			}

			function success() {

				if (box.find('.success').length) {
					resetting = true;
					setTimeout(function() {
						box.animate({ opacity: 0.0 }, 1000, function() {
							if (resetting) {
								box.css({ display: "none" });
								reset();
							}
						});
					}, 5000);
				}
			}

			if (typeof url == 'undefined')
				box.atajacksForm({ elements: box.add(extraElements), success: success });
		});
	};

	$.fn.ContentSlider = function(content, subcontent, links) {


		return $(this).each(function() {
			var root = $(this);

			var main = root.find(content);
			var alt = root.find(subcontent);
			var clickers = root.find(links);

			clickers.click(function(e) {
				e.preventDefault();
				e.stopPropagation();
				main.parent().animate({
					left: 0 - main.outerWidth()
				}, 1000);

				if (snoobi) {
					snoobi.trackPageView("/virtual/Toimialat", "Valitse toimiala - " + $(this).attr('Title'), "Generoidut klikkaukset");
				}
			});
		});
	};


	$.fn.TabbedContent = function() {
		return $(this).each(function() {
			var root = $(this);
			var height = 0;

			var tabs = root.find('.TabNavigation a');
			var contentTabs = root.find('.TabContent');

			$(function() {

				var heightMax = contentTabs.filter(function() {
					if ($(this).show().outerHeight() > height) {
						height = $(this).outerHeight();
						if (!$(this).hasClass('Selected')) $(this).hide();
						return true;
					}
					$(this).hide();
				});
				height = height + parseInt(root.find('.TabNavigation').outerHeight()) + 30;
				root.parent().height(height);
			});
			tabs.click(function(e) {
				var contentTab = root.find('#TabContent' + $(this).attr('ContentTabId'));
				contentTabs.add(tabs).not(contentTab).removeClass('Selected').addClass('Inactive');
				contentTab.add($(this)).addClass('Selected').removeClass('Inactive');
				e.preventDefault();
				e.stopPropagation();
			});

		});
	};

	$.fn.Expandable = function(expandSelector, contentSelector) {

		return $(this).each(function() {
			var root = $(this);
			var attached = root.find(expandSelector || ".Expandable");

			attached.click(function(e) {
				var content = $(this).parents().find(contentSelector || ".ExpandableContent").eq(0);
				content.toggle("fast");
				$(this).parent().toggleClass('Collapsed');
				e.preventDefault();
				e.stopPropagation();
			})

			$(function() {
				root.find(contentSelector || ".ExpandableContent").not('.Opened').css('display', 'none');
				attached.parent().addClass('Collapsed');
				root.find('.Opened').parent().removeClass('Collapsed');
			});

		});

	};

	$.fn.ContentToggler = function(categoryLinks, targetView, url) {

		return $(this).each(function() {
			var root = $(this);
			var contactPage = url;
			var links = root.find(categoryLinks);
			var view = $(targetView);
			$(function() { view.add(view.parent()).css('height', view.outerHeight()); links.addClass('Selected'); });
			links.click(function(e) {

				var category = $(this).attr('category');
				var link = $(this);

				e.preventDefault();
				e.stopPropagation();

				/* If CustomerCasesMainScroll is found, the animation is still ongoing */
				if (view.parent().find('#CustomerCasesMainScroll').length)
					return;

				link.toggleClass('Selected');

				var selectedCategories = root.find(categoryLinks).filter('.Selected');
				selectedCategories.length == 0 ? selectedCategories = root.find(categoryLinks) : '';

				/* Fetching active categories from category attribute of elements */
				var categories = '';
				selectedCategories.each(function() {
					categories += '.' + $(this).attr('category') + ',';
				});
				categories ? categories = categories.substring(0, categories.length - 1) : '';

				/* Cloning and handling of the new view we are scrolling into view */
				var ul = view.parent().find('#CustomerCasesMainScroll').length ? view.parent().find('#CustomerCasesMainScroll') : view.clone().appendTo(view.parent()).attr('id', 'CustomerCasesMainScroll');
				ul.html(view.html()).css('left', view.outerWidth()).css('position', 'absolute').css('top', 0);
				var visibleViews = ul.find(categories);
				var separator = $('<li></li>').addClass('Separator');

				ul.find('li.MainRow').not(visibleViews).addClass('inactive').hide();
				visibleViews.removeClass('inactive').removeClass('rowfirst').show();
				ul.find('.Separator').remove();
				ul.find('.Temp').remove();

				visibleViews.each(function() {
					var index = ul.find('li.MainRow:not(.Separator):not(.inactive)').index($(this));
					$(this).addClass('rowfirst');
					if ((parseInt(index) + 1) % 2 == 0) {
						$(this).after(separator.clone());
						$(this).removeClass('rowfirst');
					}
				});

				if (visibleViews.length == 0) {
					var tempLi = $('<li></li>').addClass('MainRow Temp rowfirst').html('<p>Valitsemillasi termeillä ei ole kirjoitettua referenssiä. <br/><a href="' + contactPage + '">Kysy lisää omaan toimialaasi liittyviä referenssejä »</a></p>').appendTo(ul);
				}

				view.css('position', 'absolute');
				view.animate({
					left: -view.outerWidth(),
					top: 0
				}, function() {
					view.remove();
				});

				ul.animate({
					left: 0
				}, function() {
					view = ul;
					ul.attr('id', null);

				});
			});
		});
	};

	$.fn.SupportForm = function() {
		return $(this).each(function() {
			var root = $(this);
			var submit = root.find('.AvenlaFormSubmit input');
			var contentsareas = root.find('.contentsarea');
			var select = root.find('.contenttoggler select');
			select.change(function() {
				var contentplaceholder = root.find('.ContentPlaceholder');
				contentsareas.removeClass('DynamicFormFieldInvalid');
				var select = $(this);
				var option = select.find('option').filter(function() {
					return select.val() == $(this).val();
				});
				var index = select.find('option').index(option) + 1;
				var c = "contents" + index;
				var content = root.find('.' + c);
				contentsareas.parent().slideUp();
				contentplaceholder.height(content.parent().height());
				content.parent().css({
					top: contentplaceholder.height(),
					position: 'absolute'
				}).show().animate({ top: 0 }, 200);
			});

			submit.click(function(e) {
				var fields = root.find('.ContentContainer:visible .requiredfield input, .ContentContainer:visible .requiredfield textarea, .noborder input');
				var invalid = false;
				fields.each(function() {
					if (!$(this).val()) {
						$(this).parent().parent().addClass('DynamicFormFieldInvalid');
						invalid = true;
					} else {
						$(this).parent().parent().removeClass('DynamicFormFieldInvalid');
					}
				});

				if (invalid) { $('#SupportFormValidation').show(); e.stopPropagation(); e.preventDefault(); return false; }
			});
			$(function() {
				var options = select.find('option').each(function() {
					var index = $(this).parent().find('option').index($(this)) + 1;
					var c = "contents" + index;
					var content = root.find('.' + c);
					var container = $('<div class="ContentContainer"></div>').insertBefore(content.filter(':first')).append(content);
				});
				var contentcontainers = root.find('.ContentContainer');
				var contentplaceholder = $('<div class="ContentPlaceholder"></div>').insertBefore(contentcontainers.filter(':first')).append(contentcontainers);
				var option = select.find('option').filter(function() {
					return select.val() == $(this).val();
				});
				var index = select.find('option').index(option) + 1;
				var c = "contents" + index;
				var content = root.find('.' + c);
				contentsareas.parent().hide();
				content.parent().show();
			});
		});

	};

})(jQuery);
