﻿/* VARIABLES */

/* LOAD */

$(document).ready(function(){ 
     
     //Init Tooltops
	$(".total").tooltip({ 
		showURL: false
	});
	
	$(".tooltip").tooltip({ 
		showURL: false
	}); 
	
	 $(".tooltipadmin").tooltip({ 
        delay: 0, 
		showURL: false,
		opacity: 1,
        extraClass: "admin"
	});
	
	$('.imageHoverTooltip').tooltip({ 
	track: true, 
    delay: 0, 
    showURL: false, 
    opacity: 1,
    extraClass: "imagePreview",
    //fade: 550,
    bodyHandler: function() { 
        var filename = this.src;
        var filelength = parseInt(filename.length) - 3;
        var fileext = "." + filename.substring(filelength,filelength + 3);
        var filePreview = filename.replace("_propertyroomcalendar" + fileext, "_normalpreview" + fileext);
        return $("<img/>").attr("src", filePreview).attr("style", "border:none; padding:0;"); 
        }
    });
     
     //Room Cycle
     $('#propertyImages').cycle({
        fx:      'fade',
        click:   '#propertyImages',
        timeout:  0
    });
    
    //Bind Prev/Next on Room Buttons
    $(".rateChanger a:eq(1)").click(function () { 
        showNextDays(2);
        return false;
    });
    
    //disabled=”disabled”
    //Currency Dropdown
    $(".currencyDropDown option").each( function (i) {
        if ($(this).val() == '0')
        {
            $(this).attr("disabled", "disabled");
        }
    });
    
    setTimeout("$('.divLanguageSelector table').fadeIn();", 750);
    
    updateUsersCurrency($(".currencyDropDown").val());
    
}); 

/* FUNCTIONS */

String.prototype.format = function()
{
    var pattern = /\{\d+\}/g;
    var args = arguments;
    return this.replace(pattern, function(capture){ return args[capture.match(/\d+/)]; });
}

function isNumberKey(evt)
{
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
    {
        return false;
    }
    else
    {
        return true;
    }
}

function CheckCreditCardNumbers(sender, args)
{  
    var isValid = true;

    $(".cardNumbers input").each( function (i) {
        if (i < 3)
        {
            if ($(this).val().length < 4)
            {
                isValid = false;
            }
        }
        else
        {
            if ($(this).val().length < 3)
            {
                isValid = false;
            }
        }
    });

    args.IsValid = isValid;
    
}

function CheckExpiry(sender, args)
{
    var isValid = true;

    $(".cardExpiry input").each( function (i) {
        if ($(this).val().length < 2)
        {
            isValid = false;
        }
    });

    args.IsValid = isValid;
}

function CheckTermsConditions(sender, args)
{
    var isValid = true;
    
    if (!$(".chkTermsConditions input").is(':checked'))
    {
        isValid = false;
    }

    args.IsValid = isValid;
}

function showRatesCalendarView(speedOption)
{
    if ($("#propertyCal").is(":hidden"))
	{
	    if (speedOption != '')
	    {
		    $("#propertyCal").fadeIn("slow");
		}
		else
		{
		     $("#propertyCal").show();
		}
		$("#propertyList").hide();
		hideFacilities();
		$(".nav_0").toggleClass("nav_0_active");
		$(".nav_1").toggleClass("nav_1_active");
		setRoomCookie('cal');
		$("#hdnVal2 input:hidden:eq(0)").val('2');
	}
}

function showRatesListView()
{
	if ($("#propertyList").is(":hidden"))
	{
		$("#propertyList").fadeIn("slow"); 
		$("#propertyCal").hide(); 
		hideFacilities();
		$(".nav_0").toggleClass("nav_0_active"); 
		$(".nav_1").toggleClass("nav_1_active");
		setRoomCookie('list');
		$("#hdnVal2 input:hidden:eq(0)").val('1');
	}
}

function setRoomCookie(selectedOption)
{   
    var date = new Date();
    date.setTime(date.getTime() + (180 * 24 * 60 * 60 * 1000));
    $.cookie('roomView', selectedOption, { path: '/', expires: date });
}

function getRoomCookie()
{
    return $.cookie('roomView');
}

function showBookingLoadingMessage(pathvar)
{
    tb_show('Processing',pathvar);
    return false;
}

