// JavaScript Document
$(document).ready(function() {
						   
	// Check In Date Picker
	$('.txtCheckIn').datepicker({	
	    dateFormat: 'dd MM yy',
	    showOn: 'both', 
	    buttonImage: jsAppPath + 'images/buttons/cal.png', 
	    buttonImageOnly: true,
	    minDate: '0d',
	    onSelect: function(dateText, inst) 
       {       
            var dateFrom = $(".txtCheckIn").datepicker("getDate");
            var dateTo = $(".txtCheckOut").datepicker("getDate");   
            var changeDate = new Date(dateFrom.valueOf());
            
            //Work out duration  
	        var duration = getDuration(dateFrom,dateTo);
            
            if (dateFrom >= dateTo)
	        {
		        changeDate.setDate(changeDate.getDate() + 3);
		        $(".txtCheckOut").datepicker( 'setDate' , changeDate );	
		        duration = getDuration(dateFrom,changeDate);	        
	        }
	        

	        //Remove Options
	        if (duration > 30)
	        {
	            $(".noOfNights").removeOption(/./); 
    	        
	            //Add Values
	            for (i=1;i<=duration+1;i++)
		        {
			        $(".noOfNights").addOption(i, i);
		        }
		    }
		    
		    //Select Duration
		    $(".noOfNights").val(duration);

	        
       }   
	});
	
	//CheckOut Date Picker
	$('.txtCheckOut').datepicker({
	
	    dateFormat: 'dd MM yy',
	    showOn: 'both', 
	    buttonImage: jsAppPath + 'images/buttons/cal.png', 
	    buttonImageOnly: true,
	    minDate: '0d',
       onSelect: function(dateText, inst) 
       {       
            var dateFrom = $(".txtCheckIn").datepicker("getDate");
            var dateTo = $(".txtCheckOut").datepicker("getDate");    
            var changeDate = new Date(dateTo.valueOf());
            
            //Work out duration  
	        var duration = getDuration(dateFrom,dateTo);
            
            if (dateTo <= dateFrom)
	        {
		        changeDate.setDate(changeDate.getDate() - 3);
		        $(".txtCheckIn").datepicker( 'setDate' , changeDate );	
		        duration = getDuration(changeDate,dateTo);	        
	        }       
	        
	        if (duration > 30)
	        {
	            //Remove Options
	            $(".noOfNights").removeOption(/./);     
    	        
	            //Add Values
	            for (i=1;i<=duration+1;i++)
		        {
			        $(".noOfNights").addOption(i, i);
		        }
		    }
		    
		    //Select Duration
		    $(".noOfNights").val(duration);
       }
    });	
    
    // Check In Date Picker
	$('.txtMiddleCheckIn').datepicker({	
	    dateFormat: 'dd/mm/yy',
	    showOn: 'both', 
	    buttonImage: jsAppPath + 'images/buttons/cal.png', 
	    buttonImageOnly: true,
	    minDate: '0d',
	    onSelect: function(dateText, inst) 
       {       
            var dateFrom = $(".txtMiddleCheckIn").datepicker("getDate");
            var dateTo = $(".txtMiddleCheckOut").datepicker("getDate");   
            var changeDate = new Date(dateFrom.valueOf());
            
            //Work out duration  
	        var duration = getDuration(dateFrom,dateTo);
            
            if (dateFrom >= dateTo)
	        {
		        changeDate.setDate(changeDate.getDate() + 3);
		        $(".txtMiddleCheckOut").datepicker( 'setDate' , changeDate );	
		        duration = getDuration(dateFrom,changeDate);	        
	        }
	        

	        //Remove Options
	        if (duration > 30)
	        {
	            $(".noOfNightsMiddle").removeOption(/./); 
    	        
	            //Add Values
	            for (i=1;i<=duration+1;i++)
		        {
			        $(".noOfNightsMiddle").addOption(i, i);
		        }
		    }
		    
		    //Select Duration
		    $(".noOfNightsMiddle").val(duration);

	        
       }   
	});
	
	//CheckOut Date Picker
	$('.txtMiddleCheckOut').datepicker({
	
	    dateFormat: 'dd/mm/yy',
	    showOn: 'both', 
	    buttonImage: jsAppPath + 'images/buttons/cal.png', 
	    buttonImageOnly: true,
	    minDate: '0d',
       onSelect: function(dateText, inst) 
       {       
            var dateFrom = $(".txtMiddleCheckIn").datepicker("getDate");
            var dateTo = $(".txtMiddleCheckOut").datepicker("getDate");    
            var changeDate = new Date(dateTo.valueOf());
            
            //Work out duration  
	        var duration = getDuration(dateFrom,dateTo);
            
            if (dateTo <= dateFrom)
	        {
		        changeDate.setDate(changeDate.getDate() - 3);
		        $(".txtMiddleCheckIn").datepicker( 'setDate' , changeDate );	
		        duration = getDuration(changeDate,dateTo);	        
	        }       
	        
	        if (duration > 30)
	        {
	            //Remove Options
	            $(".noOfNightsMiddle").removeOption(/./);     
    	        
	            //Add Values
	            for (i=1;i<=duration+1;i++)
		        {
			        $(".noOfNightsMiddle").addOption(i, i);
		        }
		    }
		    
		    //Select Duration
		    $(".noOfNightsMiddle").val(duration);
       }
    });	
    
    //Villa Tabs
	$(".hoteldetail ul.tabs li a").click(function () { 										   	
		var divmatch = $(this).parent().attr("id") + "_detail";		
		jQuery.each($(".tabs-detail div[rel='tab_content']"), function() {	
		  													
			var linkId = $(this).attr("class").replace("_detail","");

			// tabs_n is the same as tabs_n_detail												
			if ($(this).attr("class") == divmatch)
			{			   		    
				$(this).show();
				$("#" + linkId).attr("class",linkId + " " + linkId + "_active");
				
				// To get the google map to intialize when the map tab is clicked
				// if attribute "rel" is not empty string (rel tag contains the function to intialize the map)
				if ($("#" + linkId + " a").attr("rel") != "")
			    {   
			        // find the function from a rel tag and execute the function
			        eval($("#" + linkId + " a").attr("rel"));
			    }
			}
			else
			{			  	    
				$(this).hide();
				$("#" + linkId).attr("class",linkId);
			}
    	});
		return false;
    });
    
    //Child Age Dialog
    $("#childAges").dialog({
		bgiframe: true,
		modal: true,
		autoOpen: false,
		width: 220,
		position: ['center',311],
		title: 'Enter Child Ages',
		closeOnEscape: false,
		open: function(event, ui) {$('.ui-dialog-titlebar-close').remove();},
		buttons: {
			Confirm: function() {
			    
			    var isValid = true;
			    var childAges = "";
			    var textBoxCount = $("input", this).length;
			    textBoxCount = textBoxCount -1;
			    
			     var i=0;
                 for (i=0;i<=textBoxCount;i++)
                 {
                    var age = $("input:eq(" + i + ")", this).val();
                    
                    if (age == "")
                    {
                        isValid = false;
                        break;
                    }
                    
                    if (i < textBoxCount)
			        {
			            childAges += age + ";";
			        }
			        else
			        {
			            childAges += age;
			        }
                 }
                 
                 if (isValid)
                 {
			        $(".refinesearch input:eq(0)").val(childAges);	    
				    $(this).dialog('close');
				 }
				 else
				 {
				    alert("Please enter an age for all " + (textBoxCount + 1) + " children");
				    $(".refinesearch input:eq(0)").val("");	  
				 }
			}
		}
	});
    
    //Swap Values
    swapValues=[];
        $(".swap_value").each(
            function(i){
                swapValues[i]=$(this).val();
                $(this).focus(function()
                    {
                        if($(this).val()==swapValues[i])
                        {
                            $(this).val("")
                        }
                    }
                ).blur(function()
                    {
                        if($.trim($(this).val())=="")
                            {
                                $(this).val(swapValues[i])
                            }
                     }
                 )
            }
        )
        
    //Add Loading Function
    $(".loading").click(function () {         
       ShowLoading();       
    });
      
    $("#hrefConfirmChildAges").click(function () {         
       setChildAges();    
    });
    
    //Home Cycle
    $('.home-banner .promocontainer, .image-banner .promocontainer').cycle({ 
        prev:   '#home-banner-prev', 
        next:   '#home-banner-next', 
        timeout: 9000,
        pause: true 
    });
    
    $(".villa-list li a").hover(
      function () {
        if ($(this).hasClass("currentitem") == false)
        {          
            var newImage = $(this).attr("rel");
            $('.imgVilla').ImageSwitch({NewImage: newImage});
        }
        else
        {
            var defImage = "/Images/locations/Banyuwedang.jpg";
            $('.imgVilla').ImageSwitch({NewImage: defImage});
        }        
      }
    );
    
    $(".region-list").hover(
      function () {
      }, 
      function () {
        if ($(this).hasClass("currentitem") == false)
        {            
           var defImage = "/Images/locations/Banyuwedang.jpg";
            $('.imgVilla').ImageSwitch({NewImage: defImage});
        }     
      }
    );
    
    Cufon.replace('div#callBackService p, div#callBackService h1, .sitetitle h2 a, .heading h3 a', { fontFamily: 'Bodoni MT' });
    	
});

