var currentMainContentItem = 1;
var prevMainContentItem = 1;
var numMainContentItems = 0;
var galleryOpen = null;

var FP_timer = null;

$(document).ready(function() {
	preloadImages();
});

/*Global variables*/

var ieVersion = 0;
var layerAnimDuration = 300;

function inputFocusIn(field,defaultText,password) {
	if($(field).attr("value") != defaultText)
		return;
		
	$(field).attr("value","");
	$(field).removeClass("help");
	
	if(password) {
		$("#password2").removeClass("help");
		document.getElementById("password2").style.display = "none";
		document.getElementById("password").style.display = "block";
		document.getElementById("password").value = "";
		document.getElementById("password").focus();
	}
}

function inputFocusOut(field,defaultText,password) {
	if($(field).attr("value") != "" )
		return;
	
	$(field).attr("value",defaultText);
	$(field).addClass("help");
	
	if(password) {
		$("#password2").addClass("help");
		document.getElementById("password2").style.display = "block";
		document.getElementById("password").style.display = "none";
		document.getElementById("password2").value = defaultText;
	}
}

function getOptionIndexByValue(list,value) {
	for(var i = 0; i < list.length; i++) {
		if(list.options[i].value == value)
			return i;
	}
		
	return -1;
}

/* Layer */

function openLayer(ID, infotext, disableClose) {
	var width = getWidth();
	var height = getHeight();
	
	var pageHeight = parseInt(xDocSize().h);
	
	$("#" + ID).css("display","block");
	
	var layerHeight = parseInt($("#" + ID).height()) ? $("#" + ID).height() : 150;
	
	// Position layer
	$("#" + ID).css("top",height / 2 - parseInt(layerHeight) / 2 + getScrollY());
	
	$("#" + ID).css("left",width / 2 - parseInt($("#" + ID).width()) / 2 + getScrollX());
	
	$("#shader").css("width",getWidth());
	$("#shader").css("height", pageHeight);
	$("#shader").css("opacity",0);
	$("#shader").css("display","block");
	
	// Animation
	$("#shader").animate({opacity: 0.5},layerAnimDuration);
	
	if(disableClose != true){
		document.getElementById("shader").onmouseup = function(e) {
			closeLayer(ID);
		};
	}
	
	//Set infotext if info box
	if(infotext != 'undefined'){
		$("#finishedbox_infotext").html("<h2>"+infotext+"</h2>");
	}
}

function closeLayer(ID) {
	$("#" + ID).css("display","none");
	/*$("#shader").css("opacity",0);*/
	/*$("#shader").css("display","none");*/
	
	$("#shader").animate({opacity: 0},layerAnimDuration,null,onLayerClose);
	$("#shader").mouseover(null);
	
	document.getElementById("shader").onmouseup = null;
}

function onLayerClose() {
	$("#shader").css("display","none");
}

/* Shader tools */

function xDocSize()
{
  var b=document.body, e=document.documentElement;
  var esw=0, eow=0, bsw=0, bow=0, esh=0, eoh=0, bsh=0, boh=0;
  if (e) {
    esw = e.scrollWidth;
    eow = e.offsetWidth;
    esh = e.scrollHeight;
    eoh = e.offsetHeight;
  }
  if (b) {
    bsw = b.scrollWidth;
    bow = b.offsetWidth;
    bsh = b.scrollHeight;
    boh = b.offsetHeight;
  }
//  alert('compatMode: ' + document.compatMode + '\n\ndocumentElement.scrollHeight: ' + esh + '\ndocumentElement.offsetHeight: ' + eoh + '\nbody.scrollHeight: ' + bsh + '\nbody.offsetHeight: ' + boh + '\n\ndocumentElement.scrollWidth: ' + esw + '\ndocumentElement.offsetWidth: ' + eow + '\nbody.scrollWidth: ' + bsw + '\nbody.offsetWidth: ' + bow);
  return {w:Math.max(esw,eow,bsw,bow),h:Math.max(esh,eoh,bsh,boh)};
}

