//Jasons main .js functions here

//For testing the drop down menu
//$(function() {
//  $(".drop-down-menu").addClass('showMenu').removeClass('hideMenu');
//});

//Controls the drop down menus and the hover over of the red nav bar
$(document).ready(function() {
    var changeBack = false;
    $('li.nav-link').hover(
			function() {
			    $('ul', this).addClass('showMenu').removeClass('hideMenu');
			},
			function() {
			    $('ul', this).addClass('hideMenu').removeClass('showMenu');
			});
});

//Dynamically sets the footer position
$(document).ready(function() {
    setFooter();
});


function setFooter() {
    //hack code - set this first...
    if ($('.listing-details').height() != null) {
        //On the photos page must get the height of the photos div and not the description div
        if ($('#listing-photos.listing-details').height() != null && $('#listing-photos.listing-details').css('z-index') == '1000') {
            $('#content').height(Math.max($('#listing-photos.listing-details').height() + 255 + $('.lowerContent').height(), $('#listing-menu').height() + 245 + $('.google_adsense').height())); //Gets the max of the client content and lower content, and the menu and google advert
        } else if ($('#listing-description.listing-details').height() != null) {
        $('#content').height(Math.max($('#listing-description.listing-details').height() + 255 + $('.lowerContent').height(), $('#listing-menu').height() + 245 + $('.google_adsense').height()));
        }
        else {
            $('#content').height(Math.max($('.listing-details').height() + 255 + $('.lowerContent').height(), $('#listing-menu').height() + 245 + $('.google_adsense').height()));
        }
    }

    //so the footer gets the new height.
    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        $('#container-c').html($('#footer').html());
        $('#footer').html();
    }
    else if (navigator.userAgent.toLowerCase().indexOf('safari') > -1) {
        $('#container-c').html($('#footer').html());
        $('#footer').html();
        $('.dropdownlist').css('margin-top', '-1px');
    }
    else {
        if ($('#container-a').css('top') == '132px') {
            $('#container-b').height(($('#container-a').height() - 10));
        }
        else
            $('#container-b').height(($('#content').height() + 20));
    }
}

//Changes the css properties of the date picker textbox in IE6
$(document).ready(function() {
    if (navigator.appVersion.indexOf('MSIE 6.0') > -1) {
        $('.dxeEditArea').css('border', '1px solid #7F9DB9');
        $('.dxeEditArea').css('background', 'White');
        $('.dxeEditArea').css('height', '16px');
        $('.dxeEditArea').css('font-size', '12px');
        $('.search-a.date .search-c').css('background-color', 'Transparent');

    }
});



//On load Event Handler Functions
//Enables a dev to just register functions to run once the window has finished loading
var OnLoadEvents = new Array();
//var mapLocations = null;

function RegisterOnLoadEvent(func){
	OnLoadEvents[OnLoadEvents.length] = func;
}

window.onload = function(){
	if (OnLoadEvents.length == 0)
		return;	
	for (i=0; i < OnLoadEvents.length; i++)
	{
		OnLoadEvents[i]();
	}
}; 

var OnUnloadEvents = new Array();
function RegisterOnUnloadEvent(func){
	OnUnloadEvents[OnUnloadEvents.length] = func;
}

window.onunload = function(){
	if (OnUnloadEvents.length == 0)
		return;
	
	for (i=0; i < OnUnloadEvents.length; i++)
	{
		OnUnloadEvents[i]();
	}
};




//helper function to make sure document.getElementById exists
//be nice and give a fallback to older IEs
function GetElementById (id){
	if (document.getElementById)
		return document.getElementById(id);
	else if (document.all)
		return document.all[id];
	else
		return null;
}

//Determines if the specified date (in parts) is valid or not
function IsDate(y, m, d){
	d = Math.abs(d) || 0, m = Math.abs(m) || 0, y = Math.abs(y) || 0;
    return arguments.length != 3 ? 1 
		: d < 1 || d > 31 ? 2 
		: m < 1 || m > 12 ? 3 
		: /4|6|9|11/.test(m) && d == 31 ? 4
        : m == 2 && (d > ((y = !(y % 4) && (y % 1e2) || !(y % 4e2)) ? 29 : 28)) ? 5 + !!y 
        : 0;
}

GetDateMsg = function(x){
    return x == 0 ? "Valid Date"
    : x == 1 ? "Invalid date format"
    : x == 2 ? "Invalid day"
    : x == 3 ? "Invalid month"
    : x == 4 ? "April, June, September and November only have 30 days"
    : x == 5 ? "February only has 28 days"
    : x == 6 ? "In leap years, February has 29 days": "nothing =]";
};

