// Ajax.js starts here
var xmlhttp=false;
 
try {
  xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
 } catch (e) {
  try {
   xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  } catch (E) {
   xmlhttp = false;
  }
 }

if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
	try {
		xmlhttp = new XMLHttpRequest();
	} catch (e) {
		xmlhttp=false;
	}
}
if (!xmlhttp && window.createRequest) {
	try {
		xmlhttp = window.createRequest();
	} catch (e) {
		xmlhttp=false;
	}
}

var JSON = function () {
    var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        },
        s = {
            array: function (x) {
                var a = ['['], b, f, i, l = x.length, v;
                for (i = 0; i < l; i += 1) {
                    v = x[i];
                    f = s[typeof v];
                    if (f) {
                        v = f(v);
                        if (typeof v == 'string') {
                            if (b) {
                                a[a.length] = ',';
                            }
                            a[a.length] = v;
                            b = true;
                        }
                    }
                }
                a[a.length] = ']';
                return a.join('');
            },
            'boolean': function (x) {
                return String(x);
            },
            'null': function (x) {
                return "null";
            },
            number: function (x) {
                return isFinite(x) ? String(x) : 'null';
            },
            object: function (x) {
                if (x) {
                    if (x instanceof Array) {
                        return s.array(x);
                    }
                    var a = ['{'], b, f, i, v;
                    for (i in x) {
                        if (!x.hasOwnProperty || x.hasOwnProperty(i)) {
                            v = x[i];
                            f = s[typeof v];
                            if (f) {
                                v = f(v);
                                if (typeof v == 'string') {
                                    if (b) {
                                        a[a.length] = ',';
                                    }
                                    a.push(s.string(i), ':', v);
                                    b = true;
                                }
                            }
                        }
                    }
                    a[a.length] = '}';
                    return a.join('');
                }
                return 'null';
            },
            string: function (x) {
                if (/["\\\x00-\x1f]/.test(x)) {
                    x = x.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                        var c = m[b];
                        if (c) {
                            return c;
                        }
                        c = b.charCodeAt();
                        return '\\u00' +
                            Math.floor(c / 16).toString(16) +
                            (c % 16).toString(16);
                    });
                }
                return '"' + x + '"';
            }
        };
    return {
/*
    Stringify a JavaScript value, producing a JSON text.
*/
        stringify: function (v) {
            var f = s[typeof v];
            if (f) {
                v = f(v);
                if (typeof v === 'string') {
                    return v;
                }
            }
            return;
        },
/*
    Parse a JSON text, producing a JavaScript value.
    It returns false if there is a syntax error.
*/
        parse: function (text) {
            try {
                return !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
                        text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
                    eval('(' + text + ')');
            } catch (e) {
                return false;
            }
        }
    };
}();
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// AJAX Interaction function, which separates object creation, request, and callback.
// This function allows passing of parameters to whatever is specified as the callback() function.
// Requirements:
// - url: the URL of the asp page that loads the data in the background
// - callback: the function to call when the AJAX load is complete
// - destinationobject: the object to pass to the callback function, which is to receive the data
// - param1: an additional parameter that will be passed to the callback function. This could carry
// anything you like. For select boxes, it carries a possible preselect value.
// - It is also required that the destinationobject has a corresponding <DIV> tag with an
// ID value of "<destinationobjectname>AJAXloading". This is for the display of an animated
// .GIF beside the destinationobject.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AJAXInteraction(url, callback, destinationobject, param1) {
	var MyAJAXdiv;
	var MySelectBox;

	if (document.getElementById(destinationobject + 'AJAXloading')) { 
		MyAJAXdiv = document.getElementById(destinationobject + 'AJAXloading');
	}
	if (document.getElementById(destinationobject)) { 
		MySelectBox = document.getElementById(destinationobject);
	} 

	var http_request = init();
	http_request.onreadystatechange = processRequest;

	function init() {
	  if (window.XMLHttpRequest) {
		return new XMLHttpRequest();
	  } else if (window.ActiveXObject) {
		return new ActiveXObject("Microsoft.XMLHTTP");
	  }
	}
	
	//The function needs to check for the state of the request. If the state has the value of 4, that means that the full 
	//server response is received and it's OK for you to continue processing it.
	//The full list of the readyState values is as follows:
	//* 0 (uninitialized)
	//* 1 (loading)
	//* 2 (loaded)
	//* 3 (interactive)
	//* 4 (complete) 
	// Not all of these readyState values behave as expected in different browser. In fact, only 0 and 4 are truly reliable.

	function processRequest () {
		//alert( url + ' ' + http_request.status);
		if (http_request.readyState == 4) {
			if (http_request.status == 200) {

				if (MyAJAXdiv) {
					MyAJAXdiv.innerHTML = "";
				}
				if (MySelectBox) {
					MySelectBox.disabled=false;
				}

				if (callback) callback(http_request.responseText, destinationobject, param1);
				
				if ( InStr(url, 'getcities') > 0 ) {
					FillSuburbDropDown();
				}
				
				if ( InStr(url, 'getlocations') > 0 ) {
					HotDeals();
				}
				

				//http_request.abort(); //Prevents known minor memory leak in IE, but crashes Safari.
			}
		}
		else {
			if (MyAJAXdiv) {
				MyAJAXdiv.innerHTML = "<img src='/images/load.gif' border='0'>";
			}

			if (MySelectBox) {
				MySelectBox.innerHTML = "<img src='/images/load.gif' border='0'>";
				MySelectBox.disabled=true;
			}
		}
	}

	this.doGet = function() {
	  http_request.open('GET', url, true);
	  http_request.send(null);
	}
	
	this.doPost = function(body) {
	  http_request.open("POST", url, true);
	  http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	  http_request.send(body);
	}	
}