function showNextDays(pagedIndex)
{    
    var totalNights = $("#hdnVal input:hidden:eq(0)").val();
    var totalPages = $("#hdnVal input:hidden:eq(1)").val();
    var fadeDelay = 800;
    
    if (pagedIndex <= totalPages)
    {
        if (pagedIndex > 1)
        {
            //Setup the Previous Button
            $(".rateChanger a:eq(0)").fadeIn(fadeDelay);
            
            $(".rateChanger a:eq(0)").unbind("click");
            
            $(".rateChanger a:eq(0)").click(function () { 
              showNextDays(pagedIndex-1);
              return false;
            });

        }
        else
        {
            //Hide the Previous Button
            $(".rateChanger a:eq(0)").hide();
        }
        
        if (pagedIndex == totalPages)
        {
            //Hide Next Button
            $(".rateChanger a:eq(1)").hide();
        }
        else
        {
            //Setup Next Button
            $(".rateChanger a:eq(1)").fadeIn(fadeDelay);
            
            $(".rateChanger a:eq(1)").unbind("click")
            
            $(".rateChanger a:eq(1)").click(function () { 
              showNextDays(pagedIndex+1);
              return false;
            });
        }
    }
    else
    {
        //Hide Next
        $(".rateChanger a:eq(1)").hide();
    }
    
    $(".property ul li[class*='ratePeriod_" + pagedIndex + "']").fadeIn(fadeDelay);
    $(".rateList li[class*='ratePeriod_" + pagedIndex + "']").fadeIn(fadeDelay);
    $(".property ul li:not([class='total']):not([class*='ratePeriod_" + pagedIndex + "'])").hide();
    $(".rateList li:not([class='total']):not([class*='ratePeriod_" + pagedIndex + "'])").hide();
}

function showHideFacilities()
{
    if ($("#propContent").is(":hidden"))
    {
        showFacilities();
    }
    else
    {
        hideFacilities();
    }
}

function hideFacilities()
{
    $("#propContent").hide();
    var imageSrc = $(".showFacilitiesImage").attr("src");
    $(".showFacilitiesImage").attr("src", imageSrc.replace("_on", "_off"));
}

function showFacilities()
{
    $("#propContent").fadeIn();
    var imageSrc = $(".showFacilitiesImage").attr("src");
    $(".showFacilitiesImage").attr("src", imageSrc.replace("_off", "_on"));
}

function showHideJobSearch() {
    if ($("#propContent").is(":hidden")) 
    {
        showJobSearch();
    }
    else 
    {
        hideJobSearch();
    }
}

function hideJobSearch() 
{
    $("#propContent").hide();
    var imageSrc = $(".showJobSearchImage").attr("src");
    $(".showJobSearchImage").attr("src", imageSrc.replace("_on", "_off"));
}

function showJobSearch() 
{
    $("#propContent").fadeIn();
    var imageSrc = $(".showJobSearchImage").attr("src");
    $(".showJobSearchImage").attr("src", imageSrc.replace("_off", "_on")); 
}

function updateUsersCurrency(usersOption)
{
    $.ajax({
        type: "POST",
        url: jsAppPath + "WebService/WebService.asmx/SetUserCurrency",
        data: "{'currencyId':'" + usersOption + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data) {      

            //Build JSON Object
            var currencyObject = eval('(' + data.d + ')');

            //Set the Compare Rate on the LHS
            $("#compareRate").text(currencyObject.currency.compareRate);

            //Set the Currency Code
            $(".userCurrencyCode").text(currencyObject.currency.code);

            //Hide Same Class Elements
            $(".item_currency").show();
            $(".item_currency[lang='" + currencyObject.currency.code + "']").hide();

            var currencyCodeAU = "AUD";
            var currencyCodeNZ = "NZD";
            var exchangeRate = currencyObject.currency.rate;

            var isAlerted = false;

            //Change all the prices
            jQuery.each($(".userPrice"), function() {

                if ($(this).parent().hasClass("freeRate")) {
                    return true;
                }


                var tooltipText = $(this).attr("tooltipText");
                var tooltipTextString = "";

                var basePriceOriginal = 0;
                var basePriceTooltipOriginal = 0;

                var currentPrice = 0;
                var basePrice = 0;

                var currentPriceTooltip = 0;
                var basePriceTooltip = 0;

                var isToolTip = false;

                if (tooltipText != null && tooltipText.indexOf("span") <= -1) {
                    tooltipText = null;
                }

                if (tooltipText != null) {
                    var spanIndex = tooltipText.indexOf("<span");
                    tooltipTextString = tooltipText.substring(0, spanIndex);
                    tooltipText = tooltipText.substring(spanIndex, tooltipText.length);
                    isToolTip = true;
                }

                if (tooltipText != null && tooltipText != "") {
                    currentPriceTooltip = $(tooltipText).text();
                    basePriceTooltip = $(tooltipText).attr("id");
                    getSwapExchange(basePriceTooltip, currencyObject, currencyCodeAU, currencyCodeNZ, exchangeRate, this, isToolTip, tooltipTextString)
                }

                currentPrice = $(this).text();
                basePrice = $(this).attr("id");
                getSwapExchange(basePrice, currencyObject, currencyCodeAU, currencyCodeNZ, exchangeRate, this, false, tooltipTextString)
            });

        }
    });
}