function OnEnter(sender, evt, targetId, targetEvent){
	//get event object
	evt = (evt) ? evt : ((event) ? event : null);
	if (!evt) return;

	//make sure the enter key was pressed
	if (evt.keyCode != 13) return;
		
	//execute target function
	setTimeout("var t = GetElementById('" + targetId + "'); if (t && t." + targetEvent + ") t." + targetEvent + "();", 100);
	//setTimeout(new function(){eval("var t = GetElementById('" + targetId + "'); if (t) t." + targetEvent + "();");}, 100);
	
	return false;
}

//Helper function to dtermine if the browser supports Ajax
function SupportsAjax(){
	//lame, but check if IE and older than 6
	var ua = navigator.appVersion;
	var IEOffset = ua.indexOf("MSIE");
	if (IEOffset >= 0)
		if (parseFloat(ua.substring(IEOffset + 5, ua.indexOf(";", IEOffset))) < 6)
			return false;
			
	if (!document.getElementById) return false;
	if (typeof(XMLHttpRequest) != "undefined") return true;
	if (typeof new ActiveXObject('Microsoft.XMLHTTP') != "undefined") return true;
	if (typeof new ActiveXObject('Msxml2.XMLHTTP') != "undefined") return true;
	
	return false;
}

function SetVisible(elementId, visible) {
	$get(elementId).style.visibility = (visible) ? "visible" : "hidden";
}		

//Simple helper function to hide or show a specified element
function SetDisplay(elementId, show){
	var element = GetElementById(elementId);	
	if (element) element.style.display = (show) ? "" : "none";
}

function AnimatedToggleDisplay(elementId, height) {
	var element = jQuery('#' + elementId);
	var show = !element.is(':visible');
	var from = !(show) ? height : 0;
	var to = (show) ? height : 0;
	
	element.css({ left: (show ? 0 : height) + 'px', display: '' });	
	element.animate({ height: to }, 500, function() { SetDisplay(elementId, show); });														
}

function SetContent(elementId, content){
	var element = GetElementById(elementId);	
	if (element) element.innerHTML = content;
}

function SetDisplayUsingClass(elementId, show) {
    var element = GetElementById(elementId);	
    if(element) SetClasses(show ? 'remove' : 'add', element, 'hidden');		
}

function SetClasses(action, element,class1,class2)
{
  switch (action){
    case 'swap':
      element.className=!SetClasses('check',o,class1)?element.className.replace(class2,class1) : element.className.replace(class1,class2);
    break;
    case 'add':
      if(!SetClasses('check',element,class1)){element.className+=element.className?' '+class1:class1;}
    break;
    case 'remove':
      var rep=element.className.match(' '+class1)?' '+class1:class1;
      element.className=element.className.replace(rep,'');
    break;
    case 'check':
      return new RegExp('\\b'+class1+'\\b').test(element.className)
    break;
  }
}

function SetValue(ctrlId, value){
	var ctrl = GetElementById(ctrlId);
	if (!ctrl) return;
	
	ctrl.value = value;
}

/***********************************************
* Bookmark site script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/

/* Modified to support Opera */
function bookmarksite(title,url){

    if (window.sidebar) // firefox
	    window.sidebar.addPanel(title, url, "");
else if(window.opera && window.print){ // opera
	var elem = document.createElement('a');
	elem.setAttribute('href',url);
	elem.setAttribute('title',title);
	elem.setAttribute('rel','sidebar');
	elem.click();
} 
else if(document.all)// ie
	window.external.AddFavorite(url, title);
}


//Tab controls for Power Listings
function ShowPhoneNumbers() {
    SetDisplayUsingClass('phonedetails', true);
    RecordPhoneNumberClick();
}

//TODO (Duncan): I don't think this is needed anymore but we'll wait and see
function ShowTab(tab) {
    SetDisplayUsingClass('listingdetails', false);
    SetDisplayUsingClass('phonenumbers', false);
    SetDisplayUsingClass('amenities', false);    
    
    
    SetDisplayUsingClass('video', false);
    //SetDisplay('website', false);    
    SetDisplayUsingClass(tab, true);
    
    if (tab == 'phonenumbers')
        RecordPhoneNumberClick();
}




/**********************************************
* Statistics Recording
***********************************************/

//
// Ensure that the phone numbers are only recorded once per page load
var phoneNumberClicked;
function RecordPhoneNumberClick()
{
    if (!phoneNumberClicked)
    {
        phoneNumberClicked = true;
        Enlighten.Jasons.Site.Services.Search.RecordStatsClick(statsClientId, 17 /* PhoneNumberClick */);
    }
}

