function loadXMLDoc(xmlstring)
{
	var xmlDoc;
	
	//for IE
    if (window.ActiveXObject)
    {
	    xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	    xmlDoc.async=false;
	    xmlDoc.loadXML(xmlstring);
	}
	//for Mozilla, Firefox, Opera, etc.
    else if (document.implementation && document.implementation.createDocument)
	{	    
	    xmlDoc = (new DOMParser()).parseFromString(xmlstring, "text/xml");
	    xmlDoc.async=false;
	}	
    
	return xmlDoc;
}

function getStringFromNode(node)
{    
    if(node && node.firstChild)
    {        
        return node.firstChild.nodeValue;
    }
    else
    {
        return "";
    }
}

function Trim(str)
{  while(str.charAt(0) == (" ") )
  {  str = str.substring(1);
  }
  while(str.charAt(str.length-1) == " " )
  {  str = str.substring(0,str.length-1);
  }
  return str;
}

// This searches for the availability of searchString 
// in mainString starting from the first letter in mainString.
// THis returns TRUE if if found or else returns FALSE.
function startsWith(mainString, searchString)
{
    mainString = mainString.toLowerCase();
    searchString = searchString.toLowerCase();
    
    if(mainString && searchString)
    {		
        // Get the search string replaced with regex mapping attributes (u|ü)
		// var stringAfterReplace = getStringAfterReplace(searchString);
		// var regex = new RegExp("^"+stringAfterReplace, "gi");
	    
	    
	    if(!isValidSearchString(searchString))
	        return false;
	    
        var regex = new RegExp("^"+searchString);
        if (mainString.match(regex))
        {
	        return true;
        }
        else
        {
	        return false;
        }
    }
}

function isValidSearchString(searchString)
{
    var isValid = true;
    if(
        (searchString.indexOf('~') != -1) ||
        (searchString.indexOf('!') != -1) ||
        (searchString.indexOf('@') != -1) ||
        (searchString.indexOf('#') != -1) ||
        (searchString.indexOf('$') != -1) ||
        (searchString.indexOf('%') != -1) ||
        (searchString.indexOf('^') != -1) ||
        (searchString.indexOf('&') != -1) ||
        (searchString.indexOf('*') != -1) ||
        /*artf1053624|Scanweb - problem with small booking dialog on hotel homepage (S:t Jorgen)|Some hotel's name has : and -*/
        /*(searchString.indexOf('-') != -1) ||*/
        (searchString.indexOf('_') != -1) ||
        (searchString.indexOf('+') != -1) ||
        (searchString.indexOf('=') != -1) ||
        (searchString.indexOf('{') != -1) ||
        (searchString.indexOf('}') != -1) ||
        (searchString.indexOf('[') != -1) ||
        (searchString.indexOf(']') != -1) ||
        (searchString.indexOf('\\') != -1) ||
        /*(searchString.indexOf(':') != -1) ||Refer above comment or artf1053624*/
        (searchString.indexOf(';') != -1) ||
        (searchString.indexOf('\'') != -1) ||
        (searchString.indexOf('"') != -1) ||
        (searchString.indexOf('<') != -1) ||
        (searchString.indexOf('>') != -1) ||
        (searchString.indexOf(',') != -1) ||
        (searchString.indexOf('.') != -1) ||
        (searchString.indexOf('/') != -1) ||
        (searchString.indexOf('?') != -1) ||
        (searchString.indexOf('0') != -1) ||
        (searchString.indexOf('1') != -1) ||
        (searchString.indexOf('2') != -1) ||
        (searchString.indexOf('3') != -1) ||
        (searchString.indexOf('4') != -1) ||
        (searchString.indexOf('5') != -1) ||
        (searchString.indexOf('6') != -1) ||
        (searchString.indexOf('7') != -1) ||
        (searchString.indexOf('8') != -1) ||
        (searchString.indexOf('9') != -1)
        )
        {
            isValid = false;
        }
// TODO : Just we need to uncomment these lines as this is a correct logic and on PerformValidation the string coming here is wrong
//        else
//        {
//            isValid = isValidSearchPattern(searchString);
//        }
        
    return isValid;
}

