/***
 * Chelidonia Villas (c) 2010,2011
 * Code by Adrian Dabrowski
 * Thanks to Sam Dunn for his great scripts and of course to all the authors of jquery! I love you!
*/

$(function(){
	$.fn.supersized.options = {  
		startwidth: 4,  
		startheight: 3,
		vertical_center: 1,
		slideshow: 0,
		navigation: 0,
		transition: 1, //0-None, 1-Fade, 2-slide top, 3-slide right, 4-slide bottom, 5-slide left
		pause_hover: 0,
		slide_counter: 0,
		slide_captions: 0,
		slide_interval: 7000  
	};
	$('#supersize').supersized(); 
});


var ref=document.referrer;
var coursestart=new Date();
var course="";
var mobilebrowser=( navigator.userAgent.toLowerCase().indexOf("android")>0 ||
					 navigator.userAgent.toLowerCase().indexOf("ipad")>0 ||
					  navigator.userAgent.toLowerCase().indexOf("iphone")>0 );
var padbrowser=(navigator.userAgent.toLowerCase().indexOf("android")>0 ||
					 navigator.userAgent.toLowerCase().indexOf("ipad")>0 );


/* loads new content */
function loadsubpage(newhref,menuelement) {
		
		if (menuelement!=null) {
			var newactive = $(menuelement);	
			// menu highlighting
			if (newactive.parent().parent().hasClass("tabs")) $(".tabs .active").removeClass("active");
			$("#secondarymenu .active").removeClass("active");
			newactive.parent().addClass("active"); // .active attached to <li>
		}
			
		$("#tweetmsg").hide();
		
		var loadnext=function() { //event handler 
			$("#tab_content").load(newhref+" #tab_content_ajax", function(response,status,xhr) {
					if (status == "error" || status == "undefined" || status == undefined) {
						$("#tab_content_ajax").html("<h2>Error loading</h2><b>"+ xhr.status + "</b> " + xhr.statusText + "<br/>Clearly, this should not happen. Please write us a mail.");
						document.contentresize();
						$("#tab_content").show("slide",{ direction: "up" },"slow");
					} else {	
						document.contentresize(); // while not rendered, the size might be unknown
						$("#tab_content").show("slide",{ direction: "up" },mobilebrowser?"0":"slow", function() {
							document.contentresize();
							// fix secondary menu now, since it is new:
							attachsecondarymenuhandler();
							if ($.browser.msie && parseInt(jQuery.browser.version)<9) { // IE9 will support round css3 borders, they say..
								$("#secondarymenu li").corner("cc:#fff 5px");
							}
						});
					} // if not error
			});
		};
		
		if ($("#tab_content").is(":hidden") || mobilebrowser ) { 
			loadnext(); // when allready hidden, just load it
		} else { 
			$("#tab_content").hide("slide",{ direction: "up" },"slow",loadnext); // slide up, load next page
		} 
		
		window.location.hash=newhref; // for ext linking
		course+=newhref.replace(".html","")+" ";
		historyhandler(true);
		historyenable=true;
}