function ShowLoading()
{
    $.blockUI({  message: $('#loadingMessage'), css: { backgroundColor: 'transparent', border: 'none', padding: '0', margin: '0'} });
}

function ShowChildAges()
{
    $.blockUI({  message: $('#childAgesMessage'), css: { backgroundColor: 'transparent', border: 'none', padding: '0', margin: '0', cursor: 'normal'} });
}

function ShowOnRequestForm(hotelName)
{
    $('#villaName').text(hotelName);
    $.blockUI({  message: $('#onRequestMessage'), css: { backgroundColor: 'transparent', border: 'none', padding: '0', margin: '0', cursor: 'normal', top: '20%'} });
}

function quickSearch()
    {        
	    if ($('#ctl00_Header_txtQuickSearch').val() == 'Search...')
	    {
		    alert('Please enter a search term');
	    }
	    else
	    {	var redirectUrl = jsAppPath + "search/search.aspx?q=" + $('.txtQuickSearch').val();  
		    parent.location.href = redirectUrl;
	    }
    }

function imageAdjust() {
	// find all containers with the imageAdjust class and center images horizonally and vertically
	$(".imageAdjust").each(function(i) {
		var heightDiff = $(this).find("img").height() - $(this).height();
		var widthDiff = $(this).find("img").width() - $(this).width();
		
		if(heightDiff > 0) {
			$(this).find("img").css("marginTop",-heightDiff/2);
		}

		if(widthDiff > 0) {
			$(this).find("img").css("marginLeft",-widthDiff/2);
		}
    });
}