function isValidSearchPattern(checkString)
{
    for (i = 0; i < stringMapping.length; i++)
	{
	    key     = stringMapping[i].split(":")[0];
	    value   = stringMapping[i].split(":")[1];
	    
        var intIndexOfMatch = checkString.indexOf(value);
	    // Loop over the string value replacing out each matching
        // substring.
        while (intIndexOfMatch != -1)
        {
            // Relace out the current instance.
            checkString = checkString.replace(value, key);

            // Get the index of any next matching substring.
            intIndexOfMatch = checkString.indexOf(value);
        }
	}
	
	if(
        (checkString.indexOf('(') != -1) ||
        (checkString.indexOf(')') != -1) ||
        (checkString.indexOf('|') != -1)
      )
      {
        return false;
      }
      
      return true;
}

//function isValidSearchPattern(checkString)
//{
//    while(checkString != "" && checkString != null)
//    {
//        if( 
//            (checkString.indexOf('(') != -1) &&
//            (checkString.indexOf(')') != -1) &&
//            (checkString.indexOf('|') != -1) 
//        )
//        {
//            if( 
//                (checkString.indexOf(')') < checkString.indexOf('(')) ||
//                (checkString.indexOf('|') < checkString.indexOf('(')) ||
//                (checkString.indexOf('|') > checkString.indexOf(')'))
//            )
//            {
//                return false;
//            }
//            else
//            {
//                var leftParaIndex = checkString.indexOf('(');
//                var rightParaIndex = checkString.indexOf(')');
//                var multiLanguageCharString = checkString.substring(leftParaIndex, rightParaIndex + 1);
//                if( false === isValidMultiLanguageCharString(multiLanguageCharString))
//                    return false;
//                else
//                {
//                    if( rightParaIndex + 1 < checkString.length)
//                    {
//                        checkString = checkString.substring(rightParaIndex + 1);
//                    }
//                    else
//                    {
//                        checkString = "";
//                    }
//                }
//            }
//        }
//        else if(
//            (checkString.indexOf('(') != -1) ||
//            (checkString.indexOf(')') != -1) ||
//            (checkString.indexOf('|') != -1)
//            )
//        {
//            return false;
//        }
//        else
//            return true;
//    }
//    
//    return true;
//}

//function isValidMultiLanguageCharString(multiLanguageCharString)
//{
//    for(var i = 0; i < multiLanguageCharString.length; i++)
//    {
//        if(i % 2 === 0 && i != 0 && i != multiLanguageCharString.length - 1)
//        {
//            if( multiLanguageCharString.charAt(i) != '|')
//            {
//                return false;
//            }
//        }
//    }
//    return true;
//}

function replaceAll( str, from, to ) {
    var idx = str.indexOf(from);
    while (idx > -1) {
        str = str.replace(from, to);
        idx = str.indexOf(from);
    }
    return str;
}

// print dialog
function printWindow() 
{
	window.print();
}

function _endsWith(element)
{
    var allInputs = document.getElementsByTagName('input');
    var allSelects = document.getElementsByTagName('select');
    var allSpans = document.getElementsByTagName('span');
    var allDivs = document.getElementsByTagName('div');
	var allAs = document.getElementsByTagName('a');
	var allPs = document.getElementsByTagName('p');
	var allTextArea=document.getElementsByTagName('textarea');
	var elemLength = element.length;
    var i=0;

    var allControlArray = new Array();

    if (allInputs && allInputs.length > 0)
        allControlArray = allControlArray.concat(allInputs);
    if (allSelects && allSelects.length > 0)
        allControlArray = allControlArray.concat(allSelects);
    if (allSpans && allSpans.length > 0)
        allControlArray = allControlArray.concat(allSpans);
    if (allDivs && allDivs.length > 0)
        allControlArray = allControlArray.concat(allDivs);
    if (allAs && allAs.length > 0)
        allControlArray = allControlArray.concat(allAs);
    if (allPs && allPs.length > 0)
        allControlArray = allControlArray.concat(allPs);
    if (allTextArea && allTextArea.length > 0)
        allControlArray = allControlArray.concat(allTextArea);
   
    if (allControlArray)
    {
        for (i=0; i<allControlArray.length; i++)
        {
            var controls = allControlArray[i];
            for (j=0; j<controls.length; j++)
            {
                var input = controls[j];
                var idValue = input.id;
                if (idValue)
                {
                    var pos = idValue.indexOf(element);
                    if (pos != -1 && (pos+elemLength)==idValue.length)
                        return idValue;
                }
            }
        }
    } 
    return null;
}