function clearCombo(oList)
{
  for (var i = oList.options.length - 1; i >= 0; i--)
  {
    oList.options[i] = null;
  }
  oList.selectedIndex = -1;
}

//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global AJAX Request handler. Use this function to set up a call to retrieve data via AJAX.
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function AJAXRequest(url, outputfunction, destinationobject, param1) {
	//alert( url);
	//alert( outputfunction);
	var ai = new AJAXInteraction(url, eval(outputfunction), destinationobject, param1);
	ai.doGet();	 
	ai = null;
}


//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Global LoadSelectBox handler. Use this function to load up any SelectBox via AJAX.
// Requirements:
// - destinationobject - the select box to receive the JSON data.
// - preselect - the index of the select box item to be preselected, if any.
// - Data being returned must be JSON format.
// - The existence of a <DIV> tag on the calling page, with an ID of "<destinationobject ID>AJAXloading"
//////////////////////////////////////////////////////////////////////////////////////////////////////////
function LoadSelectBox(JSONData, destinationobject, preselect) {
			
	var SelectBoxName = destinationobject;  //First value is always the name of the object being populated (REQUIRED)
	var SelectBoxSelectItemID = preselect; //Second value is always the ID value of the item that is to be preselected (OPTIONAL)
	var MySelectBox;
	var MyAJAXdiv;
	var nPreselectIndex;

	if (document.getElementById(SelectBoxName + 'AJAXloading')) { 
		MyAJAXdiv = document.getElementById(SelectBoxName + 'AJAXloading');
	}

	if (document.getElementById(SelectBoxName)) { 
		MySelectBox = document.getElementById(SelectBoxName);
	}
	
	var myJSONtext = JSONData;
	var objData = JSON.parse(myJSONtext);
	
	clearCombo(MySelectBox);

	if (MySelectBox) {
		MySelectBox.options.length= 0;
		// Old method of populating select boxes that while not using DOM, works on all browsers, except Opera 5.02. Works fine on later Operas.
		//myOption = new Option("[Select]", "", true, true); //Text, Value, Selected, Default Selected. The last two appear to be dead ducks in most browsers.
		//MySelectBox.options[MySelectBox.options.length] = myOption;

	}
	nPreselectIndex = -1;
	if (objData) {
		for(i=0;i<objData.items.length;i++) {
			// Old method of populating select boxes that while not using DOM, works on all browsers, except Opera 5.02. Works fine on later Operas.
			if (objData.items[i].id==SelectBoxSelectItemID){
				//alert(SelectBoxSelectItemID);
				myOption = new Option(objData.items[i].name, objData.items[i].id, false, false); //Text, Value, Selected, Default Selected. The last two appear to be dead ducks in most browsers.
				myOption.selected = true; //Preselect this item on the fly. Works on most browsers

				//Some browsers require the setting of a flag, in order to force the preselect of a chosen option, after the whole <Select> has finished building.
				//One example is Opera. 
				if ((objData.items[i].id!="")&&(SelectBoxSelectItemID!="")){
				nPreselectIndex = i + 1; // i + 1 because we already added an option called [select]
				}
			}
			else {
				myOption = new Option(objData.items[i].name, objData.items[i].id, false, false); //Text, Value, Selected, Default Selected. The last two appear to be dead ducks in most browsers.
			}
			MySelectBox.options[MySelectBox.options.length] = myOption;
			MySelectBox.select

		}

		//Force a preselect here, after building the select box. Required on browsers like Opera which won't preselect elements on the fly.
		if (nPreselectIndex > -1) {
			MySelectBox.options[nPreselectIndex].selected = true; //This forces a preselect if necessary.
		}
	}
	if (SelectBoxName=="suburb"){
		document.getElementById('HotDealCity').innerHTML=document.getElementById("city").options[document.getElementById("city").options.selectedIndex].innerHTML;
	}
	myOption = null;
	MySelectBox = null;
	MyAJAXdiv = null;
	objData = null;
}	
function UpdateDiv(responseText, destinationobject, param1) {

	document.getElementById(destinationobject).innerHTML = responseText; 
	if (destinationobject=="hotdeals"){
	 document.getElementById('srchbut').disabled=false;
	 }
}
// End of Ajax.js 
// Common.js starts here
function getObject (id){ var obj = document.getElementById(id); return obj;}
//open new window
function openWnd(url, name, height, width, directories, location, menubar, resizable, scrollbars, status, toolbar) 
{
	wnd = window.open(url, name, "alwaysRaised=1,height=" + height + ",width=" + width + ",directories=" + directories + ",locaton=" + location + ",menubar=" + menubar + ",resizable=" + resizable + ",scrollbars=" + scrollbars + ",status=" + status + ",toolbar=" + toolbar)
	wnd.focus()
}

