// check mandatory fields
var mandatoryChecker = (function() {
	// private variables
	// reg exp for checking valid email address
	var emailCheck 		= /^([0-9a-zA-Z]+([_.-]?[0-9a-zA-Z]+)*@[0-9a-zA-Z]+[0-9,a-z,A-Z,.,-]*(.){1}[a-zA-Z]{2,4})+$/,
		validationOK	= true,
		$targetTitle	= $targetField = $targetField = $focusField = null;

	function checkSpecialInput(checkType) {
		//console.info(checkType);
		switch (checkType) {
			case "email":
				(!$targetField.val().match(emailCheck)) ? markMandatoryField() : "";
				break;
			default:
				alert(checkType+": this is an undefined check type");
		}
	}

	// mark empty mandatory fields
	function markMandatoryField() {
		$targetTitle.addClass("missing");
		($targetField.length === 1) ? (function() {
			$targetField.addClass("missing");
			(validationOK === true) ? $focusField = $targetField : "";
		})() : (function() {
			$targetField.each(function() {
				(validationOK === true) ? $focusField = $targetField[0] : "";
				$(this).addClass("missing");
			});
		})();

		(validationOK === true) ? (function() {			
			validationOK = false;
			$focusField.focus();
		})() : "";
	}

	return {
		// check mandatory fields
		checkMandatoryFields: function() {
			var tagName = "";
			// remove .missing class			
			$("form.feedback label, form.feedback input, form.feedback textarea, form.feedback p").removeClass("missing");
			// get mandatory fields
			$(".mandatory").each(function(){
				tagName 		= $(this).get(0).tagName.toLowerCase(),
				classes 		= $(this).attr("class").split(" "),
				$targetTitle	= $(this);				
				switch (classes.length) {
					case 1:
						(tagName === "label") ? (function(){
							// form field to be checked
							$targetField = $("#" + $targetTitle.attr("for"));
							($targetField.val() === "") ? markMandatoryField() : "";
						})() : (function(){

						});
						break;
					default:
						$targetField = ($("[id='" + classes[1] + "']").length !== 0) ? $("[id='" + classes[1] + "']") : $("[name='" + classes[1] + "']");
						// check mandatory fields
						switch ($targetField.attr("type")) {
							case "text":
								checkSpecialInput(classes[1]);
								break;
							case "radio":
								($targetField.filter(":checked").length < 1) ? markMandatoryField(): "";
								break;
							case "checkbox":
								($targetField.filter(":checked").length < 1) ? markMandatoryField(): "";
								break;
						}
				}
			});

			// return validation status
			return validationOK;
		},
		
		// reset focus field and validation status
		unFocus: function() {
			$focusField = null;
			validationOK = true;
		}
	}
})();

// dom ready
$(function(){
	// check mandatory fields for customer feedback form
	$("form.feedback").submit(function(e){
		mandatoryChecker.unFocus();
		(mandatoryChecker.checkMandatoryFields() === false) ? e.preventDefault() : function() {
			// if form is application for an account, print window
			($("form#application").length !== 0) ? sendUserData(e) : "";
		}();
	});

	// add class last to last list item
	$("li:last-child").addClass("last");
	
	// add class even to product info
	$("div.col2-product dl:not(#col2-product-use) dt:even, div.col2-product dl:not(#col2-product-use) dd:even, div.col2-product ol.more-info li:even").addClass("even");
	
	// submit content search
	$("#col3-search").submit(function () {
		$("#content-query").val($("#search-altia").val() +' -AuthoringTemplate::"Default Sitearea Content"' +' -AuthoringTemplate::"Manual pick"');
	});

	// age verification confirmation
	$("#age-verification button").click(function() {
		sessvars.ageVerification = "1";		
	});

	// age verification confirmation
	$("#age-verification a").click(function() {
			$("#age-verification #terms").fadeIn("slow");
	});	
		
	// listener for click events
	$("body").click(function(e){
	
		var id = $(e.target).attr("id"),
		idProduct = id.substring(0, id.lastIndexOf("-"));
		
		switch (id) {
			// entry - terms
			case "terms-link": 
				$("div#terms").fadeIn("def"); 
				break;
			case "close-terms":
				$("div#terms").fadeOut("def");
				break;
			// entry - responsibility
			case "responsibility-link": 
				$("div#responsibility").fadeIn("def"); 
				break;
			case "close-responsibility":
				$("div#responsibility").fadeOut("def");
				break;
			// product - more info
			case "read-more":
				$("#col2-product-more ol.more-info").show();
				$("#col2-product-more .description").show();
				$("p.more").hide();
				break;
			// font size -> smaller
			case "smaller":
				changeFontSize(-10);
				break;
			// font size -> bigger
			case "bigger":
				changeFontSize(10);
				break;
		}
				
		// show/hide product info
		(id.substring(0, id.indexOf("-")) === "product" && idProduct !== "product") ? 
			(function() {
				(id.substring(id.lastIndexOf("-")+1) === "link") ? 
					(function(){
						$("div#" + idProduct).fadeIn("def");
						addPrintCss(idProduct);
					})() : 
					(function(){
						$("div#" + idProduct).fadeOut("def");
						remPrintCss(idProduct);
					})();
			})() : "";
		});
	
	// get font size from sessvars, else font size is set to default
	(sessvars.fontSize !== undefined) ? changeFontSize(0) : sessvars.fontSize = 100;
		
	// print product information
	$("ul#col2-product-actions li#card a, #product-actions a.print").click(function(){
		window.print();
	});
	
	// send data to alko pdf creator
	$("ul#col2-product-actions li#pdf_alko a").click(function(){
		var productId = $("span#content-name").text();
		var libraryId = $("span#library-id").text();
		var productLang = $("input#language").val();

		libraryId = libraryId.split("/")[4];

		var uri = "/AltiaPDFCreator/PdfCreatorServlet?id=" + productId + "&library=" + libraryId + "&language=" + productLang;
		// var uri = "/AltiaPDFCreator/PdfCreatorServlet?id=" + productId + "&library=" + libraryId + "&language=" + productLang + "&authenticated=true";

		$("ul#col2-product-actions li#pdf_alko a").attr({
			href:	uri
		});
	});

	// send data to horeca pdf creator
	$("ul#col2-product-actions li#pdf_horeca a").click(function(){
		var productId = $("span#content-name").text();
		var libraryId = $("span#library-id").text();
		var productLang = $("input#language").val();

		libraryId = libraryId.split("/")[4];

		var uri = "/AltiaPDFCreator/PdfCreatorServlet?id=" + productId + "&library=" + libraryId + "&language=" + productLang + "&modifier=1";
		// var uri = "/AltiaPDFCreator/PdfCreatorServlet?id=" + productId + "&library=" + libraryId + "&language=" + productLang + "&authenticated=true&modifier=1";


		$("ul#col2-product-actions li#pdf_horeca a").attr({
			href:	uri
		});
	});

	
	// print product card from product information
	$("ul#col2-product-actions li#note a").click(function(){
		$("#product-print #product-description").hide();
		$("#product-print dd").hide();
		$("#product-print dt").hide();
		$("#product-print dd.note").show();
		$("#product-print dt.note").show();		
		window.print();
		return false;
	});
	
	// use tooltip plugin to display recommendations img title
	$("p#col2-product-recs img").tooltip({
		delay: 0,
		fade: 300,
		track: true,
		showURL: false,
		left: -$("#content").offset().left,
		top: 25,
		bodyHandler: function() {
			// get tooltip from image source
			var $tooltip = $(this).attr("src"),
			tooltipArr = [];
			tooltipArr = $tooltip.substring(0, $tooltip.length-4).split("/");
			$tooltip = tooltipArr[tooltipArr.length -1];
			return $tooltip;
		}
	});
	
	// partners network logout
	$("a#logout").click(function(e){
		e.preventDefault();
		var logoutUrl = $(e.target).attr("href"),
			// redirect after logout
			redirectTo = "/fi/Etusivu/";
		
		$.ajax({
			type: "GET",
			// send username and password
			url: logoutUrl,
				// username sent
				complete: function(){
					window.location.href = redirectTo;
				}
		});	
	});

	// get ageVerification flag from session, if undefined - display popup
	(sessvars.ageVerification !== undefined) ? "" : ageVerification();

});