function getScrollX() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function getScrollY() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}

function getWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
}
function getHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
}


function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

/*Gallery*/

/**
 * opens imagegallery, with optional imageSet & captions
 * 
 * @param String ID, id of the gallery container div
 * @param String imageUrl, path to image, optionally containing a caption after the ulr delimited by captionDelimiter
 * @param String imageSet, string containing urls to all images, using imageDelimiter as delimeter, 
 * 				 optionally containing a caption after each ulr delimited by captionDelimiter
 * @param String containerClass class of container div
 * @param String captionPos, caption position either 'inside' or 'below'
 * @param String imageDelimiter, image delimiter for imageSet
 * @param String captionDelimiter, caption delimiter for imageSet 
 */

function openGalleryLayer(ID, imageUrl, imageSet, containerClass, captionPos, imageDelimiter, captionDelimiter) {
	
	//containerClass = 'column.c2';
	
	// set loader, closer & prev / next images
	var loaderImage = '/images/gallery/ajax-loader.gif';
	var closeImage = '/images/gallery/layer-close.png';
	var nextImage = '/images/gallery/gallery-next.png';
	var prevImage = '/images/gallery/gallery-prev.png';
	
	// init variables
	var width = getWidth();
	var height = getHeight();
	var layerHeight = 0;
	var pageHeight = parseInt(xDocSize().h);
	var buttonTop = 0;
	var pos = null;
	var img = new Image();
	
	// handle params
	captionPos 			= (captionPos == 'below' || captionPos == 'inside')? captionPos : 'inside';
	imageDelimiter 		= (imageDelimiter)? imageDelimiter:';';
	captionDelimiter 	= (captionDelimiter)? captionDelimiter:'{{';
	imageUrl			= imageUrl.split(captionDelimiter);
	
	// sniff images off container
	
	if (containerClass) {
		imageSet = '';
		$("."+containerClass+' a').each(function(i, o) {
			fnCall = String($(o).attr('onclick'));
			imageSet += fnCall.substring(fnCall.indexOf('http:'), fnCall.indexOf('return') -8)+imageDelimiter;
		});
		imageSet = imageSet.substring(0, imageSet.length -1);
	}
	
	
	if (imageSet) {		
		images = imageSet.split(imageDelimiter);
		for ( x in images ) {		
			images[x] = images[x].split(captionDelimiter);
		}	
	} else {
		 images = new Array(imageUrl);
	}
	
	// clear old img, closer & caption
	$("#" + ID + " .close").remove();
	$("#" + ID + " .caption").remove();
	
	if (captionPos == 'inside') {
		$("#" + ID + " .wrapper").html('<div class="caption"></div>');
	} else {
		$("#" + ID + " .wrapper").html("");
		$("#" + ID).append('<div class="caption"></div>');
	}
	
	$("#" + ID + " .caption").hide();
		
	// reset layer width + height & set loader bg  
	$("#" + ID + " .wrapper").css({"width": "16px", "height": "16px", "border-radius": "0"});
	$("#" + ID +" .wrapper").css({"background":"url("+ loaderImage +") scroll center center no-repeat"});
	
	// display empty layer
	$("#" + ID).css("display","block");
	
	// Position empty layer
	layerHeight = parseInt($("#" + ID).height()) ? $("#" + ID).height() : 150;
	$("#" + ID).css("top",height / 2 - parseInt(layerHeight) / 2 + getScrollY());
	$("#" + ID).css("left",width / 2 - parseInt($("#" + ID).width()) / 2 + getScrollX());
	
	// resize & reposition layer when image has finished loading
	$(img).load(function () {			
			var maxWidth = 780;
			var maxHeight = 585;
			
			var WK = (maxWidth/img.width);
			var HK = (maxHeight/img.height);
			if ( HK < 1 || WK < 1 ) {
				img.height *= (HK<WK)?HK:WK;
				img.width *= (HK<WK)?HK:WK;
			}
			// resize layer
			$("#" + ID + " .wrapper").css({"height":parseInt( img.height ), "width":parseInt( img.width )});			
			// reposition layer
			layerHeight = parseInt($("#" + ID).height()) ? $("#" + ID).height() : 150;		
			$("#" + ID).css("top",height / 2 - parseInt(layerHeight) / 2 + getScrollY());
			$("#" + ID).css("left",width / 2 - parseInt($("#" + ID).width()) / 2 + getScrollX());
			
			// append closebutton & image
			// $("#" + ID ).prepend('<a href="" onclick="closeLayer(\''+ ID +'\'); return false;" class="close"><img src="'+closeImage+'" alt="" /></a>');
			$("#" + ID ).prepend('<a href="" onclick="closeLayer(\''+ ID +'\'); galleryOpen = false; return false;" class="close">X</a>');
			$("#" + ID + " .wrapper").prepend(this);
			
			// get image position in images array
			for(x in images) {
				if (images[x][0] == imageUrl) {
					pos = x;
				}	
			}
			
			
			// append caption
			if (images[pos].length > 1) {
				
				caption = images[pos][1];
				
				if (captionPos == 'inside') {
					$("#" + ID + " .caption").width( parseInt( img.width - 40) );
					$("#" + ID + " .caption").css({bottom : "20px", left : "20px"});
					$("#" + ID + " .caption").append('<span>' + caption + '</span>');
					$("#" + ID + " .caption").animate({height: 'toggle'},300);
				} else {
					$("#" + ID + " .caption").width( parseInt( img.width ) );
					$("#" + ID + " .caption").append('<span>' + caption + '</span>');
					$("#" + ID + " .caption").animate({height: 'toggle'},300);
				}
			}
			
			// get prev & next button top position
			buttonTop = ( $("#" + ID).height() / 2 ) - 20 ; 
			
			// append next & prev buttons if next / prev image exists
			if (parseInt(pos) > 0) {
				$("#" + ID + " .wrapper").append('<div id="prevBtn" style="position:absolute; left: -28px; top: '+ buttonTop +'px;"><a id="gallery-prev" href="javascript:"><img class="gallerycontrol" style="opacity:1;" src="'+prevImage+'" alt=""/><!--Edellinen--></a></div>');
			}
			if (parseInt(pos) < ( images.length -1)) {
				$("#" + ID + " .wrapper").append('<div id="nextBtn" style="position:absolute; right: -28px; top:'+ buttonTop +'px;"><a id="gallery-next" href="javascript:"><img class="gallerycontrol" style="opacity:1;" src="'+nextImage+'" alt=""/><!--Seuraava--></a></div>');
			}
			
			// call openLayer again on button click to switch image
			$("#gallery-prev").click(function() {
				if (parseInt(pos) > 0) { 
					pos--;
					openGalleryLayer(ID, images[pos][0], imageSet, containerClass, captionPos, imageDelimiter, captionDelimiter);
				}
			});
			
			$("#gallery-next").click(function() {
				if (parseInt(pos) < ( images.length -1)) {
					pos++;
					openGalleryLayer(ID, images[pos][0], imageSet, containerClass, captionPos, imageDelimiter, captionDelimiter);
				}
			});
			
			//left and right arrow keys change images also
			$(document).keydown(function(e){
			    if (e.keyCode == 37) {
			    	$("#gallery-prev").click();
			    }

			    if (e.keyCode == 39) {
			    	$("#gallery-next").click();
			     }    
			});
			
	})
	.attr("src", imageUrl[0]);
	
	/*$(img).mouseover(function() {
		$("#gallery-next").animate({opacity: 1}, 300);
		$("#gallery-next").animate({opacity: 1}, 300);
		$(".layer .close").animate({opacity: 1}, 300);
	});
	
	$("#shader").mouseover(function() {
		$("#gallery-next").animate({opacity: 0}, 300);
		$("#gallery-prev").animate({opacity: 0}, 300);
		$(".layer .close").animate({opacity: 0}, 300);
	});*/
	
	// dont do shader stuff if shader is already shown
	if (!galleryOpen) {
		$("#shader").css("width", getWidth());
		$("#shader").css("height", pageHeight);
		$("#shader").css("opacity",0);
		$("#shader").css("display","block");
		
		// Animation
		$("#shader").animate({opacity: 0.6},layerAnimDuration);
		galleryOpen = true;
	}
	
	document.getElementById("shader").onmouseup = function(e) {
		closeLayer(ID);
		galleryOpen = false;
	};
}

