var dom = (document.getElementById) ? 1:0 //ie5 - n6
var ie = (document.all)? true : false;
var n6 = (document.getElementById)? true : false;

var dateRegEx = [new RegExp(/^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$/),
                 new RegExp(/^(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))-[0-9]{4}$/), 
                 new RegExp(/^[0-9]{4}-(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))$/),
                 new RegExp(/^(((0[13578]|(10|12))-(0[1-9]|[1-2][0-9]|3[0-1]))|(02-(0[1-9]|[1-2][0-9]))|((0[469]|11)-(0[1-9]|[1-2][0-9]|30)))-[0-9]{4}$/)];

var arrayOfStates = ["AK", "AL", "AR", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "GA", "HI", "IA", "ID", "IL", "IN", "KS", "KY",
					 "LA", "MA", "MD", "ME", "MI", "MN", "MO", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH",
					 "OK", "OR", "PA", "PR", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY"];
var arrayOfProvinces = ["AB", "BC", "LB", "MB", "NB", "NF", "NL", "NS", "NT", "NU", "ON", "PE", "PQ", "SK", "YT"];

function isKeyPressed(_event, _keyNumberToValidate)
{
    var eventObj = _event;
    if(eventObj == null)
    {
        eventObj = window.event;
    }
   
    var nKeyCode = GetKeyPressedValue(eventObj);
    if(eventObj != null && 
       nKeyCode == _keyNumberToValidate) 
    {
        return true;
    }
    
    return false;
}
function getWindowWidth()
{
    if (parseInt(navigator.appVersion)>3) 
    {
        /*if (n6)
        {
            return window.innerWidth;
        }
        else if (ie) 
        {*/

            return document.body.offsetWidth;
        //}
    }
    return -1;
}
function getWindowHeight()
{
    if (parseInt(navigator.appVersion)>3) 
    {
         /*if (n6) 
            return window.innerHeight;
         else if (ie) */
            return document.body.offsetHeight;
    }
    return -1;
}
function getElement(_elemID)
{
    /*var elem = $get(_elemID);
    
    return elem;*/
    if(ie)
    {
        var elem = document.all[_elemID];
        if(elem == null)
        {
            elem = document.getElementById(_elemID);
        }
        return elem;
    }
    else if(n6)
    {
        return document.getElementById(_elemID);
    }
}

// this function uses an element, not an ID
function IsVisible( _element )
{
    if ( _element.style.visibility == "hidden" )
    {
        return false;
    }
    else if ( _element.parentElement )
    {
        return IsVisible( _element.parentElement );
    }
    else
    {
        return true;
    }
}

function SetFocus(_elementID)
{
    var elem = getElement(_elementID);
    if(elem != null && IsVisible( elem ) )
    {
        elem.focus();
    }
}
function findPosX(_obj)
{
	var curleft = 0;
	if (_obj.offsetParent)
	{
		while (_obj.offsetParent)
		{
			curleft += _obj.offsetLeft - _obj.scrollLeft;
			_obj = _obj.offsetParent;
		}
	}
	else if (_obj.x)
	{
		curleft += _obj.x;
    }

	return curleft;
}

function findPosY(_obj)
{
	var curtop = 0;
	if (_obj.offsetParent)
	{
		while (_obj.offsetParent)
		{
			curtop += _obj.offsetTop - _obj.scrollTop;
			_obj = _obj.offsetParent;
		}
	}
	else if (_obj.y)
	{
		curtop += _obj.y;
    }
    
	return curtop;
}

function validateDateFormat(_textBoxID)
{        
    var textBox = getElement(_textBoxID);
    if(textBox != null)
    {
        var value = textBox.value;
    
        if( !isValidDateFormat(value) )
        {
            alert("Please use '" + defaultCalendarDateFormatValue[dualCalendarDateFormatID] + "' date format.");
            textBox.value = defaultCalendarDateFormatValue[dualCalendarDateFormatID];
            textBox.select();
        }
    }
}
function isValidDate(_value)
{
    var isValid = false;
    
    if(_value != null && _value != "")
    {
        if(_value.match(dateRegEx[dualCalendarDateFormatID]))
        {
            isValid = true;
        }
    }
        
    return isValid;
}
function isValidDateFormat(_value)
{
    if(_value != defaultCalendarDateFormatValue[dualCalendarDateFormatID] && !_value.match(dateRegEx[dualCalendarDateFormatID]))
    {
        return false;
    }
    
    return true;
}
function isInvalidDateFormatOrDefaultFormat(_value)
{
    if(_value == defaultCalendarDateFormatValue[dualCalendarDateFormatID] || !_value.match(dateRegEx[dualCalendarDateFormatID]))
    {
        return true;
    }
    
    return false;
}

function getParentElement(_elemID)
{
    if(ie)
    {
        var elem = parent.document.all[_elemID];
        if(elem == null)
        {
            elem = parent.document.getElementById(_elemID);
        }
        
        return elem;
    }
    else if(n6)
    {
        return parent.document.getElementById(_elemID);
    }
}

function showIFrame(_frameObject)
{
    if ( _frameObject.style.visibility == 'hidden' )
    {
        _frameObject.style.display = 'block';
        _frameObject.style.visibility = 'visible';
    }
}

function hideIFrame(_frameObject)
{
    if ( _frameObject.style.visibility == 'visible' )
	{
        _frameObject.style.display = 'none';
        _frameObject.style.visibility = 'hidden';
    }
}

function getIFrame(_elemID)
{
    return getElement(_elemID);
}

function resetDropDownToValue(_ddID, _value)
{
    var dropDown = getParentElement(_ddID);
    var i = 0;
    for(i; i<dropDown.options.length; i++)
    {
        if(dropDown.options[i].value == _value)
        {
            dropDown.selectedIndex = i;
            i = dropDown.options.length+1;
        }
    }
}
function SetDropDownToIndex(_ddID, _index)
{
    var dd = getElement(_ddID);
    if(dd != null)
    {
        dd.selectedIndex = _index;
    }
}
function showMenu(_id)
{

    var elem = getElement(_id);
    if(elem != null)
    {
        elem.style.display = "block";
        elem.style.visibility = "visible";
    }
}

function hideMenu(_id)
{
    var elem = getElement(_id);
    if(elem != null)
    {
        elem.style.display = "block";
        elem.style.visibility = "hidden";
    }
}

function hideMenuWithNoBlock(_id)
{

    var elem = getElement(_id);
    if(elem != null)
    {
        elem.style.display = "none";
        elem.style.visibility = "hidden";
    }
}
function showMenuWithNoBlock(_id)
{
    var elem = getElement(_id);
    if(elem != null)
    {
        elem.style.display = "block";
        elem.style.visibility = "visible";
    }
}

function swapVisibilityWithNoBlockAndChangeBtnText(_id, _btnId, _textToShow, _textToHide)
{
    var elem = getElement(_id);
    var btnElem = getElement(_btnId);
    if(elem != null && btnElem != null)
    {
        if(elem.style.visibility == "visible")
        {
            hideMenuWithNoBlock(_id);
            btnElem.value = _textToShow;
        }
        else
        {    
            showMenuWithNoBlock(_id);
            btnElem.value = _textToHide;
        }
    }
}

function swapVisibilityWithNoBlock(_id)
{
    var elem = getElement(_id);
    if(elem != null)
    {
        if(elem.style.visibility == "visible")
            hideMenuWithNoBlock(_id);
        else
            showMenuWithNoBlock(_id);
    }
}
function swapVisibilityWithBlock(_id)
{
    var elem = getElement(_id);
    if(elem != null)
    {
        if(elem.style.visibility == "visible")
            hideMenu(_id);
        else
            showMenu(_id);
    }
}
function randomString(_nLength) 
{
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
	var randomstring = '';
	for (var i=0; i<_nLength; i++) 
	{
		var rnum = Math.floor(Math.random() * chars.length);
		randomstring += chars.substring(rnum,rnum+1);
	}
	
	return randomstring;
}	
function addRandomStringToUrl(_sURL)
{
    var toReturn = _sURL;

    var regExDump = new RegExp("dump=[a-z0-9]{12}", "gi");
    var match     = regExDump.exec(toReturn);
    var sReplaceText = "dump=" + randomString(12);
    
    if(match != null && match != "")
    {
        toReturn = toReturn.replace( regExDump, sReplaceText);
    }
    else
    {
        if( toReturn.indexOf('?') == -1 )
            toReturn = toReturn + "?" + sReplaceText;
        else
            toReturn = toReturn + "&" + sReplaceText;
    }

    return toReturn;	
}

/* This function must be called on input field to give focus to the right button */
/* when the Enter key is pressed */
function ClickButtonOnKeyPress(_event, id_button)
{
	var elem = getElement(id_button);
	var nKeyPressed = GetKeyPressedValue(_event);

	if(nKeyPressed )
	{
		if( (nKeyPressed == 13) )  // Enter key
		{
			elem.focus();
			elem.click();
			return true;
		}
	}
	
	return false;
}

function GetKeyPressedValue(_event)
{
    var e = _event ? _event : window.event; 

    if(!e)return;    
 
    var key = e.keyCode||e.which||0;
    
    //alert("keypress "+key);

    return key;
}

function SetObjectInnerText(_sObjName, _sToWrite)
{
	var obj = getElement(_sObjName);
    if(obj)
    {
	    obj.innerText = _sToWrite;
	}
}
/*
function AppendObjectInnerText(_sObjName, _sToWrite)
{
	var obj = getElement(_sObjName);
    if(obj)
    {
	    if(ie)
	    {
		    obj.innerText += _sToWrite;
	    }
	    else
	    {	
		    obj.innerHTML += _sToWrite;
	    }
	}
}*/

function Show(_sObjName) 
{
	var obj = getElement(_sObjName);
    if (obj != null)
    {
        obj.style.visibility = 'visible';
	    if(ie)
	    {
		    obj.style.display    = 'block';
	    }
	    else
	    {
		    obj.style.display    = ''; // otherwise tr does not show correctly
	    }
	}
}

function Hide(_sObjID) 
{
	var obj = getElement(_sObjID);
    if (obj != null)
    {
        obj.style.visibility = 'hidden';
		obj.style.display    = 'none';
	}
}

function HideSectionAndChangeText(_sObjID, _linkID, _strViewLinkText)
{
    Hide(_sObjID);
    var linkObj = getElement(_linkID);
    if(linkObj != null && _strViewLinkText != "")  
	{
	   linkObj.innerText = _strViewLinkText;
	} 
}

function HideSectionAndChangeTextFromArray(_arrayOfObjID, _arrayOfLinkID, _strViewLinkText)
{
    if(_arrayOfObjID != null && _arrayOfLinkID != null && _arrayOfObjID.length == _arrayOfLinkID.length)
    {
      for(i=0; i<_arrayOfObjID.length; i++)
      {
        HideSectionAndChangeText(_arrayOfObjID[i], _arrayOfLinkID[i], _strViewLinkText);
      }
    }
}


// This function will go throught the dd options an set it to the desired selected value
function SetDropDownValue(_ddObj, _sSlcVal)
{
    for(i=0; i<_ddObj.length; i++)
    {
        var ddVal = _ddObj.options[i].value;
        if(ddVal.toUpperCase() == _sSlcVal.toUpperCase())
        {
            _ddObj.options[i].selected = true;
            break;
        }    
    }
}

/* THIS IS A COMMON FUNCTION USED TO HIDE A SECTION WITHOUT AN IMAGE */
function ShowAndHideSection(_lnkShowAllObj, _strObjNameToHide, _strShowLinkText, _strHideLinkText, _bTextShown)
{
	var obj = getElement(_strObjNameToHide);

    var sVisibility = "HIDDEN";
    if(obj.style.visibility != null && obj.style.visibility != "")
        sVisibility = obj.style.visibility.toUpperCase();

    if(sVisibility == "HIDDEN")
    {
	    obj.style.display    = "block";
	    obj.style.visibility = "visible";  
	    if(_strHideLinkText != "" )  
	    {
	        if(_bTextShown == "false")
	            _lnkShowAllObj.innerText = _strHideLinkText;
	        else
	            _lnkShowAllObj.innerText = _strShowLinkText; 
	       
	    }
    }
    else
    {
        obj.style.display    = "none";
	    obj.style.visibility = "hidden";
	    if(_strShowLinkText != "")  
	    {
	        if(_bTextShown == "false")
	            _lnkShowAllObj.innerText = _strShowLinkText;
	        else
	            _lnkShowAllObj.innerText = _strHideLinkText;
	    }
    }
}

function ModifyLinkTextAndLinkToggleSectionWithText(_lnkShowFirstObj, _lnkShowSecondObj,_strObjNameToHide,
                                                     _strShowFirstLinkText, _strHideFirstLinkText,
                                                     _strShowSecondtLinkText, _strHideSecondLinkText)
{
	var obj = getElement(_strObjNameToHide);

    if(!obj.length)
    {    
        var sVisibility = "HIDDEN";
        if(obj.style.visibility != null && obj.style.visibility != "")
            sVisibility = obj.style.visibility.toUpperCase();

        if(sVisibility == "HIDDEN")
        {
	        obj.style.display    = "block";
	        obj.style.visibility = "visible";  
	        if(_strHideFirstLinkText != "" && _strHideSecondLinkText)  
	        {
	            _lnkShowFirstObj.innerText = _strHideFirstLinkText;
	            _lnkShowSecondObj.innerText = _strHideSecondLinkText;
	        }
        }
        else
        {
            obj.style.display    = "none";
	        obj.style.visibility = "hidden";
	        if(_strShowFirstLinkText != "" && _strHideSecondLinkText)  
	        {
	            _lnkShowFirstObj.innerText = _strShowFirstLinkText;
	            _lnkShowSecondObj.innerText = _strShowSecondtLinkText;
	        }
        }
    }
    else
    {
        for(i = 0; i < obj.length; i++)
        {
            var sVisibility = "HIDDEN";
            if(obj[i].style.visibility != null && obj[i].style.visibility != "")
                sVisibility = obj[i].style.visibility.toUpperCase();

            if(sVisibility == "HIDDEN")
            {
	            obj[i].style.display    = "block";
	            obj[i].style.visibility = "visible";  
	            if(_strHideFirstLinkText != "" && _strHideSecondLinkText)  
	            {
	                _lnkShowFirstObj.innerText = _strHideFirstLinkText;
	                _lnkShowSecondObj.innerText = _strHideSecondLinkText;
	            }
            }
            else
            {
                obj[i].style.display    = "none";
	            obj[i].style.visibility = "hidden";
	            if(_strShowFirstLinkText != "" && _strHideSecondLinkText)  
	            {
	                _lnkShowFirstObj.innerText = _strShowFirstLinkText;
	                _lnkShowSecondObj.innerText = _strShowSecondtLinkText;
	            }
            }
        }
    }
}

/* This function should be used with a link object */
function LinkToggleSectionWithText(_lnkShowAllObj, _strObjNameToHide, _strShowLinkText, _strHideLinkText, _bTextShown)
{	
	ShowAndHideSection(_lnkShowAllObj, _strObjNameToHide, _strShowLinkText, _strHideLinkText, _bTextShown);
}
/* This function will not change the link text */
function LinkToggleSection(_lnkShowAllObj, _strObjNameToHide)
{	
    ShowAndHideSection(_lnkShowAllObj, _strObjNameToHide, '', '');
}

function LinkToggleText(_lnkShowAllObj, _strShowLinkText, _strHideLinkText)
{
    if(_strShowLinkText  != null && _strHideLinkText != null)
    {
        if(_lnkShowAllObj.innerText = _strShowLinkText)
        {
            _lnkShowAllObj.innerText = _strHideLinkText;
        }
        else if(_lnkShowAllObj.innerText = _strHideLinkText)
        {
            _lnkShowAllObj.innerText = _strShowLinkText;
        }
    }
}

/* THIS IS A COMMON FUNCTION USED TO HIDE A SECTION WITHOUT AN IMAGE */
function ShowSection(_sObjNameToHideIn, _bIsSectionShowed)
{
	var obj    = getElement(_sObjNameToHideIn);
    if (obj != null)
    {
	    if(_bIsSectionShowed)
	    {
		    obj.style.display    = "block";
		    obj.style.visibility = "visible";
	    }
	    else
	    {
		    obj.style.display    = "none";
		    obj.style.visibility = "hidden";
	    }
	}
}

function ShowSectionInline(_sObjNameToHideIn, _bIsSectionShowed)
{
	var obj    = getElement(_sObjNameToHideIn);    
	if (obj != null)
    {
        obj.style.display    = "block";
        if(_bIsSectionShowed)
	    {
		    obj.style.visibility = "visible";
	    }
	    else
	    {
		    obj.style.visibility = "hidden";
	    }
	    /*
	    var iFrameWait = getElement('if_Waiting');
	    if(iFrameWait != null)
	    {
	        iFrameWait.style.display = _bIsSectionShowed ? "block" : "none";
	    }*/
	}
}

function ShowSectionDisplayInline(_sObjNameToHideIn, _bIsSectionShowed)
{
	var obj    = getElement(_sObjNameToHideIn);    
	if (obj != null)
    {
        if(_bIsSectionShowed)
	    {
		    obj.style.display    = "block";
		    obj.style.visibility = "visible";
	    }
	    else
	    {
		    obj.style.display    = "inline";
		    obj.style.visibility = "hidden";
	    }
	}
}

function ShowInlineHideNone(_sObjNameToHideIn, _bIsSectionShowed)
{
    var obj    = getElement(_sObjNameToHideIn);    
	if (obj != null)
    {
        if(_bIsSectionShowed)
	    {
		    obj.style.display    = "inline";
		    obj.style.visibility = "visible";
	    }
	    else
	    {
		    obj.style.display    = "none";
		    obj.style.visibility = "hidden";
	    }
	}
}

function DisableElement(_elementToDis )
{
    var obj    = getElement(_elementToDis);
    
    if(obj != null)
    {
        obj.disabled = true;
    }
}

/* Functions used in the thumbnails system */

var ie=document.all
var ns6=document.getElementById&&!document.all

var ImageMaxWidth = 400;

function showImage(src, e)
{
    // the following code get the real size of the selected image
    photo = new Image();
    photo.src = src ;
    var WindowWidth = getWindowWidth();
    
    var ImageToShowWidth;
    var ImageToShowHeight;
    var ImagePositionX;
    var ImagePositionY;
    if (ie||ns6)
    {
        crossobj=document.getElementById? document.getElementById("showImage") : document.all.showImage
        // Implement the treatment to have the image centered and of the good size (if too big)
        if (photo.width > ImageMaxWidth)
        {
            var ratio = photo.width / ImageMaxWidth;
            ImageToShowHeight = parseInt(photo.height / ratio);
            ImageToShowWidth = ImageMaxWidth;
        }
        else
        {
            ImageToShowHeight = photo.height;
            ImageToShowWidth = photo.width;
        }
        // Image size is ok, now we calculate the position of the tooltip to be sure it will not be outside screen
        ImagePositionX = parseInt((WindowWidth/2) - (ImageToShowWidth/2));            
        ImagePositionY = parseInt(ns6? e.pageY : event.y+document.body.scrollTop) + 20;                
        
        crossobj.style.left=ImagePositionX+"px";
        crossobj.style.top=ImagePositionY+"px";
        //alert(ImagePositionX + "px, " + ImagePositionY + "px " + '<img src="'+src+'" width=' + ImageToShowWidth + ' height=' + ImageToShowHeight + '>');
        crossobj.innerHTML='<img src="'+src+'" width=' + ImageToShowWidth + ' height=' + ImageToShowHeight + '>';
        crossobj.style.visibility="visible";
        return false;
    }
    else
        return true;
}

function hideImage(){
    crossobj.style.visibility="hidden";
}

/*
This will return the value of a given query string 
ie: if _sQueryStringValue = module will return air
http://localhost/TSGWebServicesWebApp/SearchResults.aspx?module=air&step=search&tab=ShowAll&index=0
*/
function GetQueryVariable(_sQueryStringValue)
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    
    for (var i=0;i<vars.length;i++)
    {
        var pair = vars[i].split("=");       
        if (pair[0] == _sQueryStringValue)
        {
            return pair[1];
        }
    }
} 

