$(document).ready(function(){

	if(navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod')
	{
    	$("#footer_area").css("position", "static");
	};

	/* TOGGLE MAP LINK, SEARCH */

	$("#menu-item-963 a").live("click", function(){
		$("div#haku").show();
	});

	$("#map_controls span").live("click", function(){
		$("#map_controls span").removeClass();
		$(this).addClass("active");
		//alert($(this).html());
		if($(this).html() == "Helsinki")
		{
			$("#lahti").hide();
			$("#hki").show();
		}
		else
		{
			$("#lahti").show();
			$("#hki").hide();
		}
	});

	/* SEND SPAM */
	
	$("#content form.callme input[type=submit]").live("click", function(){

		$("#content form.callme input[type=text]").removeClass("error");
		$("#content form.callme .errormsg").text("");
		var error = false;

		var callmeName = $("#content form.callme input#name").val();
		var callmeCompany = $("#content form.callme input#company").val();
		var callmeTel = $("#content form.callme input#tel").val();
		
		$("#content form.callme .required").each(function(){
			if( $(this).val() == "" ){ $(this).addClass("error"); error = true; }
		});
		
		if(error == false){

			$("#content form.callme .errormsg").text("");
			$("#content form.callme").after("<div class='callmessage'>Hetkinen...</div>").hide();
  
 			var dataString = "name=" + callmeName + "&company=" + callmeCompany + "&number=" + callmeTel;

			$.ajax({

				type: "POST",
				url: "http://www.redland.fi/php/callme.php",
				data: dataString,
				success: function() {
	
					$(".callmessage").empty().append("Soittopyyntö lähetetty.<br/>Otamme teihin yhteyttä piakkoin.");
				
				}
			
			}); 
		
		} else {
		
			$("#content form.callme .errormsg").text("Täytä vaadittavat kentät!");

		}
		
        return false;
      
    });


	/*$("#content form.newsletter input[type=submit]").live("click", function(){

		$("#content form.newsletter input[type=text]").removeClass("error");
		$("#content form.newsletter .errormsg").text("");
		var error = false;

		var email = $("#content form.newsletter input#email").val();
		
		$("#content form.newsletter .required").each(function(){
			if( $(this).val() == "" ){ $(this).addClass("error"); error = true; }
		});
		
		if(error == false){

			$("#content form.newsletter .errormsg").text("");
			$("#content form.newsletter").after("<div class='newslettermessage'>Hetkinen...</div>").hide();
  
 			var dataString = "email=" + email;

			$.ajax({

				type: "POST",
				url: "http://www.redland.fi/php/newsletter.php",
				data: dataString,
				success: function() {
	
					$(".newslettermessage").empty().append("Kiitos.<br/> Uutiskirjetilaus otettu vastaan.");
				
				}
			
			}); 
		
		} else {
		
			$("#content form.newsletter .errormsg").text("Täytä sähköposti!");

		}
		
        return false;
      
    });*/

	/* booking */
	$("#content form.bookme input[type=submit]").live("click", function(){

		$("#content form.bookme input[type=text]").removeClass("error");
		$("#content form.bookme .errormsg").text("");
		var error = false;

		var bookmeName = $("#content form.bookme input#name").val();
		var bookmeCompany = $("#content form.bookme input#company").val();
		var bookmeTel = $("#content form.bookme input#tel").val();
		var bookmeEmail = $("#content form.bookme input#email").val();
		var bookmeTimes = $("#content form.bookme textarea#times").val();
		
		$("#content form.bookme .required").each(function(){
			if( $(this).val() == "" ){ $(this).addClass("error"); error = true; }
		});
		
		if(error == false){

			$("#content form.bookme .errormsg").text("");
			$("#content form.bookme").after("<div class='callmessage'>Hetkinen...</div>").hide();
  
 			var dataString = "name=" + bookmeName + "&company=" + bookmeCompany + "&number=" + bookmeTel + "&email=" + bookmeEmail + "&times=" + bookmeTimes;

			$.ajax({

				type: "POST",
				url: "http://www.redland.fi/php/bookme.php",
				data: dataString,
				success: function() {
	
					$(".callmessage").empty().append("Ajanvaraus lähetetty.<br/>Otamme teihin yhteyttä piakkoin.");
				
				}
			
			}); 
		
		} else {
		
			$("#content form.bookme .errormsg").text("Täytä vaadittavat kentät!");

		}
		
        return false;
      
    });

	
	/* MENU */
	
	var pos = 0;
	var width = 0;
	var startPos = 0;
	var startWidth = 0;
	
	$("#menu").append("<span class='bar'></span>");

	if($("#menu li.current-menu-item").length == 0){
		$("#menu li.first").addClass("current-menu-item");
	}

	var linkPos = $("#menu .current-menu-item a").offset();
	var contentPos = $("#menu").offset();
	var activePos = linkPos.left-contentPos.left+7;
	var width = $("#menu .current-menu-item a").width();
	
	$("#menu .bar").stop().animate({left: activePos+"px", width: width+"px"}, {duration: 0, queue: false});

	$("#menu a").mouseover(function(){

		var linkPos = $(this).offset();
		var contentPos = $("#menu").offset();
		var activePos = linkPos.left-contentPos.left+7;
		var width = $(this).width();

		$("#menu .bar").stop().animate({left: activePos+"px", width: width+"px"}, {duration: 200, queue: false}); // joku pomminvarmempi systeemi tähän?

	}).mouseout(function(){

		var linkPos = $("#menu .current-menu-item a").offset();
		var contentPos = $("#menu").offset();
		var activePos = linkPos.left-contentPos.left+7;
		var width = $("#menu .current-menu-item a").width();

		$("#menu .bar").stop().animate({left: activePos+"px", width: width+"px"}, {duration: 200, queue: false});	

	}).click(function(){

		$("#menu a").not(this).parent().removeClass("current-menu-item");
		$(this).parent().addClass("current-menu-item");

	});
	
	
	/* MASTERPIECE DESCRIPTION */
	
	$("#stuff .box .masterpiece").live("mouseenter", function(){
		$("img", this).stop().fadeTo(200,0.2);
		$(".description", this).stop().fadeTo(200,1);
	}).live("mouseleave", function(){
		$("img", this).stop().fadeTo(200,1);
		$(".description", this).stop().fadeTo(200,0);
	});
	
	
	/* OPEN MASTERPIECE */
	
	var open = false;
	var page = "none";
	var height = 0;
	var imgHeight = 0;
	var imgNavi = "";
	
	var max = 0;
	var current= 1;
	var article = false;
	
	$("#stuff .box .open").live("click", function(){
	
		if( $(this).hasClass("article") == true ){
			article = true;
		} else {
			article = false;
		}
	
		$(this).parents(".box").children(".iLikeThis").children(".counter").children(".image").trigger("click");
		
		page = $(this).attr("href") + " #page";
		$("#page").animate({opacity: "0"}, 500);
		
		if(open == true){

			setTimeout( function(){
				loadPage(page);
			}, 500);
		
		} else {
		
			$("#view").css("height", "0px");
			$("#view").show();
			loadPage(page);

				height = 50;
				$("#view").animate({height: height+"px"}, 500);
			
		}

		$("html,body").animate({scrollTop: $("#view").offset().top-15},500);
	
		return false;

	});
		

	function loadPage(page){

		setHeight = $("#view").height();
		$("#view").css("height", setHeight);

		current = 1;

		$("#view").html("<div class='loader'>Ladataan...</div>");

		$("#view").load(page, function(response, status, xhr) {
		
		
			if (status == "error") {
			
				height = 50;
				$("#view").animate({height: height+"px"}, 500);
				$("#view").html("<div class='error'><strong>Tööt!</strong> Sivua ei löydy. Ota yhteyttä ylläpitoon: <a href='mailto:info@redland.fi'>info@redland.fi</a></div>");
			
			} else {
			
				$("#page").css("opacity", "0");
				max = $("#page img").length;
				if(max > 1){ $("#view .imgarea .next").show(); }
				
				$("#view .imgamount").html("<span class='current'>"+current+"</span>/<span class='total'>"+max+"</span>");
				if(current == 1){ $("#view .imgnavi .prev").addClass("disabled"); imgNavi = "first"; }
				
				if(article == false){
					$("#view .images .centerimg:nth-child("+current+") img").load(function(){
					
						$("#view .close").show();
					
						imgHeight = $("#view .images .centerimg:nth-child("+current+") img").height();
						$("#view .imgarea").css({height: imgHeight+"px"});
			
						height = $("#page").height();
						
						$("#view").animate({height: height+30+"px"}, 500, resetHeight);
			
						$("#page").css("opacity", "0").animate({opacity: "1"}, 500);
					
					});
				} else {
					$("#view .close").show();
					
					height = $("#page").height();
						
					$("#view").animate({height: height+30+"px"}, 500, resetHeight);
			
					$("#page").css("opacity", "0").animate({opacity: "1"}, 500);				
				}
					
				open = true;
				
			}
		});
		return false;
	}

	$("#view .close").live("click", function(){
		$("#view").animate({height: "0"}, 500, function(){ $("#view").fadeOut(0); });
		open = false;
		return false;
	});
	
	function resetHeight(){
		$("#view").css("height", "auto");
	}
		
	
		/* NEXT / PREV */
		
	var testPos = 0;
	
	$("#view .next").live("click", function(){

		if(imgNavi != "last"){

			current++;
		
			$("#view .current").text(current);

			$("#view .images").animate({ left: -(current-1)*750+"px"}, 300);
		
			imgHeight = $("#view .images .centerimg:nth-child("+current+") img").height();
			$("#view .imgarea").animate({height: imgHeight+"px"}, 300);
		
			if(current == max){ $("#view .imgarea .next").hide(); $("#view .imgnavi .next").addClass("disabled"); imgNavi = "last"; } else { imgNavi = ""; }
			if(current != 1){ $("#view .imgarea .prev").show(); $("#view .imgnavi .prev").removeClass("disabled"); }
			
		}

		return false;

	});

	$("#view .prev").live("click", function(){

		if(imgNavi != "first"){

			current--;

			$("#view .current").text(current);

			$("#view .images").animate({ left: -(current-1)*750+"px"}, 300);
		
			imgHeight = $("#view .images .centerimg:nth-child("+current+") img").height();
			$("#view .imgarea").animate({height: imgHeight+"px"}, 300);

			if(current == 1){ $("#view .imgarea .prev").hide(); $("#view .imgnavi .prev").addClass("disabled"); imgNavi = "first"; } else { imgNavi = ""; }
			if(current != max){ $("#view .imgarea .next").show(); $("#view .imgnavi .next").removeClass("disabled"); }
		
		}

		return false;

	});
	
	
	
	/* RESIZE SITE */
	
	var contentWidth = "0";
	var size = "0";
	
	resizeWrapper();
	$(window).resize(resizeWrapper);
	
	function resizeWrapper(){
		width = $(window).width();
		
		oldSize = size;
		if(width > "1380"){ size = "wide"; }
		if(width > "1100" && width < "1380"){ size = "average"; }
		if(width < "1100"){ size = "narrow"; }

		if(size != oldSize){
		
			$("body").removeClass("wide average narrow").addClass(size);
			//$("body").removeClass().addClass(size);
			Set_Cookie( 'size', size, '', '/', '', '' );
			var speed = 1000;  // animation speed
			var  $wall = $('#wrapper').find('#stuff');

			$wall.masonry().removeData('masonry');
			$wall.masonry({
			  columnWidth: 260, 
			  itemSelector: '.box:not(.invis)',
			  animate: true,
			  animationOptions: {
				duration: speed,
				queue: false
			  }
			});

		}

	}
	
	
	/* CALL US */
	
	$("form#callgirl").mouseenter(function(){
	
		$(this).stop().animate({top: "-150px"}, 500);
	
	}).mouseleave(function(){

		$(this).stop().animate({top: "0px"}, 500);
	
	});
	
	
	/* LOAD MORE */
	
	var category = "";
	var date = "";
	var order = "";
	var sort = false;
	var pageEnd = false;
	var status = "ready";
	var pageId = 1;
	var scrollPosition = 0;
	var documentHeight = 0;
	var msgLoading = "Etsitään lisää sisältöä <img src='http://www.redland.fi/wp-content/themes/rdlnd/images/ajaxloader2.gif' alt='' width='16' height='16' valign='middle' />";
	var msgEnd = "Kaikki valittu sisältö esillä";
	var msgError = "Sisältöä ei löydy";
	
	$(".wp-pagenavi").remove();

	if(single == false){

		loadTrigger();
		$(window).scroll(loadTrigger);
		$(window).resize(loadTrigger);
	
	}
	
	function loadTrigger(){

		documentHeight = $(document).height() - $(window).height() - 200;
		scrollPositionOld = scrollPosition;
		scrollPosition = $(window).scrollTop();
	
		if(scrollPositionOld < scrollPosition && scrollPosition > documentHeight && pageEnd == false && status == "ready"){ loadMore(category, date, order); }

	}
	
		
	/* FILTER / SORT */
	
	$("#sort .sort").click(function(){
		$(".dropdown", this).addClass("shadow").slideDown(200)
		$(this).addClass("shadow");
	}).mouseleave(function(){
		$(".dropdown", this).removeClass("shadow").slideUp(100);
		$(this).removeClass("shadow");
	});
	
	$("#sort #sortbydate").click(function(){
		
		if($("#sortbydate").text() == "Uusin ensin"){
			$("#sortbydate").text("Vanhin ensin");
			order = "ASC";
		} else {
			$("#sortbydate").text("Uusin ensin");
			order = "DESC";
		}

		sortContent();

		return false;

	});

	$("#sort .sort a").click(function(){

		$(this).parents(".sort").children(".result").text($(this).text());
		$(this).parents(".sort").children(".dropdown").hide();

		sortContent();

		return false;

	});
	
	function sortContent(){

		pageId = 0;
		pageEnd = false;

		/* get values */
  		$("#stuff .box").fadeOut(speed);
		
		category = $("#sort #category .result").text();
		date = $("#sort #date .result").text();

		setTimeout(function(){
			$wall.masonry().removeData('masonry');
	  		$("#stuff .box").remove();
			loadMore(category, date, order);
		}, speed);

		/* close open content */
		if (open == true){
			$("#view").animate({height: "0"}, 500, function(){ $("#view").fadeOut(0); });
			open = false;
		}
	
	}
	
	
	function loadMore(category, date, order){
	
		if(category == "Kaikki kategoriat"){ category = ""; }
		if(date == "Kaikki vuodet"){ date = ""; }

		category = $("#sort #category .result").text();
		if (category == "Kaikki kategoriat") category = "all";
		if (category == "Työnäytteet") category = "tyonaytteet";
		date = $("#sort #date .result").text();
		if (date == "Kaikki vuodet") date = "all";

		$("body").append("<div id='temp'></div>");

		status = "busy";
		pageId++;
		more = "page/" + pageId + "/?category=" + category + "&date=" + date + "&order=" + order + " #stuff .box";
		
		$("#loading").html(msgLoading);
 		
		$("#footer").append("<div id='loading'>"+msgLoading+"</div>");
		$("#loading").slideDown(500);
		
		$("#temp").load(more, function(response, status, xhr) {
			if (status == "error") {
				pageEnd = true;
				$("#loading").text(msgError).fadeTo(2000,1).slideUp(500);
				$("#temp").remove();
			} else {
				if ( $("#temp .box").length == 0 ) {
					pageEnd = true;
					$("#loading").text(msgEnd).fadeTo(2000,1).slideUp(500);
					$("#temp").remove();
				} else {
					$("#temp .box").addClass("new").css("opacity", "0");
					$("#stuff").append($("#temp").html());
					$("#loading").fadeTo(100,1).slideUp(500, ready);
				}

			}

		});

	}

	function ready(){
		status = "ready";
		$("#temp").remove();
		$("#loading").remove();
		$("#stuff .new").css("opacity", "1");
//		$("#stuff").masonry();
		var  $wall = $('#wrapper').find('#stuff');
		var speed = 1000;  // animation speed
		//$wall.masonry().removeData('masonry');
		$wall.masonry({
			appendedContent: $("#stuff .box.new"),
			columnWidth: 260, 
			itemSelector: '.box:not(.invis)',
			animate: true,
			animationOptions: {
		    	duration: speed,
		    	queue: false
		  	}

		}, function(){ $("#stuff .box.new").removeClass("new"); });

	} 
	

	
	
	/* MASONRY */

var speed = 1000;  // animation speed
var  $wall = $('#wrapper').find('#stuff');


$wall.masonry({
  columnWidth: 260, 
  itemSelector: '.box:not(.invis)',
  animate: true,
  animationOptions: {
    duration: speed,
    queue: false
  }
});

	
	/* SET COOKIE */
	
	function Set_Cookie( name, value, expires, path, domain, secure ){
		var today = new Date();
		today.setTime( today.getTime() );

		if ( expires ){ expires = expires * 1000 * 60 * 60 * 24; }
		
		var expires_date = new Date( today.getTime() + (expires) );

		document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
		( ( path ) ? ";path=" + path : "" ) +
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
	}
	
	
	
	
	
	
	
	
		
		
});	