/**
 * Preloads images
 */
function preloadImages() {
	if (document.images) {
		
		var images = new Array();
		
		// Button
		/*images[0] = "/images/navi/fi/apuja2.png";
		images[1] = "/images/navi/fi/etusivu2.png";
		images[2] = "/images/navi/fi/hommaraha2.png";
		images[3] = "/images/navi/fi/kilpailut2.png";
		images[4] = "/images/navi/fi/palvelusta2.png";
		images[5] = "/images/navi/fi/projektit2.png";
		images[6] = "/images/navi/fi/ryhmat2.png";
		images[7] = "/images/navi/fi/yhteistyossa2.png";*/
		
		images[0] = "/images/button/button_bg_color1.png";
		images[1] = "/images/button/button_bg_color1_over.png";
		images[2] = "/images/button/button_left_color1.png";
		images[3] = "/images/button/button_left_color1_over.png";
		images[4] = "/images/button/button_right_color1.png";
		images[5] = "/images/button/button_right_color1_over.png";
		images[6] = "/images/button/button_bg_color2.png";
		images[7] = "/images/button/button_bg_color2_over.png";
		images[8] = "/images/button/button_left_color2.png";
		images[9] = "/images/button/button_left_color2_over.png";
		images[10] = "/images/button/button_right_color2.png";
		images[11] = "/images/button/button_right_color2_over.png";
			
		for(var i = 0; i < images.length; i++) {
			var preload_image_object = new Image(25,25);
			preload_image_object.src = images[i];
		}
	}
}