function loadhash(href) {
	var newhref=href.replace(/:|\/|\?| |\.\.|\(|\)|\[|\]|=|'|"/g,""); // clean string
	if (newhref.match(/.html$/)) { // adopt this, when integrating into a CMS
		if ($(".tabs a[href='"+newhref+"']").text()>"") { // is there a main menu for that?
			if ($(".tabs a[href='"+newhref+"']").text() != $(".tabs .active").text()) {
				// simulate click only, if subpage is'nt the current selected page anyway
				$(".tabs a[href='"+newhref+"']").click();
			}
		} else {
			// there is no menu for that, we try to load it directly
			loadsubpage(newhref,null);
		}
	} else if (newhref.match(/.jpg$/)) { // adopt this, when integrating into a CMS
		// show background-image
		nextslide('backgrounds/'+newhref);
		$("#tab_content").hide();
		$("#tweetmsg").text($(".activeslide img").attr("title")+$(".activeslide img").attr("alt"));
		$("#tweetmsg").show("slow");
	}
}

/** Reservation form **/
function checkreservation() {
	var toshort=false;
	var nonnullfields=new Array('firstname','surename','nationality', 'email','adults','email2');
       for (var i=0; i<nonnullfields.length; i++) {
		var f=document.getElementsByName(nonnullfields[i])[0];
		if (f && f!=null && f.value ) 
			f.value=f.value.trim();
			if (typeof(f.value)!="undefined" && f.value.length<1) {
				f.style.backgroundColor="#ffcccc";
				//f.style.borderColor="#ff0000";
				toshort=true;
			} else {
				f.style.backgroundColor=null;
			}

	}	       
	if (toshort) { 
		alert("Some mandatory fields have not been filled");
		return false;
	}

	if (document.getElementsByName("email")[0].value!=document.getElementsByName("email2")[0].value) {
		alert("Please check both eMail-Addresses. They need to be equal. (It's a common mistake)");
		return false;	
	}
	
	document.getElementsByName("checkfield")[0].value=document.getElementsByName("firstname")[0].value;
	document.getElementsByName("course")[0].value=course;
	var now=new Date();
	document.getElementsByName("coursestart")[0].value=(now.getTime()-coursestart.getTime())/60000;
	document.getElementsByName("ref")[0].value=ref;

	return true;

}

/** Webcam update **/
var webcamhires="";
var webcamhiresimg=null;
function changepic(fn,fnhi) {
	document.getElementById('webcampic').src=null;
	document.getElementById('webcampic').src='webcam/cam2/'+fn;
	//alert($('#webcampic').src);
	webcamhires='webcam/cam2/'+fnhi;
	if (webcamhires) {
		$('#webcamlupe').css('backgroundImage',"url("+webcamhires+")");
		webcamhiresimg=new Image();
		webcamhiresimg.src=webcamhires;
	}

	$('#webcamview').unbind('mousemove').unbind('mouseleave');
	if (webcamhires)  $('#webcamview').bind({
		mousemove: function(e) {
			var globx=e.pageX;
			var globy=e.pageY;
			var x=e.pageX-$('#webcampic').offset().left;
			var y=e.pageY-$('#webcampic').offset().top;
			var w= $('#webcamlupe').outerWidth();
			var h= $('#webcamlupe').outerHeight();
			
			if(x>640 ||y>400) {
				$('#webcamlupe').css("display","none");
			} else {
			 	//$('#webcamlupe').css("display","block").css("left",e.pageX-w/2).css("top",e.pageY-h/2-$('#webcampic').position().top);
			 	$('#webcamlupe').css("display","block").css("left",x-w/2).css("top",y-h/2+$('#webcampic').position().top);
			 	$('#webcamlupe').css("backgroundPosition",(x*-2+w/2)+"px "+(y*-2+h/2)+"px");
			}
		},
		mouseleave: function(e) {
			 $('#webcamlupe').css("display","none");
		}		
	});;


	return false;
}


var historyinterval=null;
var historyenable=false;
var historycurrenthref=window.location.hash.substring(1,99);

/* manages history back button */
function historyhandler(disable) {
	var newhref=window.location.hash.substring(1,99);
	if (newhref!=historycurrenthref) {
		//console.log("new href detected:"+newhref);
		//console.log("histenable "+historyenable+" local disable "+disable);
		if (historyenable && !disable) {
			if (newhref.length>0) {
				loadhash(newhref);
			} else {
				window.location=window.location; // return to vanilla state
			}
		} 
		historycurrenthref=newhref;
	}
}


// changes to made to the newly loaded content...
function attachsecondarymenuhandler() {
	$("#secondarymenu a").click(function(event){
		var newhref = $(this).attr('href');
		var newactive = $(this);
		event.preventDefault(); // default action is only for javascript-less users
		// clicked on active element? -> just hide content
		/* if ($("#secondarymenu .active").text()==newactive.parent().text()) {
			window.location="#"; // delete anchor
			$("#tab_content").hide("slide",{ direction: "up" },"slow"); // hide content
			return;
		} else { */
			loadsubpage(newhref,this); // load new page
		/* } */
	});
	// reservation form, datepicker
	$("#arrivaldate, #departuredate").datepicker(
		{showWeek: true, 
		firstDay: 1, 
		minDate:"+1d", 
		dateFormat: "yy-mm-dd",
		changeMonth: true, 
		changeYear: true, 
		duration: 'fast', 
		yearRange:'0:+1' ,
		onSelect: function() {
			$("#departuredate").datepicker("option","minDate",$("#arrivaldate").datepicker("getDate"));
		}
	});
	$("#departuredate").datepicker("option","numberOfMonths",2);
	$('.internlink, .internlinksmall').click(function(event) {
		var newhref = $(this).attr('href');
		event.preventDefault();
		loadsubpage(newhref,null);
	});
		
}


$(document).ready(function() {

	// preload transparent 90% image
	var transp90=new Image();
	transp90.src="transp90.png";

	/* gallery */
	$("#nextbutton").hide();
	$("#prevbutton").hide();

	var buttonshow=1; // 0 left, 1,2 mid, 3 right
	/* // disabled: show gallery all the time
	$(document).bind("mousemove", function(e) {
		var x=e.pageX;
		var xx=$(window).width();
		var newbuttonshow=Math.floor(x*4/xx);
		if (newbuttonshow!=buttonshow) { // only react when state changed
			switch(newbuttonshow) {
				case 0:
					$("#prevbutton").fadeIn("fast");
					$("#nextbutton").fadeOut("fast");
				break;
				case 1:
				case 2:
					$("#prevbutton").fadeOut("fast");
					$("#nextbutton").fadeOut("fast");
				break;
				case 3:
					$("#prevbutton").fadeOut("fast");
					$("#nextbutton").fadeIn("fast");
				break;
			}
		}
		buttonshow=newbuttonshow;
	});
	*/
	$("#prevbutton").fadeIn("fast"); // show always
	$("#nextbutton").fadeIn("fast");

	$("#nextbutton").click(function() {
		$("#tweetmsg").hide();
		$(".tabs .active").removeClass("active")
		//if ($("#tab_content").is(":visible")) 
		$("#tab_content").fadeOut();
		var f=nextslide();
		$("#tweetmsg").text($(".activeslide img").attr("title")+$(".activeslide img").attr("alt"));
		$("#tweetmsg").show(/* "slow" */);
		window.location="#"+f.replace(/^.*\//,"");
		historyhandler(true);
		historyenable=true;
		course+=f.replace(/^.*\//,"")+" ";
		return false;
	});
	
	$("#prevbutton").click(function() {
		$("#tweetmsg").hide();
		$(".tabs .active").removeClass("active")
		$("#tab_content").fadeOut();
		var f=prevslide();
		$("#tweetmsg").text($(".activeslide img").attr("title")+$(".activeslide img").attr("alt"));
		$("#tweetmsg").show(/* "slow" */);
		window.location.hash=f.replace(/^.*\//,"");
		historyhandler(true);
		historyenable=true;
		course+=f.replace(/^.*\//,"")+" ";
		return false;
	});
	
	// click auf hintergrundbild -> hide content
	if (!mobilebrowser) {
		$("#supersize, #content").click(function(e) {
			//alert($(e.target).attr("id"));
			if (($(this).attr("id")=="supersize" && e.pageY>150) || $(e.target).attr("id")=="content" ) {
				if (!$("#tab_content").is(":hidden")) {
					$(".tabs .active").removeClass("active");
					$("#tab_content").hide("slide",{ direction: "up" },"slow");
					course+="- ";
				} else {
					if (!document.getElementById("donotslideopen")) {
						$("#tab_content").show("slide",{ direction: "up" },"slow");
						course+="+ ";
					}
				}
			}
		});
	} // !mobile browser
	
	/* tweet messages */
	$("#tweetmsg").hide();
	
	if (!mobilebrowser) {
		$("#tweetbird").click(function() {
			$("#tweetmsg").toggle("slow"); // slide open
		} );
	}
	
	/* Menu functions */
	
	$("ul.tabs li a").click(function(event) { 
		var newhref = $(this).attr('href');
		var newactive = $(this);
		event.preventDefault(); // default action is only for javascript-less users
		
		// clicked on active element? -> just hide content
		if ($(".tabs .active").text()==newactive.parent().text()) {
			f=$('#supersize .activeslide').find('img').attr("src");
			window.location.hash=window.location="#"+f.replace(/^.*\//,"");; // delete anchor, set to bg image
			historyhandler(true);
			historyenable=true;
			$(".tabs .active").removeClass("active");
			$("#tab_content").hide("slide",{ direction: "up" },"slow"); // hide content
			course+="-- ";
			return;
		} else {
			loadsubpage(newhref,this); // load new page
		}
	} );
	
	attachsecondarymenuhandler(); // if there is a secondary menu, we need to attach js-code to it.
	
	// resize content with window, also call on load of new content
	var contentresize= function(){
		var defaultsize=470;
		var contentheight=$("#tab_content_ajax").height();
		if (contentheight-1>$("#tab_container").height()) {
			var maxheight=Math.round($(window).height()-$("#tab_content").offset().top-90);
			//alert($(window).height());
			if ( maxheight>defaultsize ) {
				var currentsize=$("#tab_content").height();
				if (contentheight>maxheight) {
					if (currentsize>maxheight || $("#tab_content").is(":hidden") || mobilebrowser ) {
						$("#tab_content").height(maxheight+"px"); // verkleinern: sofort
					} else {
						$("#tab_content").animate({height:maxheight+"px"},"fast"); // vergrößern: animiert
					}
				} else {
					if (currentsize>contentheight || $("#tab_content").is(":hidden") || mobilebrowser ) {
						$("#tab_content").height(contentheight+"px"); // verkleinern: sofort
					} else {
						$("#tab_content").animate({height:contentheight+"px"},"fast"); // vergrößern: animiert
					}
				}
			} else {
				$("#tab_content").height(defaultsize+"px"); // fallback to default.
			}
		} else {
			$("#tab_content").height(defaultsize+"px"); // fallback to default.
		}
	};
	
	$(window).bind("resize", contentresize);
	document.contentresize=contentresize;
	
	
	/*************************************/
	/* Window Load */
	
	$(window).load(function () { 
	
		// lazy loading of images after the rest of the page finishes
		// if we add much more, we will have to implement a better lazy-loading algorithm
		$("#supersize a").delay(1250).after( /* more supersize images */
			'<a href="#"><img src="backgrounds/3.jpg" alt="The volcano islands shot from a Chelidonia living room"/> </a>'+
			'<a href="#"><img src="backgrounds/3-honeymoon.jpg" alt="Our brand new Honeymoon Suite"/> </a>'+
			'<a href="#"><img src="backgrounds/4.jpg" alt="A slightly differing angle of view, sun and wind silver coating the sea"/></a>'+
			'<a href="#"><img src="backgrounds/5.jpg" alt="This could be your home on the Santorini Caldera"/></a>'+
			'<a href="#"><img src="backgrounds/5a.jpg" alt="Upscale traditional - the style we prefer"/></a>'+
			'<a href="#"><img src="backgrounds/6.jpg" alt="Absolute tranquillity all night guaranteed"/></a>'+
			'<a href="#"><img src="backgrounds/7a.jpg" alt="As you might have guessed: we love Bougainvilleas"/></a>'+
			'<a href="#"><img src="backgrounds/7b.jpg" alt=""/></a>'+
			'<a href="#"><img src="backgrounds/8.jpg" alt="Idyll on the southwestern rim of Chelidonia Bay"/> </a>'+
			'<a href="#"><img src="backgrounds/8a.jpg" alt="A relaxed afternoon, boats passing by, true serendipity"/> </a>'+
			// '<a href="#"><img src="backgrounds/9.jpg" alt="9"/></a>'+
			'<a href="#"><img src="backgrounds/tib2116.jpg" alt="This villa once used to house families up to nine members ."/></a>'+
			'<a href="#"><img src="backgrounds/10.jpg" alt="Chelidonia Bay, southeastern rim, in the glory of Santorinian spring.   "></a>'+
			'<a href="#"><img src="backgrounds/11.jpg" alt="Croisieres beleaguering Thira harbour. Behind: mount Prophet Elias"/></a>'+
			'<a href="#"><img src="backgrounds/11a.jpg" alt=""/></a>'+
			'<a href="#"><img src="backgrounds/12.jpg" alt="Would you expect this intimate house to sport broadband internet?"/></a>'+
			'<a href="#"><img src="backgrounds/12a.jpg" alt="Try to find the former owners of this house. Hint: They look down from some wall."/></a>'+
			'<a href="#"><img src="backgrounds/12b.jpg" alt="Did we alreday say that we love Bougainvilleas?"/></a>'+
			'<a href="#"><img src="backgrounds/12b1.jpg" alt=""/></a>'+
			'<a href="#"><img src="backgrounds/12c.jpg" alt="Cruising ships, ferries, cargo ships and sometimes even NATO vessels parade below our terraces"/></a>'+
			'<a href="#"><img src="backgrounds/13.jpg" alt="On clear days the White Mountains of Crete emerge behind tiny Aspronisi"/></a>'+
		'');

		/** So we have external links **/
		if (window.location.hash) {
			var newhref=window.location.hash.substring(1,99);
			loadhash(newhref);
		}
		
		
		if ($.browser.msie && parseInt(jQuery.browser.version)<9) { // IE9 will support round css3 borders, they say..
			$(".tabs li").corner("cc:#fff 5px");
			$("#secondarymenu li").corner("cc:#fff 5px");
		}
		
		// open tweet on empty page
		
		if ( $("#tab_content").is(":hidden") && $('#tweetmsg').is(':hidden')) $('#tweetbird').click();
		
		
		// history timer
		historyinterval=setInterval(function() { historyhandler(false); }, 1000);
		
	});
	
});