function showFAQ(id){
	if(getObject(id).style.display=='none')
		getObject(id).style.display='block';
	else 
		getObject(id).style.display='none';
}

//replace or add name/value pairs in url-encoded querystring
function setQStringName(qString, name, arrVal) {
var qStringNew = remQStringName(qString, name)
var start = qStringNew == "" ? 1 : 0
for (var i in arrVal) qStringNew += "&" + escape(name) + "=" + escape(arrVal[i])
return qStringNew.substr(start)
}

//remove all name/value pairs with the passed name from url-encoded querystring
function remQStringName(qString, name) {
var i
var qStringNew = ""

if (qString != "") {
var curName
var arrNameVal = qString.split("&")

for (i in arrNameVal) {
curName = URLDecode(arrNameVal[i].split("=")[0])
if (curName.toLowerCase() != name.toLowerCase()) qStringNew += "&" + arrNameVal[i]
}
}

return qStringNew.substr(1)
}

//get select box text
function GetSelText(ctl) {
var selIdx = ctl.selectedIndex
return selIdx == -1 ? "" : ctl[selIdx].text
}

function ChangeCurrency(currCtl) 
{
	var frm = document.MainLangSwitch  //reuse language switch form
	var URL = location.pathname + "?" + setQStringName(location.search.substr(1), "curr", new Array(GetSelText(currCtl)))  //replace or add currency code to the page url
	if (frm) 
	{
		frm.action = URL
		frm.submit()
	} 
	else
	{
		location = URL
	}

}


function URLDecode(urlStr) {
return unescape(urlStr.replace(/\+/g, " "))
}

//get select box value
function GetSelVal(ctl) {
var selIdx = ctl.selectedIndex
return selIdx == -1 ? "" : ctl[selIdx].value
}

function notNumber(number) {
number = number.toString()
for (var i=0; i<number.length; i++) {
if (number.charAt(i) > "9" || number.charAt(i) < "0") return true
}
return false
}

//check whether text-box is empty
function isEmpty(field, fieldName, msg) 
{ //alert(field)
	if (Trim(field.value) == "") 
	{
		if (msg == null)
			msg = "Please enter " + fieldName + "."
			field.focus()
			return true
		
	}

		return false
}



//validate ASCII Character Set
function charCheck(field, message, toASCIIfield) {
if (toASCIIfield == null)
var txt = field.value
else
var txt = ToASCII(field)

for (var i=0; i<txt.length; i++) {
if (txt.charCodeAt(i) >= 128) {
alert(message)
field.focus()
return true
}}

return false
}

//check whether text-box is empty
function isEmptyContact(field, fieldName, msg) 
{ //alert(field)
	if (Trim(field.value) == "") 
	{
		if (msg == null)
			msg = "Please enter " + fieldName + "."
			field.focus()
			return true
		
	}

		return false
}


//validate ASCII Character Set
function charCheckContact(field, message, toASCIIfield) 
	{
		if (toASCIIfield == null)
			var txt = field.value
		else
			var txt = ToASCII(field)
			for (var i=0; i<txt.length; i++) 
			{
				if (txt.charCodeAt(i) >= 128) 
				{
				field.focus()
				return true
				}
			}
		return false
	}






function notSelected(field, fieldName, msg) 
{
	if (field.selectedIndex == 0) 
	{
		if (msg == null)
			msg = "Please select " + fieldName + "."
			field.focus()
			return true
	}

		return false
}