// 	Function to hide client error messages
function hideClientError()
{
    $fn(_endsWith(errorDivID)).style.display = 'none';
    $fn(_endsWith(errorDivID)).style.visibility = isHidden;
    
    $fn("lblUserName").className = "";
    $fn("lblPassword").className = "";
    $fn("destCont").className = "";
    $fn("atCont").className = "";
    $fn("dtCont").className = "";
    $fn("nnCont").className = "";
    $fn("spanRegularCode").className = "";
}

//	Function to set the activeTab id to the current tab.
// 	@param  Current Tab ID
function changeActiveTab(currentTab)
{
	 $fn(activeTab).id='';
	 $fn(currentTab).parentNode.id=activeTab;
}	

//	Function to show the contents of current tab and hide other tab contents
// 	@param		
//function showTabContent(currentTabID) 
//{

//    // BUG FIX: artf695582 | Free Night is not coming as selected in refine search module. 
//    // Setting the value for path, domain and secure too.
//	setCookie('ActiveTab', currentTabID, cookieExpDate, '/', '', '');
//	
//	$fn(sT).value = currentTabID;
//	
//	for(i=1; i<4; i++) 
//	{	 
//		tabID = 'Tab'+i;
//	    if(tabID == currentTabID) 
//	    {		
//		      dt = $fn(DepartureDate);
//		      at = $fn(ArrivalDate);
//		      nt = $fn(NoOfNight);
//		      dest = $fn(Destination);
//		      spcode=$fn(splBookingCode);
//		      vouCode=$fn(VoucherNumber);
//		      negCode=$fn(DNumber);
//		      promoCode = $fn(splBookingCode);
//		      
//		      //Hide the Remember Code Checkbox/Link for Bonus check tab
//		      //Display them for Regular Booking tab
//		      if(currentTabID == "Tab2" || currentTabID == "Tab3") 
//		      {
//		         $fn("rememberFunctionality").style.display = 'none';    
//		      }
//		      else if (currentTabID == "Tab1") 
//		      {
//		         $fn("rememberFunctionality").style.display = 'block';    
//		      }

//		      bRedemtionLogin = $fn(guestLogin).value; // possible values or true / false
//		      //$fn(_endsWith(errorDivID)).style.display = 'none';
//              //$fn(_endsWith(errorDivID)).style.visibility = isHidden;
//			  if((currentTabID == "Tab3") && (bRedemtionLogin=='false')) 
//			  { 
//				    $fn(commonControls).style.display = 'none';
//				    $fn(commonFooter).style.display = 'none';
//				    $fn(tabID).style.display = 'block';
//				    //$fn(singleLeg).style.display = 'none';
//				    //$fn(multiLeg).style.display = 'none';
//				    $fn(RedemptionFooter).style.display = 'block';				
//		      } 
//		      else if ((currentTabID == "Tab3") && (bRedemtionLogin=='true')) 
//		      {						
//				    $fn(commonControls).style.display = 'block';
//				    $fn(commonFooter).style.display = 'block';
//				    $fn(tabID).style.display = 'none';
//				    $fn(singleLeg).style.display = 'block';
//				    $fn(multiLeg).style.display = 'none';
//				    $fn(RedemptionFooter).style.display = 'none';
//			   }
//			   else 
//			   {
//                    $fn(tabID).style.display = 'block';
//                    $fn(commonControls).style.display = 'block';
//                    $fn(multiLeg).style.display = 'block';
//                    $fn(singleLeg).style.display = 'none';
//                    $fn(commonFooter).style.display = 'block';
//                    $fn(RedemptionFooter).style.display = 'none';			                    
//                }
//		     }
//        else
//	     {	 
//	        $fn(tabID).style.display = 'none';
//	     }
//	 }
//}	 
	 
//	Function to  hide DropDowns  below the calendar layer when calendar popup is open ( for IE6 browser  )
function hideDropDowns(){
	var invisibleFields = hideDropDowns.arguments;	
	if(invisibleFields.length == 0)
	{
		invisibleFields = $fn(commonControls).getElementsByTagName("SELECT");
		for (var i = 0; i < invisibleFields.length; i++){
			finalval = $fn(invisibleFields[i].id);
			if (finalval != null) {
				finalval.style.visibility = "hidden";				
			}
		}
	} else {		
		for (var i = 0; i < invisibleFields.length; i++) {
			var fieldName = invisibleFields[i];		
			finalval = $fn(fieldName);
			if (finalval != null) {
				finalval.style.visibility = "hidden";				
			}
		}
	}	
}