function getSwapExchange(basePrice, currencyObject, currencyCodeAU, currencyCodeNZ, exchangeRate, currentObject, isToolTip, tooltipText)
{
         var duration = 0;
         var propCurrency = "";
         var newPrice = 0;
         basePriceOriginal = basePrice;
        
        //Populate Fields: Base Price, Property Currency & Duration
        if (basePrice.indexOf(":") > -1)
        {
            var infoArray = basePrice.split(":");
            basePrice = infoArray[0].replace(",","");
            propCurrency = infoArray[1];
            
            if (infoArray.length > 2)
            {
                duration = infoArray[2];
            }
        }
        
        //Work out the Properties Currency
        if (propCurrency == currencyObject.currency.code)
        {
            //If the Properties Currency matches the Users Currency set currency to 1
            exchangeRate = 1;
        }
        
        if (propCurrency != currencyCodeAU && propCurrency != currencyObject.currency.code)
        {
            basePrice = (basePrice / currencyObject.currency.nzdrate);
        }   
        
        if (propCurrency == currencyObject.currency.code)
        {
            newPrice = basePrice;
        }
        else
        {
             newPrice = calculateExchangeAmount(basePrice, exchangeRate, duration);
        }     
        
        var replacePrice = currencyObject.currency.sample;
        var textPrice = replacePrice.replace("1", newPrice);
        
        if (textPrice.length > 7)
        {
            $(currentObject).html("<span style='font-size: 80%;'>" + textPrice + "</span>");
            
            if (isToolTip == true)
            {
                $(currentObject).attr("tooltipText", tooltipText + "<span id='" + basePriceOriginal + "'>" + textPrice  + "</span>");
            }                
        }
        else
        {
            //$(this).attr("tooltipText",textPrice);;
            $(currentObject).text(textPrice);
            
            if (isToolTip == true)
            {
                $(currentObject).attr("tooltipText", tooltipText + "<span id='" + basePriceOriginal + "'>" + textPrice  + "</span>");
            }
        }
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function calculateExchangeAmount(basePrice, exchangeRate, duration)
{
    var newPrice = parseFloat(basePrice) * parseFloat(exchangeRate);
    /*        
    if (duration > 0)
    {
        newPrice = 0;
        newPrice = basePrice / duration * parseFloat(exchangeRate);
        newPrice = newPrice * duration;            
    }*/
    
    return newPrice.toFixed(2);
}

function CheckSurveyOption(sender, args)
{
    var isValid = true;
    var totalQuestions = $("#spanTotalQuestions input").val();
    var checkedCount = $(".surveySection input[type=radio]:checked").length;
    var selectedCount = 0;
    
    jQuery.each($(".surveySection .select"), function() {
      if ($(this).val() > 0)
      {
        selectedCount++;
      }
    });
    
    if ((checkedCount + selectedCount) != totalQuestions)
    {
        isValid = false;
    }

    args.IsValid = isValid;
}

function CheckPropertyAndArrivalDate(sender, args)
{  
    var isValid = true;
    var propertyId = $(".ddlPropertyList").val();
    var arrivalDate = $(".date input:eq(0)").val();   
    
    if (propertyId == '0' && arrivalDate != '')
    {
        sender.errormessage = "Please select a property as you have entered an arrival date";
        isValid = false;
    }
    else if (propertyId != '0' && arrivalDate == '')
    {
        sender.errormessage = "Please enter an arrival date as you have selected a property";
        isValid = false;
    }

    args.IsValid = isValid;
    
    return false;
    
}