// JavaScript Document

document.write('<link href="theclub/css/javascript.css" rel="stylesheet" type="text/css" media="all" />');
Cufon.replace('.header h3, .trajan');
Cufon.replace('.submenu ul li a.link', {hover:true});
Cufon.replace('.submenu ul li.over a.link', {hover:true});
Cufon.replace('.submenu ul li.active a.link', {hover:true});
Cufon.replace('.menu ul li a', {hover:true});
Cufon.replace('.moreOffers strong');

loyaltyPage = true;
var currentLeft = 0;
var xhr;

function activateBooking() {
	$('#roomCount').change(roomsChange);
	roomsChange();
}

function roomsChange() {
	var currentRooms = $('#roomCount').attr('selectedIndex');
	var parentform = $('.bookingbox');
	for(var i=0;i<parentform.find('.roomRow').length;i++) {
		if(i > currentRooms) {
			parentform.find('.roomRow:eq('+i+')').hide();
		} else {
			parentform.find('.roomRow:eq('+i+')').show();
		}
	}
	setupMenu();
}

$(document).ready( function() {
	
	var newContents = "";
	$('.calendar').datepicker({
		numberOfMonths: 2,
		showButtonPanel: true,
		dateFormat: 'dd/mm/yy',
		width: 200,
		onSelect: function(dateText, inst) { 
			if(this.id == 'arrDate') {
				$('#depDate').datepicker('option', 'minDate', $('#arrDate').datepicker('getDate'));
			}
			if($('#depDate').datepicker('getDate') < $('#arrDate').datepicker('getDate')) {
				var selectedDate = $('#arrDate').datepicker('getDate');
				selectedDate.setDate(selectedDate.getDate()+1);
				$('#depDate').datepicker('setDate', selectedDate);
			}
		}
	});
	$('.footer div.padding').prepend('<span>Change Text Size: <a href="javascript:changetoDefault()" class="a_s" title="Change the text to the default size.">a</a> | <a href="javascript:changetoMedium()" class="a_m" title="Change the text to a larger size.">a</a> | <a href="javascript:changetoLarge()" class="a_l" title="Change the text to the largest size.">a</a></span> &nbsp; ');

	$('#arrDate').datepicker('option', 'minDate', 0);
	$('#arrDate').datepicker('setDate', new Date());
	$('#depDate').datepicker('option', 'minDate', 0);
	var depDate = new Date();
	depDate.setDate(depDate.getDate() + 1);
	$('#depDate').datepicker('setDate', depDate);
	$('#rooms').change(roomsChange);
	
	setupMenu();
	
	$('.drop_head').click(function() {
		var sibling = $(this).siblings('.drop_body');
		if(sibling.css('display') == 'block') {
			sibling.stop(true,true).animate({height:'hide'},'slow');
			$(this).find('input').attr('checked',false);
			$(this).parent().removeClass("active");
		} else {
			sibling.stop(true,true).animate({height:'show'},'slow');
			$(this).find('input').attr('checked',true);
			$(this).parent().addClass("active");
		}
		if($(this).attr('nodeName') == "A") {
			return false;
		}
	});
	
	if($('#hotel_map').length > 0) {
		var fo = new FlashObject("business/flash/map.swf", "flash_map", "320", "462", "7", "#FFFFFF");
		fo.addParam("wmode", "transparent");
		fo.addVariable("xmlFile", "business/xml/map.xml");
		fo.write("hotel_map");
	}
	
	trident = navigator.userAgent.match(/Trident\/([0-9])/) || [0,0];
	
	if(document.all && !window.opera) {
		if(trident[1] < 5) {
			$('#propertyCode').each( function() {
				$(this).wrap('<span class="selectboxContainer" />');
				$(this).parent().attr('forceWidth', $(this).attr('offsetWidth'));
				$(this).parent().css( { 'width':$(this).attr('offsetWidth')+'px', 'height':$(this).attr('offsetHeight')+'px', 'padding':0, 'border':0, 'margin-top':$(this).css('margin-top'), 'margin-left':$(this).css('margin-left'), 'margin-bottom':$(this).css('margin-bottom'), 'margin-right':$(this).css('margin-right'), 'display':'block', 'clear':'both' });
				$(this).css( { 'position':'absolute','width':$(this).attr('offsetWidth')+'px'});
				$(this).mousedown(function() { $(this).css('width','auto') });
				$(this).click(function() { if($(this).attr('clicked')) { $(this).attr('clicked',false); $(this).css('width',$(this).parent().attr('forceWidth')+'px'); } else { $(this).attr('clicked',true); $(this).css('width','auto') } });
				$(this).focus(function() { $(this).css('width','auto') });
				$(this).blur(function() { $(this).css('width',$(this).parent().attr('forceWidth')+'px') });
				$(this).change(function() { $(this).css('width',$(this).parent().attr('forceWidth')+'px') });
			});
		}
	}
	
	roomsChange();
	
	userTypeString = userType.toString()
	userTypeString = userTypeString.toLowerCase();
	var myOffers = $('.moreOffers');
	var myImage = myOffers.find('img[src*="theclub/images/logolink_"]');
	switch(userTypeString) {
		case "elite":
		case "club":
		case "stay0":
		case "stay1":
		case "invitation":
			myImage.attr('src',"/theclub/images/logolink_club.gif");
			myImage.parent().attr('href',"/theclub/");
			break;
		case "corporate":
		case "booker":
		case "agent":
			myImage.attr('src',"/theclub/images/logolink_corporate.gif");
			myImage.parent().attr('href',"/theclub/corporate/");
			break;
	}
});