/*This function is used to display the popup used to print the itinerary*/
function showItineraryDetails(uniqueId, typeOfObject)
{
    window.open(FormatLinkUrl("/HotelDetails.aspx?uniqueID="+uniqueId+"&typeOfObject="+typeOfObject),"",
        "alwaysRaised=yes,directories=no,location=no,menubar=no,status=no,toolbar=no,z-lock=no,resizable=yes,width=660,scrollbars=yes", false);
    /*window.open("HotelDetails.aspx?uniqueID="+uniqueId+"&typeOfObject="+typeOfObject, "",
        "alwaysRaised=yes,directories=yes,location=yes,menubar=yes,status=yes,toolbar=yes,z-lock=no,resizable=yes,width=800,scrollbars=yes", false);*/
}

/* This function is used to create the images in Itinerary XSL - Tourism. Creates an image from the specified size parameters*/

function CreateImageWithParams(imageUrl, maxWidth, maxHeight)
{
    var img = new Image();
    img.src = imageUrl ; 
    var imgX = img.width;
    var imgY = img.height;
    var newSizeX = 0;
    var newSizeY = 0;
    var imgRatio = imgX / imgY;
    if (parseInt(maxWidth) > 0 && parseInt (maxHeight) > 0)
    {
        newSizeX = parseInt(maxWidth);
        newSizeY = parseInt (maxHeight);
    }
    else
    {
        if (parseInt(maxWidth) > 0)
        {
            newSizeX = parseInt(maxWidth);
            newSizeY = imgY / (imgX / parseInt(maxWidth));
        }
        else if (parseInt(maxHeight) > 0)
        {
            newSizeX = imgX / (imgY / parseInt(maxHeight));
            newSizeY = parseInt (maxHeight);
        }
    }
    return "<img src=\"" + imageUrl + "\" style=\"border-width:0px; width: " + newSizeX + "; height: " + newSizeY + ";\"/>";
}

var mousePositionX;
var mousePositionY;