// change body font size
function changeFontSize(size) {
	// set maximum and minimum limits for font size
	sessvars.fontSize = ((sessvars.fontSize < 60 & size < 0) || (sessvars.fontSize > 150 & size > 0)) ? 
		// minimum or maximum reached
		(function() {
			// add disabled class if minimum or maximum reached
			(size < 0) ? $("a#smaller").addClass("disabled") : $("a#bigger").addClass("disabled");
			return sessvars.fontSize;
		})()
		// change session font size
		: (function() {
			// remove disabled class
			(size < 0) ? $("a#bigger").removeClass("disabled") : $("a#smaller").removeClass("disabled");				
			return sessvars.fontSize+size;
		})();
	// change html font size
	$("html").css("font-size", sessvars.fontSize+"%");
}

// add print css for product cards
function addPrintCss(idProduct) {
	var head = $("head");
	var cssUri = "/styles/css/product-card-print.css";
	$(document.createElement('link')) 
    .attr({type: "text/css", href: cssUri, rel: "stylesheet", media: "print", id: "product-card-print"})
    .appendTo(head);

	(idProduct) ? $("#col2 #" +idProduct+ ".col2-product").css({'display':'block'}) : "";
}

// after printing product card
function afterPrint() {
	remPrintCss();
	$("div.col2-product p.more").show();
}

// remove print css for product cards
function remPrintCss(idProduct){
	$("head link#product-card-print").remove();
}

// print user data
function sendUserData(e){	
	window.print();
}

// age verification
function ageVerification() {
	
	// do not display overlay on terms page
	if ($("body.terms").length != 0 ) {
		return false;
	}
	
	$("#age-verification").overlay({ 
		expose: {
			color: '#333',
			loadSpeed: '200',
			opacity: '0.6'
		},
		left: 200,
		closeOnClick: false,
		api: true
	}).load();

	$("body div:last").css("margin-left", "-25%");
	$("body div:last").css("padding-left", "300px");
	$("body div:last").css("padding-right", "300px");
	$("body div:last").css("padding-bottom", "200px");
}

// age verification on liity-klubiin
$("#liity-klubiin").submit(function(){
//	var day = $("#day").val();
//	var month = $("#month").val();
	var year = $("#year").val();
	var age = 18;
	var mydate = new Date();

	if (isNaN(year)) {
		alert("Kirjoita syntymävuosi neljällä numerolla (esim. 1990)");
		return false;		
	}

	mydate.setFullYear(year, 1, 1);
	var currdate = new Date();

	currdate.setFullYear(currdate.getFullYear() - age);

	if ((currdate - mydate) < 0) {
		alert("Vain 18-vuotta täyttäneet voivat liittyä klubiin.");
		return false;
	}
	return true;
});