function CheckTermsConditions(sender, args)
{
    var isValid = true;
    
    if (!$(".chkTermsConditions input").is(':checked'))
    {
        isValid = false;
    }

    args.IsValid = isValid;
}

function CheckCardHolderDOB(sender, args)
{
    var isValid = true; 
 
    if (validateDate(document.getElementById($(".txtCardHolderDateOfBirth").attr("id"))) == false)
    {
        isValid = false;
    } 

    args.IsValid = isValid;
}

function validateDate(field) 
{ 
    var allowBlank = true; 
    var minYear = 1902; 
    var maxYear = (new Date()).getFullYear(); 
    var errorMsg = ""; // regular expression to match required date format 
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/; 
    if(field.value != '') 
    { 
    if(regs = field.value.match(re)) 
    { 
    if(regs[1] < 1 || regs[1] > 31) 
    { 
    errorMsg = "Invalid value for day: " + regs[1]; 
    } 
    else if(regs[2] < 1 || regs[2] > 12) 
    { 
    errorMsg = "Invalid value for month: " + regs[2]; 
    }
    else if(regs[3] < minYear || regs[3] > maxYear) 
    { 
    errorMsg = "Invalid value for year: " + regs[3] + " - must be between " + minYear + " and " + maxYear; 
    } 
    } 
    else 
    { 
    errorMsg = "Invalid date format: " + field.value; 
    } 
    } 
    else if(!allowBlank) 
    { 
    errorMsg = "Empty date not allowed!"; 
    } 

    if(errorMsg != "") 
    { 
    //alert(errorMsg); 
    //field.focus(); 
    return false; 
    }

    return true; 
}

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
        return false;
    }
    else
    {
        return true;
    }
}