function RegisterMousePosition(){
	mousePositionX = 0;
	mousePositionY = 0;
	document.onmousemove = MousePosition;
}

function MousePosition(evt){
	if(!evt) evt = window.event;	
	mousePositionX = evt.clientX;
	mousePositionY = evt.clientY;
}

function ShowHideTooltips(_id, _shown, _class)
{
    var elem = getElement(_id);
    if (elem != null)
    {
        if (_shown)
        {
            elem.style.top = mousePositionY + 10;
            elem.style.left = mousePositionX;

            elem.style.visibility = "visible";
            elem.style.display = "inline";

            elem.setAttribute("class", _class); 
            elem.setAttribute("className", _class); 
        }
        else
        {
            elem.style.visibility = "hidden";
            elem.style.display = "none";
        }
    }
}

function ShowHideTooltipsWithCoordsFromCurrentMousPosition(_id, _shown, _class, _posX, _posY)
{
    var elem = getElement(_id);
    if (elem != null)
    {
        if (_shown)
        {
            elem.style.top = mousePositionY + _posY;
            elem.style.left = mousePositionX + _posX;
            
            elem.style.visibility = "visible";
            elem.style.display = "inline";

            elem.setAttribute("class", _class); 
            elem.setAttribute("className", _class); 
        }
        else
        {
            elem.style.visibility = "hidden";
            elem.style.display = "none";
        }
    }
}

function IsStringValueInArray(_arrayOfString, _sValueToFind)
{
	var sVal = "";
	var bFound = false;
	
	for(i=0; i<_arrayOfString.length; i++)
	{
		sVal = _arrayOfString[i];
		if(sVal == _sValueToFind)
		{
			bFound = true;
			break;	
		}
	}
	
	return bFound;
}

function DisplayConfirmBoxAndShowWaiting( _sWaitingPageText, _sConfirmBoxText)
{	//return confirm("Are you sure you want to delete this credit card?");
	var name = confirm(_sConfirmBoxText)	
	if (name==true)
	{
		// You pressed the OK button!
        UpdateWaitingMessageAndShowWaitingPage(_sWaitingPageText, true);
        return true;
	}
	else
	{
		// You pressed the Cancel button!
	    return false;
	}
}

function GetTourHotDealsFromCity(_originCode)
{
    document.forms[0].elements["tour.m.originCode"].value = _originCode;
    document.forms[0].submit();
}

function SelectValueInDDLForTourHotDeals(_id)
{
    var elem = getElement(_id);
    if (elem != null)
    {
        elem.selected = true;
    }
}

function GetTourHotDealsResults(originCode, destinationCodeList, departureDate, duration, daysAllowedBefore, daysAllowedAfter, tourOperatorsList, hotelName, maximumResults, minimumPrice, maximumPrice, minimumStarRating, maximumStarRating, amenitiesList, mealPlanType, preDefinedRequest)
{
	document.forms[0].elements["tour.m.originCode"].value = originCode;
	document.forms[0].elements["tour.m.destinationCodeList"].value = destinationCodeList;
	document.forms[0].elements["tour.m.departureDate"].value = departureDate;
	document.forms[0].elements["tour.m.tripDuration"].value = duration;
	document.forms[0].elements["tour.o.daysAllowedAfter"].value = daysAllowedAfter;
	document.forms[0].elements["tour.o.daysAllowedBefore"].value = daysAllowedBefore;
	document.forms[0].elements["tour.o.tourOperatorsList"].value = tourOperatorsList;
	document.forms[0].elements["tour.o.hotelName"].value = hotelName;
	document.forms[0].elements["tour.o.maximumResults"].value = maximumResults;
	document.forms[0].elements["tour.o.minimumPrice"].value = minimumPrice;
	document.forms[0].elements["tour.o.maximumPrice"].value = maximumPrice;
	document.forms[0].elements["tour.o.minimumStarRating"].value = minimumStarRating;
	document.forms[0].elements["tour.o.maximumStarRating"].value = maximumStarRating;
	document.forms[0].elements["tour.o.amenitiesList"].value = amenitiesList;
	document.forms[0].elements["tour.o.mealPlanType"].value = mealPlanType;
	document.forms[0].elements["tour.o.preDefinedRequest"].value = preDefinedRequest;
	document.forms[0].elements["SearchType"].value = "tour2";
	document.forms[0].action = document.forms[0].elements["fileToCall"].value;
	document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
	document.forms[0].submit();
}

function IsNullOrEmpty(_value)
{
    if(_value == null || _value.length == 0 || _value =="")
        return true;
    return false;
}

/*function ContainsString(_sSource, _sToFind)
{   
    var regExSearchString = new RegExp("["+_sToFind+"]","g");
    return _sSource.match(regExSearchString);
}*/

function OpenPopupWithObjectProperties(_obj)
{
    pop=window.open('about:blank');
    pop.document.write(GetObjectProperties(_obj));
}

function GetObjectProperties (object) 
{
    var result = '';
    for (var property in object) 
    {
        result += property + ': ' + object[property] + '<br />';
    }

    return result;
}

// this will set focus to the button when the ENTER (13) key is pressed
// and will act has if user clicked on the button
// ex: search panel vs login form
function SetDefaultButtonFocus(_event, _btnID)
{   
    var btn = getElement(_btnID);
    if(btn != null)
    {
        if(btn.disabled == false)
        {
            switch(_event.type)
            {
                case "keypress":
                    if(isKeyPressed(_event, 13)) 
                    {       
                        // cancel the default submit
                        //_event.returnValue = false;
                        //_event.cancel = true;

                        btn.focus();
                    } 
                    break;
                    
                case "click":     
                    //btn.focus();
                    break;                    
            }
        }
    }
}

function SetInnerHTMLToHTMLElement(_id, _text)
{
    var elem = getElement(_id);
    if (elem != null)
    {
        elem.innerHTML = "";
        elem.innerHTML = _text;
    }
}

function SetValueToHTMLFormInput(_id, _value)
{
    var elem = getElement(_id);
    if (elem != null)
    {
        elem.value = "";
        elem.value = _value;
    }
}


//addEvent(window, 'load', function(){ document.getElementById('myfield').focus() }); 

function addEvent(obj, evType, fn)
{ 
    if (obj.addEventListener){ 
        obj.addEventListener(evType, fn, true); 
        return true; 
    }else if (obj.attachEvent){ 
        var r = obj.attachEvent("on"+evType, fn); 
        return r; 
    } 
    else{ 
        return false; 
    } 
} 
function removeEvent(obj, evType, fn)
{
    if(obj.removeEventListener){
        obj.removeEventListener(evType, fn, false);
    }
    else if(obj.detachEvent){
        obj.detachEvent("on"+evType, obj[type+fn]);
        obj[evType+fn]=null;
        obj["e"+evType+fn]=null;
    }
}
function getElementHeight(elementId) 
{
    var xPos = null;
    	
    var elem = getElement(elementId)
    
//    if (op5) 
//    { 
//        xPos = elem.style.pixelHeight;
//    } 
    
    xPos = elem.offsetHeight;
    
    return xPos;
}

function getElementWidth(elementId) 
{
	var xPos = null;
	
	var elem = getElement(elementId);
//	if (op5) 
//	{
//		xPos = elem.style.pixelWidth;
//	} 
		
	xPos = elem.offsetWidth;
	
    return xPos;
}