var AllowDocLangClick;
var AllowDocCurrClick;

AllowDocLangClick = false;
AllowDocCurrClick = false;

var LangjustClicked;
LangjustClicked = false;

var CurrjustClicked;
CurrjustClicked = false;

function RTGtoggleDisplay(divId, ops) {

  var div = document.getElementById(divId);
  div.style.display = ops;

  if (divId == 'dropmenulang') {
    AllowDocLangClick = true;
    LangjustClicked = true;
    CurrjustClicked = false;
  }
  else {
    AllowDocCurrClick = true;
    CurrjustClicked = true;
    LangjustClicked = false;
  }
  
}

function showLangFalse() {

	if (LangjustClicked == true)
		{
		    LangjustClicked = false;
			return;
		}
		
    if (AllowDocLangClick == true) {
        document.getElementById('dropmenulang').style.display="none";
        AllowDocLangClick = false;
    }
}

function showCurrFalse() {
	if (CurrjustClicked == true) {
		    CurrjustClicked = false;
			return;
	}

    if (AllowDocCurrClick == true) {
        document.getElementById('RTGdropmenucurr').style.display="none";
        AllowDocCurrClick = false;
    }
}

function showDivsFalse() {

    showCurrFalse();
    showLangFalse();
}

document.onclick = showDivsFalse;

function ChangeValue(urlVar, varValue) {
	if (varValue != "") {
		var frm = document.MainLangSwitch
		var URL = switch_URL(urlVar, varValue)

		if (frm) {
			frm.action = URL
			frm.submit()
		} else {
			location = URL
		}
	}
}


//replace or add language code to the document url
function switch_URL(urlVar, varValue) {
	var qString = location.search.substr(1)
	var arrQString = qString.split("&")
	var varAdded = false

	for (var i in arrQString) {
		if (arrQString[i].split("=")[0].toLowerCase() == urlVar) {
			arrQString[i] = urlVar + "=" + varValue
			varAdded = true
		}
	}

	qString = arrQString.join("&")

	if (!varAdded) {
		if (qString != "") qString += "&"
		qString += urlVar + "=" + varValue
	}

	return location.pathname + "?" + qString
}

// End of Common.js 
// Utils.js starts here

function LTrim(str)
//LTrim(string) : Returns a copy of a string without leading spaces.
//==================================================================
/***
PURPOSE: Remove leading blanks from our string.
IN: str - the string we want to LTrim

RETVAL: An LTrimmed string!
***/
{
var whitespace = new String(" \t\n\r");
var s = new String(str);

if (whitespace.indexOf(s.charAt(0)) != -1) {
// We have a string with leading blank(s)...

var j=0, i = s.length;
// Iterate from the far left of string until we
// don't have any more whitespace...
while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
j++;
// Get the substring from the first non-whitespace
// character to the end of the string...
s = s.substring(j, i);
}
return s;
}
//==================
function RTrim(str)
//RTrim(string) : Returns a copy of a string without trailing spaces.
//==================================================================
/***
PURPOSE: Remove trailing blanks from our string.
IN: str - the string we want to RTrim
RETVAL: An RTrimmed string!
***/
{
// We don't want to trip JUST spaces, but also tabs,
// line feeds, etc.  Add anything else you want to
// "trim" here in Whitespace
var whitespace = new String(" \t\n\r");
var s = new String(str);
if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
// We have a string with trailing blank(s)...
var i = s.length - 1;       // Get length of string
// Iterate from the far right of string until we
// don't have any more whitespace...
while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
i--;
// Get the substring from the front of the string to
// where the last non-whitespace character is...
s = s.substring(0, i+1);
}
return s;
}
//===============
function Trim(str)
//Trim(string) : Returns a copy of a string without leading or
//trailing spaces
//=============================================================
/***
PURPOSE: Remove trailing and leading blanks from our string.
IN: str - the string we want to Trim
RETVAL: A Trimmed string!
***/
{
return RTrim(LTrim(str));
}
function Len(str)
/***
        IN: str - the string whose length we are interested in

        RETVAL: The number of characters in the string
***/
{  return String(str).length;  }
function Left(str, n)
/***
        IN: str - the string we are LEFTing
            n - the number of characters we want to return

        RETVAL: n characters from the left side of the string
***/
{
        if (n <= 0)     // Invalid bound, return blank string
                return "";
        else if (n > String(str).length)   // Invalid bound, return
                return str;                // entire string
        else // Valid bound, return appropriate substring
                return String(str).substring(0,n);
}
function Right(str, n)
/***
        IN: str - the string we are RIGHTing
            n - the number of characters we want to return

        RETVAL: n characters from the right side of the string
***/
{
        if (n <= 0)     // Invalid bound, return blank string
           return "";
        else if (n > String(str).length)   // Invalid bound, return
           return str;                     // entire string
        else { // Valid bound, return appropriate substring
           var iLen = String(str).length;
           return String(str).substring(iLen, iLen - n);
        }
}
function Mid(str, start, len)
/***
        IN: str - the string we are LEFTing
            start - our string's starting position (0 based!!)
            len - how many characters from start we want to get

        RETVAL: The substring from start to start+len
***/
{
        // Make sure start and len are within proper bounds
        if (start < 0 || len < 0) return "";

        var iEnd, iLen = String(str).length;
        if (start + len > iLen)
                iEnd = iLen;
        else
                iEnd = start + len;

        return String(str).substring(start,iEnd);
}
function InStr(strSearch, charSearchFor)
/*
InStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
                           was found in the string str.  (If the character is not
                           found, -1 is returned.)
                           
Requires use of:
	Mid function
	Len function
*/
{
	for (i=0; i < Len(strSearch); i++)
	{
	    if (charSearchFor == Mid(strSearch, i, Len(charSearchFor) ))
	    {
			return i;
	    }
	}
	return -1;
}