function CheckExpiry(sender, args)
{
    var isValid = true;

    $(".cardExpiry input").each( function (i) {
        if ($(this).val().length < 2)
        {
            isValid = false;
        }
    });

    args.IsValid = isValid;
}

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
    {
        return false;
    }

    return true;
}

function getDuration(checkIn, checkOut)
{
    //Set 1 day in milliseconds
    var one_day=1000*60*60*24
    
    if (checkOut != null)
    {
        //Calculate difference btw the two dates, and convert to days
        return parseInt(Math.ceil((checkOut.getTime()-checkIn.getTime())/(one_day)));
    }
    else
    {
        return 0;
    }
}

function showAgePopUp(varChildCount)
{    
    var childAgeHtml = "<table width='100%' cellpadding='3' cellspacing='3'>"; 
    
    $("#childAgesMessage span").html("");
    
    //Build Select
    var selectMessage = "<select>";
    selectMessage += "<option value=''>Please select child age</option>";
    selectMessage += "<option value='1'>0-12 Months</option>";
    selectMessage += "<option value='1'>1</option>";
    selectMessage += "<option value='2'>2</option>";
    selectMessage += "<option value='3'>3</option>";
    selectMessage += "<option value='4'>4</option>";
    selectMessage += "<option value='5'>5</option>";
    selectMessage += "<option value='6'>6</option>";
    selectMessage += "<option value='7'>7</option>";
    selectMessage += "<option value='8'>8</option>";    
    selectMessage += "<option value='9'>9</option>";
    selectMessage += "<option value='10'>10</option>";
    selectMessage += "<option value='11'>11</option>";
    selectMessage += "<option value='12'>12</option>";
    selectMessage += "<option value='13'>13</option>";
    selectMessage += "<option value='14'>14</option>";
    selectMessage += "<option value='15'>15</option>";
    selectMessage += "<option value='16'>16</option>";
    selectMessage += "<option value='17'>17</option>";    
    
    var i=1;
    varChildCount = parseInt(varChildCount);
    for (i=1;i<=varChildCount;i++)
    {
        childAgeHtml += "<tr><td width='40' style='color:#fff;font-weight:bold;text-align:center;'>Child " + i + "</td><td width='85' style='text-align:left;'>" + selectMessage + "</td></tr>";
    }
    
    childAgeHtml+= "</table>"; 
    
    $("#childAgesMessage span.data").append(childAgeHtml);
    
    //$('#childAges').dialog('open');
    ShowChildAges();
}

function clearChildDropDown()
{    
    $(".ddlChildren").val("");
}

function setChildAges()
{
    var isValid = true;
    var childAges = "";
    var selectBoxCount = $("#childAgesMessage select").length;
    selectBoxCount = selectBoxCount -1;   
     
    var i=0;
    for (i=0;i<=selectBoxCount;i++)
    {         
        var age = $("#childAgesMessage select:eq(" + i + ")").val();
        
        if (age == "")
        {
            isValid = false;
            break;
        }
        
        if (i < selectBoxCount)
        {
            childAges += age + ";";
        }
        else
        {
            childAges += age;
        }
     }
     
     if (isValid)
     {
        $(".refinesearch input:eq(0)").val(childAges);    
        $(".ddlChildren").val(selectBoxCount + 1);
        $.unblockUI();
     }
     else
     {
        alert("Please enter an age for all " + (selectBoxCount + 1) + " children");
        $(".refinesearch input:eq(0)").val("");	  
     }      
}



function SetCheckOutDate(varNoOfNights)
{   
    var dateFrom = $(".txtCheckIn").datepicker("getDate"); 
    var dateTo = $(".txtCheckOut").datepicker("getDate"); 
    var changeDate = new Date(dateFrom.valueOf());
          
    changeDate.setDate(changeDate.getDate() + parseInt(varNoOfNights)); 
    
	$(".txtCheckOut").datepicker( 'setDate' , changeDate );	    
}