function setupMenu() {
	var locat = location.href;
	if(locat.lastIndexOf('/') == locat.length-1) {
		locat += "index.htm";
	}
	$('.menu ul li').each(function()
	{
		var oldHtml = $(this).html();
		var thisHref = $(this).children('a').attr('href');
		if(locat.indexOf(thisHref) >= 0)
		{
			$(this).addClass("active");
		}
		if(!userType && thisHref.indexOf('?skin=loyalty') > 0) {
			$(this).children('a').attr('href', thisHref.replace('?skin=loyalty', ''));
		}
	}).hover(function() { $(this).addClass('over') },function() { $(this).removeClass('over') });
	$('.submenu ul li').each(function()
	{
		var oldHtml = $(this).html();
		if(locat.indexOf($(this).find('a').attr('href')) >= 0)
		{
			$(this).addClass("active");
		}
	}).hover(function() { $(this).addClass('over') },function() { $(this).removeClass('over') });
	$('.drop_body').each( function() {
		if(!$(this).children('li').hasClass('active')) {
			$(this).hide();
		}
	});
	$('.rewardtable').find('input[type="checkbox"]').each(function(){checkBoxCheck(this); $(this).click(function(){checkBoxCheck(this)});});
}

function checkBoxCheck(checkbox) {
	if($(checkbox).attr('checked') != true) {
		$(checkbox).parent().addClass('disabled');
	} else {
		$(checkbox).parent().removeClass('disabled');
	}
}

function textFocus(thisInput) {  
	switch(thisInput.value) {
		case "Enter Email Address":
		case "e.g. 330000000 (9 digit number)":
		case "Enter No. of Nights":
			thisInput.value = ""
			break
	}
}

function textBlur(thisInput, myText) {  
	if(thisInput.value == "") {
		thisInput.value = myText;
	}
}

var addresses

function populateAddress(mySelect, address1, address2, city, postcode, country) {
	var i = mySelect.selectedIndex;
	$('#'+address1).html(addresses[i].address1);
	$('#'+address2).html(addresses[i].address2);
	$('#'+city).html(addresses[i].city);
	$('#'+postcode).html(addresses[i].postcode);
	$('#'+country).html(addresses[i].country);
}

function propertyList()
{
    this.properties = [];
}

function propertyInfo(code, name)
{
    this.code  = code;
    this.name = name;
    this.searchRegions = [];
}

propertyList.prototype.addProperty = function(property) {
    this.properties.push(property);
}

propertyInfo.prototype.addRegion = function(regionCode)
{
	var region = new Object();
    region.code = regionCode;
    this.searchRegions.push(region);
}

populateProperties = function(locationElId, propertyElId)
{
    var selectLocation = document.getElementById(locationElId);
    var selectProperty = document.getElementById(propertyElId);
    var regionCode = selectLocation.options[selectLocation.selectedIndex].value;
    var regionName = selectLocation.options[selectLocation.selectedIndex].text;
    if (regionCode != '')
    {
        
        selectProperty.options.length = 0;
        selectProperty.options[selectProperty.options.length] = new Option('All Macdonald Hotels in ' + regionName, '');
        for(var index = 0; index < properties.properties.length; index++)
	{
	    currentProperty = properties.properties[index];
            for(var i = 0; i < currentProperty.searchRegions.length; i++)
            {
                if (currentProperty.searchRegions[i].code == regionCode)
                {
                    //add this property to drop down list
                    selectProperty.options[selectProperty.options.length] = new Option(currentProperty.name, currentProperty.code);
                }
            }
	}
	if(selectProperty.options.length == 2)
	{
		selectProperty.remove(0);	
	}
    }
    else
    {
        selectProperty.options.length = 0;
        selectProperty.options[selectProperty.options.length] = new Option('Any Macdonald Hotel', '');
        for(var index = 0; index < properties.properties.length; index++)
	{
	    currentProperty = properties.properties[index];
	    selectProperty.options[selectProperty.options.length] = new Option(currentProperty.name, currentProperty.code);
	}
	
    }
	selectBoxReplacement(selectProperty);
}

