/**
 *
 * Hotel.im Api-Search Engine
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2010, Christopher Pietsch
 * @link          http://chrispie.com
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */


$.query = $.query.load(location.href);

$(function() {
	
	var windowHeight=$(window).height();
	
	$('a').click(function(){
		this.blur();
	});
	
//	console.log($.query.toString());
	
	
	$('#sorterBox').bind('change',function(){
		var sort=$("#sortBox option:selected").attr('value').split("-");
		$.query.SET('sort', sort[1]).SET('direction', sort[0]).SET('page',1);

		updateList();

	});
	
	$('#currencySelect').change(function(){
		var currency=$(this,"option:selected").attr('value');
		$.query.SET('currency', currency).SET("priceFrom","").SET("priceTo","");
		updateList();
		
	});
	
	$('.changeHandler').change(function(){		
		$.query.SET($(this).attr('id'), $(this,"option:selected").attr('value')).SET('page', 1);
		updateList();
	});
	
	function updateParams(callback){
		$.get(AjaxUpdateParams+"/"+$.query.toString().replace('#','?'), callback);
		document.location = $.query.toString();
	}
	

	function updateDetail(){
		document.location = $.query.toString();
	}
	function isScrolledIntoView(elem)
	{
		var rand=60;
	    var docViewTop = $(window).scrollTop()-rand;
	    var docViewBottom = docViewTop + $(window).height()-rand;

	    var elemTop = $(elem).offset().top;
	    var elemBottom = elemTop + $(elem).height();

	    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom));
	}
	
	$.datepicker.setDefaults($.extend({
		showMonthAfterYear: false,
		minDate: 0,
		numberOfMonths: 1,
		showButtonPanel: true,
		showAnim:'',
		altFormat: 'yy-mm-dd'
		//dateFormat: 'yy-mm-dd'
		}, $.datepicker.regional[currentLanguage]));
	
	
	
	$('#HotelsDate1').datepicker({
		onSelect: function(){
			var checkin=$(this).datepicker( 'getDate' );
			//setter
			$( "#HotelsDate2" ).datepicker( "option", "minDate", checkin ); 
		}
	});
	
	$('#HotelsDate2').datepicker({
		onSelect: function(){
			var checkout=$(this).datepicker( 'getDate' );
			var checkin=$('#HotelsDate1').datepicker( 'getDate' );

			var diff = checkout.getTime() - checkin.getTime();
			var days = Math.floor(diff / (1000 * 60 * 60 * 24));

			if(days>30){
				alert($(this).next('span').text());
			}
		}
	});
	
	$('#OverlayHotelsDate1').datepicker({
		onSelect: function(){
			var checkin=$('#OverlayHotelsDate1').datepicker( 'getDate' );
			//setter
			$( "#OverlayHotelsDate2" ).datepicker( "option", "minDate", checkin ); 
		}
	});
	
	$('#OverlayHotelsDate2').datepicker({
		onSelect: function(){
			var checkout=$(this).datepicker( 'getDate' );
			var checkin=$('#OverlayHotelsDate1').datepicker( 'getDate' );

			var diff = checkout.getTime() - checkin.getTime();
			var days = Math.floor(diff / (1000 * 60 * 60 * 24));

			if(days>30){
				alert($(this).next('span').text());
			}
		}
	});
	


	
	/*
	var dates=$('#HotelsDate1, #HotelsDate2').datepicker({
		onSelect: function( selectedDate ) {
				//console.log($('#'+this.id+"Real"));
				var instance = $( this ).data( "datepicker" );
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				// for url
				var newFormat = $.datepicker.formatDate("yy-mm-dd", date);
				//$(this).data("realDate",newFormat);
				$.query.SET($(this).attr("name"), newFormat);
				// set the other datepicker
				if(this.id == "HotelsDate1"){
					date.setDate(date.getDate()+1);
					var maxDate=new Date();
					maxDate.setMonth(date.getMonth()+1);
					dates.not( this ).datepicker( "option", "maxDate", maxDate ).not( this ).datepicker( "option", "minDate", date );
				}
			}
	});
	
	var datesOverlay=$('#OverlayHotelsDate1, #OverlayHotelsDate2').datepicker({
		onSelect: function( selectedDate ) {
				//console.log($('#'+this.id+"Real"));
				var instance = $( this ).data( "datepicker" );
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings );
				// for url
				var newFormat = $.datepicker.formatDate("yy-mm-dd", date);
				//$(this).data("realDate",newFormat);
				$.query.SET($(this).attr("name"), newFormat);
				// set the other datepicker
				if(this.id == "OverlayHotelsDate1"){
					date.setDate(date.getDate()+1);
					var maxDate=new Date();
					maxDate.setMonth(date.getMonth()+1);
					dates.not( this ).datepicker( "option", "maxDate", maxDate ).not( this ).datepicker( "option", "minDate", date );
				}
			}
	});
	*/
	
	
	// first startup
	if($.query.get('checkin')!="" && $.query.get('checkout')!=""){
		var checkin=$.datepicker.parseDate('yy-mm-dd',$.query.get('checkin'));
		var checkout=$.datepicker.parseDate('yy-mm-dd',$.query.get('checkout'));
		$('#HotelsDate1,#OverlayHotelsDate1').datepicker("setDate", checkin);
		$('#HotelsDate2,#OverlayHotelsDate2').datepicker("setDate", checkout);
	} else {
		$('#HotelsDate1, #HotelsDate2, #OverlayHotelsDate1, #OverlayHotelsDate2').val('');
	}
	

	
	// MODAL
	$('.morePics').fancybox({
		
	});
	
	$( ".checkPricesBox a" ).fancybox({
		
	}).click(function(){
		$.query.SET('detail', $(this).attr('rels'));
		$('#dateOverlay').show();
		$('#searchingOverlay').hide();
	});
	
	$('#getRates').fancybox({
		
	}).click(function(){
		$.query.SET('checkin',$.datepicker.formatDate("yy-mm-dd", $('#HotelsDate1').datepicker( 'getDate' )));
		$.query.SET('checkout',$.datepicker.formatDate("yy-mm-dd", $('#HotelsDate2').datepicker( 'getDate' )));
		
		$('#dateOverlay').hide();
		$('#errorOverlay').hide();
		if($.query.get('checkin')!="" && $.query.get('checkout')!=""){
			
			$('#searchingOverlay').show();
			$.query.SET('guests', $('#HotelsGuests').val()).SET('rooms', $('#HotelsRooms').val());
			//console.log($.query.toString());
			queryLive();
		} else {
			$('#dateOverlay').show();
			//$('#errorOverlay').show();
		}
	});
	
	$('#getFrontRates').click(function(){
		$.query.SET('checkin',$.datepicker.formatDate("yy-mm-dd", $('#HotelsDate1').datepicker( 'getDate' )));
		$.query.SET('checkout',$.datepicker.formatDate("yy-mm-dd", $('#HotelsDate2').datepicker( 'getDate' )));
	
		var filename=$('#HotelCityFilename').val();
		if(filename==""){
			$('#HotelsCity').focus();
			
		} else {
			//$.query.SET('filename', filename);
			$.fancybox('',{
				'href': '#checkPrices'
			});
			here='/'+$('#HotelCityFilename').val();
		//	console.log($.query.get('checkin'));
			$('#dateOverlay').hide();
			$('#errorOverlay').hide();
			if($.query.get('checkin')!="" && $.query.get('checkout')!=""){
				$('#searchingOverlay').show();
				$.query.SET('guests', $('#HotelsGuests').val()).SET('rooms', $('#HotelsRooms').val());
				//console.log($.query.toString());
				queryLive(filename);
			} else {
				$('#errorOverlay').fadeIn();
			}
		}
		return false;
	});
	
	$('#getRatesOverlay').click(function(){
		$.query.SET('checkin',$.datepicker.formatDate("yy-mm-dd", $('#OverlayHotelsDate1').datepicker( 'getDate' )));
		$.query.SET('checkout',$.datepicker.formatDate("yy-mm-dd", $('#OverlayHotelsDate2').datepicker( 'getDate' )));
		
		// validierung machen
		if($.query.get('checkin')!="" && $.query.get('checkout')!=""){
			
			$.query.SET('guests', $('#OverlayHotelsGuests').val()).SET('rooms', $('#OverlayHotelsRooms').val());
		
			// fade In des Search layers
			$('#errorOverlay').hide();
			$('#searchingOverlay').fadeIn();
			$('#dateOverlay').fadeOut();
		
			queryLive();
		} else {
			$('#dateOverlay').css('position','relative');
			$('#errorOverlay').css('position','relative').slideDown();
		}
		return false;
	});
	
	
	// AJAXQUERY
	
	var progress;
	function queryLive(name){
		$.query.SET('priceFrom','').SET('priceTo','');
		
		$("#status").show();
		$("#error").hide();
		if(name) {
			fileName=name;
		}
		// request an controller das er einen neuen async search starten soll
		$( "#progressbar" ).progressbar({
					value: 0
		});
		window.clearInterval(progress);
		$.query.SET('page',1);
		//console.log($.query.toString());
		var percent=0;
		var finished=1;
		progress = window.setInterval(function() { 
		//	$.getJSON("demo.php?id=" + progress_key, function(data) {
				if (percent >=10000) {
					window.clearInterval(progress);
					//updateList();
					//location.reload(true);
					return;
				}
				//console.log(percent);
				if(((percent%100)==0) && finished==1){
					finished=0;
					$.getJSON(AjaxHotelsCrawl+'/'+fileName+$.query.toString(), function(data) {
						//console.log(data);
						if(data){
							if(data.status=="finished"){
								window.clearInterval(progress);
								$("#progressbar").progressbar( "option", "value", 100 );
								window.setTimeout("updateList()",300);
								
							}
							if(data.status=="crawling"){
								$("#OverlayNumFound").hide().text(data.stats.results).fadeIn('fast');
							}
							if(data.status=="error"){
								$("#status").hide();
								$("#error").show();
								clearInterval(progress);
								$("#progressbar").progressbar( "option", "value", 100 );
								$('#HotelsDate1, #HotelsDate2, #OverlayHotelsDate1, #OverlayHotelsDate2').val('');
							}
						}	
						finished=1;
					});
				}
				percent = percent+10;
				$("#progressbar").progressbar( "option", "value", percent/15 );
		//	});
		}, 200);
	}
	
	
	$('#citySearchForm').submit(function(){
		
		document.location= AjaxHotelsSearch+"/"+$('#HotelCityFilename').val();
		
		return false;
	});
	//$('.searchResultBox .hotelResultItemBox:eq(0)').css('height','250').addClass('hilight');
	
	var firstImage= $('#SearchResultBox .hilight .hotelImage');
	firstImage.attr('src', firstImage.attr('rel'));
	// RESULT CLICK
	
	$('.searchResultBox .topBox').bind('click', function(){
		//this.blur();
		/*
		
		$.query.SET('detail',id);
		*/

		var id=$(this).attr('rel');
		var toShow=$('#hotel'+id);		
		var toHide =$('#SearchResultBox .hilight');
		var oldId=toHide.attr('rel');
		
		$('.hotelImage',toShow).attr('src', $('.hotelImage',toShow).attr('rel'));
		
		if(!toShow.hasClass('hilight')){
			
			
			var hideHeight = toShow.find('.hidden').height()+100;
			//var showHeight = toHide.height();
			//var	difference = showHeight / hideHeight;


			toShow.addClass("hilight");
			toHide.removeClass("hilight").animate({height:50},{
				step: function(now) {
					var current = (hideHeight - now);
					if ($.browser.msie || $.browser.opera) {
						current = Math.ceil(current);
					}
					toShow.height( current );
					//toHide.css("opacity", 1-now/toHide.height())
				},
				duration: 300,
				easing: "swing",
				complete: function() {
					if(markers && markers[oldId]){
						deselectMarker(markers[oldId]);
					}
					if(markers && markers[id]){
						selectMarker(markers[id]);
					}
					
				}
			});	
	
		}
		
		if(!isScrolledIntoView(toShow)){
			var offset=(windowHeight/2);
			if(offset>toShow.offset().top){
				offset=0;
			}
			$.scrollTo( toShow, 700, {
				offset:{left: 0, top:-offset },
				easing:'easeInOutExpo'
				//onAfter: function(){}
			});
		}
		return false;
	});
	

		
	// Hotel Name filter
	$('#hotelnameForm').submit(function(){
		$('#HotelnameFilter').click();
		return false;
		
	})
	$('#HotelnameFilter').click(function(){
		var name = $('#hotelname').val();
//		if(name!=""){
			$.query.SET("hotelname", name).SET("page", 1);
			updateList();
//		}
	});
	
	// STAR FILTER
	$('#starList :checkbox').click(function(){
		var ids="";
		var sum=0;
		$("#starList input:checked").each(function(){
			var id=$(this).attr('name').split("-");
			ids+=id[1]+",";
			sum=sum+parseInt(id[1]);
		});
		if(sum==15){
			$.query.SET("ratings","");
		} else {
			$.query.SET("ratings",ids);
		}
		$.query.SET("page",1);
		updateList();
	});
	
	// FACILITY FILTER
	/*
	$('#facilityList').hover(function(){
		$(this).css("overflow-y","scroll");
	}, function(){
		$(this).css("overflow-y","hidden");
	})
	*/
	$('#facilityList').find(":checkbox").click(function(){
		var ids="";
		$("#facilityList input:checked").each(function(){
			var id=$(this).attr('name').split("-");
			ids+=id[1]+",";
		});
		$.query.SET("facilities",ids).SET("page",1);
		updateList();
	});
	
	// PROPERTY
	
	$('#propertyList').find(":checkbox").click(function(){
		var ids="";
		$("#propertyList input:checked").each(function(){
			var id=$(this).attr('name').split("-");
			ids+=id[1]+",";
		});
		$.query.SET("properties",ids).SET("page",1);
		updateList();
	});
	

	
	// FILTERBAR
	
	$('#filterbar .price').bind('click',function(){
		$.query.SET("priceFrom","").SET("priceTo","").SET('page', 1);
		updateList();
	});
	
	$('#filterbar .distance').bind('click',function(){
		$.query.SET("attraction",0).SET("distance",0).SET('page', 1);
		updateList();
	});
	
	$('#filterbar .facility').bind('click',function(){
		$('#facility-'+$(this).attr('rel')).attr('checked','').click().attr('checked','');
	});
	
	$('#filterbar .property').bind('click',function(){
		$('#property-'+$(this).attr('rel')).attr('checked','').click().attr('checked','');
	});
	
	$('#filterbar .ratings').bind('click',function(){
		$.query.SET("ratings","").SET("page",1);
		updateList();
	});
	
	$('#filterbar .hotelname').bind('click',function(){
		$.query.SET("hotelname","").SET("page",1);
		updateList();
	});
	// SLIDER

	$( "#slider-range" ).slider({
				range: true,
				min: parseInt($( "#priceFrom" ).attr('rel')),
				max: parseInt($( "#priceTo" ).attr('rel')),
				values: [ parseInt($( "#priceFrom" ).text()), parseInt($( "#priceTo" ).text()) ] // toINT 
	}).bind('slide', function( event, ui ) {
			$( "#priceFrom" ).text(ui.values[ 0 ]);
			$( "#priceTo" ).text(ui.values[ 1 ]);
	}).bind('slidestop', function( event, ui ) {
			if(ui.values[ 0 ]==parseInt($( "#priceFrom" ).attr('rel')) && ui.values[ 1 ]==parseInt($( "#priceTo" ).attr('rel')) ){
				$.query.SET("priceFrom","").SET("priceTo","").SET('page', 1);
			} else {
				$.query.SET("priceFrom",ui.values[ 0 ]).SET("priceTo",ui.values[ 1 ]).SET('page', 1);
			}
			updateList();	
	}).bind('reset', function(){
		$( "#slider-range" )
		.slider( "option", "min", stats['priceMin'])
		.slider( "option", "max", stats['priceMax'])
		.slider( "values", [ stats['priceMin'], stats['priceMax'] ] )
		$.query.SET("page",1).SET("priceFrom",stats['priceMin']).SET("priceTo",stats['priceMax']).SET('page', 1);
		$( "#priceFrom" ).text(stats['priceMin']);
		$( "#priceTo" ).text(stats['priceMax']);
		updateList();
	});
	//$( "#amount" ).val( "$" + $( "#slider-range" ).slider( "values", 0 ) + " - $" + $( "#slider-range" ).slider( "values", 1 ) );
	
	
	$('#paging a').bind('click', function(){
		$.query.SET('page', $(this).attr("rel"));
		updateList();
		//updateDetail();
		return false;
	});
	
	/*
	$("#HotelsAutocomplete").autocomplete(
		AjaxHotelsAutoComplete,
		{
			delay:10,
			minChars:3,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			onItemSelect:selectHotel,
			onFindValue:findHotels,
			formatItem:formatHotel,
			autoFill:false,
			maxItemsToShow: 10,
			selectFirst:true
		}
	);
	*/
	
	// LANGUAGE SELECT

	$('#languageSelect').change(function(){
		var sub=$("#languageSelect option:selected").attr('value');
		sub=sub.substr(0,2);
		sub=sub+".";
		if(sub=="en.") sub="";

		document.location='http://'+sub+domain+here+$.query.toString().replace('#','?');
		
		
	});
	
	
	// DETAILS
	
	$('.more','#HotelSearchDetailBox').bind('click',function(){
		var target=$(this).parent().prev('.moreContent');
		if(target.is(':visible')){
			var old=$(this).text();
			$(this).text($(this).attr('rel'));
			$(this).attr('rel',old);
			target.hide();	
		} else {
			var old=$(this).text();
			$(this).text($(this).attr('rel'));
			$(this).attr('rel',old);
			target.show();
		}
	});
	
	
	
	
	// MAP 
	$(function () {
	
	if($('#map_canvas')[0]){
		 var msie6 = $.browser == 'msie' && $.browser.version < 7;

		  if (!msie6) {
		    var top = $('#map_canvas').offset().top - parseFloat($('#map_canvas').css('margin-top').replace(/auto/, 0));
		    $(window).scroll(function (event) {
		      // what the y position of the scroll is
		      var y = $(this).scrollTop();
			windowHeight=$(window).height();

		      // whether that's below the form
		      if (y >= top) {
		        // if so, ad the fixed class
		        var ua = $.browser;
		    	if (!$.browser.msie || ($.browser.msie && ua.version.substr(0,1) != '6'))
		    	{
		    		$('#map_canvas').addClass('fixed');
		    	}
		      } else {
		        // otherwise remove it
		        $('#map_canvas').removeClass('fixed');
		      }
		    });
		  }
	}

	 
	});
	
	
	// AUTO COMPLETE
	$("#HotelsCity").autocomplete(
		AjaxCityAuto,
		{
			delay:10,
			minChars:2,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			onItemSelect:selectItem,
			onFindValue:findValueHotels,
			formatItem:formatItem,
			autoFill:true,
			maxItemsToShow: 10,
			selectFirst:true
		}
	);


	
});