function SetCheckOutDateMiddle(varNoOfNights)
{   
    var dateFrom = $(".txtMiddleCheckIn").datepicker("getDate"); 
    var dateTo = $(".txtMiddleCheckOut").datepicker("getDate"); 
    var changeDate = new Date(dateFrom.valueOf());
          
    changeDate.setDate(changeDate.getDate() + parseInt(varNoOfNights)); 
    
	$(".txtMiddleCheckOut").datepicker( 'setDate' , changeDate );	    
}

function getItinerary()
{
    $.ajax({
      type: "POST",
      url:  jsAppPath + "WebService/WebService.asmx/GetUserItinerary",
      data: "index=0",
      dataType: "xml",
      success: function(msg){
        var results = $("string", msg).text();
        $("#itinerary .detail div:eq(0)").html("");
        if (results != null && results != "")
        {
            $(".btn-itinerary-checkout").show();
            $("#itinerary .detail div:eq(0)").append(results);
        }
        else
        {
            $(".btn-itinerary-checkout").hide();
            $("#itinerary .detail div:eq(0)").append("There are no items in your itinerary");
        }
        
        
        
      },
      error: function (xhr, desc, exceptionobj) {
        alert(xhr.responseText);
      }
    });
}

function addItinerary(roomGuid)
{
    $.ajax({
      type: "POST",
      url: jsAppPath + "Search/Detail.aspx/AddItineraryWebMethod",
      data: "{'roomGuid':'" + roomGuid + "'}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        // Replace the div's content with the page method's return.
        //$("#Result").text(msg.d);
        
        getItinerary();  
        setTimeout("showItinerary();", 800);  
      },
      error: function (xhr, desc, exceptionobj) {
        alert(xhr.responseText);
      }
    });
}

function removeItinerary(roomGuid)
{
    $.ajax({
      type: "POST",
      url:  jsAppPath + "WebService/WebService.asmx/RemoveRoom",
      data: "guid=" + roomGuid,
      dataType: "xml",
      success: function(msg){
        getItinerary();
        setTimeout("if ($('#itinerary .detail div dl').length == 0) { hideItinerary();} else { showItinerary(); }", 750);
        
      },
      error: function (xhr, desc, exceptionobj) {
        alert(xhr.responseText);
      }
    });
}

function SignUpNewsletter(mailingListId)
{
	//CustomFields
	var extraParams = "&FormValue_CustomFieldIDs=";

	jQuery.ajax({ 
		url: "http://www.hotelonlinemarketing.com.au/WebService/WebService.asmx/RegisterNewsletterExtra",
		data: { email:jQuery(".txtEmailAddressSignup").val(), password: "", mailinglistId: mailingListId, extraInfo: extraParams },			
		dataType: "jsonp"
	});
	
	alert('Thanks for signing up to our newsletter');
}

function SignUpNewsletterFromNewsletterPage(mailingListId)
{       
	//CustomFields
	var extraParams = "&FormValue_CustomFieldIDs=";

	jQuery.ajax({ 
		url: "http://www.hotelonlinemarketing.com.au/WebService/WebService.asmx/RegisterNewsletterExtra",
		data: { email:jQuery(".txtEmailAddressSignupNewsletterPage").val(), password: "", mailinglistId: mailingListId, extraInfo: extraParams },			
		dataType: "jsonp"
	});
	
	alert('Thanks for signing up to our newsletter');
}

function toggleItinerary()
{
    var itineraryHeight = $("#itinerary").height(); 
    itineraryHeight = itineraryHeight + 26;
    
    var itineraryDetailHeight = $(".detail").height();   
    itineraryHeight = itineraryDetailHeight;
    //itineraryHeight = itineraryHeight + 26;
    
    if ($("#itinerary .detail").is(":visible"))
    {
        $("#itinerary .detail").hide();
        $("#itinerary .view").text("Show");
        $("#itinerary .btn-itinerary-button").animate({ top: '0' }, { duration: 350} );
    }
    else
    {    
    $("#footer").css( { 'margin-bottom' : itineraryHeight } );      
        $("#itinerary .detail").show();
        $("#itinerary .view").text("Hide");
        $("#itinerary .btn-itinerary-button").animate({ top: itineraryHeight }, { duration: 350} );
        
    }
    
}