//	Function to  show DropDowns below the calendar layer when calendar popup is open ( for IE6 browser  )
function showDropDowns()
{
	if(ie6) {		
		var visibleFields = showDropDowns.arguments;		
		if(visibleFields.length == 0) {
			visibleFields = $fn(commonControls).getElementsByTagName("SELECT");
			for (var i = 0; i < visibleFields.length; i++) {
					finalval = $fn(visibleFields[i].id);
					if (finalval != null){
						finalval.style.visibility = "visible";				
					}
			}
		} else {			
			for (var i = 0; i < visibleFields.length; i++) {
					finalval = $fn(visibleFields[i]);
					if (finalval != null){
						finalval.style.visibility = "visible";				
					}
			}
		}
		
		if (($fn(autosuggest) != null) && ($fn(autosuggest).style.display == "none")) {
			visibleFields = $fn(commonControls).getElementsByTagName("SELECT");
			for (var i = 0; i < visibleFields.length; i++) {
					finalval = $fn(visibleFields[i].id);
					if (finalval != null){
						finalval.style.visibility = "visible";				
					}
			}
		}
	}	
}

// 	Function to reset the label colors 
function resetLabelColor() 
{	
	if($fn(autosuggest) != null) 
	{
    	if(typeof(destDiv) != "undefined")
	    {
	        RemoveClassName(destDiv, "errorText");
	    }
	}
	RemoveClassName(aDiv, "errorText");
    RemoveClassName(dDiv, "errorText");
    RemoveClassName(nDiv, "errorText");
}

// 	Function set the old values for ArrivalDate, DepartureDate, NoOfNight and destination
function setDefaultFields(val) 
{	
    switch(val)
    {
        // If validation fails for arrival date then
        // set the old value back to the arrival date
        // by calculating it from depature date and no of night
        case "Arrival":
            var dateArray   = dt.value.split(CONST_DATE_SEP);
            var depDate     = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
            var oldArrival  = DateDiff("d", nt.value, depDate);
            
            var month=parseInt(oldArrival.getMonth())+1;
	        var year = parseInt(oldArrival.getYear());
	        if(navigator.appName == "Netscape")
	        {
		        year = year+1900;       
	        }
	        
	        var strOldArrDay = oldArrival.getDate();
	        if (strOldArrDay < 10)
	        {
		        strOldArrDay = "0"+ strOldArrDay;
	        }
	        if (month < 10)
	        {
		        month = "0"+ month;
	        }
	        var strOldArrival = strOldArrDay+"/"+month+"/"+year;  
            at.value = strOldArrival;
            break;
            
        // If validation fails for departure date then
        // set the old value back to the departure date
        // by calculating it from arrival date and no of night
        case "Departure":
            var dateArray   = at.value.split(CONST_DATE_SEP);
            var arrDate     = new Date(dateArray[2], dateArray[1] - 1, dateArray[0]);
            var oldDep  = DateAdd("d", nt.value, arrDate);
            
            var month=parseInt(oldDep.getMonth())+1;
	        var year = parseInt(oldDep.getYear());
	        if(navigator.appName == "Netscape")
	        {
		        year = year+1900;       
	        }
	        var strOldDepDay = oldDep.getDate();
	        if (strOldDepDay < 10)
	        {
		        strOldDepDay = "0"+ strOldDepDay;
	        }
	        if (month < 10)
	        {
		        month = "0"+ month;
	        }
	        var strOldDep = strOldDepDay+"/"+month+"/"+year;  
            dt.value = strOldDep;
            break;
       
    }
	if(typeof(dest) != "undefined")
	{	
	    dest.value = "";
	}
}

function DateAdd(timeU, byMany, dateObj) 
{
	var millisecond=1;
	var second=millisecond*1000;
	var minute=second*60;
	var hour=minute*60;
	var day=hour*24;
	var year=day*365;

	var newDate;
	var dVal=dateObj.valueOf();
	switch(timeU) 
	{
		case "ms": newDate=new Date(dVal+millisecond*byMany); break;
		case "s": newDate=new Date(dVal+second*byMany); break;
		case "mi": newDate=new Date(dVal+minute*byMany); break;
		case "h": newDate=new Date(dVal+hour*byMany); break;
		case "d": newDate=new Date(dVal+day*byMany); break;
		case "y": newDate=new Date(dVal+year*byMany); break;
	}
	return newDate;
}