function populateAdults() {
    var properties = document.getElementById('propertyCode');
    var propCode = properties.options[properties.selectedIndex].value;
    var maxAdults = 2;
    var maxChildren = 3;
    if(propCode == 'ERMITA') {
        maxAdults = 8;
        maxChildren = 8;
    } else if(propCode == 'AVIEHI') {
		maxAdults = 6;
        maxChildren = 6;
	}
    var i = 1;
    while(document.getElementById('adultCount' + i))
    {
        var adultCount = document.getElementById('adultCount' + i);
        var childCount = document.getElementById('childCount' + i);
        var numberAdults = adultCount.options[adultCount.selectedIndex].value;
        var numberChildren = childCount.options[childCount.selectedIndex].value;
        
        adultCount.options.length = 0;
        for(var j=0; j <= maxAdults; j++) {
            adultCount[j] = new Option(j);
            adultCount[j].value = j;
            if (j == numberAdults)
	    {
		adultCount.selectedIndex = j;
            }
        }
        childCount.options.length = 0;
        for(var j=0; j <= maxChildren; j++) {
            childCount[j] = new Option(j);
            childCount[j].value = j;
            if (j == numberChildren)
	    {
	        childCount.selectedIndex = j;
            }
        }
        if(numberAdults >= adultCount.length)
	{
		if(i == 1) {
			adultCount.selectedIndex = 2;
		}
		else {
			adultCount.selectedIndex = 0;
		}
	}
        i++;
    }
}

function iotbs() {
	switcher = new switchManager();
};

var switcher;

//setup initialisation function
//.. gecko, safari, konqueror and generic
if(typeof window.addEventListener != 'undefined') {
	window.addEventListener('load', iotbs, false);
}
//.. opera 7
else if(typeof document.addEventListener != 'undefined') {
	document.addEventListener('load', iotbs, false);
}
//.. win/ie
else if(typeof window.attachEvent != 'undefined') {
	window.attachEvent('onload', iotbs);
}


//preferences manager
function switchManager() {
	//string for storing the overall custom classname
	//I was originally storing it in the body class name directly
	//but 1.7+ mozilla builds were not honouring the trailing whitespace we need
	this.string  = '';

	//store reference to body element
	this.body = document.getElementsByTagName('body')[0];

	//store the initial classname
	this.initial = this.body.className;

	//if the default classname is empty, add "iotbs"
	//because we need there to be at least one classname already -
	//the leading and trailing space in each custom classname is required,
	//but you can't set the body classname as " something" (beginning with a leading space)
	//because that may not work in Opera 7
	if(this.initial == '') {
		this.initial = 'itobs';
	}

	//look for a stored cookie
	this.cookie = this.read();

	//if it exists
	if(this.cookie != null) {
		//store cookie value to string
		this.string = this.cookie;

		//set new body class name
		this.body.className = this.initial + ' ' + this.string;
	}

	//*** dev
	//document.title = '<' + this.body.className.replace(/ /g,'+') + '>   [' + this.string.replace(/ /g,'+') + ']';
};

//set a cookie method
switchManager.prototype.set = function(days) {
	//format expiry date
	this.date = new Date();
	this.date.setTime(this.date.getTime() + ( days *24*60*60*1000));

	//store the string, replacing spaces with '#' so that leading spaces are preserved
	this.info = this.string.replace(/ /g,'#');

	//if the value is empty, set its expiry in the past to delete the cookie
	if(this.info == '') { this.date.setTime(0); }

	//create the cookie
	document.cookie = 'bodySwitcher=' + this.info
		+ '; expires=' + this.date.toGMTString()
		+ '; path=/';
};