/*Tab navi*/

function openTab(tabID,tabBoxID) {
	var boxNav = $("#" + tabBoxID).children(".tabNavi");
	var boxItems = $("#" + tabBoxID).children(".tab");
	// var boxItemsNum = $(boxNav).children().length;
	
	// Clear all
	$(boxNav).children("li").removeClass("selected");
	$(boxItems).css("display","none");
	
	// Select current
	$(boxItems[tabID - 1]).css("display","block");
	$(boxNav).children("li:nth-child(" + tabID + ")").addClass("selected");
}

function tellAFriend() {
	var canSend = true;
	
	var email  = $("#tellAFriend_Email").val();
	var sender = $("#tellAFriend_Sendername").val();
	var msg    = $("#tellAFriend_Message").val();
	
	if (!email.match(/[a-z]@[a-z]/)) {
		$("#tellAFriend_Email_error").show();
		$("#tellAFriend_Email").addClass("error");
		canSend = false;
	} else {
		$("#tellAFriend_Email_error").hide();
		$("#tellAFriend_Email").removeClass("error");
	} 
	if ( sender.length < 1 ) {
		$("#tellAFriend_Sendername_error").show();
		$("#tellAFriend_Sendername").addClass("error");
		canSend = false;
	} else {
		$("#tellAFriend_Sendername_error").hide();
		$("#tellAFriend_Sendername").removeClass("error");	
	}
	
	if ( msg.length < 1 ) {
		$("#tellAFriend_Message_error").show();
		$("#tellAFriend_Message").addClass("error");
		canSend = false;
	} else {
		$("#tellAFriend_Message_error").hide();
		$("#tellAFriend_Message").removeClass("error");
	}
	
	if ( canSend ) {
		$.post("/index/tellafriend",$("#tellafriendForm").serialize(), function(data){
			$("#tellAFriend_Email").val("");
			$("#tellAFriend_Sendername").val("");
			$("#tellAFriend_Message").val("");
			
			
		} );
		
		
	}
	return canSend;
}