function showItinerary()
{   
    var itineraryHeight = $("#itinerary").height(); 
    itineraryHeight = itineraryHeight + 26;
    
    var itineraryDetailHeight = $(".detail").height();     
    itineraryHeight = itineraryDetailHeight;  
    
    $("#footer").css( { 'margin-bottom' : itineraryHeight } );
    $("#itinerary .detail").show();
    $("#itinerary .view").text("Hide");
    $("#itinerary .btn-itinerary-button").animate({ top: itineraryHeight }, { duration: 350} );
    
}

function hideItinerary()
{   
    var itineraryHeight = $("#itinerary").height(); 
    itineraryHeight = itineraryHeight + 26;
    
    var itineraryDetailHeight = $(".detail").height();     
    itineraryHeight = itineraryDetailHeight;  
    
    $("#itinerary .detail").hide();
    $("#itinerary .view").text("Show");
    $("#itinerary .btn-itinerary-button").animate({ top: '0' }, { duration: 350} );
}

function SaveOnRequestEnquiry()
{   
     // check the form entries
	 var isFailed = false;
	 var errorMessage = "";
	 
	 var propertyName =  $('#villaName').text();
				    
     // name
     var name = $(".txtName").val();
     
     // email address
     var emailAddress = $(".txtEmailAddress").val();
     
     // home telephone
     var homeTelephone = $(".txtDaytimeTelephone").val();
     
     // mobile
     var mobile = $(".txtMobile").val();
     
     // comments (not mandatory can be null)
     var comments = $(".txtComments").val();
     
     // check name
     if(name == "")
     {
        isFailed = true;
        errorMessage += "- Please enter a Name \n";
     }	
     
      // check email address
     if(emailAddress == "")
     {
        isFailed = true;
        errorMessage += "- Please enter a Email Address \n";
     }				  
    
     // check home telephone
     if(homeTelephone == "")
     {
        isFailed = true;
        errorMessage += "- Please enter a Daytime Telephone \n";
     } 
    
     // check mobile
     if(mobile == "")
     {
        isFailed = true;
        errorMessage += "- Please enter a Mobile \n";
     }   	    
	   				    
     // more validation if required..
     if (isFailed == true && errorMessage != "")
     {
        alert(errorMessage);
        return false;
     }
     
     //Success
     $("#onRequestMessage .form").hide();
     $(".hrefOnRequestEnquiry").hide();
     $("#onRequestMessage .finish").fadeIn();
     
    //WS				   
    $.ajax({
      type: "POST",
      url:  jsAppPath + "WebService/WebService.asmx/SaveOnRequestEnquiry",
      data: "propertyName=" + propertyName + "&name=" + name + "&mobileNumber=" + mobile + "&daytimeTelephoneNumber=" + homeTelephone + "&comments=" + comments + "&emailAddress=" + emailAddress,
      dataType: "xml",
      success: function(msg){
        var results = $("success", msg).text(); 
      },
      error: function (xhr, desc, exceptionobj) {
        alert(xhr.responseText);
      }
    });
}

function SaveCallBackEnquiry()
{   
     // check the form entries
	 var isFailed = false;
	 var errorMessage = "";
        
     // phone number
     var phoneNumber = $(".txtCallBackServicePhoneNo").val();     
     
     // contact time
     var timeOfDayToContact = $(".ddlCallBackServiceTime").val();    
    
     // check phone number
     if(phoneNumber == "" || phoneNumber == "Your phone number")
     {
        isFailed = true;
        errorMessage += "- Please enter a Phone Number \n";
     }    
	   				    
     // more validation if required..
     if (isFailed == true && errorMessage != "")
     {
        alert(errorMessage);
        return false;
     }
          
     //WS				   
     $.ajax({
      type: "POST",
      url:  jsAppPath + "WebService/WebService.asmx/SaveCallBackEnquiry",
      data: "phoneNumber=" + phoneNumber + "&timeOfDayToContact=" + timeOfDayToContact,
      dataType: "xml",
      success: function(msg){
        var results = $("success", msg).text(); 
        // show a notify message
        $.notifyBar({
         html: "Thank you, your Call Back Service request was successfully received. We will contact at the time specified.",
         delay: 2000,
         animationSpeed: "normal",
         cls: "success"
        }); 
      },
      error: function (xhr, desc, exceptionobj) {
        alert(xhr.responseText);
      }
    });
    
    
}