<!--
$(function()
{
	
    /**** Date Picker ****/
    var dtNow = new Date;
    var dayName = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    
    if ($("#arrivalCal").length > 0){
        $("#arrivalCal").datepicker({
            showOn: "button",
            buttonImage: "/assets/img/cal.png",
            buttonImageOnly: true,
            dateFormat: 'yy-mm-dd',
            minDate: 0,
            maxDate: "+11M",
            onSelect: function(dt, dp) { 
               setDateSelection('arrival', dt);
           }
        });
        $("#departureCal").datepicker({
            showOn: "button",
            buttonImage: "/assets/img/cal.png",
            buttonImageOnly: true,
            dateFormat: 'yy-mm-dd',
            minDate: 0,
            maxDate: "+11M",
            onSelect: function(dt, dp) { 
               setDateSelection('departure', dt);
           }
        });
    }
    
    
    function setDateSelection(tpe, dt)
    {
        var dt_split = dt.split('-');
        var d = dt_split[2];
        d = d.substr(0,1) == '0' ? d.substr(1,2) : d;
        $("#" + tpe + "Day").val(d);
        $("#" + tpe + "Month").val(dt_split[1] - 1);
        $("#" + tpe + "Day").change();
        $("#" + tpe + "Month").change();
    }
	//Month selection for check in day
	$("#arrivalMonth").change(function () {
		var $sel = $(this).find("option:selected")
		var seltxt = $sel.text();
		if (seltxt == "")
			$("#arrivalDay").attr("disabled", "disabled").trigger('change');
		else
		{
			$("#arrivalDay").removeAttr("disabled").trigger('change');
			setDayOptions($("#arrivalDay"), $sel.val());
		}
	});
	//Month selection for check out day
	$("#departureMonth").change(function () {
		var $sel = $(this).find("option:selected")
		var seltxt = $sel.text();
		if (seltxt == "")
			$("#departureDay").attr("disabled", "disabled").trigger('change');
		else
		{
			$("#departureDay").removeAttr("disabled").trigger('change');
			setDayOptions($("#departureDay"), $sel.val());
		}
	});
	//Day selection
	$(".selectDay").change(function () {
		var tpe = $(this).attr('id');
		var dy = $(this).find("option:selected").text();
		var prefTpe = tpe.substr(0, tpe.length - 3);
		var mo = $("#" + prefTpe + "Month option:selected").val();
		var dayInWeek = "";
		if (mo != "" && dy != "")
		{
                    var yr = dtNow.getFullYear();
                    if (mo < dtNow.getMonth()) yr++;
                    var nwDay = new Date(yr , mo, dy);
                    dayInWeek = dayName[nwDay.getDay()];
                    $("#" + prefTpe + "Cal").datepicker( "setDate" , nwDay );
                    if (prefTpe == 'arrival')
                    {
                        var nmo = $("#departureMonth option:selected").val();
                        var nda = $("#departureDay option:selected").val();
                        if (nmo == "" && nda == "")
                        {
                            var neDay = new Date(nwDay.setDate(nwDay.getDate() + 1));
                            var y = neDay.getFullYear().toString().substring(2,4);
                            var m = neDay.getMonth() + 1;
                            m = '0' + m.toString();
                            var d = neDay.getDate().toString();
                            setDateSelection("departure", y + '-' + m.substr(-2) + '-' + '0' + d);
                        }
                    }
		}
		$("#week" + tpe).text(dayInWeek);
		var nrd = getNrOfDays();
                $("#nrOfNights").text(nrd);
		if (nrd != "")
                {
                    $("#nrOfNightsRow").show();
                }
		showRooms(nrd);
	});
	
	function setDayOptions($days, selMonth)
	{
		var yr = dtNow.getFullYear();
		if (selMonth < dtNow.getMonth()) yr++;
		var nrOfDays = daysInMonth(yr , parseInt(selMonth) + 1);
		for (indx = 28; indx <= 31; indx++)
		{
			if (indx > nrOfDays)
				$days.find("option[value='" + indx + "']").attr("disabled", "disabled");
			else
				$days.find("option[value='" + indx + "']").removeAttr("disabled");
		}
		//For current month don't show passed days
		var isCurMonth = (dtNow.getMonth() == parseInt(selMonth));
		for (indx = 1; indx < dtNow.getDate(); indx++)
		{
			if (isCurMonth)
				$days.find("option[value='" + indx + "']").attr("disabled", "disabled");
			else
				$days.find("option[value='" + indx + "']").removeAttr("disabled");
		}
		//check if current day isn't invalid
		var selDay = $days.find("option:selected").val();
		if ((isCurMonth && selDay <  dtNow.getDate()) || selDay > nrOfDays)
		{
			$days.find("option[value='']").attr("selected", "selected");
		}
	}
	
	function daysInMonth(year, month) 
	{
		var dd = new Date(year, month, 0);
		return dd.getDate();
	}
	
	function getNrOfDays()
	{
		var dy = $("#arrivalDay option:selected").val();
		var mo = $("#arrivalMonth option:selected").val();
                var difDays = "";
		if (mo != "" && dy != "")
		{
			var yr = dtNow.getFullYear();
			if (mo < dtNow.getMonth()) yr++;
			dy1 = new Date(yr , mo, dy);
			
			dy = $("#departureDay option:selected").val();
			mo = $("#departureMonth option:selected").val();
			
			if (mo != "" && dy != "")
			{
				yr = dtNow.getFullYear();
				if (mo < dtNow.getMonth()) yr++;
				dy2 = new Date(yr , mo, dy);
                                
				var oneDay = 1000*60*60*24;
				difDays = Math.round((dy2.getTime() - dy1.getTime())/oneDay);
			}
		}
		difDays = difDays < 0 ? "" : difDays;
		
		return difDays;
	}
	
	function showRooms(nrd)
	{
		if (nrd == "")
		{
			$("#roomtable").hide();
			$("div.roombox").addClass("hide");
			$('#childAge').hide();
		}
		else
		{
			$("#roomtable").show();
			$("div.roombox").removeClass("hide");
			$(".childCnt").trigger('change');
		}
	}
	
	//select rooms
	$("#numberOfRooms").change(function(){
		var sel = $(this).find("option:selected").val();
		for (ind = 1; ind < 6; ind++)
		{
			if (sel > 1) 
				$('#roomlabel' + ind).show();
			else
				$('#roomlabel' + ind).hide();
			if (sel >= ind)
			{
				$('#roomrow' + ind).show();
				var ch = $("#room-" + ind + "-child-total").find("option:selected").val();
				selAge(ind, ch);
			}
			else
			{
				$('#roomrow' + ind).hide();
				selAge(ind, 0);
			}
		}
	});
	
	//select nr of children
	$(".childCnt").change(function(){
		var nrofChildren = $(this).find("option:selected").val();
		var roomNr = $(this).attr("id").substr(5,1);
		selAge(roomNr, nrofChildren);
	});
	
	function selAge(roomNr, nrofChildren)
	{
		var maxChildren = 0;
		$(".childCnt").each(function(indx){
			nrofChildrenTmp = $(this).find("option:selected").val();
			if ($(this).css('display') != 'none')
				maxChildren = Math.max(maxChildren, nrofChildrenTmp);									 
		});
		for (indx = 1; indx < 7; indx++)
		{
			if (indx <= maxChildren)
				$('#childHeadCol' + indx ).show();
			else
				$('#childHeadCol' + indx ).hide();
				
			if (indx <= nrofChildren)
				$('#childRow' + roomNr + 'Col' + indx ).show();
			else
				$('#childRow' + roomNr + 'Col' + indx ).hide();
		}
		
		if (nrofChildren > 0)
		{
			$('#childRow' + roomNr).show();
			$('#childAge').show();
		}
		else
		{
			$('#childRow' + roomNr).hide();
			if (maxChildren < 1)
			{
				$('#childAge').hide();
			}
		}
	}
	
	//Search for hotels
	$("#hotelSearchForm").submit(function(event){
		var frm = document.myForm;
		var city = frm.city.value;
		if (city == '')
		{
			alert("Please enter the destination");
			frm.city.focus();
			event.preventDefault();
		}
		else
		{
			var room = new Array(5);
			var missingAge = false;
			var textChildError = "Please specify the ages of all children.";
			for (indx = 1; indx <= frm.numberOfRooms.value; indx++)
			{
				nra = document.getElementById('room-' + (indx) + '-adult-total').value;
				nrc = document.getElementById('room-' + (indx) + '-child-total').value;
				ages = "";
				for (indy = 1; indy <= nrc; indy++)
				{
					age = document.getElementById('room-' + (indx) + '-child-' + (indy) + '-age').value;
					ages += age + ",";
					if (age < 0) missingAge = true;
				}
				room[indx - 1] = nra + ";" + nrc + ";" + ages;
			}
			var dest = document.getElementById('landmarkDestinationID');
			var lm = '';
			if (dest != null)
				lm = document.getElementById('landmarkDestinationID').value;
			var s = $('#hotelbookingtpe').text();
			
			//check if option has been selected
			//var opra = document.getElementById('minRating').selectedIndex;
			var opra = 0;
			if (dest != null)
				var oplm = document.getElementById('landmarkDestinationID').selectedIndex;
			var opam = $('table#amenities input:checked').length;
			
			var op = opra + oplm + opam > 0 ? 1 : 0; //see if there are options selected
			var ae = '';
			$('#amenities :checked').each(function() {
					   ae += $(this).val() + ';';
					 });
			
			if (missingAge === true && $("#childAge").css('display') != 'none') 
			{
				alert(textChildError);
				event.preventDefault();
			}
			else
			{
                            $('#searchcityhotels').val('Searching');
                            $.dots();
                            //Store hotel settings in session
                            $.ajax({url:'/functions/ajax/setuserhoteldata.php', async:false, cache:false, data:{'src':s,'city':city, 'am':frm.arrivalMonth.value, 'ad':frm.arrivalDay.value, 'dm':frm.departureMonth.value, 'dd':frm.departureDay.value,'ln':frm.locale.value,'cur':frm.currencyCode.value,'ro':frm.numberOfRooms.value,'r1':room[0],'r2':room[1],'r3':room[2],'r4':room[3],'r5':room[4], 'lm':lm, 'ra':frm.minRating.value,'op':op, 'ae':ae}});
                            //event.preventDefault();
			}
		}
	});
        
	//initialize default values
	$("#arrivalMonth").trigger('change');
	$("#departureMonth").trigger('change');
	
	
	//autocomplete main form city field
	var hascity = document.getElementById("city_main");
	if (hascity != null)
	{
		$("#city_main").autocomplete("/functions/ajax/autocomplete_hotelcity.php", {
			matchContains: false,
			selectFirst: false,
			max: 10,
			minChars: 1
		});
	}
	/*
        $.ui.autocomplete.prototype._renderItem = function( ul, item){
          var term = this.term.split(' ').join('|');
          var re = new RegExp("(" + term + ")", "gi") ;
          var t = item.label.replace(re,'<span class="bold">$1</span>');
          return $( "<li></li>" )
             .data( "item.autocomplete", item )
             .append( "<a>" + t + "</a>" )
             .appendTo( ul );
        };
        */
        
	//load deals if available
	var hasdeals = document.getElementById("ajaxdeals");
	if (hasdeals != null)
	{
		var codef = $('#dealcodefeed').text();
		var codew = $('#dealcodeweb').text();
		$.post('/functions/ajax/gethoteldeals.htm', {'codef': codef, 'codew': codew, 'tpe':'hotelpage'}, function(data) {
				if (data != "")
				{
					$('#dealsloading').addClass("hide");
					$('#ajaxdata').removeClass("hide");
					$('#ajaxdeals').html(data);
					bindDeals();
				}
		});
	}
	
	function bindDeals()
	{
	}
	
	
	//Load tabs
	// Check if tab is loaded -> binding needed
	//var isTab = false;
	/*if (!$('#article #ajaxdata').hasClass("hide"))
	{
		var tpe = $("#tabkey").text();
		isTab = true;
		bindRelated(tpe);
	}*/
	$('#cityhotels .tabwrap .tabs li').click(function(event){
		event.preventDefault();
		var sel = $(this).is('.sel');
		var tpe = $(this).attr('id');
		if (!sel)
		{
			$('.tabwrap .tabs li.sel').removeClass("sel").addClass("desel");
			$(this).removeClass("desel").addClass("sel");
			$('.bartop .total .sel').removeClass("sel").addClass("hide");
			$('.bartop .total .lbl'+tpe).removeClass("hide").addClass("sel");
		}
		var $content = $('#ajaxdata');
		if (tpe == 'search')
		{
			$('#hoteldata').show();
			$('#ajaxdata').hide();
		}
		else
		{
			$('#hoteldata').hide();
			$('#ajaxdata').removeClass().addClass(tpe);
			$('#ajaxdata').show();
			$content.html('<div class="loading">Loading...</div>');
				
			var key = $('#citykey').text();
			$.post('/functions/ajax/getcityhotelsrelated.htm', {'citykey': key, 'tpe':tpe}, function(data) {
					$content.html(data);
					//bindRelated(tpe);
			});
			return false;
		}
  	});
  
  	$('table#amenities :checkbox').click(function(event){
		var nrsel = $('table#amenities input:checked').length;
		if (nrsel > 3)
		{
			$('span.msg').removeClass("hide").fadeIn(200);
			$('span.msg').text("Maximum 3 amenities can be selected").fadeOut(3000);
			event.preventDefault();
		}
	});
	
  	$('.optionsButton').click(function(event){
		{
			$('.optionsButton').css('visibility', 'hidden');
			$('span.options').removeClass("hide").show();
			$('div.optionbox').removeClass("hide");
		}
	});
        
        
        $.dots = function() 
        {;
            this.dotItUp = function() 
            {
                var buttonVal = $('#searchcityhotels').val();
                if (buttonVal.length == 13) 
                {
                    $('#searchcityhotels').val("Searching");
                } 
                else 
                {
                    $('#searchcityhotels').val(buttonVal + ".");
                }
            };
            
            this.init = function() 
            {

                this.theInterval = setInterval(this.dotItUp, 300);

            };

            this.init();
        }
}); 

//-->