function IsArray(_obj) 
{
   if (_obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

/// -1 indicates the current checkbox in the _arrayOfCheckBoxesStatus
function BookingCheckboxEnabler(_arrayOfCheckBoxesIDs, _arrayOfCheckBoxesStatus)
{
    // array size must match
    if(IsArray(_arrayOfCheckBoxesIDs) & IsArray(_arrayOfCheckBoxesStatus))
    {
        if(_arrayOfCheckBoxesIDs.length == _arrayOfCheckBoxesStatus.length)
        {
            var nSize = _arrayOfCheckBoxesIDs.length;
            for(i=0; i<nSize; i++)
            {
                var cb = document.getElementById(_arrayOfCheckBoxesIDs[i]);
                var val = _arrayOfCheckBoxesStatus[i];
                if(val == 1)
                   cb.checked = true;
                else if( val == 0)
                   cb.checked = false;                                  
            }
        }
        else
        {
            alert("Array size does not match");
        }
    }
    else
    {
        alert("Expecting array has parameters");
    }
}

function GroupBooking_HideAllPassengerSections(_idDiv, _numberOfPax, _idTab, _class)
{
    for(i=0; i<_numberOfPax; i++)
    {
        var elem = getElement(_idDiv + i);
        if (elem != null)
        {
            ShowSection(_idDiv + i, false);
        }
        
        var elemTab = getElement(_idTab + i);
        if (elemTab != null)
        {
            SetClassToElement(_idTab + i, _class);
        }
    }
    
    // move back to top of the screen
    window.scrollTo(0,0);
}

function SetClassToElement(_id, _classToApply)
{
    var elem = getElement(_id);
    if (elem != null)
    {
        elem.setAttribute("class", _classToApply); 
        elem.setAttribute("className", _classToApply);
    }
}

//These Functions is used to display popup windows for Deck plan 
function showCuiseDeckDetails1(ImageDeck)
{
    window.open(ImageDeck, "mywindow","resizable=1,scrollbars=1,width=150,height=4000");
}
function showCuiseDeckDetails2(ImageDeck)
{
    window.open(ImageDeck, "mywindow","resizable=1,scrollbars=1,width=490,height=150");
}

//This function allows you to enable a checkbox based on the status of another checkbox
function EnableCheck2IfCheck1IsSelected(_checkbox1ID, _checkbox2ID)
{
    var checkbox1 = getElement(_checkbox1ID);
    var checkbox2 = getElement(_checkbox2ID);
    if (checkbox1 != null && checkbox2 != null)
    {
        //alert('prout3');
        if (checkbox1.checked == true)
        {
            checkbox2.disabled = false;
        }
        else
        {
            checkbox2.disabled = true;
        }
    }
}
function EnableCheck2AndCheck1IfCheckIsSelected(_checkboxID, _checkbox1ID, _checkbox2ID)
{
    var checkbox = getElement (_checkboxID);
    var checkbox1 = getElement(_checkbox1ID);
    var checkbox2 = getElement(_checkbox2ID);
    if (checkbox != null && checkbox1 != null && checkbox2 != null)
    {
        //alert('prout3');
        if (checkbox.checked == true)
        {
            checkbox1.disabled = false;
            checkbox2.disabled = false;
        }
        else
        {
            checkbox1.disabled = true;
            checkbox2.disabled = true;
        }
    }
}

function DisableEnableCheckboxOnload(_clientIDArray)
{
    var array = _clientIDArray;
    var arraySize = _clientIDArray.length;
    var i = 0;
    
    for(i;i<arraySize;i++)
    {
        var stringArray = array[i].split(" ");
        var checkbox = getElement(stringArray[0]);
        var enabled = parseInt(stringArray[1]);
        
        if(enabled == 0)
        {
            checkbox.disabled = true;
        }
        else if(enabled == 1)
        {
            checkbox.disabled = false;
        }
    }
}

function DisableDDL2DependingOnDDL1(_DDL1ID, _DDL2ID)
{
    var dropDownList1 = getElement(_DDL1ID);
    var dropDownList2 = getElement(_DDL2ID);
    
    if(dropDownList1 != null && dropDownList2 != null)
    {
        if(dropDownList1.selectedIndex == 0)
        {
            dropDownList2.disabled = true;
            dropDownList2.selectedIndex = 0;
        }
        else
        {
            dropDownList2.disabled = false;
        }
    }
}

function EnableDataListBasedOnCheckBox(_dataListID, _checkboxID)
{
    var datalist = getElement(_dataListID);
    var checkbox = getElement(_checkboxID);
    if (datalist != null && checkbox != null)
    {
        if (checkbox.checked == true)
        {
            datalist.setAttribute("disabled", "");
        }
        else
        {
            datalist.setAttribute("disabled", "disabled");
        }
    }
}

//Given the Array of clientID hide/show according to the value passed
function hideShowElementsOnInit(_clientIDArray, _hide)
{
    var array = _clientIDArray;
    var arraySize = _clientIDArray.length;
    var i = 0;
    
    for(i;i<arraySize;i++)
    {
        hideShowElements(array[i], _hide);
    }
}

//Given the Array of clientID hide/show on click of checkbox
function hideShowElementsBasedOnCheckBox(_clientIDArray, _checkboxID)
{
    var array = _clientIDArray;
    var arraySize = _clientIDArray.length;
    var i = 0;
    var checkbox = getElement(_checkboxID);
    
    if (checkbox != null)
    {
        for(i;i<arraySize;i++)
        {
            if (checkbox.checked == true)
            {
                hideShowElements(array[i], 0);
            }
            else
            {
                hideShowElements(array[i], 1);
            }
        }
    }
}

function hideShowElements(_objId, _hide)
{
    var element = getElement(_objId);
    if(element != null)
    {
        if(_hide)
        {
            element.style.visibility = 'hidden';
            element.style.display = "none";
        }
        else
        {
            element.style.visibility = 'visible';
            element.style.display = "block";
        }
    }
}

//Given the Array of clientID (that reside in a datalist) enable/disable on click of checkbox
function DisableEnableDataListBasedOnCheckBox(_clientIDArray, _checkboxID)
{
    var array = _clientIDArray;
    var arraySize = _clientIDArray.length;
    var i = 0;
    var checkbox = getElement(_checkboxID);
    
    if (checkbox != null)
    {
        for(i;i<arraySize;i++)
        {
            if (checkbox.checked == true)
            {
                disableAnchor(array[i], 0);
            }
            else
            {
                disableAnchor(array[i], 1);
            }
        }
    }
}

//pass it an element client ID and 0 for enable or 1 for disable.
function disableAnchor(objId, disable)
{
    var obj = document.getElementById(objId);
    if(obj != null)
    {
        if(disable)
        {
            var href = obj.getAttribute("href");
            var onclick = obj.getAttribute("onclick");
            //First we store previous value in a new attribute
            if(href && href != "" && href != null)
            {
                obj.setAttribute('href_bak', href);
            }
            if(onclick != null)
            {
                obj.setAttribute('onclick_back', onclick);
                obj.setAttribute('onclick', "void(0);");
            }
            obj.removeAttribute('href');
            obj.style.color="gray";
        }
        else
        {
            var hrefBack = obj.getAttribute("href_bak");
            var onclickBack = obj.getAttribute("onclick_back");
            if(onclickBack !=null )
            {
                obj.setAttribute('onclick', onclickBack);
                obj.removeAttribute('onclick_back');
            }
            if(hrefBack !=null )
            {
                obj.setAttribute('href', hrefBack);
                obj.removeAttribute('href_bak');
                obj.style.color="blue";
            }
        }
    }
}  

/*When the Button Link is clicked, we take the selected value 
from the drop down list and add it to the textBox*/
function ModifyTxtBoxOnBtnClick(_linkBtnID, _dropDownListID, _textBoxID, _labelID)
{
    var linkBtn = getElement(_linkBtnID);
    var dropDownList = getElement(_dropDownListID);
    var textBox = getElement(_textBoxID);
    var errorlabel = getElement(_labelID);
    
    if (linkBtn != null && dropDownList != null && textBox != null)
    {
        var selectedValue = dropDownList.options[dropDownList.selectedIndex].value;
        
        if(selectedValue == -1)
        {
            if(ie)
            {
                errorlabel.innerText = "You must pick a CommandFieldID";
            }
            else if(n6)
            {
                errorlabel.textContent = "You must pick a CommandFieldID";
            }
        }
        else
        {
            if(ie)
            {
                errorlabel.innerText = "";
            }
            else if(n6)
            {
                errorlabel.textContent = "";
            }
            
            if (document.selection) 
            {
                textBox.focus();
                sel = document.selection.createRange();
                sel.text = "{" + selectedValue + "}";
            }
            else if (textBox.selectionStart || textBox.selectionStart == '0') 
            {
                var startPos = textBox.selectionStart;
                var endPos = textBox.selectionEnd;
                textBox.value = textBox.value.substring(0, startPos)
                                + "{" + selectedValue + "}"
                                + textBox.value.substring(endPos, textBox.value.length);
            } 
            else 
            {
                textBox.value += "{" + selectedValue + "}";
            }
        }
    }
}

function ValidateInsuranceOption(source, args)
{
	var tblInsuranceOption = null;

	tblInsuranceOption = document.getElementById('insuranceOption');
	
	if(tblInsuranceOption != null)
	{
		arrayOfInputs = tblInsuranceOption.getElementsByTagName('input');
		var i = 0;
		var bIsRadioSelected = false;

		for (i = 0; i < arrayOfInputs.length; i++) 
		{
			var input     = arrayOfInputs[i];
			var inputType = input.type;

			if(inputType == "radio")
			{	
				if(input.checked == true)
				{
					if(input.value == "DeclineInsurance")
					{
						ShowSection('TableCreditCardInfo', false);
					}
					else
					{
						ShowSection('TableCreditCardInfo', true);
					}
					
					bIsRadioSelected = true;
				}
			}
		}
	}
	
	args.IsValid = bIsRadioSelected;
}

function GetNumberOfDayBetweenDates(_startDateId, _endDateId)
{
    var cdt_pickupDate = document.getElementById(_startDateId);
    var cdt_dropoffDate = document.getElementById(_endDateId);
    
    if(!isValidDate(cdt_pickupDate.value))
        return 0;
    if(!isValidDate(cdt_dropoffDate.value))
        return 0;  
        
    var differenceInDate = 0;
    var dropOffDate = GetDateFromString(cdt_dropoffDate.value);
    var pickupDate = GetDateFromString(cdt_pickupDate.value);

    differenceInDate = dropOffDate - pickupDate;

    var day = 1000 * 60 * 60 * 24;
    var temp;
    
    differenceInDate = (differenceInDate/day);
    return Math.round(differenceInDate);
}
        
function GetDigitsOnlyInString(_string) 
{
    var digitsOnly = "";
    var character;
    for(var i = 0; i < _string.length; i++) 
    {
        character = _string.charAt(i);
        if (!isNaN(character) && character != ' ') 
        {
            digitsOnly += character;
        }
    }
    return digitsOnly;
}

function LuhnValidator(_cardNumber) 
{
    var digitsOnly = GetDigitsOnlyInString(_cardNumber);
    var sum = 0;
    var digit = 0;
    var addend = 0;
    var timesTwo = false;
    if (!IsCreditCardNumberMasked(_cardNumber))
    {
        for(var i = digitsOnly.length - 1; i >= 0; i--) 
        {
            digit = parseInt(digitsOnly.substring (i, i + 1));
            if(timesTwo) 
            {
                addend = digit * 2;
                if(addend > 9) 
                {
                    addend -= 9;
                }
            }
            else 
            {
                addend = digit;
            }
            sum += addend;
            timesTwo = !timesTwo;
        }

        var modulus = sum % 10;
        return modulus == 0;
    }
    else
    {
        return true;
    }
}

function IsCreditCardNumberMasked(_cardNumber)
{
    if (_cardNumber.toLowerCase().charAt(0) == "x")
    {
        return true;
    }
    else
    {
        return false;
    }
}

function ValidateCreditCardProvider(_cardNumber, _provider) 
{
    var digitsOnly = GetDigitsOnlyInString(_cardNumber);
    var doesMatch = false;
    if (IsCreditCardNumberMasked(_cardNumber))
    {
        doesMatch = true;
    }
    else
    {   
        var reg=new RegExp(" ", "g");
        var provider = _provider.replace(reg, "");

        switch(provider)
        {
            case "AmericanExpress":
                if ((digitsOnly.substr(0,2) == "34" || digitsOnly.substr(0,2) == "37") && digitsOnly.length == 15)
                {
                    doesMatch = true;
                }
                break;
                
            case "DinersClub":
            case "DINERS_CLUB":
                if ((digitsOnly.substr(0,3) == "300" || digitsOnly.substr(0,3) == "301" || digitsOnly.substr(0,3) == "302" || digitsOnly.substr(0,3) == "303" || digitsOnly.substr(0,3) == "304" || digitsOnly.substr(0,3) == "305" || digitsOnly.substr(0,2) == "36" || digitsOnly.substr(0,2) == "38") && digitsOnly.length == 14)
                {
                    doesMatch = true;
                }
                break;
                
            case "Discover":
            case "DISCOVER":
                if (digitsOnly.substr(0,4) == "6011" && digitsOnly.length == 16)
                {
                    doesMatch = true;
                }
                break;
                
            case "MasterCard":
            case "MASTER_CARD":
                if ((digitsOnly.substr(0,2) == "51" || digitsOnly.substr(0,2) == "52" || digitsOnly.substr(0,2) == "53" || digitsOnly.substr(0,2) == "54" || digitsOnly.substr(0,2) == "55") && digitsOnly.length == 16)
                {
                    doesMatch = true;
                }
                break;
                
            case "Visa":
            case "VISA":
                if (digitsOnly.substr(0,1) == "4" && (digitsOnly.length == 13 || digitsOnly.length == 16))
                {
                    doesMatch = true;
                }
                break;
                
            case "AMEX":
                doesMatch = false;
                break;
                
            case "COUNT":
                doesMatch = false;
                break;                
        }
    }   
    return doesMatch;
}

function ValidateSearchParameters(dcc_ServerStartDateFromID, dcc_ServerStartDateToID, tb_ServerIPID, tb_ServerBasePathID, dcc_RequestStartTimeFromID, dcc_RequestStartTimeToID, tb_AgencyID, tb_TripID, tb_SessionID, tb_ClientID, tb_LimitCountID, cb_LimitID, event)
{
    var elem_ServerStartDateFrom = getElement(dcc_ServerStartDateFromID);
    var elem_ServerStartDateTo = getElement(dcc_ServerStartDateToID);
    var elem_ServerIP = getElement(tb_ServerIPID);
    var elem_ServerBasePath = getElement(tb_ServerBasePathID);
    var elem_RequestStartTimeFrom = getElement(dcc_RequestStartTimeFromID);
    var elem_RequestStartTimeTo = getElement(dcc_RequestStartTimeToID);
    var elem_AgencyId = getElement(tb_AgencyID);
    var elem_TripId = getElement(tb_TripID);
    var elem_SessionId = getElement(tb_SessionID);
    var elem_ClientId = getElement(tb_ClientID);
    var elem_LimitCount = getElement(tb_LimitCountID);
    var elem_Limit = getElement(cb_LimitID);
    
    var nElementCount = 0;
    
    if(elem_ServerStartDateFrom != null)
    {
        if(elem_ServerStartDateFrom.value != "")
            nElementCount++;
    }
    if(elem_ServerStartDateTo != null)
    {
        if(elem_ServerStartDateTo.value != "")
            nElementCount++;
    }
    if(elem_ServerIP != null)
    {
        if(elem_ServerIP.value != "")
            nElementCount++;
    }
    if(elem_ServerBasePath != null)
    {
        if(elem_ServerBasePath.value != "")
            nElementCount++;
    }
    if(elem_RequestStartTimeFrom != null)
    {
        if(elem_RequestStartTimeFrom.value != "")
            nElementCount++;
    }
    if(elem_RequestStartTimeTo != null)
    {
        if(elem_RequestStartTimeTo.value != "")
            nElementCount++;
    }
    if(elem_AgencyId != null)
    {
        if(elem_AgencyId.value != "")
            nElementCount++;
    }
    if(elem_TripId != null)
    {
        if(elem_TripId.value != "")
            nElementCount++;
    }
    if(elem_SessionId != null)
    {
        if(elem_SessionId.value != "")
            nElementCount++;
    }
    if(elem_ClientId != null)
    {
        if(elem_ClientId.value != "")
            nElementCount++;
    }
    if(elem_LimitCount != null && elem_Limit != null)
    {
        if(elem_LimitCount.value != "" && elem_Limit.checked==true)
            nElementCount++;
    }
        
    if(nElementCount <3)
    {
        alert("You need to fill at least 3 search criterias");
        event.cancelBubble = true; 
		event.returnValue = false;
    }
}

function SetHRefToLink(_lnkId, _url)
{
    var elem = getElement(_lnkId);
    if (elem != null)
    { 
        var newURL;
        if (_url.toLowerCase().indexOf("module=air", 1) > -1)
        {
            var reg=new RegExp("searchresults.aspx", "g");
        
            var urlPath = _url.substring(0, _url.indexOf("?", 1)).toLowerCase();
            urlPath = urlPath.replace(reg, "searchresultsair.aspx");
            newURL = urlPath + _url.substring(_url.indexOf("?", 1));
        }
        else
        {
            newURL = _url;
        }

        elem.href = FormatLinkUrl(newURL);
    }
}

function FormatLinkUrl(_url, _applicationName)
{
    // checks if _url starts with a /. If not, adding it
    if (_url.indexOf("/") != 0)
        _url = "/" + _url;
        
    if (!IsNullOrEmpty(_applicationName))
    {
        if (_applicationName.indexOf("/") != 0)
            _applicationName = "/" + _applicationName;
            
        return _applicationName + _url;
    }
    else
    {
        var urlPath = window.location.pathname.substring(0, window.location.pathname.indexOf("/", 1)); 
        // Checks if the application pathname is already defined in the URL       
        if (_url.toLowerCase().indexOf(urlPath.toLowerCase() + "/") == -1)
        {
            var urlCopy = _url;
            // checks if _url contains TSGWebServicesWebApp. If so, removing it
            if (_url.toLowerCase().indexOf("tsgwebserviceswebapp") != -1)
            {
                var reg = new RegExp("/tsgwebserviceswebapp", "g");
                _url = _url.toLowerCase().replace(reg,"");
                
                reg = new RegExp("tsgwebserviceswebapp", "g");
                _url = _url.toLowerCase().replace(reg,"");
            }
            
            // get back to the URL with lower and upper case - DO NOT REMOVE, it's important to keep the case as the code behind is case sensitive
            if (_url.length != urlCopy.length)
            {
                _url = urlCopy.substring(urlCopy.length - _url.length);
            }
            
            return urlPath + _url;
        }
        else
        {
            return _url;
        }
    }
}

function ChangeDDLProvinceState(_countryDDLID, _StateProvinceDDLID, _validatorCountryProvinceID)
{
   var ddlStateProvince         = getElement(_StateProvinceDDLID);
   var ddlCountry               = getElement(_countryDDLID); 
   var validatorCountryProvince = getElement(_validatorCountryProvinceID); 
    
    if (ddlCountry)
    {
        if (ddlStateProvince)
        {
            if ( ddlCountry.value  == "CA" || ddlCountry.value  == "US")
            {
                PopulateProvinceStateDDL(ddlStateProvince, ddlCountry.value);
            }
            
            if(validatorCountryProvince)
                ValidatorValidate(validatorCountryProvince);
        }
    }
}

function SelectDDLStateProvince(_StateProvinceDDLID,_stateProvinceValue)
{
    var dllStateProvince = getElement(_StateProvinceDDLID);
    
    if(dllStateProvince)
    {
        dllStateProvince.value = _stateProvinceValue;
    }
}

function PopulateProvinceStateDDL(_StateProvinceInput, _countryCode)
{
    // we have to support ddl and textbox as valid input types (silent search forms -> the programmer can choose the type to use)
    if (_StateProvinceInput.options != null && _StateProvinceInput.options != "undefined")
    {
        for(var i=_StateProvinceInput.options.length-1; i>=0; i--)
        {
            _StateProvinceInput.remove(i);
        }
        if (_countryCode  == "CA")
        {
            var options = [["AB","Alberta"],["BC","British Columbia"],["LB","Labrador"],["MB","Manitoba"],["NB","New Brunswick"],["NF","Newfoundland"],["NL","Newfoundland & Labrador"],["NS","Nova Scotia"],["NT","Northwest Territories"],["NU","Nunavut Territory"],["ON","Ontario"],["PE","Prince Edward Island"],["PQ","Quebec"],["SK","Saskatchewan"],["YT","Yukon Territory"]];
        }
        else if (_countryCode  == "US")
        {
            var options = [["AK","Alaska"],["AL","Alabama"],["AR","Arkansas"],["AZ","Arizona"],["CA","California"],["CO","Colorado"],["CT","Connecticut"],["DC","District Of Columbia"],["DE","Delaware"],["FL","Florida"],["GA","Georgia"],["HI","Hawaii"],["IA","Iowa"],["ID","Idaho"],["IL","Illinois"],["IN","Indiana"],["KS","Kansas"],["KY","Kentucky"],["LA","Louisiana"],["MA","Massachusetts"],["MD","Maryland"],["ME","Maine"],["MI","Michigan"],["MN","Minnesota"],["MO","Missouri"],["MS","Mississippi"],["MT","Montana"],["NC","North Carolina"],["ND","North Dakota"],["NE","Nebraska"],["NH","New Hampshire"],["NJ","New Jersey"],["NM","New Mexico"],["NV","Nevada"],["NY","New York"],["OH","Ohio"],["OK","Oklahoma"],["OR","Oregon"],["PA","Pennsylvania"],["PR","Puerto Rico"],["RI","Rhode Island"],["SC","South Carolina"],["SD","South Dakota"],["TN","Tennessee"],["TX","Texas"],["UT","Utah"],["VA","Virginia"],["VI","Virgin Islands"],["VT","Vermont"],["WA","Washington"],["WI","Wisconsin"],["WV","West Virginia"],["WY","Wyoming"]];
        }
               
        _StateProvinceInput.options.add(new Option( "None", "-1"));
        if (options != null)
        {
            for(var i=0; i<options.length; i++)
            {
                _StateProvinceInput.options.add(new Option( options[i][1], options[i][0]));
            }
        }
    }
}

var ddl_CountryID ;
var ddl_StateProvinceID ;

function SetCountryDelayed(countryDdlId, textInputClientID, StateProvinceID, AjaxUrl)
{
	setTimeout("SetCountry('"+countryDdlId+"','"+textInputClientID+"','"+StateProvinceID+"','"+AjaxUrl+"');", 500);
}

function SetCountry(countryDdlId, textInputClientID, StateProvinceID, AjaxUrl)
{
   ddl_CountryID        = countryDdlId;
   ddl_StateProvinceID  = StateProvinceID;
   
   var textInput = getElement(textInputClientID);
   if (textInput)
   {
       var urlPage1;
       if (IsNullOrEmpty(AjaxUrl) || AjaxUrl == "undefined")
       {
            urlPage1 = FormatLinkUrl("/CountryByAirPortCodeAjaxHandler.ashx");
       }
       else
       {
            urlPage1 = AjaxUrl;
       }
       new Ajax.Request(urlPage1 , {parameters:"AirPortCode=" + textInput.value, onComplete: CompletedCountryByAirportAjaxCall, onFailure:FailedConnectionCodeCheckAjaxCall} );
   }
}

var ddl_HotelLandmarksID;
function PopulateDLLHotelLandmarksDelayed(ddlHotelLandmarksID, textInputClientID, AjaxUrl)
{
    setTimeout("PopulateDLLHotelLandmarks('"+ddlHotelLandmarksID+"','"+textInputClientID+"','"+AjaxUrl+"');", 500);
}

function PopulateDLLHotelLandmarks(ddlHotelLandmarksID, textInputClientID, AjaxUrl)
{
   ddl_HotelLandmarksID        = ddlHotelLandmarksID;
   var ddl_HotelLandmarks = getElement(ddl_HotelLandmarksID);
  
  if ( ddl_HotelLandmarks)
  { 
       CleanDropDown( ddl_HotelLandmarks );
       
       var textInput = getElement(textInputClientID);
       if (textInput)
       {
           var urlPage1;
           if (IsNullOrEmpty(AjaxUrl) || AjaxUrl == "undefined")
           {
                   //urlPage1 = FormatLinkUrl("HotelLandmarksByLocationCode.aspx");

                  urlPage1 = "/TSGUtilityApp/AutoComplete/HotelLandmarksByDestinationCode.aspx";
           }
           else
           {
                urlPage1 = AjaxUrl;
           }
           
           urlPage1 +="?DestinationCode=" + encodeURI(textInput.value);
           new Ajax.Request(urlPage1 , {onComplete: CompletedHotelLandmarksByCityAjaxCall, onFailure:FailedConnectionCodeCheckAjaxCall} );
       }
   }
}

function CompletedHotelLandmarksByCityAjaxCall(_ajaxRequest)
{
    eval( _ajaxRequest.responseText );
   
    if( !textArrayForCombo || !valueArrayForCombo )
    {
	    return;
    }
    var ddl_HotelLandmarks = getElement(ddl_HotelLandmarksID);
    if (ddl_HotelLandmarks != null)
    {
        for (i = 0; i < valueArrayForCombo.length; i++) 
        {
	        ddl_HotelLandmarks.options.add(new Option( textArrayForCombo[i], valueArrayForCombo[i]));
        }
    }
}

function FailedConnectionCodeCheckAjaxCall(_ajaxRequest)
{
	//alert('There was a problem with the result of this AJAX request.');
	alert(_ajaxRequest.responseText);
}
function InitMultiSelectionDropDownList(_dropDownExtenderClientID, _textBoxTargetControlClientID, _panelItemsClientID )
{    
    var textBoxTargetControl = getElement(_textBoxTargetControlClientID);
    if (textBoxTargetControl != null)
    {
        while( _panelItemsClientID.indexOf('$') != -1 )
        {
            _panelItemsClientID = _panelItemsClientID.replace("$","_");
        }
        var panelItems = getElement(_panelItemsClientID);
        if (panelItems != null)
        {
            if (textBoxTargetControl.clientWidth)
                panelItems.style.width = textBoxTargetControl.clientWidth;  
           
           if (ie)
           {
           }
           else if(n6)
           {
                 panelItems.style.visibility = "hidden";
           }
       }
    }
}

var validMultiSelectedItems;
function DisplayMultiSelectDropDownList(_checkBoxListClientID,  _targetControlCLientID, _maxNumberItems)
{
   CheckMultiSelectDropDownList(_checkBoxListClientID,  _targetControlCLientID, _maxNumberItems ) 
   if (validMultiSelectedItems == true)
   {
       var targetControl = getElement(_targetControlCLientID);
       if (targetControl != null)
       {
            
            targetControl.value = "";
            var i = 0;
            
            var checkBox = GetMultiSelectCheckBox(_checkBoxListClientID, i);
            while (checkBox != null)
            {

                if (checkBox.checked == true)
                {
                    var label = checkBox.nextSibling;
                    var checkBoxText;
                    if (n6)
                        checkBoxText = label.innerHTML;
                    else
                        checkBoxText = label.innerText;
                    
                    if (targetControl.value == "")
                    {
                        targetControl.value =  checkBoxText;
                    }
                    else
                    {
                        targetControl.value = targetControl.value +", "+ checkBoxText ;
                    }
                }
                i= i+1;
                checkBox = GetMultiSelectCheckBox(_checkBoxListClientID, i);            
            }
       }
   }
}

function GetMultiSelectCheckBox( _checkBoxListClientID, i )
{
    var checkBoxClientID  = _checkBoxListClientID+"$"+i ;
    if (n6)
    {
        while( checkBoxClientID.indexOf('$') != -1 )
        {
            checkBoxClientID = checkBoxClientID.replace("$","_");
        }
    }
    var checkBox = getElement(checkBoxClientID);
    return checkBox;
}
function CheckMultiSelectDropDownList(_checkBoxListClientID,  _targetControlCLientID, _maxNumberItems ) 
{
   validMultiSelectedItems = true;
   var targetControl = getElement(_targetControlCLientID);

   if (targetControl != null )
   {
        var i = 0;
        var checkedItemsNumber = 0
        var checkBox = GetMultiSelectCheckBox(_checkBoxListClientID, i);
        while (checkBox != null)
        {
            if (checkBox.checked == true)
            {
                checkedItemsNumber = checkedItemsNumber + 1;
                if (checkedItemsNumber > _maxNumberItems)
                {
                    validMultiSelectedItems = false;
                    PopulateMultiSelectDropDownList(_checkBoxListClientID,  targetControl);
                    alert("Please select a maximum of 3 amenities.");
                    return;
                }
            }
            i= i+1;
            checkBox = GetMultiSelectCheckBox(_checkBoxListClientID, i);
        }
   }
}

function PopulateMultiSelectDropDownList(_checkBoxListClientID,  targetControl)
{
     var i = 0;
     
     var targetControlText = targetControl.value;
     var ArrayOfSelectedItems = targetControlText.split(', ');
    
     var checkBox = GetMultiSelectCheckBox(_checkBoxListClientID, i);
     while (checkBox != null)
     {
        checkBox.checked = false;
        for(var j = 0; j < ArrayOfSelectedItems.length; j++)
        {
            if (checkBox.nextSibling.innerHTML == ArrayOfSelectedItems[j])
            {
                checkBox.checked = true;
                break;
            }
        }
        i= i+1;
        checkBox = GetMultiSelectCheckBox(_checkBoxListClientID, i);
     }
}
function ChangeDdlHotelProvinceState(countryInputID, stateProvinceInputID, hotelDestinationID, stateProvinceLblID)
{

   var stateProvinceInput   = getElement(stateProvinceInputID);
   var countryInput         = getElement(countryInputID);   
   var lblStateProvince     = getElement(stateProvinceLblID);
   var hotelDestination     = getElement(hotelDestinationID)
    if (hotelDestination)
    {
        hotelDestination.style.visibility = "hidden";
    }
    
    if (countryInput)
    {
        if (stateProvinceInput)
        {
            if ( countryInput.value  == "CA" || countryInput.value  == "US" || countryInput.value  == "" )
            {
                   stateProvinceInput.style.visibility = "visible";
                   if (lblStateProvince)
                   {
                        lblStateProvince.style.visibility = "visible";
                   }
                   PopulateProvinceStateDDL(stateProvinceInput, countryInput.value);     
            }
            else
            {
                   stateProvinceInput.style.visibility = "hidden";
                   if (lblStateProvince)
                   {
                        lblStateProvince.style.visibility = "hidden";
                   }
            }
        }
    }
}

function SelectAllCheckBoxClicked(_idCheckBoxTable)
{
    var elem = getElement(_idCheckBoxTable);
    if (elem != null)
    {
        var boolChecked = false;
        var j = 0;
        
        arrayOfInputs = document.getElementsByTagName('input');
		for (i = 0; i < arrayOfInputs.length; i++) 
		{
			var input     = arrayOfInputs[i];
			var inputType = input.type;
            
			if(inputType == "checkbox" && input.id != "useFlightPassCheckBox")
			{
			    boolChecked = input.checked;
			    j = i;
			    i = arrayOfInputs.length;
			}
		}
		for (i = j; i < arrayOfInputs.length; i++) 
		{
			var input     = arrayOfInputs[i];
			var inputType = input.type;
            
			if(inputType == "checkbox"  && input.id != "useFlightPassCheckBox")
			{
			    input.checked = boolChecked;
			    
			    if(input.nextSibling.innerText == "AC2U")
			        ShowSection('useFlightPassDiv', boolChecked);
			}
		}
    }
}

function ModifySelectAllIfCheckBoxClicked(_cb, _idCheckBoxTable)
{
    var elem = getElement(_idCheckBoxTable);
    if (_cb != null && elem != null)
    {
        if (_cb.checked == false)
        {
            arrayOfInputs = document.getElementsByTagName('input');
		    for (i = 0; i < arrayOfInputs.length; i++) 
		    {
			    var input     = arrayOfInputs[i];
			    var inputType = input.type;
                
			    if(inputType == "checkbox")
			    {
			        input.checked = false;
			        i = arrayOfInputs.length;
			    }
		    }
		}
		
		if(_cb.nextSibling.innerText == "AC2U")
			ShowSection('useFlightPassDiv', _cb.checked);
    }
}

function PositionDOMElementRelativelyToAnotherOne(_referenceDiv, _divToPosition, _xPos, _yPos)
{
    if (_referenceDiv != null && _divToPosition != null)
    {
        var elemX = findPosX(_referenceDiv);
        var elemY = findPosY(_referenceDiv);
        
        _divToPosition.style.left = elemX + _xPos + "px";
        _divToPosition.style.top = elemY + _referenceDiv.offsetHeight + _yPos + "px";
    }
}

/* Tooltip display functions */

var lockSeparateTooltip = false;
var windowX = 1024;
var windowY = 768;

function ReplaceIfEmpty(_string, _language)
{
    if (_language == 'EN' && _string != null)
    {
        if (_string.length == null || _string.length == 0 || _string == "")
        {
            return 'n/a';
        }
    }
    else if (_language == 'FR' && _string != null)
    {
        if (_string.length == null || _string.length == 0 || _string == "")
        {
            return 'n/d';
        }
    }
    return _string;
}

function MoveTooltipInsideScreen(_id)
{
    var elem;
    if (IsNullOrEmpty(_id))
    {
        elem = getElement('SeparateTooltip');
    }
    else
    {
        elem = getElement(_id);
    }
    if (elem != null)
    {
        var ySize = parseInt(elem.offsetHeight);
        var xSize = parseInt(elem.offsetWidth);
        var yPos = findPosY(elem);
        var xPos = findPosX(elem);
        
        var WaitResults = getElement('WaitResultsDiv');
        var WaitResultsHeight = WaitResults.offsetHeight;

        // check if the tooltip is inside the screen or not // TO FINISH - not OK for FF
        if (xPos + xSize > windowX)
        {
            elem.style.left = xPos - ((xPos + xSize) - windowX);
        }
        if (yPos + ySize > windowY - WaitResultsHeight)
        {
            elem.style.top = yPos - ((yPos + ySize) - windowY) - WaitResultsHeight;
        }
    }
}

function MoveTooltipToScreenCenter(_id)
{
    var elem;
    if (IsNullOrEmpty(_id))
    {
        elem = getElement('SeparateTooltip');
    }
    else
    {
        elem = getElement(_id);
    }
    if (elem != null)
    {
        var ySize = parseInt(elem.offsetHeight);
        var xSize = parseInt(elem.offsetWidth);
        var posX = Math.round((windowX / 2) - ( xSize / 2));
        var posY = Math.round((windowY / 2) - ( ySize / 2));
        elem.style.left = posX + "px";
        elem.style.top = posY + "px";
    }
}

function InitializeSeparateTooltip()
{
    if (!lockSeparateTooltip)
    {
        var elem = getElement('SeparateTooltip');
        if (elem != null)
        { 
            elem.innerHTML = "";
        }
    }
}

function HideSeparateTooltip()
{
    if (!lockSeparateTooltip)
    {
        ShowSection('SeparateTooltip',false);
    }
}

function FreeSeparateTooltip()
{
    var elem = getElement('SeparateTooltip');
    if (elem != null && !lockSeparateTooltip)
    {
        elem.innerHTML = "";
    }
}

function CreateSeparateTooltipControl(_htmlDisplay, _arrayTags, _arrayReplace, _xPos, _yPos, _language, _needsAdjustment)
{
    if (!lockSeparateTooltip)
    {
        for(i=0; i<_arrayTags.length; i++)
        {
            _htmlDisplay = _htmlDisplay.replace(_arrayTags[i], ReplaceIfEmpty(_arrayReplace[i], _language));
        }
        var elem = getElement('SeparateTooltip');
        if (elem != null)
        {
            var scrollTop = document.documentElement.lastChild.scrollTop;
             
            elem.innerHTML = elem.innerHTML + _htmlDisplay;
            elem.style.visibility = "visible";
            elem.style.position = "absolute";
            elem.style.display = "inline";
            SetClassToElement("SeparateTooltip", "PackageCodeTooltip");
            
            elem.style.top = mousePositionY + _yPos + scrollTop + 'px';
            elem.style.left = mousePositionX + _xPos + 'px';
            
            if(_needsAdjustment)
            {
                MoveTooltipInsideScreen();
            }
        } 
    }
}
// Used by B2C
function CreateB2CSeparateTooltip(_htmlDisplay, _arrayTags, _arrayReplace, _xPos, _yPos, _language)
{
    CreateSeparateTooltipControl(_htmlDisplay, _arrayTags, _arrayReplace, _xPos, _yPos, _language, false);
}

// Used by CPro
function CreateSeparateTooltip(_htmlDisplay, _arrayTags, _arrayReplace, _xPos, _yPos, _language)
{
    CreateSeparateTooltipControl(_htmlDisplay, _arrayTags, _arrayReplace, _xPos, _yPos, _language, true);
}

function ShowAndPlaceProviderTooltip(_show)
{
    var elem = getElement('ProviderTooltip');
       
    //For Flight pass feature special treatment
    if(document.getElementById("flightPass_1"))
    {
        if(document.getElementById("flightPass_1").checked  && _show)
        {
            _show = true;
        }
        else
        {
            _show = false;
        }
    }
        
    if (elem != null)
    {
        if (_show)
        {
            elem.style.visibility = "visible";
            elem.style.position = "absolute";
            elem.style.display = "inline";
            SetClassToElement("ProviderTooltip", "ProviderTooltip");

            var searchPanel = getElement('searchPanelDiv');
            if (searchPanel != null)
            {
                elem.style.top = searchPanel.offsetHeight + "px";
            }
            elem.style.right = 0 + 'px';
        }
        else
        {
            ShowSection('ProviderTooltip', false);
        }
    }
}

function CreateSeparateTooltipWithoutArray(_htmlDisplay, _xPos, _yPos)
{
    if (!lockSeparateTooltip)
    {
        var elem = getElement('SeparateTooltip');
        if (elem != null)
        { 
            elem.innerHTML = elem.innerHTML + _htmlDisplay;
            elem.style.visibility = "visible";
            elem.style.position = "absolute";
            elem.style.display = "inline";
            SetClassToElement("SeparateTooltip", "PackageCodeTooltip");

            elem.style.top = mousePositionY + _yPos + 'px';
            elem.style.left = mousePositionX + _xPos + 'px';
            MoveTooltipInsideScreen();
        } 
    }
}

function ShowAirAvailabilityControlTooltip(_msgType, _msg, _airType)
{
    lockSeparateTooltip = true;
    SetClassToElement("SeparateTooltip", "PackageCodeTooltip");
    var elem = getElement('SeparateTooltip');
    if (elem != null)
    {                    
        elem.innerHTML = "<table><tr><td class='txt15B_Black' valign='middle' height='20px'>Availability</td><td align='right' valign='top'><img src='/Custom/Generic/default/B2B/images/buttons/close_menu_trans_bg.gif' alt='Close' title='Close' onClick='javascript:HideAndUnlockSeparateTooltip();' class='cursorHand'/></td></tr><tr><td colspan='2' class='txt13B_Red'><span id='spanMessageType'></span></td></tr><tr><td colspan='2' class='txt12N_Black'><span id='spanMessage'></span></td></tr></table><table id='tableAirYesNoButtons' style='visibility: hidden; display: none; width: 150px;' cellpadding='0' cellspacing='0' border='0'><tr><td align='center' width='50%'><input type='submit' id='AirAvailChangedYesButton' Value='Yes' style='width: 50px;' onclick=\"javascript:AirProductAddToItinerary(\'" + _airType + "\');\" /></td><td align='center' width='50%'><input type='button' id='AirAvailChangedNoButton' Value='No' style='width: 50px;' onClick='javascript:HideAndUnlockSeparateTooltip();' /></td></tr></table>";
        
        var elemMessageType = getElement('spanMessageType');
        var elemMessage = getElement('spanMessage');
    
        if (elemMessageType != null)
        {
            elemMessageType.innerHTML = _msgType;
        }
        if (elemMessage != null)
        {
            elemMessage.innerHTML = _msg;
        }
        elem.style.visibility = "visible";
        elem.style.position = "absolute";
        elem.style.display = "inline";
        
        MoveTooltipToScreenCenter();
    }

}

function setCookie(name, value) 
{
    var exp = new Date();                                    // make new date object
    exp.setTime(exp.getTime() + (1000 * 60 * 60 * 24 * 30)); // set it 30 days ahead
    document.cookie = name + "=" + escape(value) + "; expires=" + exp.toGMTString() +"; path=/";
    
}

function ValidatorValidateFromID(validatorID) 
{
    var validator = getElement(validatorID);
    if (validator != null)
    {
        ValidatorValidate(validator);
    }
}

function ValidateAllPageValidators()
{
    for(var i = 0; i < Page_Validators.length; ++i)
    {
        ValidatorValidate(Page_Validators[i]);
    }
}

function ToggleAllPageValidators(_enabled)
{
    for(var i = 0; i < Page_Validators.length; ++i)
    {
        Page_Validators[i].enabled = _enabled;
    }
}

function ValidateGroup( _valGroupName)
{
    for(var i = 0; i < Page_Validators.length; ++i)
    {
        if(Page_Validators[i].validationGroup == _valGroupName)
        {
            ValidatorValidate(Page_Validators[i]);
        }
    }
}

//==================== Web air Canada(AC2U) Price Options functions ================//

function GetSelectedPriceOptions(_arrayOfClientID, _arrayOfControlType, _arrayOfOptionsIndex)
{
    var selectedPriceOptions = "";
    
    for(var i = 0; i < _arrayOfClientID.length; i++)
    {
        var obj = getElement(_arrayOfClientID[i]);
        
        if(obj != null)
        {
            switch(_arrayOfControlType[i])
            {
                case "CheckBox":
                    if(obj.checked)
                    {
                        selectedPriceOptions += _arrayOfOptionsIndex[i];
                    } 
                    break;
                case "RadioButtonList":
                    {
                        var radioButton = getElement(_arrayOfClientID[i] + "_0");
                        if(radioButton != null)
                        {
                            if(radioButton.checked)
                            { 
                                selectedPriceOptions += _arrayOfOptionsIndex[i];
                            }
                            else
                            { 
                                var optionIndex = parseInt(_arrayOfOptionsIndex[i]) + 1
                                selectedPriceOptions += optionIndex.toString();
                            }                            
                        }
                    }
                    break;
               case "RadioButton":
                    {
                        var radioButton = getElement(_arrayOfClientID[i]);
                        if(radioButton!=null)
                        {
                            if(radioButton.checked)
                            {
                                selectedPriceOptions += _arrayOfOptionsIndex[i];
                            }
                        }
                    }
                    break;     
            }
            
            if(i < _arrayOfClientID.length - 1)
                selectedPriceOptions += ",";
        }
    }
    
    selectedPriceOptions += "_";
    
    var myForm = document.forms[0];
             
    myForm.listOfPriceOptions.value = selectedPriceOptions;
}

function UpdatePriceOptions( selectedFareType, _arrayOfClientID1, _arrayOfControlType1, _arrayOfOptionsIndex1, 
                                               _arrayOfClientID2, _arrayOfControlType2, _arrayOfOptionsIndex2,
                                               _arrayOfClientID3, _arrayOfControlType3, _arrayOfOptionsIndex3,
                                               _arrayOfClientID4, _arrayOfControlType4, _arrayOfOptionsIndex4)
{
    var myForm = document.forms[0];
    
    var options ="";
    
    var ArrayOfSelectedFareType = selectedFareType.split(',');
    
    for(var i = 0; i < ArrayOfSelectedFareType.length; i++)
    {
        
        switch(i)
        {
           case 0:
               GetSelectedPriceOptions(_arrayOfClientID1, _arrayOfControlType1, _arrayOfOptionsIndex1);
               break;
                
           case 1:
               GetSelectedPriceOptions(_arrayOfClientID2, _arrayOfControlType2, _arrayOfOptionsIndex2);
           break;
            
           case 2:
               GetSelectedPriceOptions(_arrayOfClientID3, _arrayOfControlType3, _arrayOfOptionsIndex3);
           break;
            
           case 3:
               GetSelectedPriceOptions(_arrayOfClientID4, _arrayOfControlType4, _arrayOfOptionsIndex4);
           break;

        }
 
        options += myForm.listOfPriceOptions.value;
    }
         
     myForm.listOfPriceOptions.value = options;
          
    return true;   
}
function ShowHideChildrenAgesRoomDropDownList( _childrenNumberDDLClientID, _childrenAge1DDL, _childrenAge2DDL, _childrenAge3DDL)
{
    var childrenNumberDDL =  getElement(_childrenNumberDDLClientID);
    
    var childrenAge1DDL =  getElement(_childrenAge1DDL);
    var childrenAge2DDL =  getElement(_childrenAge2DDL);
    var childrenAge3DDL =  getElement(_childrenAge3DDL);
    
    
    if (childrenNumberDDL)
    {
        switch(childrenNumberDDL.value)
        {
            case "0":
                    childrenAge1DDL.style.visibility = "hidden";
                    childrenAge2DDL.style.visibility = "hidden";
                    childrenAge3DDL.style.visibility = "hidden";
                    break;
            case "1":
                    childrenAge1DDL.style.visibility = "visible";
                    childrenAge2DDL.style.visibility = "hidden";
                    childrenAge3DDL.style.visibility = "hidden";
                    break;
            case "2":
                    childrenAge1DDL.style.visibility = "visible";
                    childrenAge2DDL.style.visibility = "visible";
                    childrenAge3DDL.style.visibility = "hidden";
                    break;
            case "3":
                    childrenAge1DDL.style.visibility = "visible";
                    childrenAge2DDL.style.visibility = "visible";
                    childrenAge3DDL.style.visibility = "visible";
                    break;
        }
    }
}
var hotelNbRoomLabel;
var hotelNbAdultsLabel;
var hotelNbChildrenLabel;


function ShowHotelRoomInputPreference( _hotelNbRoomLabelClientID, _hotelNbAdultsLabelClientID, _hotelNbChildrenLabelClientID ) 
{
    hotelNbRoomLabel        = getElement(_hotelNbRoomLabelClientID);
    hotelNbAdultsLabel      = getElement(_hotelNbAdultsLabelClientID);
    hotelNbChildrenLabel    = getElement(_hotelNbChildrenLabelClientID);
    
    window.open(FormatLinkUrl("/HotelRoomInputPreference.aspx"), "",
        "alwaysRaised=yes,directories=no,location=no,menubar=no,status=no,toolbar=no,z-lock=no,resizable=yes,width=450,Height=650,scrollbars=yes", false);
}

function UpdateRoomLabel( _hotelNbRoom , _hotelNbAdults, _hotelNbChildren)
{
    if (window.opener.window.hotelNbRoomLabel != null)
            window.opener.window.hotelNbRoomLabel.innerHTML = _hotelNbRoom;
            
    if (window.opener.window.hotelNbAdultsLabel != null)
            window.opener.window.hotelNbAdultsLabel.innerHTML = _hotelNbAdults;
            
    if (window.opener.window.hotelNbChildrenLabel != null)
            window.opener.window.hotelNbChildrenLabel.innerHTML = _hotelNbChildren;
}

//===========================================================================================

function ShowTSARequirements()
{
    var lineBreak                = "<br/>"; 
    var tsaSecureFlightPrg       = "http://www.tsa.gov/what_we_do/layers/secureflight/index.shtm";
    var tsaPrivacyPolicy         = "www.tsa.gov";
    var title                    = "United States Transportation Security Administration (TSA) - Secure Flight Program"; 
    var body                     = "The Transportation Security Administration requires us to collect information from all passengers for purposes of watch list matching." + lineBreak +
                                   "This is required under the authority of 49 U.S.C. Section 114, and the Intelligence Reform and Terrorism Prevention Act of 2004." + lineBreak + 
                                   "Providing this information is voluntary; however, if it is not provided, you may be subject to additional screening or denied transport or authorization to enter a sterile area." + lineBreak + 
                                   "TSA may share information you provide with law enforcement or intelligence agencies or others under its published system of records notice." + lineBreak + 
                                   "If you wish to use this site to make your travel arrangements, your name, gender and date of birth information will automatically be sent to TSA." + lineBreak + lineBreak;     
                                  
    var infoTsaSecureFlightPrg    = "For more information on the TSA Secure Flight Program:";
    var infoTsaPrivacyPolicy      = "For more information on TSA Privacy policies or to view the system of records notice and the privacy impact assessment:";
    
    tsaWdn =window.open('about:blank', "", "toolbar=yes, menubar=yes, scrollbars=yes, width=800,height=400,resizable=yes")

    tsaWdn.document.write("<p>" + title.big() + "</p>");
    tsaWdn.document.write("<p>" + body.small() + "</p>");
    tsaWdn.document.write("<p>" + infoTsaSecureFlightPrg.small() );
    tsaWdn.document.write(tsaSecureFlightPrg.link("http://www.tsa.gov/what_we_do/layers/secureflight/index.shtm"));
    tsaWdn.document.write(lineBreak);
    tsaWdn.document.write(infoTsaPrivacyPolicy.small());
    tsaWdn.document.write(tsaPrivacyPolicy.link("http://www.tsa.gov"));
    tsaWdn.document.write("</p>");
}

function GetValueOfIdContainingText(text,theForm)
{
    var nbOfElement = 0;
     
     if(theForm!=null)//For the main search
     {
        nbOfElement = theForm.elements.length;
        for( i = 0; i < nbOfElement ; i++ )
        {
           if(theForm.elements[i].id.toString().length > text.length)
           {         
                var startIndex = 0;
                startIndex = theForm.elements[i].id.length - text.length; 
                if(theForm.elements[i].id.toString().substring(startIndex,theForm.elements[i].id.toString().length) == text.toString())
                {
                    return theForm.elements[i].value;
                }
           }
        }
     }
}

function GetElementOfIdContainingText(text,theForm)
{
    var nbOfElement = 0;
     
     if(theForm!=null)//For the main search
     {
        nbOfElement = theForm.elements.length;
        for( i = 0; i < nbOfElement ; i++ )
        {
           if(theForm.elements[i].id.toString().length > text.length)
           {         
                var startIndex = 0;
                startIndex = theForm.elements[i].id.length - text.length; 
                if(theForm.elements[i].id.toString().substring(startIndex,theForm.elements[i].id.toString().length) == text.toString())
                {
                    return theForm.elements[i];
                }
           }
        }
     }
}
function ValidateFromToDates( _tbDateFromId, _tbDateToId, _isMandatory )
{  
    var defaultValue = defaultCalendarDateFormatValue[dualCalendarDateFormatID]; 
    var tbFrom = getElement(_tbDateFromId);
    var tbTo = getElement(_tbDateToId); 

    if(_isMandatory == null || _isMandatory != true)
    {
        _isMandatory = false;
    }
    if(tbFrom != null && tbTo != null)
    {
        if(_isMandatory)
        {
            if(tbFrom.value == "")
            {
                alert('Select a valid From Date.');
                return false;
            }
            else if(tbTo.value == "")
            {
                alert('Select a valid To Date.');
                return false;
            }
        }
        
        if(tbFrom.value != "" && !isValidDate(tbFrom.value))
        {
            alert('Select a valid From Date.');
            return false;
        }
        if(tbTo.value != "" && !isValidDate(tbTo.value))
        {
            alert('Select a valid To Date.');
            return false;
        }
        
        //validate 'from before to' only if both date are valid.
        if(isValidDate(tbFrom.value) && isValidDate(tbTo.value))
        { 
            var dtAvailFrom = GetDateFromString(tbFrom.value);
            var dtAvailTo   = GetDateFromString(tbTo.value);
            
            if(dtAvailFrom >= dtAvailTo)
            {
                alert('From Date should be sooner than To Date.');
                return false;
            }
        }
        return true;
    }
    
    return true;
}

//On selected index of the list of flight pass change
function SelectFlightPass(index)
{
    var obj = getElement("flightPass_"+index);
    var elem = getElement("useFlightPassDiv");

    if(index > 1)
    {
        ShowAndPlaceProviderTooltip(false);
    }
    
    if(document.getElementById("flightPass_"+index) != null)
    {
        document.getElementById("flightPass_"+index).checked = "checked";
    }
    
    if(elem != null)
    {
        ShowSection("useFlightPassDiv", true);
    }
    
    var myForm = document.forms[0];
    if(myForm != null)
        myForm.FlightPassPosition.value = index;
    
    __doPostBack( 'divToHide_SearchPanel' ,'');//Update without refresh the Search Panel for fit with the good search mode.
}

//Set a default selected index in the list of flight pass
function SetDefaultSelectedIndex(index)
{
    var myForm = document.forms[0];
    if(myForm != null)
        myForm.FlightPassPosition.value = index;
}

function ValidateFlightPassOwner(_textBoxId, _messageToDisplay)
{
    var elem = getElement(_textBoxId);
    
    if(elem != null)
    {
        if(elem.value != '')
        {
            UpdateWaitingMessageAndShowWaitingPage(_messageToDisplay, true);
        }
        else
        {
            alert('Please enter a valid flight pass owner');
        }
    }
}

function ShowHideAdjustedFlightPassPanel(_lnkShowAllObj, _strObjNameToHide, _strShowLinkText, _strHideLinkText, _bTextShown)
{
    //LinkToggleSectionWithText(_idHider, _idToHide, _textDisplayed, _txtHidden);
    var obj = getElement(_strObjNameToHide);

    var sVisibility = "HIDDEN";
    if(obj.style.visibility != null && obj.style.visibility != "")
        sVisibility = obj.style.visibility.toUpperCase();

    if(sVisibility == "HIDDEN")
    {
	    obj.style.display    = "block";
	    obj.style.visibility = "visible";  
	    if(_strHideLinkText != "" )  
	    {
	       _lnkShowAllObj.innerText = _strShowLinkText;
	    }
    }
    else
    {
        obj.style.display    = "none";
	    obj.style.visibility = "hidden";
	    if(_strShowLinkText != "")  
	    {
	        _lnkShowAllObj.innerText = _strHideLinkText;
	    }
    }
    
    ChangeIconOnHider("FlightPassPanelHiderBtn","flightPassPanelHidingSectionHide","flightPassPanelHidingSectionShow", _strObjNameToHide);
    
    SetSubElementsToCorrectSize();
}

function RegexValid( _stringToValidate, _regex)
{
    var strRegex = new RegExp(_regex, "gi");
    return _stringToValidate.search(strRegex)!=-1;
}

// THE FOLLOWING 2 FUNCTIONS ARE FOR US ADDRESSES ONLY.
// They are not even used in the generic XSLTs, we made them for YTB.

var populateUSAddressTimer;
function PopulateUSAddressFromStructure(_idAddressLine1, _idAddressLine2, _paxIndex)
{
    // necessary as when loading the page, the different arrays may not be initialized yet. We set a timeout that will call that function again
    // until the arrays are initialized.
    try
    {    
        var usAddressLine1 = getElement(_idAddressLine1);
        var usAddressLine2 = getElement(_idAddressLine2);
        
        if (usAddressLine1 != null && usAddressLine2 != null && !IsNullOrEmpty(array_tb_AddressDoorNumber[_paxIndex].value))
        {
            usAddressLine1.value = array_tb_AddressDoorNumber[_paxIndex].value + " " + array_tb_AddressStreetName[_paxIndex].value;
            if (array_ddl_AddressStreetDirection[_paxIndex].selectedIndex > 0)
                usAddressLine1.value += " " + array_ddl_AddressStreetDirection[_paxIndex].options[array_ddl_AddressStreetDirection[_paxIndex].selectedIndex].text;
            if (array_ddl_AddressSubType[_paxIndex].selectedIndex > 0)
                usAddressLine1.value += ", " + array_ddl_AddressSubType[_paxIndex].options[array_ddl_AddressSubType[_paxIndex].selectedIndex].text;
            if (!IsNullOrEmpty(array_tb_AddressSubTypeNumber[_paxIndex].value))
                usAddressLine1.value += " " + array_tb_AddressSubTypeNumber[_paxIndex].value;
                
            // this is used to re-populate line1 and line2. As this function is used in 2 situations (automatic population of us address
            // when first loading the page and population of next passenger when clicking "next passenger", "previous passenger" or the passengers tab)
            // then we must set the values in the fields.
            var splitLine2 = array_tb_AddressStreetName[_paxIndex].value.split("::");
            if (splitLine2.length >= 2 && !IsNullOrEmpty(splitLine2[1]))
            {
                usAddressLine1.value = array_tb_AddressDoorNumber[_paxIndex].value + " " + splitLine2[0];
                usAddressLine2.value = splitLine2[1];
            }
            else
            {
                usAddressLine2.value = "";
            }
        }
            
        clearTimeout(populateUSAddressTimer);
    }
    catch (Error)
    {
        populateUSAddressTimer = setTimeout("PopulateUSAddressFromStructure('" + _idAddressLine1 + "', '" + _idAddressLine2 + "', " + _paxIndex + ")", 1000);
        return;
    }
}

function PopulateStructuredAddressFromUSAddress(_idAddressLine1, _idAddressLine2, _paxIndex)
{
    var usAddressLine1 = getElement(_idAddressLine1);
    var usAddressLine2 = getElement(_idAddressLine2);
    
    if (usAddressLine1 != null && usAddressLine2 != null)
    {
        var stringAddress = usAddressLine1.value.replace(",", " ");
        
        var attributesSpace = usAddressLine1.value.split(" ");
        var concatenatedAddress = "";
        for(i = 0; i < attributesSpace.length; i++)
        {
            if (attributesSpace[i].length > 0 && i == 0)
                array_tb_AddressDoorNumber[_paxIndex].value = attributesSpace[i];
            else
            {
                concatenatedAddress += attributesSpace[i] + " ";
            }
        }
        if (!IsNullOrEmpty(usAddressLine2.value))
            concatenatedAddress += "::" + usAddressLine2.value;
        array_tb_AddressStreetName[_paxIndex].value = concatenatedAddress;
        
        array_ddl_AddressStreetDirection[_paxIndex].selectedIndex = 0;
        array_ddl_AddressSubType[_paxIndex].selectedIndex = 0;
        array_tb_AddressSubTypeNumber[_paxIndex].value = "";
    }
}

/********************************************
* usage: 
* http://www.bloggingdeveloper.com?author=bloggingdeveloper
* var author_value = getQuerystring('author');
*
* tahnk you mister blogger developer:
* http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
*********************************************/
function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.search);
  if(qs == null)
    return default_;
  else
    return qs[1];
}