//
// Ensure that the enquiries are only recorded once per page load
var enquiryClicked;
function RecordEnquiryClick(clientId)
{

    if (!enquiryClicked)
    {
        enquiryClicked = true;
        Enlighten.Jasons.Site.Services.Search.RecordStatsClick(clientId !=null ? clientId : statsClientId, 7 /* EnquiryClick */);
    }
}

function RecordVideoClick(clientId) 
{
    Enlighten.Jasons.Site.Services.Search.RecordStatsClick(clientId != null ? clientId : statsClientId, 22 /* VideoClick */);
}

function RecordPrintClick()
{
    Enlighten.Jasons.Site.Services.Search.RecordStatsClick(statsClientId, 12 /* PrintClick */);
    
   }

function RecordExternalWebsiteClick() {
	Enlighten.Jasons.Site.Services.Search.RecordStatsClick(statsClientId, 11 /* WebsiteClick */);
}

function DisplayVideo(clientId, effect){

	if ($("#video-wrapper").css('display') != 'none') {
		if (typeof $("#Video").GotoFrame == "function") {
			$("#Video").GotoFrame(0);
		}
            
        if (detectMacXFF2() || effect == 'pop')
        	$("#video-wrapper").css('display', 'none');
        else
        	$("#video-wrapper").hide('slow');
    } else {
        RecordVideoClick(clientId);
        if (detectMacXFF2() || effect == 'pop')
            $("#video-wrapper").css('display', 'block');
        else
        	$("#video-wrapper").show('slow');
    }

}

//javascript hack by jake olsen to bypass the 
//Css Opacity and Flash Transparency in Mac Firefox issue
function detectMacXFF2() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (/firefox[\/\s](\d+\.\d+)/.test(userAgent)) {
        var ffversion = new Number(RegExp.$1);
        if (ffversion < 3 && userAgent.indexOf('mac') != -1) {
            return true;
        }
    }
}

//Can't do this because you're not allowed to access the parent document
//RegisterOnLoadEvent(function() {
//    var fullURL = parent.document.URL;
//    var request = fullURL.substring(fullURL.indexOf('?'), fullURL.length)
//    if (request.indexOf('auto-play') != -1) 
//        if ($("Video") != null) $("Video").GotoFrame(1);
//});


function OpenPopUp(URL, width, height, scrollbar) {
	day = new Date();
	id = day.getTime();
	window.open(URL,  id , 'toolbar=0,scrollbars='+scrollbar+',location=0,statusbar=0,menubar=0,resizable=1,width=' + width + ',height=' + height);
}
	
	
	
	function Util_Today() {
	var today = new Date();
	today.setTime(Util_ParseDate(Util_FormatDate_DDMMMMYYYY(today)));
	return today;
}


/*Booking Util*/

function Util_FormatDate_YYYYMMDD(date) {
	return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();	
}

function Util_FormatDate_DDMMYYYY(date) {
	return date.getDate() + '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
}

function Util_FormatDate_DDMMMMYYYY(date) {
	var month=new Array(12);
	month[0]="January";
	month[1]="February";
	month[2]="March";
	month[3]="April";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="August";
	month[8]="September";
	month[9]="October";
	month[10]="November";
	month[11]="December";


	return date.getDate() + ' ' + month[date.getMonth()] + ' ' + date.getFullYear();	
}


function Util_ParseDate(datetime) {
	if(datetime.toLowerCase() == 'today') {
		return Util_Today();
	}
	
	if(datetime.toLowerCase() == 'tomorrow') {
		var tomorrow = Util_Today();
		tomorrow.setDate(tomorrow.getDate() + 1);	
		return tomorrow;
	}

	var DDMMYY = datetime.split('/');
	if(DDMMYY.length == 3) {
		if(DDMMYY[2] < 100)
			DDMMYY[2] = "20" + DDMMYY[2];
	
		datetime = DDMMYY[1] + '/' + DDMMYY[0] + '/' + DDMMYY[2];
	}
	
	var DDMMMMYY = datetime.split(' ');
	if(DDMMMMYY.length == 3) {
		if(DDMMMMYY[2] < 100)
			DDMMMMYY[2] = "20" + DDMMMMYY[2];
	
		datetime = DDMMMMYY[0] + ' ' + DDMMMMYY[1] + ' ' + DDMMMMYY[2];
	}	
	
	return Date.parse(datetime);
}

function Util_Today() {
	var today = new Date();
	today.setTime(Util_ParseDate(Util_FormatDate_DDMMMMYYYY(today)));
	return today;
}

function Util_DateIsValid(value) {
	var date = new Date();
	date.setTime(Util_ParseDate(value));		
	
	var today = Util_Today();		
	if(isNaN(date) || date.getTime() - today.getTime() < 0) {								
		return false;
	}		
	
	return true;
}