//read a cookie method
switchManager.prototype.read = function() {
	//set null reference so we always have something to return
	this.cookie = null;

	//if a cookie exists
	if(document.cookie) {
		//if it's our cookie
		if(document.cookie.indexOf('bodySwitcher')!=-1) {
			//extract and store relevant information (turning '#' back into spaces)
			this.cookie = document.cookie.split('bodySwitcher=');
			this.cookie = this.cookie[1].split(';');
			this.cookie = this.cookie[0].replace(/#/g,' ');
		}
	}
	return this.cookie;
};


function changetoDefault() {
	switcher.string = 'default'
	switcher.body.className = " iotbs  ";
	switcher.set(365);
}

function changetoMedium() {
	switcher.string = 'medium';
	switcher.body.className = " iotbs  " + switcher.string +' ';
	switcher.set(365);
}

function changetoLarge() {
	switcher.string = 'large';
	switcher.body.className = " iotbs  " + switcher.string +' ';
	switcher.set(365);
}
function openLinkedOffer() {
}
function redeyeload()
{
	var redEyeStart = "http://reporting.macdonaldhotels.co.uk/cgi-bin/rr2/";
	var redEyeEnd = "?nourl=theclub.macdonaldhotels.co.uk/";
	var redEyeNobook = 'http://reporting.macdonaldhotels.co.uk/cgi-bin/rr.cgi/';

	for(var i=0;i<document.anchors.length;i++)
	{
		var oldHref = document.anchors[i].href;
		var linkName = document.anchors[i].name;
		if(linkName.indexOf('_lnk_') > 0)
		{
			linkName = linkName.replace(/_/ig,"/");
			document.anchors[i].href=redEyeStart+oldHref+redEyeEnd+linkName;
		} else if(linkName.indexOf('nobook') >= 0) {
			document.anchors[i].href=redEyeNobook+linkName+"/"+oldHref
		}
	}
}


function redeyetag()
{
	var redeyedomain = 'reporting.macdonaldhotels.co.uk';
	var nourlvalue = location.href;
	nourlvalue = nourlvalue.toLowerCase();
	if(nourlvalue.indexOf('?') > 0) { nourlvalue = nourlvalue.substring(0,nourlvalue.indexOf('?')); }
	nourlvalue = nourlvalue.replace('.com','.co.uk');
	if(nourlvalue.lastIndexOf("/") == (nourlvalue.length-1))
	{ 
		if(nourlvalue.indexOf(".co.uk/") == nourlvalue.lastIndexOf("/") - 6 || nourlvalue.indexOf(".co.uk/resorts/") == nourlvalue.lastIndexOf("/") - 14)
		{
			nourlvalue += "home.htm" 
		}
		else
		nourlvalue += "index.htm" 
	}
	var tag = 'http://' + redeyedomain + '/cgi-bin/rr.cgi/images/blank.gif?nourl=' + nourlvalue + '&norefer=' + escape(window.document.referrer);

	var enquiryID = "";
	var GETDATA = new Array();
	var sGet = window.location.search;
	if (sGet)
	{
		sGet = sGet.substr(1);
		var sNVPairs = sGet.split("&");
		for (var i = 0; i < sNVPairs.length; i++)
		{
			var sNV = sNVPairs[i].split("=");
			var sName = sNV[0];
			var sValue = sNV[1];
			if(sName = 'enquiryReference')
			{
				enquiryID = sValue;
			}
		}
	}

	if(nourlvalue.indexOf('weddings/thanks.asp') > 0 || nourlvalue.indexOf('weddings/thanks.htm') > 0)
	{
		tag += "&amp;r_wedding_enquiry=confirm&amp;f_wedding_enqref=" + enquiryID;
	}
	else if((nourlvalue.indexOf('thankyou.asp') > 0 || nourlvalue.indexOf('thankyou.htm') > 0) && nourlvalue.indexOf('/resorts/') > 0)
	{
		tag += "&amp;r_resort_enquiry=confirm&amp;f_resorts_enqref=" + enquiryID;
	}
	else if((nourlvalue.indexOf('thankyou.asp') > 0 || nourlvalue.indexOf('thankyou.htm') > 0) && nourlvalue.indexOf('/rfp/') < 0 && nourlvalue.indexOf('/golf/') < 0)
	{
		if(nourlvalue.indexOf('business/') > 0)
		tag += "&amp;r_hotel_enquiry=confirm&amp;f_hotelbus_enqref=" + enquiryID;
		else
		tag += "&amp;r_hotel_enquiry=confirm&amp;f_hotel_enqref=" + enquiryID;
	}
	else if((nourlvalue.indexOf('thankyou.asp') > 0 || nourlvalue.indexOf('thankyou.htm') > 0) && nourlvalue.indexOf('/rfp/') >= 0)
	{
		tag += "&amp;r_business_enquiry=confirm&amp;f_businessrfp_enqref=" + enquiryID;
	}
	else if((nourlvalue.indexOf('thankyou.asp') > 0 || nourlvalue.indexOf('thankyou.htm') > 0) && nourlvalue.indexOf('/golf/') >= 0)
	{
		tag += "&amp;r_golf_enquiry=confirm&amp;f_golf_enqref=" + enquiryID;
	}
	else if(nourlvalue.indexOf('thanksfortheenquiry') > 0)
	{
		tag += "&amp;r_offer_enquiry=confirm&amp;f_offer_enqref=" + enquiryID;
	}

	document.write("<img src='" + tag + "' width='1' id='redeyepagetag' height='1' alt='' />");
}