//trim string
function trim(stringToTrim) {
	var i, j

	//left trim
	for(i=0; i<stringToTrim.length; i++) {
		if (stringToTrim.charAt(i) != " ") break
	}

	//right trim
	for(j=stringToTrim.length-1; j>=i; j--) {
		if (stringToTrim.charAt(j) != " ") break
	}

	return stringToTrim.substring(i, j + 1)
}
// Scripts below are used for room specials pop up existing in SR, DH, and SL page
function HidePopup(oid) {
    document.getElementById(oid).style.display = "none";
}

function showpopup(obj, mainobj, x, y) {
    var topoffset = 18;
    if (x == 'undefined') x = 0;
    if (y == 'undefined') y = 0;
    //obj = document.getElementById(cid);
    //obj.innerHTML = text;
    //mainobj = document.getElementById(parentobj);
    var curleft = curtop = 0;
    if (mainobj.offsetParent) {
        curleft = mainobj.offsetLeft;
        curtop = mainobj.offsetTop;
        while (mainobj = mainobj.offsetParent) {
            curleft += mainobj.offsetLeft;
            curtop += mainobj.offsetTop;
        }
    }
    obj.style.position = "absolute";
    obj.style.display = "";
    obj.style.left = (curleft + x) + 'px'; //Fix for bug#1737
    obj.style.top = (curtop + topoffset + y) + 'px';
}

function DisplayRoomSpecials(mainobj, RoomNameForSpecial, specialDesc, cxlPolicy) {

   // alert(text);
   // var popupHtml = '<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">' +
   //                 '<tr><td bgcolor="#fbfbf7"><h1 class="hotelname"><<PopUpText>></h1><a  onclick="javascript:HidePopup(\'room_special_popup\');" class="closebutton">' +
    //                '<img src="/images/popup-close-button.gif" alt="close" width="17" height="16" /></a><div class="clear"></div></td></tr></table>';
    //popupHtml = popupHtml.replace('<<PopUpText>>', text);
    var popupHtml = '<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">' +
                     '<tr>' +
                        '<td bgcolor="#fbfbf7" width="94%"><h6 class="SpecialHeader">' + RoomNameForSpecial + '</h6></td>' +
                        '<td valign="top"><a  onclick="javascript:HidePopup(\'room_special_popup\');" class="closebutton">' +
                        '<img src="/images/popup-close-button.gif" alt="close" width="17" height="16" /></a><div class="clear"></div></td></tr>' +
                     '<tr>' +
                        '<td align="left" valign="top" bgcolor="#fbfbf7" colspan="2">' +
                        '<table width="100%" border="0" cellpadding="2" cellspacing="0" bgcolor="#FFFFFF">' +
                            '<tr><td width="35%" valign="top"><strong>' + SpecialDescTag + '</strong></td></tr>' +
                            '<tr><td>' + specialDesc + '</td></tr>' +
                            '<tr><td width="35%" valign="top"><br><strong>' + SpecialCnxPlyTag + '</strong></td></tr>' +
                            '<tr><td>' + cxlPolicy + '</td></tr>' +
                        '</table>' +
                        '<br /><div class="dividerRed"></div>' +
                        '</td>' +
                    '</tr></table>'

    var popup = document.getElementById('room_special_popup');
    popup.innerHTML = popupHtml;
    showpopup(popup, mainobj, -265, 0);
}
//End of Utils.js