function DateDiff(timeU, byMany, dateObj) 
{
	var millisecond=1;
	var second=millisecond*1000;
	var minute=second*60;
	var hour=minute*60;
	var day=hour*24;
	var year=day*365;

	var newDate;
	var dVal=dateObj.valueOf();
	switch(timeU) 
	{
		case "ms": newDate=new Date(dVal-millisecond*byMany); break;
		case "s": newDate=new Date(dVal-second*byMany); break;
		case "mi": newDate=new Date(dVal-minute*byMany); break;
		case "h": newDate=new Date(dVal-hour*byMany); break;
		case "d": newDate=new Date(dVal-day*byMany); break;
		case "y": newDate=new Date(dVal-year*byMany); break;
	}
	return newDate;
}


// 	Function set the default values for ArrivalDate and DepartureDate 
function setDefaultFields1() 
{        
	var defaultArrivalDate = sysDate;
	var defaultDepartureDate = addDays(sysDate,1);       
	at1.value = defaultArrivalDate;
	dt1.value = defaultDepartureDate;
}

//	Function to strip the string's characters from the bag
function stripCharsInBag(s, bag)
{

    var returnString = "";
    // Search through string's characters one by one.If character is not in bag, append to returnString.
    for (var i = 0; i < s.length; i++)
    {   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year)
{
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}


function differenceDay(depDate,arrDate) 
{
    var dateArray1 = depDate.split("/");
    var dateArray2 = arrDate.split("/");
    var newDate1 = new Date(dateArray1[2],dateArray1[1]-1,dateArray1[0]);
    var newDate2 = new Date(dateArray2[2],dateArray2[1]-1,dateArray2[0]);           
    var dayDiff ;
	var diffInMilliSec = newDate1.getTime() - newDate2.getTime();
	var milliSecInDay = 24*60*60*1000;	

	if ((diffInMilliSec % milliSecInDay == 0)  || (((diffInMilliSec % milliSecInDay)/milliSecInDay) < 0.499)) {
		dayDiff = (diffInMilliSec / milliSecInDay);
	} else {
		dayDiff = (diffInMilliSec / milliSecInDay) + 1;
	}	

	return Math.floor(dayDiff);      
}

/*------------------------------------ COOKIE MANIPULATION ------------------------------------*/
/*---------------------------------------------------------------------------------------------*/

// name - name of the cookie
// value - value of the cookie
// [expires] - expiration date of the cookie (defaults to end of current session)
// [path] - path for which the cookie is valid (defaults to path of calling document)
// [domain] - domain for which the cookie is valid (defaults to domain of calling document)
// [secure] - Boolean value indicating if the cookie transmission requires a secure transmission
// * an argument defaults when it is assigned null as a placeholder
// * a null placeholder is not required for trailing omitted arguments
function setCookie( name, value, expires, path, domain, secure ) 
{
    
    // BUG FIX: artf695582 | Free Night is not coming as selected in refine search module. 
    // Deleting the cookie with the name, so that we are not 
    // accidentally adding duplicate cookie with same name.
    deleteCookie(name, '/', '');
    
    var expires_date = new Date( today.getTime() + (1 * 20 * 60 * 1000) );

    var currCookie = name + "=" +escape( value ) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
    
    document.cookie = currCookie;
}

// name - name of the desired cookie
// * return string containing value of specified cookie or null if cookie does not exist
function getCookie( name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed name
		if ( cookie_name == name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

// name - name of the cookie
// [path] - path of the cookie (must be same as path used to create cookie)
// [domain] - domain of the cookie (must be same as domain used to create cookie)
// * path and domain default if assigned null or omitted if no explicit argument proceeds
function deleteCookie( name, path, domain ) 
{
    if ( getCookie( name ) ) document.cookie = name + "=" +
    ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

/**
	Using this function we can read a browser cookie.
	@param: name of the cookie.
	@return: If cookie of passed cookie name exists it will return the cookie value 
			 Else method will return the null.

**/

function readBrowserCookie(name) {
		
	var nameEQ = name + "=";
	var cookieValue = null;
	var ca = document.cookie.split(';');
	
	for(var i=0;i < ca.length;i++) {
		
		var c = ca[i];
		
		while (c.charAt(0)==' ') {
				c = c.substring(1,c.length);
		}

		if (c.indexOf(nameEQ) == 0) {
				cookieValue = c.substring(nameEQ.length,c.length);
		}
	}		
	return cookieValue;  
}