function updateList(){
	var sub = currentLanguage;
	if(sub=="en") {
		sub="";
	} else {
		sub=sub+".";
	}

	document.location='http://'+sub+domain+here+$.query.toString().replace('#','?');
}


// AUTOCOMPLETE


		function findValueHotels(li) {
			if( li == null ) return alert("No match!");

			// if coming from an AJAX call, let's use the CityId as the value
			if( !!li.extra ) var sValue = li.extra[3];

			// otherwise, let's just display the value in the text box
			else var sValue = li.selectValue;

			//alert("The value you selecte	d was: " + sValue);	
			//$('.city').attr('action',$('.city').attr('action')+'/'+li.extra[1]);
			//
			//$('#citySearchForm').data("cityName",li.extra[1]).data("cityId",li.extra[2]);
			$('#HotelCityFilename').val(li.extra[1]);
			$('#HotelCityId').val(li.extra[2]);
			
		//	console.log(li.extra[1]);
		//	console.log($('#citySearchForm .g-button'));
			$('#HotelsDate1').focus();	

			//console.log($('.city').attr('action'));
			//$('.city').submit();

		}

		function selectItem(li) {
			findValueHotels(li);
		}

		function formatItem(row) {
			return '<b>'+row[0] + "</b> (" + row[1] + ")";
		}

		function lookupAjax(){
			var oSuggest = $("#HotelsCity")[0].autocompleter;

			oSuggest.findValue();

			return false;
		}
	
	
// Datepicker
$.datepicker.regional['de'] = {
                closeText: 'schließen',
                prevText: '&#x3c;zurück',
                nextText: 'Vor&#x3e;',
                currentText: 'heute',
                monthNames: ['Januar','Februar','März','April','Mai','Juni',
                'Juli','August','September','Oktober','November','Dezember'],
                monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun',
                'Jul','Aug','Sep','Okt','Nov','Dez'],
                dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
                dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
                dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
                dateFormat: 'dd.mm.yy', firstDay: 1,
                isRTL: false};