function Util_UpdateDateOnBlur(sender) {
	var date = new Date();
	date.setTime(Util_ParseDate($get(sender).value));
	if(!isNaN(date)) {
		$get(sender).value = Util_FormatDate_DDMMMMYYYY(date);
	}
}


function AmenityFilter_ValidateDate(sender, args)
{    					
	sender.errormessage = "An invalid date was entered. Please make sure the date is in the correct format and that the date is not in the past";					
	args.IsValid = Util_DateIsValid(args.Value);				
}


function AmenityFilter_CompareDate(val) {		
	if(ValidatorGetValue(val.controltovalidate) == "")
		return true;

    return Util_ParseDate(ValidatorGetValue(val.controltovalidate)) >= Util_ParseDate(ValidatorGetValue(val.controltocompare));
}

function ScrollToEnquiryForm() {
	location.href = '#EnquiryForm';
}

function AddToCart_OnClick(productId, quantityElementId, messageElementId){
   var quantity = $get(quantityElementId)[$get(quantityElementId).selectedIndex].value
   
   Enlighten.Jasons.Datalogic.Comrade.ComradeService.AddToCart(productId, quantity, "Main",
    function(message) {
       $get(messageElementId).innerHTML = message;
    }   
   );


}
//JI (15/02/2010) - Modification to only record clicks in anchor links in the listing text.
function RecordListingTextWebClick() {
    try {
        var listText = GetElementById("listingdetails").innerHTML.toString();
        regx = new RegExp("href=\"(.*?)\"") ;
        if (regx.test(listText))
            RecordExternalWebsiteClick();
    }
    catch(e){}
}
function SetDestination(term) {
    //Enlighten.Jasons.Site.Services.Search.SetRegion(term, Success, Failed);
}
function SearchGuide(term) {
    if (term == '')
        document.location.href = '/travel-guide';
    else
        SearchDestination(term);
}
function SearchDestination(term) {
    Enlighten.Jasons.Site.Services.Search.SetUrl(term, function (result) { document.location.href = result; }, Failed);
}
function Success(result) {
    //TODO:Do some shindigs with Robs list here..
}

function Failed(error) {
}


// RWP - Scripts used on the search listings page(s)

function ReplaceQueryString(url, param, value) {
    preURL = "";
    postURL = "";
    newURL = "";

    start = url.indexOf(param + "=");
    if (start > -1) {
        // Parameter already exists in URL. Change it to new value.
        end = url.indexOf("=", start);
        preURL = url.substring(0, end) + "=" + value;

        startRest = url.indexOf("&", start);
        postURL = "";
        if (startRest > -1) {
            postURL = url.substring(startRest);
        }

    } else {
        // Parameter does not exist in URL. Append it
        separator = "&";
        params = url.indexOf("?");
        if (params < 0) {
            // No query string parameters at all. Use '?' instead
            separator = "?";
        }

        preURL = url;
        postURL = separator + param + "=" + value;
    }
    newURL = preURL + postURL;

    return newURL;
}

// Removes the specified paramter from the QueryString (if it exists)
function RemoveQueryString(url, parameter) {
    var urlparts = url.split('?');   // prefer to use l.search if you have a location/link object
    if (urlparts.length >= 2) {
        var prefix = encodeURIComponent(parameter) + '=';
        var params = urlparts[1].split(/[&;]/g);

        for (var i = params.length; i-- > 0; ) {             // reverse iteration as may be destructive
            if (params[i].lastIndexOf(prefix, 0) !== -1)   // idiom for string.startsWith
                params.splice(i, 1);
        }

        url = urlparts[0];
        if (params.length > 0)
            url = url + '?' + params.join('&');
    }

    return url;
}

// Reorders the search results by the specified value
function ReorderSearch(obj) {
    // Remove any '#' symbols before the QueryString
    var currentUrl = document.location.href;
    var hashLocation = currentUrl.indexOf("#", 0);
    var queryStringStart = currentUrl.indexOf("?", 0);
    if ((hashLocation > 0) && ((hashLocation < queryStringStart) || (queryStringStart == -1))) {
        // A hash symbol exists before QueryString. This will mess up redirects, so we remove it.
        currentUrl = currentUrl.substr(0, hashLocation) + currentUrl.substr(hashLocation + 1);
    }
    var newUrl = ReplaceQueryString(currentUrl, 'sort', obj.value);
    document.location.href = newUrl;
}

// Adds the search term(s) for a specific client name to the URL as a QueryString
function SearchByName(SearchTerm) {
    var url = RemoveQueryString(document.location.href, 'cp');
    document.location.href = ReplaceQueryString(url, 'q', SearchTerm);
}


