/*****************/
/* UPDATE ACTION */
/*****************/

// This function sets the action (used before a submit() call)
function updateAction(straction)
{
	//alert("Updating action to " + action);
	document.main_form.Action.value = straction;
	//alert("Updating target to ''");
	document.main_form.target = '';
}

// This function sets the form action
// The form action refers to the page this form will post to
function updateFormAction(straction)
{
    document.main_form.action = straction;
}

// This function sets the form target
// The form target refers to the page this form will post to
function updateFormTarget(strtarget)
{
    document.main_form.target = strtarget;
}

//This function returns a string representing a number in currency format (thousands separator, two decimal places)
function getMoneyFormat(num, thousandmarker, decimalmarker, blnshowdecimal)
{
    num = num.toString().replace(/\$|\, /g,'');
    if (isNaN(num))
        num = "0";
       
    if (thousandmarker == null)
        thousandmarker = ',';
    if (decimalmarker == null)
        decimalmarker = '.';
    if (blnshowdecimal == null)
        blnshowdecimal = true;
    
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    
    if (cents < 10)
        cents = "0" + cents;
    
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - ((3 + thousandmarker.length) * i + 3)) + thousandmarker + num.substring(num.length - ((3 + thousandmarker.length) * i + 3));
    if (!blnshowdecimal)
        return (((sign) ? '' : '-') + num);
    else
        return (((sign) ? '' : '-') + num + decimalmarker + cents);
}


/*******************/
/* CHECK ENTER KEY */
/*******************/
// This function returns true if the key pressed is the enter key
function checkEnterKey(evt)
{
//	if(!evt){var evt=window.event;}
//    if(evt.keyCode == 13)
//    {
//        return true;
//    }
//    else
//    {
//        return false;
    //    }
    if (window.event && window.event.keyCode == 13) { return true; }
    else if (evt.which && evt.which == 13) { return true; }
    else { return false; }
}

/******************/
/* CENTER DISPLAY */
/******************/

// This function places the specified element in the center of the window
function CenterDisplay(tid)
{
    try
    {
        document.getElementById(tid).style.position = 'absolute';
        //Remember the old display style of the element
        var strdisp = document.getElementById(tid).style.display;
        //Make the element visisble. If the element is not visible, offsetHeight and width are zero.
        document.getElementById(tid).style.display = 'block';
        var offsetW = document.getElementById(tid).getAttribute('offsetWidth');
        var offsetH = document.getElementById(tid).getAttribute('offsetHeight');
        if (!offsetW)
            offsetW = document.getElementById(tid).offsetWidth;
        if (!offsetH)
            offsetH = document.getElementById(tid).offsetHeight;
        document.getElementById(tid).style.left = ((GetWindowWidth()  / 2) + GetScrollX() - (offsetW  / 2)) + 'px';
        document.getElementById(tid).style.top  = ((GetWindowHeight() / 2) + GetScrollY() - (offsetH / 2)) + 'px';
        document.getElementById(tid).style.display = strdisp;
    }
    catch (ex)
    {
        //alert('Could not center element ' + tid + ':\n' + ex.message);
    }
}

function GetWindowWidth()
{
    if (typeof(window.innerWidth) == 'number')
    {
        //Non-IE
        return window.innerWidth;
    }
    else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientWidth;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        return document.body.clientWidth;
    }
}

function GetWindowHeight()
{
    if (typeof(window.innerWidth) == 'number')
    {
        //Non-IE
        return window.innerHeight;
    }
    else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight))
    {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientHeight;
    }
    else if (document.body && (document.body.clientWidth || document.body.clientHeight))
    {
        //IE 4 compatible
        return document.body.clientHeight;
    }
}

function GetScrollX()
{
    if (typeof(window.pageXOffset) == 'number')
    {
        //Netscape compliant
        return window.pageXOffset;
    }
    else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
    {
        //DOM compliant
        return document.body.scrollLeft;
    }
    else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
    {
        //IE6 standards compliant mode
        return document.documentElement.scrollLeft;
    }
    else
    {
        return 0;
    }
}
function GetScrollY()
{
    if (typeof(window.pageYOffset) == 'number')
    {
        //Netscape compliant
        return window.pageYOffset;
    }
    else if (document.body && (document.body.scrollLeft || document.body.scrollTop))
    {
        //DOM compliant
        return document.body.scrollTop;
    }
    else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop))
    {
        //IE6 standards compliant mode
        return document.documentElement.scrollTop;
    }
    else
    {
        return 0;
    }
}

function getPosition(tid)
{   
	var e = document.getElementById(tid);
	if (e)
	{
		var left = 0;   
		var top  = 0;   
	  
		while (e.offsetParent)
		{   
			left += e.offsetLeft;   
			top  += e.offsetTop;   
			e     = e.offsetParent;   
		}   
	  
		left += e.offsetLeft;   
		top  += e.offsetTop;   
	  
		return {x:left, y:top};
    }
    else
    {
		return {x:0, y:0};
    }
}  

/******************/
/* TOGGLE DISPLAY */
/******************/

// This function hides or shows single or multiple items based on ID
// The inputs for tid this function handles are:
//	1 Element:		Element ID		"X2"
//	Multiple:		Element list	"X2,D4,J6"
//	Multiple:		Element range	"X3-15"

// Input:
//	-tid		The element ID to show or hide
//	-obj		The object that requested to show or hide tid (usually a picture or button)
//	-showtxt	The text (or image url) to place on obj when tid is hidden ("Show options")
//	-hidetxt	The text (or image url) to place on obj when tid is shown  ("Hide options")
function toggleDisplay(tid, obj, showtxt, hidetxt)
{
    /*
	if (showtxt == "")
		showtxt = "Show";
	if (hidetxt == "")
		hidetxt = "Hide";
	*/
	var i, s, e, b;
	var validChars = '0123456789';
	var x;

	if(tid.indexOf('-') > -1)
	{
		x = 0;
		s = '';					
		
		//This allows to name elements with a number in them, like td390_1 for example
		//Now we can do toggleDisplay('td390_1-10')
		if(tid.indexOf('_') > -1)
		{
			for(i = tid.indexOf('_'); i < tid.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid.substr(i , tid.indexOf('-') - i);
						b = tid.substr(0, i);
						x = 1;
					}
				}
			} 		
			e = tid.substr(tid.indexOf('-') + 1);
			//alert('Toggling ' + s + ' to ' + e);
			for(i = s; i <= e; i++)
			{
			    //alert('Trying to toggle ' + b + i);
				if(document.getElementById(b + i))
				{
					toggleOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
		else
		{
			for(i = 0; i < tid.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid.substr(i , tid.indexOf('-') - i);
						b = tid.substr(0, i);
						x = 1;
					}
				}
			} 		
			e = tid.substr(tid.indexOf('-') + 1);
			for(i = parseInt(s); i <= parseInt(e); i++)
			{
				if(document.getElementById(b + i))
				{
					//alert('Toggling ' + b + i);
					toggleOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
	}
	else if(tid.indexOf(',') > -1)
	{
		s = tid;
		while(s.indexOf(',') > -1)
		{
			x=s.indexOf(',');
			b=s.substr(0, x);
			s=s.substr(x + 1);
			if(document.getElementById(b))
			{
				toggleOne(b, obj, showtxt, hidetxt);
			}
		}

        //toggle display of last item
		if (document.getElementById(s)) {
		    toggleOne(s, obj, showtxt, hidetxt);
		}
	}
	else
	{
		if(document.getElementById(tid))
		{
			toggleOne(tid, obj, showtxt, hidetxt);
		}
	}
}

/******************/
/* TOGGLE DISPLAY 2 */
/******************/

// This function is derived from toggleDisplay() function.
// This function is used in HOTEL Search List Display if CITY code is numeric.
function toggleDisplay2(tid1,citycode,tid2, obj, showtxt, hidetxt)
{
	var i, s, e, b;
	var validChars = '0123456789';
	var x;
	var tid=tid1+citycode+tid2;
	var ntid=tid1+citycode;
	
	if(tid.indexOf('-') > -1)
	{
		x = 0;
		s = '';					
		
		//This allows to name elements with a number in them, like td390_1 for example
		//Now we can do toggleDisplay('td390_1-10')
		if(tid.indexOf('_') > -1)
		{
			for(i = tid2.indexOf('_'); i < tid2.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid2.substr(i , tid2.indexOf('-') - i);
						b = ntid;
						x = 1;
					}
				}
			} 		
			e = tid2.substr(tid2.indexOf('-') + 1);
			//alert('Toggling ' + s + ' to ' + e);
			for(i = s; i <= e; i++)
			{
			    //alert('Trying to toggle ' + b + i);
				if(document.getElementById(b + i))
				{
					toggleOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
		else
		{
			for(i = 0; i < tid2.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid2.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid2.substr(i , tid2.indexOf('-') - i);
						b = ntid;
						x = 1;
					}
				}
			} 		
			e = tid2.substr(tid2.indexOf('-') + 1);
			for(i = parseInt(s); i <= parseInt(e); i++)
			{
				if(document.getElementById(b + i))
				{
					//alert('Toggling ' + b + i);
					toggleOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
	}
	else if(tid2.indexOf(',') > -1)
	{
		s = tid2;
		while(s.indexOf(',') > -1)
		{
			x=s.indexOf(',');
			b=s.substr(0, x);
			s=s.substr(x + 1);
			if(document.getElementById(b))
			{
				toggleOne(b, obj, showtxt, hidetxt);
			}
		}
	}
	else
	{
		if(document.getElementById(tid))
		{
			toggleOne(tid, obj, showtxt, hidetxt);
		}
	}
}
 
// This function toggles the display of a single element based on ID
// This is used as a helper for toggleDisplay()
function toggleOne(oid, obj, showtxt, hidetxt)
{
    /*
	if (showtxt == "")
		showtxt = "Show";
	if (hidetxt == "")
		hidetxt = "Hide";
	*/
	if(document.getElementById(oid).style.display == 'none')
	{
		document.getElementById(oid).style.display = '';
		
		if (obj && hidetxt != "")
		{
			if (obj.type == "button")
				obj.value = hidetxt;
			else if (obj.type == "link")
			    obj.innerHTML = hidetxt;
			else
				obj.src = hidetxt;
		}
	}
	else
	{
		document.getElementById(oid).style.display = 'none';
		
		if (obj && showtxt != "")
		{
			if (obj.type == "button")
				obj.value = showtxt;
			else if (obj.type == "link")
			    obj.innerHTML = showtxt;
			else
				obj.src = showtxt;
		}
	}
}

/************************/
/* FIND OPTION INDEX    */
/************************/
// This function will loop the options in the given drop 
// down ID and return the index of the sought value

function findOptionIndex(id, strValue)
{
    
    var i;
    //loop
    for(i = 0; i <= document.getElementById(id).options.length; i++)
	{
	    
	    if(document.getElementById(id).options[i] && document.getElementById(id).options[i].value == strValue)
	    {
	        //alert('found index for ' + strValue +  ':' + i);
	        return i;
	    }
	} 	
	//alert('index not found for ' + strValue);
	return -1;	
    
}



/********/
/* SHOW */
/********/

// This function works like toggleDisplay except it will always show the items
//	1 Element:		Element ID		"X2"
//	Multiple:		Element list	"X2,D4,J6"
//	Multiple:		Element range	"X3-15"

// Input:
//	-tid		The element ID to show or hide
//	-obj		The object that requested to show or hide tid (usually a picture or button)
//	-showtxt	The text (or image url) to place on obj when tid is hidden ("Show options")
//	-hidetxt	The text (or image url) to place on obj when tid is shown ("Hide options")
function show(tid, obj, showtxt, hidetxt)
{
    /*
	if (showtxt == "")
		showtxt = "Show";
	if (hidetxt == "")
		hidetxt = "Hide";
	*/
	var i, s, e, b;
	var validChars = '0123456789';
	var x;

	if(tid.indexOf('-') > -1)
	{
		x = 0;
		s = '';					
		
		//This allows to name elements with a number in them, like td390_1 for example
		//Now we can do toggledisplay('td390_1-10')
		if(tid.indexOf('_') > -1)
		{
			for(i = tid.indexOf('_'); i < tid.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid.substr(i , tid.indexOf('-') - i);
						b = tid.substr(0, i);
						x = 1;
					}
				}
			} 		
			e = tid.substr(tid.indexOf('-') + 1);
			//alert('Toggling ' + s + ' to ' + e);
			for(i = s; i <= e; i++)
			{
			    //alert('Trying to toggle ' + b + i);
				if(document.getElementById(b + i))
				{
					showOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
		else
		{
			for(i = 0; i < tid.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid.substr(i , tid.indexOf('-') - i);
						b = tid.substr(0, i);
						x = 1;
					}
				}
			} 		
			e = tid.substr(tid.indexOf('-') + 1);
			
			for(i = s; i <= e; i++)
			{
				if(document.getElementById(b + i))
				{
					//alert('Toggling ' + b + i);
					showOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
	}
	else if(tid.indexOf(',') > -1)
	{
		s = tid;
		while(s.indexOf(',') > -1)
		{
			x=s.indexOf(',');
			b=s.substr(0, x);
			s=s.substr(x + 1);
			if(document.getElementById(b))
			{
				showOne(b, obj, showtxt, hidetxt);
			}
		}
	}
	else
	{
		if(document.getElementById(tid))
		{
			showOne(tid, obj, showtxt, hidetxt);
		}
	}
}

// This function shows a single element based on ID
// This is used as a helper for show()
function showOne(oid, obj, showtxt, hidetxt)
{
    /*
	if (showtxt == "")
		showtxt = "Show";
	if (hidetxt == "")
		hidetxt = "Hide";
	*/
	//document.getElementById(oid).style.display = 'block'; // must be changed to empty string ('') to work correctly with firefox
	document.getElementById(oid).style.display = '';
	
	if (obj && showtxt != "")
	{
		if (obj.type == "button")
			obj.value = showtxt;
		else
			obj.src = showtxt;
	}
}



/********/
/* HIDE */
/********/

// This function works like toggleDisplay except it will always hide the items
//	1 Element:		Element ID		"X2"
//	Multiple:		Element list	"X2,D4,J6"
//	Multiple:		Element range	"X3-15"

// Input:
//	-tid		The element ID to show or hide
//	-obj		The object that requested to show or hide tid (usually a picture or button)
//	-showtxt	The text (or image url) to place on obj when tid is hidden ("Show options")
//	-hidetxt	The text (or image url) to place on obj when tid is shown ("Hide options")
function hide(tid, obj, showtxt, hidetxt)
{
    /*
	if (showtxt == "")
		showtxt = "Show";
	if (hidetxt == "")
		hidetxt = "Hide";
	*/
	var i, s, e, b;
	var validChars = '0123456789';
	var x;

	if(tid.indexOf('-') > -1)
	{
		x = 0;
		s = '';					
		
		//This allows to name elements with a number in them, like td390_1 for example
		//Now we can do toggledisplay('td390_1-10')
		if(tid.indexOf('_') > -1)
		{
			for(i = tid.indexOf('_'); i < tid.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid.substr(i , tid.indexOf('-') - i);
						b = tid.substr(0, i);
						x = 1;
					}
				}
			} 		
			e = tid.substr(tid.indexOf('-') + 1);
			//alert('Toggling ' + s + ' to ' + e);
			for(i = s; i <= e; i++)
			{
			    //alert('Trying to toggle ' + b + i);
				if(document.getElementById(b + i))
				{
					hideOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
		else
		{
			for(i = 0; i < tid.indexOf('-'); i++)
			{
				if(validChars.indexOf(tid.charAt(i)) > -1)
				{
					if(x == 0)
					{
						s = tid.substr(i , tid.indexOf('-') - i);
						b = tid.substr(0, i);
						x = 1;
					}
				}
			} 		
			e = tid.substr(tid.indexOf('-') + 1);
			
			for(i = s; i <= e; i++)
			{
				if(document.getElementById(b + i))
				{
					//alert('Toggling ' + b + i);
					hideOne(b + i, obj, showtxt, hidetxt);							
				}					
			}
		}
	}
	else if(tid.indexOf(',') > -1)
	{
		s = tid;
		while(s.indexOf(',') > -1)
		{
			x=s.indexOf(',');
			b=s.substr(0, x);
			s=s.substr(x + 1);
			if(document.getElementById(b))
			{
				hideOne(b, obj, showtxt, hidetxt);
			}
		}
	}
	else
	{
		if(document.getElementById(tid))
		{
			hideOne(tid, obj, showtxt, hidetxt);
		}
	}
}

// This function hides a single element based on ID
// This is used as a helper for hide()
function hideOne(oid, obj, showtxt, hidetxt)
{
    /*
	if (showtxt == "")
		showtxt = "Show";
	if (hidetxt == "")
		hidetxt = "Hide";
	*/
	document.getElementById(oid).style.display = 'none';
	
	if (obj && hidetxt != "")
	{
		if (obj.type == "button")
			obj.value = hidetxt;
		else
			obj.src = hidetxt;
	}
}


//This function enables all fields to make sure they are submitted with the form
function enableAll()
{
	for(var i = 0; i < document.forms[0].elements.length; i++)
	{
		//alert('Enabling ' + document.forms[0].elements[i].id);
		document.forms[0].elements[i].disabled = false;
	}
}


// This fucntion will Turn On the ability to enter data into the given field
 function TurnOn(elmid)
    {
        if(document.getElementById(elmid))
        {
            document.getElementById(elmid).className = 'formbox';
            if(document.getElementById(elmid).type == 'radio')
            {
                document.getElementById(elmid).className = '';
            }
            document.getElementById(elmid).disabled  = false;
            document.getElementById(elmid).readOnly  = false;
        }
    }


/**************/
/* BUILD MASK */
/**************/

// This function builds a mask based on the requested rooms
// and sets the form variable "searchmask" with the computed value
// This function REQUIRES the following input elements:
//      numadts
//      numchds
//      chd1age
//      chd2age
// There MUST be the same number of elements of each name
// (4 numadts, 4 numchds, 4 chd1age, 4 chd2age)
// This function returns true if it manages to build a mask, false if it fails.
function buildMask()
{
    var myMask, tempMask;
    var i, j;
    
    myMask = "";
    for (i = 0; i < document.main_form.numadts.length; i++)
    {
        tempMask = "";
        
        //First, check for shares in each room
        if (document.main_form.numadts[i].value > 0 && document.getElementById('chksharey' + (i + 1)) && document.getElementById('chksharey' + (i + 1)).checked && document.getElementById('rdosharetypeA' + (i + 1)) && document.getElementById('rdosharetypeA' + (i + 1)).checked)
               tempMask = 'A';
        else if (document.main_form.numadts[i].value > 0 && document.getElementById('chksharey' + (i + 1)) && document.getElementById('chksharey' + (i + 1)).checked && document.getElementById('rdosharetypeAA' + (i + 1)) && document.getElementById('rdosharetypeAA' + (i + 1)).checked)
               tempMask = 'AA';
        else if (document.main_form.numadts[i].value > 0 && document.getElementById('chksharey' + (i + 1)) && document.getElementById('chksharey' + (i + 1)).checked && document.getElementById('rdosharetypeAAA' + (i + 1)) && document.getElementById('rdosharetypeAAA' + (i + 1)).checked)
               tempMask = 'AAA';
        else if (document.main_form.numadts[i].value > 0 && document.getElementById('chksharey' + (i + 1)) && document.getElementById('chksharey' + (i + 1)).checked && document.getElementById('rdosharetypeAAAA' + (i + 1)) && document.getElementById('rdosharetypeAAAA' + (i + 1)).checked)
               tempMask = 'AAAA';
        else
        {  
            for (j = 1; j <= document.main_form.numadts[i].value; j++)
            {
                tempMask = tempMask + "A";
            }
            for (j = 1; j <= document.main_form.numchds[i].value; j++)
            {
                //Check that at least one adult was selected for this room
                if (document.main_form.numadts[i].value == 0)
                {
                    if (document.main_form.allowzeroadts)
                    {
                        if (document.main_form.allowzeroadts.value != 'Y')
                        {
                            alert("Please select at least one adult for room #" + (i + 1));
                            return false;
                        }
                    }
                    else
                    {
                        alert("Please select at least one adult for room #" + (i + 1));
                        return false;
                    }
                }
                tempMask = tempMask + "C";
                if (j == 1)
                {
                    //First child
                    if (document.main_form.chd1age[i].value == "0")
                    {
                        alert("Please select child 1 age for room #" + (i + 1));
                        return false;
                    }
                    tempMask = tempMask + document.main_form.chd1age[i].value;
                }
                else if (j == 2)
                {
                    //Second child
                    if (document.main_form.chd2age[i].value == "0")
                    {
                        alert("Please select child 2 age for room #" + (i + 1));
                        return false;
                    }
                    tempMask = tempMask + document.main_form.chd2age[i].value;
                }
                else if (j == 3)
                {
                    //Third child
                    if (document.main_form.chd3age[i].value == "0")
                    {
                        alert("Please select child 3 age for room #" + (i + 1));
                        return false;
                    }
                    tempMask = tempMask + document.main_form.chd3age[i].value;
                }
                else if (j == 4)
                {
                    //First child
                    if (document.main_form.chd4age[i].value == "0")
                    {
                        alert("Please select child 4 age for room #" + (i + 1));
                        return false;
                    }
                    tempMask = tempMask + document.main_form.chd4age[i].value;
                }
                else if (j == 5)
                {
                    //Second child
                    if (document.main_form.chd5age[i].value == "0")
                    {
                        alert("Please select child 5 age for room #" + (i + 1));
                        return false;
                    }
                    tempMask = tempMask + document.main_form.chd5age[i].value;
                }
                else if (j == 6)
                {
                    //Third child
                    if (document.main_form.chd6age[i].value == "0")
                    {
                        alert("Please select child 6 age for room #" + (i + 1));
                        return false;
                    }
                    tempMask = tempMask + document.main_form.chd6age[i].value;
                }
            }
        }
        if (tempMask != "")
        {
            if (i > 0)
                myMask = myMask + "/" + tempMask;
            else
                myMask = tempMask;
        }
    }
    //alert("Mask: " + myMask);
    document.main_form.searchmask.value = myMask;
//    if (document.getElementById('numairadts'))
//    {
//        document.getElementById('numairadts').value = (myMask.length - myMask.replace(/A/g, '').length);
//    }
//    if (document.getElementById('numairchds'))
//    {
//        document.getElementById('numairchds').value = (myMask.length - myMask.replace(/C/g, '').length);
//    }
    return true;
}


/************************/
/* BUILD SPECIAL MASK   */
/************************/

// This function builds a mask based on the requested rooms
// and sets the form variable "searchmask" with the computed value
// This function REQUIRES the following input elements:
//      numadts
//      numspec
// There MUST be the same number of elements of each name
// (4 numadts, 4 numspec)
// This function returns true if it manages to build a mask, false if it fails.
function buildSpecMask()
{
    var myMask, tempMask;
    var i, j;
    
    myMask = "";
    for (i = 0; i < document.main_form.numspec.length; i++)
    {
        tempMask = "";
        for (j = 1; j <= document.main_form.numspec[i].value; j++)
        {
            tempMask = tempMask + "D";
        }
        for (j = 1; j <= document.main_form.numadts[i].value; j++)
        {
            //Check that at least one adult was selected for this room
            if (document.main_form.numspec[i].value == 0)
            {
                alert("Please select at least one diver for room #" + (i + 1));
                return false;
            }
            tempMask = tempMask + "A";
        }
        if (tempMask != "")
        {
            if (i > 0)
                myMask = myMask + "/" + tempMask;
            else
                myMask = tempMask;
        }
    }
    //alert("Mask: " + myMask);
    document.main_form.searchmask.value = myMask;
    return true;
}



/******************/
/* IS VALID EMAIL */
/******************/

//This function checks the validity of an email address using a regular expression
//Returns false if the email is invalid or blank, true if the email is valid and not blank
function isValidEmail(strEmail)
{
    //Regex from http://www.aspfaqs.com/webtech/052899-1.shtml
    var emailReg = "^[\\w-_\.+]*[\\w-_\.]\@([\\w-_]+\\.)+[\\w-_]+[\\w-_]$";
    var regex = new RegExp(emailReg);
    return regex.test(strEmail) && strEmail != '';
}

function IsInteger(strIn)
{
    var i = 0;
    for (i = 0; i < strIn.length; i++)
    {
        if (strIn.charAt(i) < "0" || strIn.charAt(i) > "9")
            return false;
    }
    
    return true;
}


/******************/
/* IS VALID NAME  */
/******************/

//This function checks the validity of an Name using a regular expression
//Returns false if the Name is invalid or blank, true if the Name is valid and not blank
function isValidName(strName)
{
    var nameReg = "^([a-z]|[A-Z]|-| |\')+$";
    var regex = new RegExp(nameReg);
    return regex.test(strName) && strName != '';
}



/****************************/
/* REMOVE AMOUNT FORMATTING */
/****************************/
// This function removes all formatiing except for a decimal from An "Amount" text box
function unformatAmount(strAmt)
{
    
    strAmt = strAmt.replace('$','');
    strAmt = strAmt.replace(',','');
    strAmt = strAmt.replace(' ','');
    strAmt = strAmt.replace('£','');
    strAmt = strAmt.replace(/,/g,''); // regular exp for replacing multiple , for millions
    strAmt = strAmt.replace(/ /g,''); // regular exp for replacing multiple spaces
          
    return strAmt;
}

function ParseFloat(strIn)
{
    return parseFloat(unformatAmount(strIn));
}


/****************************/
/*       PASSENGERS         */
/****************************/

/**** Function will build ContactXML from fields on the Passenger Screen Issue Date and return value 
to passportissue text box if all values are available     

RIGHT NOW, ONLY PARSES THE FORM FOR VALUES THAT THE SEARCH FOR TRAVEL COMPANION REQUEST NEEDS 
TO BE EXPANDED UPON FOR FUTURE NEEDS

****/
function buildPassContactXML(strPaxNum)
{
    var strOut;
    
   //ConactID
    if(document.getElementById('txtpaxcontactid' + strPaxNum) && document.getElementById('txtpaxcontactid' + strPaxNum).value != "")
   {
        strOut = strOut + '<PaxContactID>' + document.getElementById('txtpaxcontactid' + strPaxNum).value + '</PaxContactID>';
   }
   //Email
   if(document.getElementById('txtemail' + strPaxNum) && document.getElementById('txtemail' + strPaxNum).value != "")
   {
        strOut = strOut + '<Email>' + document.getElementById('txtemail' + strPaxNum).value + '</Email>';
   }
   //First
   if(document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "")
   {
        strOut = strOut + '<FirstName>' + document.getElementById('txtfirst' + strPaxNum).value + '</FirstName>' ;
   }
   //Last
   if(document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "")
   {
        strOut = strOut + '<LastName>' + document.getElementById('txtlast' + strPaxNum).value + '</LastName>';
   }
   //Address
   strOut = strOut + '<Address>';
       //Address1
       if(document.getElementById('txtaddress1' + strPaxNum) && document.getElementById('txtaddress1' + strPaxNum).value != "")
       {
            strOut = strOut + '<Address1>' + document.getElementById('txtaddress1' + strPaxNum).value + '</Address1>';
       }
       else if(document.getElementById('txtbilladdress1' + strPaxNum) && document.getElementById('txtbilladdress1' + strPaxNum).value != "")
       {
            strOut = strOut + '<Address1>' + document.getElementById('txtbilladdress1' + strPaxNum).value + '</Address1>';
       }
       //Zip
       if(document.getElementById('txtzip' + strPaxNum) && document.getElementById('txtzip' + strPaxNum).value != "")
       {
            strOut = strOut + '<Zip>' + document.getElementById('txtzip' + strPaxNum).value + '</Zip>';
       }
       else if(document.getElementById('txtbillzip' + strPaxNum) && document.getElementById('txtbillzip' + strPaxNum).value != "")
       {
            strOut = strOut + '<Zip>' + document.getElementById('txtbillzip' + strPaxNum).value + '</Zip>';
       }
   strOut = strOut + '</Address>';
   //Phone
   if (document.getElementById('chkNonUS'+ strPaxNum) &&    document.getElementById('chkNonUS'+ strPaxNum).checked==false)
   {     //three phone text boxes - concatenate em
          if(document.getElementById('txtphone1' + strPaxNum) && document.getElementById('txtphone2' + strPaxNum) && document.getElementById('txtphone3' + strPaxNum)) 
          {
            if(document.getElementById('txtphone1' + strPaxNum).value != "" && document.getElementById('txtphone2' + strPaxNum).value != "" && document.getElementById('txtphone3' + strPaxNum).value != "")
            {
                strOut = strOut + '<Phone>' + document.getElementById('txtphone1' + strPaxNum).value  + '-' + document.getElementById('txtphone2' + strPaxNum).value + '-' + document.getElementById('txtphone3' + strPaxNum).value + '</Phone>';
            }
          }
   }
   else
   {     //one phone text box - pull the value
           if(document.getElementById('txtphone' + strPaxNum) && document.getElementById('txtphone' + strPaxNum).value != "")
           {
                strOut = strOut + '<Phone>' + document.getElementById('txtphone' + strPaxNum).value + '</Phone>';
           }
   }   
   
   //Gender
   if(document.getElementById('txtgender' + strPaxNum) && document.getElementById('txtgender' + strPaxNum).value != "")
   {
        strOut = strOut + '<Gender>' + document.getElementById('txtgender' + strPaxNum).value + '</Gender>';
   }
   //DOB
   if(document.getElementById('txtbirthdate' + strPaxNum) && document.getElementById('txtbirthdate' + strPaxNum).value != "")
   {
        strOut = strOut + '<BirthDate>' + document.getElementById('txtbirthdate' + strPaxNum).value + '</BirthDate>';
   }
   //Passport #
   if(document.getElementById('txtpassportnumber' + strPaxNum) && document.getElementById('txtpassportnumber' + strPaxNum).value != "")
   {
        strOut = strOut + '<PassportNumber>' + document.getElementById('txtpassportnumber' + strPaxNum).value + '</PassportNumber>';
   }
   
   //Done - return the XML for the fileds we found
   return strOut;
}


/**** 
Function will check to see if we have enough contact fields for the DUPLICATE check
****/
function HaveFieldsForDupCheck(strPaxNum)
{
     var blnContinue = false;
     
    //ConactID
   if(document.getElementById('txtpaxcontactid' + strPaxNum) && document.getElementById('txtpaxcontactid' + strPaxNum).value != "")
   {
        blnContinue = true;
   }
   //Email Only 
   if(!blnContinue && document.getElementById('txtemail' + strPaxNum) && document.getElementById('txtemail' + strPaxNum).value != "")
   {
        blnContinue = true;   
   }
   // First Name + Last Name + Email Address 
   if(!blnContinue && document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "" && document.getElementById('txtemail' + strPaxNum) && document.getElementById('txtemail' + strPaxNum).value != "") 
   {
        blnContinue = true;
   }
   // First Name + Last Name + Address1 + Zip 
   if(!blnContinue && document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "" && document.getElementById('txtzip' + strPaxNum) && document.getElementById('txtzip' + strPaxNum).value != "")
   {
        blnContinue = true;
   }
    // First Name + Last Name + Address1 + BillZip 
   if(!blnContinue && document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "" && document.getElementById('txtbillzip' + strPaxNum) && document.getElementById('txtbillzip' + strPaxNum).value != "" )
   {
        blnContinue = true;
   }
   // First Name + Last Name + Phone 
   if(!blnContinue && document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "")
   {  
      
       if (document.getElementById('chkNonUS'+ strPaxNum) && document.getElementById('chkNonUS'+ strPaxNum).checked ==false)
       {     //three phone text boxes - concatenate em
              if(document.getElementById('txtphone1' + strPaxNum) && document.getElementById('txtphone2' + strPaxNum) && document.getElementById('txtphone3' + strPaxNum)) 
              {
                if(document.getElementById('txtphone1' + strPaxNum).value != "" && document.getElementById('txtphone2' + strPaxNum).value != "" && document.getElementById('txtphone3' + strPaxNum).value != "")
                {
                    blnContinue = true;
                }
              }
       }
       else
       {     //one phone text box - pull the value    
               
               if(document.getElementById('txtphone' + strPaxNum) && document.getElementById('txtphone' + strPaxNum).value != "")
               {
                    blnContinue = true;
               }
       } 
   }
   // First Name + Last Name + Gender + Date of Birth (DOB) 
   if(!blnContinue && document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "" && document.getElementById('txtgender' + strPaxNum) && document.getElementById('txtgender' + strPaxNum).value != "" && document.getElementById('txtbirthdate' + strPaxNum) && document.getElementById('txtbirthdate' + strPaxNum).value != "")
   {
        blnContinue = true;
   }
   // First Name + Last Name + Passport #  
   if(!blnContinue && document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "" && document.getElementById('txtpassportnumber' + strPaxNum) && document.getElementById('txtpassportnumber' + strPaxNum).value != "")
   {
        blnContinue = true;
   }
   
   //Return true or false
   return blnContinue;
}

/**** 
Function will first ask if we have enough contact fields for the DUPLICATE check, 
if we do, it will then do the ajax call to get the list of contact records which are past Travel Companions  
****/
function GetTravelCompanions(sess)
{
    var blnContinue = false;
    var strPaxNum = '1'; // The Lead pax, can be expanded to use other PaxSeq's in the future if possible
    var strRequest, strXML, strTemp, strValue;
    var lpos, rpos, optCount;
    
    strRequest = '';
    strXML = '';
    strValue = '';
    strTemp = '';
    lpos = 0;
    rpos = 0;
    optCount = 2;
    
              
   //1)  See if we have enough info to even attempt yet
   blnContinue = HaveFieldsForDupCheck(strPaxNum);

   
   //2) If Continue - send the AJAX request to get the Travel Companions
   
   
   if(blnContinue)
   {
        //get the form data
        strRequest =  buildPassContactXML(strPaxNum); 
        strXML = returnTravelCompanions(sess, strRequest);
          
              
        for (var i = 2; i <= 20; i++)
        {
            optCount = 2;
            if(document.getElementById('selTravelCompanions' + i))
            {
                 //clear the dropdown 
                document.getElementById('selTravelCompanions' + i).options.length = 2;  //first option is "Select a Travel Companion...."  Second is "Clear All Fields for this Passenger"
                //Loop through the response to load the dropdowns
                lpos = strXML.indexOf('**') + 2;
                while (lpos > -1)
                {
                    rpos = strXML.indexOf('**', lpos);
                    
                    if (rpos > lpos)
                    {
                        strtemp = strXML.substr(lpos, (rpos - lpos));
                        if (strtemp.split('|').length >= 3) // then i have the [0] & [1] indexes needed for FirstName (which is [2]) and LastName (which is [1])
                        {
                             // FirstName LastName
                             strValue= strtemp.split('|')[2] + ' ' +  strtemp.split('|')[1];
                            
                             // We have a first and last name, let's show some other info to the user
                             //Gender
                             //if (strtemp.split('|').length >= 12 && strtemp.split('|')[11] != '') 
                             //{                               
                             //    strValue= strValue + '   (' +  strtemp.split('|')[11] + ')';              
                             //}
                             //Email
                             if (strtemp.split('|').length >= 14 && strtemp.split('|')[13] != '') 
                             {                               
                                 strValue= strValue + '   ' +  strtemp.split('|')[13];              
                             }
                             //Phone
                             if (strtemp.split('|').length >= 15 && strtemp.split('|')[14] != '') 
                             {                               
                                 strValue= strValue + '   ' +  strtemp.split('|')[14];               
                             }
                             //Address1
                             if (strtemp.split('|').length >= 6 && strtemp.split('|')[5] != '') 
                             {                               
                                 strValue= strValue + '   ' +  strtemp.split('|')[5];             
                             }
                             //City
                             if (strtemp.split('|').length >= 8 && strtemp.split('|')[7] != '') 
                             {                               
                                 strValue= strValue + '   ' +  strtemp.split('|')[7];               
                             }
                             
                            if(strValue.replace(/ /g,'') != '')
                            {    
                                                   
                                //Add to the dropdown list of all Pax > 1                         
                                document.getElementById('selTravelCompanions' + i).options[optCount]= new Option(strValue, strtemp);  // EX:  ANDREA SIMERSON w Value= entire Contact string like so field1|field2|field3|||field6... etc..
                                optCount++;
                            }
                        }
                    }
                    if (rpos > 0)
                    {
                        lpos = strXML.indexOf('**', rpos);
                        if (lpos > -1)
                            lpos += 2;
                    }
                    else
                    {
                        //exit while
                        lpos = -1;
                    }
                }  //end while
                
                
            }
        }
                  
   }  // if blnContinue   
   else
   {
        //Make sure all subsequent pax have no travel companions from a previous search
         for (var i = 2; i <= 20; i++)
         {
            optCount = 2;
            if(document.getElementById('selTravelCompanions' + i))
            {
                 //clear the dropdown 
                document.getElementById('selTravelCompanions' + i).options.length = 2;  //first option is "Select a Travel Companion...."  Second is "Clear All Fields for this Passenger"
            }
         }   
   }
}

/**** 
Function will first ask if we have enough contact fields for the DUPLICATE check, 
if we do, it will then do the ajax call to get the list of contacts records which could potentially be the record for who is being entered 

strPaxNum = the Passenger Num of the Return_IndivPax

****/
function SearchForPossibleContacts(sess, strPaxNum)
{
    var blnContinue = false;
    var strRequest, strXML, strTemp, strValue, strContactID;
    var lpos, rpos, optCount;
    
    strRequest = '';
    strXML = '';
    strValue = '';
    strTemp = '';
    strContactID = '';
    lpos = 0;
    rpos = 0;
    optCount = 1; //Start at 1 because there is one hardcoded value in the list "Select an Existing..." value = [empty]


    
   
   //1)  See if we have enough info to even attempt yet.  Start searching as soon as we have first/last 
   if(document.getElementById('txtfirst' + strPaxNum) && document.getElementById('txtfirst' + strPaxNum).value != "" && document.getElementById('txtlast' + strPaxNum) && document.getElementById('txtlast' + strPaxNum).value != "" || document.getElementById('txtpaxcontactid' + strPaxNum) && document.getElementById('txtpaxcontactid' + strPaxNum).value != "") 
   {
        blnContinue = true;
   }
   //2) If Continue - send the AJAX request to get possible contacts
   
   
   
   if(blnContinue)
   {     
   
        //get the form data
        strRequest =  buildPassContactXML(strPaxNum); 
        strXML = returnPossibleContacts(sess, strRequest);
        
        
                
        //Loop through the response to load the dropdown for strPaxNum that was passed in
        //clear the dropdown 
        document.getElementById('selPossibleContacts' + strPaxNum).options.length = 2;  //first option is "Select a Travel Companion...."   Second is "Clear All Fields for this Passenger"
        
        
        lpos = strXML.indexOf('**') + 2;
            while (lpos > -1)
            {
                rpos = strXML.indexOf('**', lpos);
                
                if (rpos > lpos)
                {
                    strtemp = strXML.substr(lpos, (rpos - lpos));
                    if (strtemp.split('|').length >= 3) // then we have the [1] & [2] indexes needed for FirstName (which is [1]) and LastName (which is [2])
                    {
                        // FirstName LastName
                        strValue= strtemp.split('|')[2] + ' ' +  strtemp.split('|')[1];
                        
                         // We have a first and last name, let's show some other info to the user
                         //Gender
                         //if (strtemp.split('|').length >= 12 && strtemp.split('|')[11] != '') 
                         //{                               
                         //    strValue= strValue + '   (' +  strtemp.split('|')[11] + ')';              
                         //}
                         //Email
                         if (strtemp.split('|').length >= 14 && strtemp.split('|')[13] != '') 
                         {                               
                             strValue= strValue + '   ' +  strtemp.split('|')[13];              
                         }
                         //Phone
                         if (strtemp.split('|').length >= 15 && strtemp.split('|')[14] != '') 
                         {                               
                             strValue= strValue + '   ' +  strtemp.split('|')[14];               
                         }
                         //Address1
                         if (strtemp.split('|').length >= 6 && strtemp.split('|')[5] != '') 
                         {                               
                             strValue= strValue + '   ' +  strtemp.split('|')[5];             
                         }
                         //City
                         if (strtemp.split('|').length >= 8 && strtemp.split('|')[7] != '') 
                         {                               
                             strValue= strValue + '   ' +  strtemp.split('|')[7];               
                         }
                         
                         
                        if(strValue.replace(/ /g,'') != '')
                        {                       
                           //Add to this Pax Num's "Existing Contact Search" dropdown
                            document.getElementById('selPossibleContacts' + strPaxNum).options[optCount]= new Option(strValue, strtemp);  // EX:  ANDREA SIMERSON w Value= entire Contact string like so field1|field2|field3|||field6... etc..
                            optCount++;
                        }
                    
                    }                             
                }
                                           
                //Reset the index to find the next record
                if (rpos > 0)
                {
                    lpos = strXML.indexOf('**', rpos);
                    if (lpos > -1)
                        lpos += 2;
                }
                else
                {
                    //exit while
                    lpos = -1;
                }
            }//end while
            
            //After looping, always add the "Clear" and "New Account" fields
            //clear will clear the textboxes
            //New account will clear and show the text boxes
            document.getElementById('selPossibleContacts' + strPaxNum).options[optCount]= new Option('Clear All Fields for This Passenger','clear');  
            optCount++;
            document.getElementById('selPossibleContacts' + strPaxNum).options[optCount]= new Option('Create New','clear');  
            optCount++;
            
            
       
       
   }  // if blnContinue
   
}

/****
Function will parse a string of values to passed from a drop down (Travel Buddies & Search Pobbible Contacts)  
and fill all input on a passengers block

***/
 function SetPaxToChosenContact(id, paxNum, sess)
 {
    
    var strtemp;
    var blnKeepName;
    var strFirstName;
    var strLastName;
    var strJS; 
    var strRequest;
    strRequest = '';
    strJS = '';
    strFistName = '';
    strLastName = '' ;
    blnKeepName = false;
    strtemp = '';
    
        // Set the optional parameter if needed
        // need the session to get the Contact Rewards
        //if (sess === undefined ) 
        //{      sess = '';      }
        
        if(document.getElementById(id))
        {
            strtemp = document.getElementById(id).value;  
            //alert(strtemp);
            if(strtemp =="clear")
            {
            
                //user wants to clear the pax block, set strtemp to all empty values
                strtemp = '||||||||||US||||||||1900/1/1||||1900/1/1||1900/1/1|US||'
                
                var i = document.getElementById(id).selectedIndex;
                if(document.getElementById(id).options[i].text!="Create New")
                {        
                  
                  if(document.getElementById('txtfirst' + paxNum))
                  {//the fields will be cleared below, but we want the focus back on First Name of the Pax block that was cleared
                      //Set it back to the "Select an Existing..."
                      document.getElementById(id).value = "";
                      //Focus
                      document.getElementById('txtfirst' + paxNum).focus();
                      
                      //Keep pax block hidden
                      hide('trPaxInfo'+paxNum); 
                      
                  }
                                    
                }
                else
                {
                    //leave expanded
                    //set the focus on FirstName also
                    if(document.getElementById('txtfirst' + paxNum))
                    {
                       blnKeepName = true;
                       if(document.getElementById('txtfirst' + paxNum))
                       {
                            strFirstName = document.getElementById('txtfirst' + paxNum).value;
                       }
                       if(document.getElementById('txtlast' + paxNum))
                       {
                            strLastName = document.getElementById('txtlast' + paxNum).value;  
                       }
                       document.getElementById('txtfirst' + paxNum).focus(); 
                    }
                }
                
                

            }           
            if(strtemp != "")
            {   
                
                //Look through the value from the drop down to load the passenger block
                //Fields in Order:  ContactID|LastName|FirstName|CareOf|AddressID|Address1|Address2|City|State|Zip|Country|Gender|Title|Email|Phone|PhoneExt|MobilePhone|Fax|BirthDate|BirthPlace|Age|PassportNumber|PassportExpiration|PassportAuthority|PassportIssueDate|Nationality|EmergencyContact|EmergencyPhone
                //                     0        1         2         3       4         5        6      7    8    9     10      11    12    13    14    15         16       17      18       19      20          21               22             23               24              25             26               27       

                 
                //Pax Contact ID                  
                if (strtemp.split('|').length >= 1 && document.getElementById('txtpaxcontactid'+paxNum)) 
                {     //ContactID [0]
                      document.getElementById('txtpaxcontactid'+paxNum).value = strtemp.split('|')[0];
                }
                if (strtemp.split('|').length >= 2 && document.getElementById('txtlast'+paxNum)) 
                {     //LastName  [1]
                      document.getElementById('txtlast'+paxNum).value = strtemp.split('|')[1];
                }
                if (strtemp.split('|').length >= 3 && document.getElementById('txtfirst'+paxNum)) 
                {     //FirstName  [2]
                      document.getElementById('txtfirst'+paxNum).value = strtemp.split('|')[2];
                }
                //CareOf [3]
                //AddressID [4]
                if (strtemp.split('|').length >= 6 && document.getElementById('txtaddress1'+paxNum)) 
                {     //Address1 [5]
                      document.getElementById('txtaddress1'+paxNum).value = strtemp.split('|')[5];
                }
                if (strtemp.split('|').length >= 7 && document.getElementById('txtaddress2'+paxNum)) 
                {     //Address2 [6]
                      document.getElementById('txtaddress2'+paxNum).value = strtemp.split('|')[6];
                }
                if (strtemp.split('|').length >= 8 && document.getElementById('txtcity'+paxNum)) 
                {     //City [7]
                      document.getElementById('txtcity'+paxNum).value = strtemp.split('|')[7];
                }
                if (strtemp.split('|').length >= 9 && document.getElementById('txtstate'+paxNum)) 
                {     //State [8]
                      document.getElementById('txtstate'+paxNum).value = strtemp.split('|')[8];
                }  
                if (strtemp.split('|').length >= 9 && document.getElementById('selstate'+paxNum)) 
                {     //State [8]
                      document.getElementById('selstate'+paxNum).value = strtemp.split('|')[8];
                }
                if (strtemp.split('|').length >= 10 && document.getElementById('txtzip'+paxNum)) 
                {     //Zip [9]
                      document.getElementById('txtzip'+paxNum).value = strtemp.split('|')[9];
                }
                if (strtemp.split('|').length >= 11 && document.getElementById('txtcountry'+paxNum)) 
                {     //Country [10]
                      document.getElementById('txtcountry'+paxNum).value = strtemp.split('|')[10];
                }
                if (strtemp.split('|').length >= 11 && document.getElementById('selcountry'+paxNum)) 
                {     //Country [10]
                      document.getElementById('selcountry'+paxNum).value = strtemp.split('|')[10];
                }
                //Set the NON-US checkbox
                if (strtemp.split('|').length >= 11 && document.getElementById('selcountry'+paxNum) && document.getElementById('selcountry'+paxNum).value.toUpperCase()!="US") 
                {     //Country [10]                       
                      if(document.getElementById('chkNonUS'+paxNum)){document.getElementById('chkNonUS'+paxNum).checked=true; changePhone(paxNum,'chkNonUS'+paxNum,'chkUS'+paxNum);}
                }
                else
                {      
                      if(document.getElementById('chkNonUS'+paxNum)){document.getElementById('chkNonUS'+paxNum).checked=false; changePhone(paxNum,'chkNonUS'+paxNum,'chkUS'+paxNum);}
                }
                if (strtemp.split('|').length >= 12 && document.getElementById('txtgender'+paxNum)) 
                {     //Gender [11]
                      document.getElementById('txtgender'+paxNum).value = strtemp.split('|')[11];
                }
                 if (strtemp.split('|').length >= 12 && document.getElementById('radgender1')) 
                {     //Gender [11]
                      if(strtemp.split('|')[11] == "M" && document.getElementById('radgenderM'+paxNum))
                      {
                        document.getElementById('radgenderM'+paxNum).checked = true;
                      }
                      else if(strtemp.split('|')[11] == "F" && document.getElementById('radgenderF'+paxNum))
                      {
                        document.getElementById('radgenderF'+paxNum).checked = true;
                      }
                      else   //neither
                      {
                        document.getElementById('radgenderF'+paxNum).checked = false;
                        document.getElementById('radgenderM'+paxNum).checked = false;
                      }
                }
                else
                {   //empty em out
                   if(document.getElementById('radgenderM'+paxNum)){document.getElementById('radgenderM'+paxNum).checked = true;}
                   if(document.getElementById('radgenderF'+paxNum)){document.getElementById('radgenderF'+paxNum).checked = true;}
                }
                if (strtemp.split('|').length >= 13 && document.getElementById('seltitle'+paxNum)) 
                {     //Title [12]
                      document.getElementById('seltitle'+paxNum).value = strtemp.split('|')[12];
                }
                if (strtemp.split('|').length >= 14 && document.getElementById('txtemail'+paxNum)) 
                {     //Email  [13]
                      document.getElementById('txtemail'+paxNum).value = strtemp.split('|')[13];
                }
                if (strtemp.split('|').length >= 15) 
                {     //Phone [14]
                      if( document.getElementById('selcountry'+paxNum) &&  document.getElementById('selcountry'+paxNum).value == "US")
                      {    
                           if(strtemp.split('|')[14].split('-').length >= 3)
                           {
                               if(document.getElementById('txtphone1'+paxNum)){document.getElementById('txtphone1'+paxNum).value = strtemp.split('|')[14].split('-')[0];}
                               if(document.getElementById('txtphone2'+paxNum)){document.getElementById('txtphone2'+paxNum).value = strtemp.split('|')[14].split('-')[1];}
                               if(document.getElementById('txtphone3'+paxNum)){document.getElementById('txtphone3'+paxNum).value = strtemp.split('|')[14].split('-')[2];}
                           }
                           else
                           {
                                if(document.getElementById('txtphone'+paxNum)){document.getElementById('txtphone'+paxNum).value = strtemp.split('|')[14];}
                                //empty out the 3 text boxees
                                if(document.getElementById('txtphone1'+paxNum)){document.getElementById('txtphone1'+paxNum).value = '';}
                                if(document.getElementById('txtphone2'+paxNum)){document.getElementById('txtphone2'+paxNum).value = '';}
                                if(document.getElementById('txtphone3'+paxNum)){document.getElementById('txtphone3'+paxNum).value = '';}
                           }
                      }
                      else
                      {     
                            if(document.getElementById('txtphone'+paxNum)){document.getElementById('txtphone'+paxNum).value = strtemp.split('|')[14];}
                      }
                                            
                }
                if (strtemp.split('|').length >= 16 && document.getElementById('txtphone4'+paxNum)) 
                {     //PhoneExt [15]
                      document.getElementById('txtphone4'+paxNum).value = strtemp.split('|')[15];
                }
                if (strtemp.split('|').length >= 17) 
                {     //MobilePhone [16]
                      if( document.getElementById('selcountry'+paxNum) &&  document.getElementById('selcountry'+paxNum).value == "US")
                      {
                           if(strtemp.split('|')[16].split('-').length >= 3)
                           {
                               if(document.getElementById('txtmobilephone1'+paxNum)){document.getElementById('txtmobilephone1'+paxNum).value = strtemp.split('|')[16].split('-')[0];}
                               if(document.getElementById('txtmobilephone2'+paxNum)){document.getElementById('txtmobilephone2'+paxNum).value = strtemp.split('|')[16].split('-')[1];}
                               if(document.getElementById('txtmobilephone3'+paxNum)){document.getElementById('txtmobilephone3'+paxNum).value = strtemp.split('|')[16].split('-')[2];}
                           }
                           else
                           {
                               if(document.getElementById('txtmobilephone'+paxNum)){document.getElementById('txtmobilephone'+paxNum).value = strtemp.split('|')[16];}
                               //empty out the 3 text boxees
                               if(document.getElementById('txtmobilephone1'+paxNum)){document.getElementById('txtmobilephone1'+paxNum).value = '';}
                               if(document.getElementById('txtmobilephone2'+paxNum)){document.getElementById('txtmobilephone2'+paxNum).value = '';}
                               if(document.getElementById('txtmobilephone3'+paxNum)){document.getElementById('txtmobilephone3'+paxNum).value = '';}
                           }
                      }
                      else
                      {
                          if(document.getElementById('txtmobilephone'+paxNum)){document.getElementById('txtmobilephone'+paxNum).value = strtemp.split('|')[16];}
                      }
                      
                }
               if (strtemp.split('|').length >= 18) 
                {     //Fax [17]
                      if( document.getElementById('selcountry'+paxNum) &&  document.getElementById('selcountry'+paxNum).value == "US")
                      {
                           if(strtemp.split('|')[17].split('-').length >= 3)
                           {
                               if(document.getElementById('txtfax1'+paxNum)){document.getElementById('txtfax1'+paxNum).value = strtemp.split('|')[17].split('-')[0];}
                               if(document.getElementById('txtfax2'+paxNum)){document.getElementById('txtfax2'+paxNum).value = strtemp.split('|')[17].split('-')[1];}
                               if(document.getElementById('txtfax3'+paxNum)){document.getElementById('txtfax3'+paxNum).value = strtemp.split('|')[17].split('-')[2];}
                           }
                           else
                           {
                               if(document.getElementById('txtfax'+paxNum)){document.getElementById('txtfax'+paxNum).value = strtemp.split('|')[17];}
                               //empty out the 3 text boxees
                               if(document.getElementById('txtfax1'+paxNum)){document.getElementById('txtfax1'+paxNum).value = '';}
                               if(document.getElementById('txtfax2'+paxNum)){document.getElementById('txtfax2'+paxNum).value = '';}
                               if(document.getElementById('txtfax3'+paxNum)){document.getElementById('txtfax3'+paxNum).value = '';}
                           }
                      }
                      else
                      {
                          if(document.getElementById('txtfax'+paxNum)){document.getElementById('txtfax'+paxNum).value = strtemp.split('|')[17];}
                      }
                      
                }
                if (strtemp.split('|').length >= 19 && FormatDate(strtemp.split('|')[18],'yyyy') != '1900') 
                {     //BirthDate [18]   as a selection 
                
                      if(document.getElementById('txtbirthdate'+paxNum)){document.getElementById('txtbirthdate'+paxNum).value = '';}
                      if(document.getElementById('selDOBDay'+paxNum)){document.getElementById('selDOBDay'+paxNum).value = FormatDate(strtemp.split('|')[18],'dd');}                 
                      if(document.getElementById('selDOBMonth'+paxNum)){document.getElementById('selDOBMonth'+paxNum).value = FormatDate(strtemp.split('|')[18],'MM');}
                      if(document.getElementById('txtDOBYear'+paxNum)){document.getElementById('txtDOBYear'+paxNum).value = FormatDate(strtemp.split('|')[18],'yyyy');}
                }
                else
                {   //empty em out 
                
                     if(document.getElementById('selDOBDay'+paxNum)){document.getElementById('selDOBDay'+paxNum).value = '';}                 
                     if(document.getElementById('selDOBMonth'+paxNum)){document.getElementById('selDOBMonth'+paxNum).value = '';}
                     if(document.getElementById('txtDOBYear'+paxNum)){document.getElementById('txtDOBYear'+paxNum).value = 'Year';}
                     if(document.getElementById('txtbirthdate'+paxNum)){document.getElementById('txtbirthdate'+paxNum).value = '';}
                }
                if (strtemp.split('|').length >= 19 && document.getElementById('txtbirthdate'+paxNum) && FormatDate(strtemp.split('|')[18],'yyyy') != '1900') 
                {     //BirthDate [18]  as a text box
                      document.getElementById('txtbirthdate'+paxNum).value = FormatDate(strtemp.split('|')[18],'dd MMM yyyy');
                }
                else
                {    // empty out
                     if(document.getElementById('txtbirthdate'+paxNum)){document.getElementById('txtbirthdate'+paxNum).value = '';}
                }
                if (strtemp.split('|').length >= 20 && document.getElementById('txtbirthplace'+paxNum)) 
                {     //BirthPlace [19]
                      document.getElementById('txtbirthplace'+paxNum).value = strtemp.split('|')[19];
                }
                if (strtemp.split('|').length >= 21 && document.getElementById('txtage'+paxNum)) 
                {     //Age [20]
                      document.getElementById('txtage'+paxNum).value = strtemp.split('|')[20];
                }
                if (strtemp.split('|').length >= 22 && document.getElementById('txtpassportnumber'+paxNum)) 
                {     //PassportNumber [21]
                      document.getElementById('txtpassportnumber'+paxNum).value = strtemp.split('|')[21];
                }
                if (strtemp.split('|').length >= 23 && FormatDate(strtemp.split('|')[22],'yyyy') != '1900') 
                {     //PassportExpiration [22]   as a selection                       
                      if(document.getElementById('selPassExpirationDay'+paxNum)){document.getElementById('selPassExpirationDay'+paxNum).value = FormatDate(strtemp.split('|')[22],'dd');}                 
                      if(document.getElementById('selPassExpirationMonth'+paxNum)){document.getElementById('selPassExpirationMonth'+paxNum).value = FormatDate(strtemp.split('|')[22],'MM');}
                      if(document.getElementById('txtPassExpirationYear'+paxNum)){document.getElementById('txtPassExpirationYear'+paxNum).value = FormatDate(strtemp.split('|')[22],'yyyy');}
                }
                else
                {     //empty em out
                      if(document.getElementById('selPassExpirationDay'+paxNum)){document.getElementById('selPassExpirationDay'+paxNum).value = '';}                 
                      if(document.getElementById('selPassExpirationMonth'+paxNum)){document.getElementById('selPassExpirationMonth'+paxNum).value = '';}
                      if(document.getElementById('txtPassExpirationYear'+paxNum)){document.getElementById('txtPassExpirationYear'+paxNum).value = 'Year';}
                }
                if (strtemp.split('|').length >= 23 && document.getElementById('txtpassportexpiration'+paxNum)) 
                {     //PassportExpiration [22] as a text box
                      document.getElementById('txtpassportexpiration'+paxNum).value = strtemp.split('|')[22];
                }
                if (strtemp.split('|').length >= 24 && document.getElementById('txtpassportauthority'+paxNum)) 
                {     //PassportAuthority [23]
                      document.getElementById('txtpassportauthority'+paxNum).value = strtemp.split('|')[23];
                }
                if (strtemp.split('|').length >= 25 && FormatDate(strtemp.split('|')[24],'yyyy') != '1900') 
                {     //PassportIssueDate [24]    as a selection                      
                      if(document.getElementById('selPassIssueDay'+paxNum)){document.getElementById('selPassIssueDay'+paxNum).value = FormatDate(strtemp.split('|')[24],'dd');}                 
                      if(document.getElementById('selPassIssueMonth'+paxNum)){document.getElementById('selPassIssueMonth'+paxNum).value = FormatDate(strtemp.split('|')[24],'MM');}
                      if(document.getElementById('txtPassIssueYear'+paxNum)){document.getElementById('txtPassIssueYear'+paxNum).value = FormatDate(strtemp.split('|')[24],'yyyy');}
                }
                else
                {     //empty em out
                      if(document.getElementById('selPassIssueDay'+paxNum)){document.getElementById('selPassIssueDay'+paxNum).value = '';}                 
                      if(document.getElementById('selPassIssueMonth'+paxNum)){document.getElementById('selPassIssueMonth'+paxNum).value = '';}
                      if(document.getElementById('txtPassIssueYear'+paxNum)){document.getElementById('txtPassIssueYear'+paxNum).value = 'Year';}
                }
                if (strtemp.split('|').length >= 25 && document.getElementById('txtpassportissue'+paxNum)) 
                {     //PassportIssueDate [24]   as a text box
                      document.getElementById('txtpassportissue'+paxNum).value = strtemp.split('|')[24];
                }
                if (strtemp.split('|').length >= 26 && document.getElementById('txtnationality'+paxNum)) 
                {     //Nationality [25] 
                      document.getElementById('txtnationality'+paxNum).value = strtemp.split('|')[25];
                }
                if (strtemp.split('|').length >= 27 && document.getElementById('txtemergencycontact'+paxNum)) 
                {     //EmergencyContact [26] 
                      document.getElementById('txtemergencycontact'+paxNum).value = strtemp.split('|')[26];
                }
                 if (strtemp.split('|').length >= 28) 
                {     //Emergency Phone [27]
                      if( document.getElementById('selcountry'+paxNum) &&  document.getElementById('selcountry'+paxNum).value == "US")
                      {
                           if(strtemp.split('|')[27].split('-').length >= 3)
                           {
                               if(document.getElementById('txtemergencyphone1'+paxNum)){document.getElementById('txtemergencyphone1'+paxNum).value = strtemp.split('|')[27].split('-')[0];}
                               if(document.getElementById('txtemergencyphone2'+paxNum)){document.getElementById('txtemergencyphone2'+paxNum).value = strtemp.split('|')[27].split('-')[1];}
                               if(document.getElementById('txtemergencyphone3'+paxNum)){document.getElementById('txtemergencyphone3'+paxNum).value = strtemp.split('|')[27].split('-')[2];}
                           }
                           else
                           {
                               if(document.getElementById('txtemergencyphone'+paxNum)){document.getElementById('txtemergencyphone'+paxNum).value = strtemp.split('|')[27];}
                               //empty out the 3 text boxees
                               if(document.getElementById('txtemergencyphone1'+paxNum)){document.getElementById('txtemergencyphone1'+paxNum).value = '';}
                               if(document.getElementById('txtemergencyphone2'+paxNum)){document.getElementById('txtemergencyphone2'+paxNum).value = '';}
                               if(document.getElementById('txtemergencyphone3'+paxNum)){document.getElementById('txtemergencyphone3'+paxNum).value = '';}
                           }
                      }
                      else
                      {
                          if(document.getElementById('txtemergencyphone'+paxNum)){document.getElementById('txtemergencyphone'+paxNum).value = strtemp.split('|')[27];}
                      }
                      
                }
                
                 //check whether or not this selected contact has Contact Rewards, need to display that drop down and add options if so
                //alert('strtemp =' + strtemp); 
                if (strtemp.split('|').length >= 1 && strtemp.split('|')[0] != '') 
                {                               
                    strContactID = strtemp.split('|')[0];   // [0] is ContactID           
                    //alert('strContactID =' + strContactID + ' paxNum:  ' + paxNum);                        
                    strRequest =  '<ContactID>' + strContactID + '</ContactID><PaxNum>' + paxNum + '</PaxNum>';
                    //alert('strRequest =' + strRequest);                        
                    strJS = returnContactRewards(sess, strRequest);                     
                 }
                 else
                 {
                     strJS = " hide('rewardtr1" + paxNum + "');    if(document.getElementById('btnApplyReward" + paxNum + "')){ document.getElementById('btnApplyReward" + paxNum + "').disabled = false; }";                  
                 }
                 //alert('JavaScript:  ' + strJS);
                 
                //strJS will now have any javascript needed for:
                //  1) Adding their Contact Rewards to the drop down  (if there are any)  
                //  2) Showing the contact rewards row for this contact (if there are any)
                eval(strJS);
                
                
           } // end of if strTemp  != "" 
           if(blnKeepName)
           {
                //Reset the FirstName and LastName textboxes
                if(document.getElementById('txtfirst' + paxNum))
                {
                    document.getElementById('txtfirst' + paxNum).value = strFirstName;
                }
                if(document.getElementById('txtlast' + paxNum))
                {
                    document.getElementById('txtlast' + paxNum).value = strLastName;  
                }
           }
        }  // end if the drop down exists    
 }

/**** Function will build Passport Issue Date and return value 
to passportissue text box if all values are available  ****/
function buildPassIssueDate(strid, strPaxNum)
{


     // Set the optional parameter if needed
    if (strPaxNum === undefined ) 
    {      strPaxNum = '';      }

    //Expects form elements:  selPassIssueMonth, selPassIssueDay, txtPassIssueYear to be present
    if(    document.getElementById('selPassIssueMonth' + strPaxNum).value != '' &&     document.getElementById('selPassIssueDay' + strPaxNum).value != '' &&     document.getElementById('txtPassIssueYear' + strPaxNum).value.replace('Year','').replace('YEAR').replace('year') != ''   )
    { //have full passport issue date!             
        //set element
       document.getElementById(strid).value = (document.getElementById('txtPassIssueYear' + strPaxNum).value + '-' + document.getElementById('selPassIssueMonth' + strPaxNum).value + '-' + document.getElementById('selPassIssueDay' + strPaxNum).value);
       var PassIssue = new Date(document.getElementById('txtPassIssueYear' + strPaxNum).value + '/' + document.getElementById('selPassIssueMonth' + strPaxNum).value + '/' + document.getElementById('selPassIssueDay' + strPaxNum).value);
       var Today = new Date();
       if(PassIssue > Today)                               
       {   //this date is in the future, can't be a Passport Issue Date
            document.getElementById(strid).value = '';
            alert('Please check Passport Issue Date.  Date entered is in the future and therefore invalid.') ;  
                                  
       }
       if(PassIssue.getFullYear() < 1900)
       {  // this date is not a valid SQL date even though it is a valid JavaScript date
           document.getElementById(strid).value = '';
            alert('Please check Passport Issue Date.  Date entered is invalid.') ;            
       }
    }
    else
    {
        //don't have all fields to build full passport issue date!  
        document.getElementById(strid).value = '';
    }    
}

/**** Function will build Passport Exp Date and return value to 
passportexpiration text box if all values are available  ****/
function buildPassExpirationDate(strid, strPaxNum)
{     
     // Set the optional parameter if needed
    if (strPaxNum === undefined ) 
    {      strPaxNum = '';      }

    //Expects form elements:  selPassExpirationMonth, selPassExpirationDay, txtPassExpirationYear to be present
    if(    document.getElementById('selPassExpirationMonth' + strPaxNum).value != '' &&     document.getElementById('selPassExpirationDay' + strPaxNum).value != '' &&     document.getElementById('txtPassExpirationYear' + strPaxNum).value.replace('Year','').replace('YEAR').replace('year') != ''   )
    { //have full passport exp date!             
        //set element
       document.getElementById(strid).value = (document.getElementById('txtPassExpirationYear' + strPaxNum).value + '-' + document.getElementById('selPassExpirationMonth' + strPaxNum).value + '-' + document.getElementById('selPassExpirationDay' + strPaxNum).value);
       var PassExp = new Date(document.getElementById('txtPassExpirationYear' + strPaxNum).value + '/' + document.getElementById('selPassExpirationMonth' + strPaxNum).value + '/' + document.getElementById('selPassExpirationDay' + strPaxNum).value);
       var Today = new Date();
       if(PassExp < Today) 
       {   //this date is in the past, can't be a passport exp. date
            document.getElementById(strid).value = '';
            alert('Please check Passport Expiration Date.  Date entered is in the past and therefore invalid.') ;            
       }
       if(PassExp.getFullYear() < 1900)
       {  // this date is not a valid SQL date even though it is a valid JavaScript date
           document.getElementById(strid).value = '';
            alert('Please check Passport Expiration Date.  Date entered is invalid.') ;            
       }                                    
    }
    else
    {
        //don't have all fields to build full passport exp date!  
        document.getElementById(strid).value = '';
    }
    //alert( document.getElementById(strid).value);
}

/**** Function will build birthdate and return value to 
birthdate text box if all values are available  ****/
function buildBirthDate(strid, strPaxNum)
{
      

     // Set the optional parameter if needed
     if (strPaxNum === undefined ) 
    {      strPaxNum = '';      }

    //Expects form elements:  selDOBMonth, selDOBDay, txtDOBYear to be present
    if(    document.getElementById('selDOBMonth' + strPaxNum).value != '' &&     document.getElementById('selDOBDay' + strPaxNum).value != '' &&     document.getElementById('txtDOBYear' + strPaxNum).value.replace('Year','').replace('YEAR').replace('year') != ''   )
    { //have full birthdate!             
               
        //set element
       document.getElementById(strid).value = (document.getElementById('txtDOBYear' + strPaxNum).value + '-' + document.getElementById('selDOBMonth' + strPaxNum).value + '-' + document.getElementById('selDOBDay' + strPaxNum).value);
       var Birthdate = new Date(document.getElementById('txtDOBYear' + strPaxNum).value + '/' + document.getElementById('selDOBMonth' + strPaxNum).value + '/' + document.getElementById('selDOBDay' + strPaxNum).value);
       var Today = new Date();
       
       if(Birthdate > Today) 
       {   //this date is in the future, can't be a Birth Date
            document.getElementById(strid).value = '';
            alert('Please check birthdate.  Date entered is in the future and therefore invalid.') ;               
                    
       }
       if(Birthdate.getFullYear() < 1900)
       {  // this date is not a valid SQL date even though it is a valid JavaScript date
           document.getElementById(strid).value = '';
            alert('Please check birthdate.  Date entered is invalid.') ;            
       }
    }
    else
    {
        //don't have all fields to build full birthdate!
        document.getElementById(strid).value = '';
    }
    //alert(strid + ' build:' + document.getElementById(strid).value);
}

/**** 
This function will take the birthdate, the departure date, and the age textbox and will calculate the pax's age at
the time of departure and auto fill the age text box
****/
function calculateAge(datDOB, datDepDate, id)
{
    
   if(document.getElementById(id))
   {    // age input exists
                  
        datDepDate = new Date(datDepDate);
        datDOB = new Date(datDOB.replace(/-/g, '/'));
        
        //alert(  ((datDepDate - datDOB) / (365.25 * 24 * 60 * 60 * 1000)) );  
        //  alert(datDepDate.getDate() + '  /  ' +  datDOB.getDate()  + '  /  ' +    datDepDate.getMonth()  + '  /  ' +  datDOB.getMonth()); 
        
        if(datDepDate.getDate() ==  datDOB.getDate() && datDepDate.getMonth() == datDOB.getMonth())
        {   
            //if its the same day, add 1
            document.getElementById(id).value = Math.floor(((datDepDate - datDOB) / (365.25 * 24 * 60 * 60 * 1000))) + 1;     
        }
        else
        {
            document.getElementById(id).value = Math.floor(((datDepDate - datDOB) / (365.25 * 24 * 60 * 60 * 1000)));     
        }
    }

}


/**** Validates that the Date entered is in a correct format ****/
 function validateDate(dat, obj, min, max, strfieldName)
{
    
    var dat2 = new Date(dat);
    var dat3 = new Date(min);
    var dat4 = new Date(max); //want to make max today if unspecified
    
    if (strfieldName == '' || !strfieldName)
    {
        strfieldName = ''
    }
    else
    {
        strfieldName = ' for the ' + strfieldName
    }
    
    //get max date if empty
    if (dat4 == '' || !dat4 || dat4 == null || dat4 == 'NaN' || isNaN(dat4))
    {
        dat4 = new Date(); // Today
    }
    
    
    if (dat2 == '' || !dat2 || dat2 == null || dat2 == 'NaN' || isNaN(dat2))
    {
        alert('Invalid Date Format. Please enter in the format dd MMM yyyy' + strfieldName);
        obj.focus();
        return false;
    }

    if (dat2 < dat3)
    {
        alert('Minimum date allowed is ' + (dat3.getMonth() + 1) + '/' + dat3.getDate() + '/' + dat3.getFullYear() + strfieldName);
        obj.focus();
        return false;
    }
   
   if (dat4 < dat2)
    {
        alert('Maximum date allowed is ' + (dat4.getMonth() + 1) + '/' + dat4.getDate() + '/' + dat4.getFullYear()  + strfieldName);
        obj.focus();
        return false;
    }
    
    
        obj.value = FormatDate(dat, 'dd MMM yyyy');
        return true;
    
}

/*
    FormatDate
    ----------
        Returns a string representation of the specified date object
        Input:
            dat     The date to format
            frm     The formatting string
                        yyyy - 4-digit year
                        yy   - 2-digit year
                        MM   - 2-digit month
                        MMM  - Short month (Jan, Feb etc.)
                        MMMM - Full month (January, February etc.)
                        d    - Date (without padding/zeros)
                        dd   - 2-digit day
*/
//Full month names
var fullmonths  = new Array(12);
fullmonths[0]   = 'January';
fullmonths[1]   = 'February';
fullmonths[2]   = 'March';
fullmonths[3]   = 'April';
fullmonths[4]   = 'May';
fullmonths[5]   = 'June';
fullmonths[6]   = 'July';
fullmonths[7]   = 'August';
fullmonths[8]   = 'September';
fullmonths[9]   = 'October';
fullmonths[10]  = 'November';
fullmonths[11]  = 'December';

//Short month names
var shortmonths = new Array(12);
shortmonths[0]  = 'Jan';
shortmonths[1]  = 'Feb';
shortmonths[2]  = 'Mar';
shortmonths[3]  = 'Apr';
shortmonths[4]  = 'May';
shortmonths[5]  = 'Jun';
shortmonths[6]  = 'Jul';
shortmonths[7]  = 'Aug';
shortmonths[8]  = 'Sep';
shortmonths[9]  = 'Oct';
shortmonths[10] = 'Nov';
shortmonths[11] = 'Dec';

function FormatDate(dat, frm)
{
    try
    {
        
        var strout;   
        if (!frm || frm == '')
        {
            frm = 'dd MMM yyyy'
        }
        //dat = dat.toString().replace(/-/g, '/');
        dat = dat.toString().replace(/ 00:00:00.000/g, '');
        
        strout = frm;
        dat = new Date(dat);
        if (dat == '' || !dat || dat == null || dat == 'NaN' || isNaN(dat)) 
        {
            //alert('Converted dat is nothing/blank/null/nan');
            return '';
        }
        //Year
        //If before 1900, it should be 2000's
        if (dat.getFullYear() < 1900)
            dat.setFullYear(dat.getFullYear() + 100);
        //yyyy
        strout = strout.replace(/yyyy/g, dat.getFullYear());
        //yy
        strout = strout.replace(/yy/g, ('' + dat.getFullYear()).substring(2, 4));
        
        //Day
        //dd
        if (dat.getDate() < 10)
        {
            strout = strout.replace(/dd/g, '0' + dat.getDate());
        }
        else
        {
            strout = strout.replace(/dd/g, dat.getDate());
        }
        //d
        strout = strout.replace(/d/g, dat.getDate());
        
        //Month
        //MMMM
        strout = strout.replace(/MMMM/g, fullmonths[dat.getMonth()]);
        //MMM
        strout = strout.replace(/MMM/g, shortmonths[dat.getMonth()]);
        //MM
        if ((dat.getMonth() + 1) < 10)
        {
            strout = strout.replace(/MM/g, '0' + (dat.getMonth() + 1));
        }
        else
        {
            strout = strout.replace(/MM/g, dat.getMonth() + 1);
        }
        
        //Done
        return strout;
    }
    catch (ex)
    {
        alert('FormatDate() Failed: ' + ex.message);
    }
}

/**************************************************************/
/* Car Rental Service Pickup/Dropoff time functions */
/**************************************************************/
//For Car Only, when a car service radio button is selected, save the service and check if its Per24Hrs.
function checkPer24(dest, svc, grace)
{
    if (document.getElementById('maincarpickuploc' + dest))
	    document.getElementById('maincarpickuploc' + dest).disabled = false;
    if (document.getElementById('maincarpickuptime' + dest))
        document.getElementById('maincarpickuptime' + dest).disabled = false;
    if (document.getElementById('maincardropoffloc' + dest))
        document.getElementById('maincardropoffloc' + dest).disabled = false;
    if (document.getElementById('maincardropofftime' + dest))
        document.getElementById('maincardropofftime' + dest).disabled = false;

	document.getElementById('selectedcarsvc' + dest).value = svc;

	if (document.getElementById('per24Hrs_' + svc).value == 'Y')
	{
		compareTimes(dest, grace);
	}
	else
	{
		document.getElementById('maincarwarning' + dest).style.display = 'none';
		document.getElementById('carover24hrs' + dest).value = 'N';
	}
}

//For Car Only, when pickup or dropoff times changes, see if the currently selected Car service is Per24Hrs.
function getSelectedCarSvc(dest, grace)
{
	var car = document.getElementById('selectedcarsvc' + dest).value;

	if (document.getElementById('per24Hrs_' + car).value == 'Y')
	{
		compareTimes(dest, grace);
	}
}
	
//This function compares the times selected in the pickup and dropoff lists on various screens
//For car rental services that need to charge an extra day fee (which is almost universal)
//If the difference between pickup and dropoff time is greater than 24 hrs + an optional predefined grace period (from DefaultID = CarGracePeriod)
//Then a warning message is displayed, and if booked, an extra day is added to the duration.
function compareTimes(dest, grace)
{
    var t1, t2, hr, min;
    var t1diff, t2diff, total, limit;

    t1 = document.getElementById('maincarpickuptime' + dest).value;
    t2 = document.getElementById('maincardropofftime' + dest).value;

    t1diff = new Number();
    t2diff = new Number();

    total = new Number();
    limit = new Number();

	//the limit is how much time, in minutes, the dropoff time can be from the pickup time without charging an extra day.
	//1440 = 24 hours * 60.
	//The second number comes from the default value CarGracePeriod - any extra time a company allows after 24 hours.
    limit = 1440 + grace;

    //Get the total number of minutes from t1 until midnight
    hr = new Number(t1.split(":")[0]);
    min = new Number(t1.split(":")[1]);
    t1diff = 1440 - ((hr * 60) + min)

    //Get the total number of minutes from midnight until t2
    hr = new Number(t2.split(":")[0]);
    min = new Number(t2.split(":")[1]);
    t2diff = (hr * 60) + min

    //Get the total number of minutes between the pickup and dropoff times
    total = t1diff + t2diff

    //Is the total greater than the allowed amount of time? If yes, then display a warning
    if (total > limit)
    {
		document.getElementById('maincarwarning' + dest).style.display = 'block';
		document.getElementById('carover24hrs' + dest).value = 'Y';
    }
    else
    {
    	document.getElementById('maincarwarning' + dest).style.display = 'none';
    	document.getElementById('carover24hrs' + dest).value = 'N';
    }
}

/******************/
/* IS NUMBER KEY */
/******************/

//This function checks phone numbers,fax numbers, and zip codes to make sure only numbers are entered
function isNumberKey(evt)
{
     var charCode = evt.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

/*****************/
/*  CHANGE PHONE */
/*****************/
//This function changes the phone formats depending on if this Country is US/CA or not
function changePhone()
{
    if(document.getElementById('selcountry').value != 'US' && document.getElementById('selcountry').value != 'CA' && document.getElementById('selcountry').value != '')
    {
        if (document.getElementById('usphonetd'))
        {
            document.getElementById('usphonetd').style.display = 'none';
            document.getElementById('nonusphonetd').style.display = '';
        }
        if (document.getElementById('usmobilephonetd'))
        {
            document.getElementById('usmobilephonetd').style.display = 'none';
            document.getElementById('nonusmobilephonetd').style.display = '';
        }
        if (document.getElementById('usfaxtd'))
        {
            document.getElementById('usfaxtd').style.display = 'none';
            document.getElementById('nonusfaxtd').style.display = '';
        }
        if(document.getElementById('usemergencyphonetd'))
        {
           document.getElementById('usemergencyphonetd').style.display = 'none';
           document.getElementById('nonusemergencyphonetd').style.display = '';
        }
        
        /* Now do customers */
        if (document.getElementById('custusphonetd'))
        {
            document.getElementById('custusphonetd').style.display = 'none';
            document.getElementById('custnonusphonetd').style.display = '';
        }
        if (document.getElementById('custusmobilephonetd'))
        {
            document.getElementById('custusmobilephonetd').style.display = 'none';
            document.getElementById('custnonusmobilephonetd').style.display = '';
        }
        if (document.getElementById('custusfaxtd'))
        {
            document.getElementById('custusfaxtd').style.display = 'none';
            document.getElementById('custnonusfaxtd').style.display = '';
        }
        if(document.getElementById('custusemergencyphonetd'))
        {
           document.getElementById('custusemergencyphonetd').style.display = 'none';
           document.getElementById('custnonusemergencyphonetd').style.display = '';
        }
    }
    else
    {
        if (document.getElementById('usphonetd'))
        {
            document.getElementById('nonusphonetd').style.display = 'none';
            document.getElementById('usphonetd').style.display = '';
        }
        if (document.getElementById('usmobilephonetd'))
        {
            document.getElementById('nonusmobilephonetd').style.display = 'none';
            document.getElementById('usmobilephonetd').style.display = '';
        }
        if (document.getElementById('usfaxtd'))
        {
            document.getElementById('nonusfaxtd').style.display = 'none';
            document.getElementById('usfaxtd').style.display = '';
        }
        if(document.getElementById('usemergencyphonetd'))
        {
           document.getElementById('usemergencyphonetd').style.display = '';
           document.getElementById('nonusemergencyphonetd').style.display = 'none';
        }
        
        /* Now do customers */
        if (document.getElementById('custusphonetd'))
        {
            document.getElementById('custnonusphonetd').style.display = 'none';
            document.getElementById('custusphonetd').style.display = '';
        }
        if (document.getElementById('custusmobilephonetd'))
        {
            document.getElementById('custnonusmobilephonetd').style.display = 'none';
            document.getElementById('custusmobilephonetd').style.display = '';
        }
        if (document.getElementById('custusfaxtd'))
        {
            document.getElementById('custnonusfaxtd').style.display = 'none';
            document.getElementById('custusfaxtd').style.display = '';
        }
        if(document.getElementById('custusemergencyphonetd'))
        {
           document.getElementById('custusemergencyphonetd').style.display = '';
           document.getElementById('custnonusemergencyphonetd').style.display = 'none';
        }
    }
}

/*******************/
/*  COUNTRY CHANGE */
/*******************/
//Function changes the display of state/province textbox or dropdown based on US address or not
//input of paxnNum 
//input of AddrType (MAIL or BILL)
function countryChangeMailBill(paxNum, strAddrType)
{
    if (strAddrType.toUpperCase() =='BILL')
    {
        if (
                document.getElementById('selbillcountry' + paxNum).value != 'US' 
                && document.getElementById('selbillcountry' + paxNum).value != ''
            )
        {
            document.getElementById('txtbillstate' + paxNum).style.display='';
            document.getElementById('selbillstate' + paxNum).style.display='none';
        } 
        else //US - show dropdown, not textbox
        {
            document.getElementById('selbillstate' + paxNum).style.display='';
            document.getElementById('txtbillstate' + paxNum).style.display='none';
        }
    }
        
    if (strAddrType.toUpperCase() =='MAIL')
    {
        if (
                document.getElementById('selcountry' + paxNum).value != 'US' 
                && document.getElementById('selcountry' + paxNum).value != ''
            )
        {
            document.getElementById('txtstate' + paxNum).style.display='';
            document.getElementById('selstate' + paxNum).style.display='none';
        } 
        else //US - show dropdown, not textbox
        {
            document.getElementById('selstate' + paxNum).style.display='';
            document.getElementById('txtstate' + paxNum).style.display='none';
        }
    }        
}

//Function changes the display of state/province textbox or dropdown based on US address or not
//input of paxnNum
function countryChange(paxNum) 
{ 
    if (
        (document.getElementById('selbillcountry' + paxNum) && document.getElementById('selbillstate' + paxNum)) 
        || 
        (document.getElementById('txtbillcountry' + paxNum)  && document.getElementById('txtbillstate' + paxNum))
        )
        {
            if (
                    document.getElementById('selbillcountry' + paxNum).value != 'US' 
                    && document.getElementById('selbillcountry' + paxNum).value != ''
                )
            {
                document.getElementById('txtbillstate' + paxNum).style.display='';
                document.getElementById('selbillstate' + paxNum).style.display='none';
            } 
            else //US - show dropdown, not textbox
            {
                document.getElementById('selbillstate' + paxNum).style.display='';
                document.getElementById('txtbillstate' + paxNum).style.display='none';
            }
        }
    if (
        (document.getElementById('selcountry' + paxNum) && document.getElementById('selstate' + paxNum)) 
        || 
        (document.getElementById('txtcountry' + paxNum)  && document.getElementById('txtstate' + paxNum))
        )
        {
            if (
                    document.getElementById('selcountry' + paxNum).value != 'US' 
                    && document.getElementById('selcountry' + paxNum).value != ''
                )
            {
                document.getElementById('txtstate' + paxNum).style.display='';
                document.getElementById('selstate' + paxNum).style.display='none';
            } 
            else //US - show dropdown, not textbox
            {
                document.getElementById('selstate' + paxNum).style.display='';
                document.getElementById('txtstate' + paxNum).style.display='none';
            }
        }        
       
}

//Function changes the display of state/province textbox or dropdown based on US address or not
//no input
function countryChange()
{ 
    if (
        (document.getElementById('selbillcountry') && document.getElementById('selbillstate')) 
        || 
        (document.getElementById('txtbillcountry')  && document.getElementById('txtbillstate'))
        )
        {
            if (
                    document.getElementById('selbillcountry').value != 'US' 
                    && document.getElementById('selbillcountry').value != ''
                )
            {
                document.getElementById('txtbillstate').style.display='';
                document.getElementById('selbillstate').style.display='none';
            } 
            else //US - show dropdown, not textbox
            {
                document.getElementById('selbillstate').style.display='';
                document.getElementById('txtbillstate').style.display='none';
            }
        }
    if (
        (document.getElementById('selcountry') && document.getElementById('selstate')) 
        || 
        (document.getElementById('txtcountry')  && document.getElementById('txtstate'))
        )
        {
            if (
                    document.getElementById('selcountry').value != 'US' 
                    && document.getElementById('selcountry').value != ''
                )
            {
                document.getElementById('txtstate').style.display='';
                document.getElementById('selstate').style.display='none';
            } 
            else //US - show dropdown, not textbox
            {
                document.getElementById('selstate').style.display='';
                document.getElementById('txtstate').style.display='none';
            }
        }        
    
}

/********/
/* IIF */
/********/
function Iif(bln, trueval, falseval)
{
    if (bln == true)
    {
        return trueval;
    }
    else
    {
        return falseval;
    }
}

/**********************/
/* IS VALID CHARACTER */
/**********************/

//This function field to make sure no Invalid Character (listed below) are being typed in.
function isValidChar(evt)
{        
    
    //var charCode = evt.keyCode;
    var charCode = evt.charCode ? evt.charCode : evt.keyCode;
   
    /*--------EXCLUDE THE FOLLOWING CHAR CODES--------------
        ! " # $ % &                   = 33 to 38
         ( ) * +                      = 40 to 43
          /                           = 47 
         0 1 2 3 4  5 6 7 8 9         = 48 to 57
         : ; < = > ? @                = 58 to 64   
         [ \ ] ^ _ `                  = 91 to 96
         { | } ~                      = 123 to 126
     -------------------------------------------------------*/      
     //alert(charCode);
   
        if ((charCode >= 33 && charCode <= 38) ||(charCode >= 40 && charCode <= 43) || (charCode == 47) || (charCode >= 48 && charCode <= 57) || (charCode >= 58 && charCode <= 64) || (charCode >= 91 && charCode <= 96) || (charCode >= 123 && charCode <= 126) )
        {
         
            return false;
        }
    return true;
}



//<!-- Coded by Larry & Tim 10/28/04 -->
function BGNew(obj, new_style, message)
{ 
    obj.className = new_style; 
    window.status = message; 
}

//reloads the window if Nav4 resized
function MM_reloadPage(init)
{
    if (init==true) with (navigator)
    {
        if ((appName=="Netscape")&&(parseInt(appVersion)==4))
        {
            document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage;
        }
    }
    else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH)
        location.reload();
}
MM_reloadPage(true);

//v4.01
function MM_findObj(n, d)
{
    var p, i, x; 
    if(!d)
        d = document;
    if((p = n.indexOf("?")) > 0 && parent.frames.length)
    {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if(!(x = d[n]) && d.all)
        x = d.all[n];
    
    for(i = 0; !x && i < d.forms.length; i++)
        x = d.forms[i][n];
    for(i = 0; !x && d.layers && i < d.layers.length; i++)
        x = MM_findObj(n, d.layers[i].document);
    if(!x && d.getElementById)
        x = d.getElementById(n);
    
    //Done
    return x;
}

//v6.0
function MM_showHideLayers()
{
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3)
    {
        if ((obj=MM_findObj(args[i]))!=null)
        {
            v = args[i + 2];
            if (obj.style)
            {
                obj = obj.style;
                v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v;
            }
            obj.visibility = v;
        }
    }
}

function timeout()
{
    setTimeout("MM_showHideLayers('europe-menu','','hide','asia-menu','','hide','americas-menu','','hide','med-menu','','hide','sp-menu','','hide','cruises-menu','','hide');", 15000);
}//-->


// Validate Credit Card Number
function ValidateCC(sCC)
{
	var i, t1, t2, t3, t4;
		
	if (sCC.charAt(sCC.length) == 'X') {
		return false;	
	}
	if (sCC.length < 13) {
		return false;	
	}
		
	t1 = parseInt(sCC.charAt(sCC.length - 1));
	t2 = 0;
	t3 = 0;
		
	for (i = sCC.length - 1; i >= 1; i--){
	    t2 = parseInt(t2) + 1;
	    t4 = sCC.charAt(i - 1);
	    if (t2 % 2 == 0)
	        t3 = parseInt(t3) + parseInt(t4)
	    else {
	        t4 = parseInt(t4) * 2;
	        if (parseInt(t4) > 9) 
				t3 = parseInt(t3) + 1 + (parseInt(t4) - 10);
	        if (t4 <= 9)
				t3 = parseInt(t3) + parseInt(t4);
	    }
	}
	t2 = parseInt(t3) + parseInt(t1);
	if (t2 % 10 > 0) return false;
	if (t2 == 0) return false;
	return true;	
}


// Validate the card type from the card number prefix and length
function ValidateCCType(sCC, sType)
{
	var prefix;
	
	switch(sType)
	{
		case "MC":
			prefix = parseInt(sCC.substr(0,2));
			if( sCC.length == 16 && prefix >= 51 && prefix <= 55 ) 
				return true;
			break
		case "VI":
			if ( (sCC.length == 16 || sCC.length == 13) && sCC.charAt(0) == '4' )
				return true;
			break
		case "AX":
		case "MX":
			prefix = sCC.substr(0,2);
			if( sCC.length == 15 && (prefix == '34' || prefix == '37' ) )
				return true;
			break
		case "DS":
			prefix = sCC.substr(0,4);
			if( sCC.length == 16 && prefix == '6011') 
				return true;
			break
		case "DI":
			prefix = parseInt(sCC.substr(0,3));
			if( sCC.length == 14 && ((prefix >= 300 && prefix <= 305) || sCC.substr(0,2) == '36' || sCC.substr(0,2) == '38') ) 
				return true;
			break
		case "LS":
			if( sCC.length <= 19 && sCC.length >= 16)
				return true;
		default:
			return false;
	}
	return false;
}





//All used in PKGRates
function buildQS()
{
    var iPreDur, iPostDur;
    var QS;
    var datIn, datOut, blnHasShares;
    QS = "";
    iPreDur = 0;
    iPostDur = 0;
    
    //Pre/Post options
    if (document.getElementById('chkAirY'))
    {
        if (document.getElementById('chkAirY').checked)
            QS = QS + '&chkAir=Y';
        else
        {
            if (document.getElementById('chkAirG'))
            {
                if (document.getElementById('chkAirG').checked)
                    QS = QS + '&chkAir=Y';
            }
            else
                QS = QS + '&chkAir=N';
        }
    }
      
    if (document.getElementById('airfromcity'))
        QS = QS + '&airfromcity=' + document.getElementById('airfromcity').value;
    if (document.getElementById('airtocity'))
        QS = QS + '&airtocity=' + document.getElementById('airtocity').value;
    if (document.getElementById('airdateout'))
        QS = QS + '&airdateout=' + document.getElementById('airdateout').value;
    if (document.getElementById('airdateret'))
        QS = QS + '&airdateret=' + document.getElementById('airdateret').value;
    if (document.getElementById('aircabinclass'))
        QS = QS + '&aircabinclass=' + document.getElementById('aircabinclass').value;
    if (document.getElementById('aircarrier'))
        QS = QS + '&aircarrier=' + document.getElementById('aircarrier').value;
    if (document.getElementById('airrettocity'))
        QS = QS + '&airrettocity=' + document.getElementById('airrettocity').value;
    if (document.getElementById('airretfromcity'))
        QS = QS + '&airretfromcity=' + document.getElementById('airretfromcity').value;
    if (document.getElementById('airoutstopcity'))
        QS = QS + '&airoutstopcity=' + document.getElementById('airoutstopcity').value;
    if (document.getElementById('blockonly'))
        QS = QS + '&blockonly=' + document.getElementById('blockonly').value;
        
	if (document.getElementById('airpreference') && document.getElementById('airpreference').checked == true)
	{
	        QS = QS + '&airpreference=' + document.getElementById('airpreference').value;
	}

    //see if we need to extend StopOver due to pre- and -post options.        
    if(document.getElementById('preacc'))
    {
        if(document.getElementById('preaccdur').value != '0' && document.getElementById('preaccdur').value != '' && document.getElementById('preacc').checked)
        {
            iPreDur = parseInt(document.getElementById('preaccdur').value);
        }
    }
    if(document.getElementById('postacc'))
    {
        if(document.getElementById('postaccdur').value != '0' && document.getElementById('postaccdur').value != '' && document.getElementById('postacc').checked)
        {
            iPostDur = parseInt(document.getElementById('postaccdur').value);
        }
    }
    if (document.getElementById('airoutstopduration'))
        QS = QS + '&airoutstopduration=' + (parseInt(document.getElementById('airoutstopduration').value) + iPreDur);
    if (document.getElementById('airretstopcity'))
        QS = QS + '&airretstopcity=' + document.getElementById('airretstopcity').value;
    if (document.getElementById('airretstopduration'))
        QS = QS + '&airretstopduration=' + (parseInt(document.getElementById('airretstopduration').value) + iPostDur);
    if (document.getElementById('dtime'))
        QS = QS + '&dtime=' + document.getElementById('dtime').value;
    if (document.getElementById('atime'))
        QS = QS + '&atime=' + document.getElementById('atime').value;
    if (document.getElementById('airoffset'))
        QS = QS + '&airoffset=' + document.getElementById('airoffset').value;
    if (document.getElementById('numairadts'))
        QS = QS + '&numairadts=' + document.getElementById('numairadts').value;
    if (document.getElementById('numairchds'))
        QS = QS + '&numairchds=' + document.getElementById('numairchds').value;
    if (document.getElementById('airfaretype'))
        QS = QS + '&airfaretype=' + document.getElementById('airfaretype').value;
    if (document.getElementById('aircontract'))
        QS = QS + '&aircontract=' + document.getElementById('aircontract').value;
    if (document.getElementById('airmarket'))
        QS = QS + '&airmarket=' + document.getElementById('airmarket').value;
    
    //see about inner air
    if (document.getElementById('chkInnerAir'))
    {
        if (document.getElementById('chkInnerAir').checked)
        {//mark that we have inner air so STRES will pull airInfo from ProductCode
            QS = QS + '&innerair=Y';
        }
    }
    //Everything else always gets sent
    QS = QS + '&productcode=' + document.getElementById('productcode').value;
    //send over the plan/selectedservicegroup/itemnumber
    if (document.getElementById('txtItemNumber'))
    {
        if (document.getElementById('txtItemNumber').value != '')
            QS = QS + '&ItemNumber=' + document.getElementById('txtItemNumber').value;
        else
            QS = QS + '&ItemNumber=' + document.getElementById('SelectedSeq').value;
    }
    datIn = new Date();
    datIn.setTime(Date.parse(document.getElementById('tbCheckIn').value));
    QS = QS + '&tbCheckIn=' + datIn.getFullYear() + '-' + (datIn.getMonth() + 1) + '-' + datIn.getDate();
    datOut = new Date();
    datOut.setTime(Date.parse(document.getElementById('tbCheckOut').value));
    QS = QS + '&tbCheckOut=' + datOut.getFullYear() + '-' + (datOut.getMonth() + 1) + '-' + datOut.getDate();
    QS = QS + '&searchmask=' + document.getElementById('searchmask').value;
    QS = QS + '&SelectedSeq=' + document.getElementById('SelectedSeq').value;
    
    //Pre/Post options
    if(document.getElementById('preacc'))
    {
        if(document.getElementById('preaccdur').value != '0' && document.getElementById('preaccdur').value != '' && document.getElementById('preacc').checked)
        {
            QS = QS + '&preacc=' + document.getElementById('preacc').value;
            QS = QS + '&preaccduration=' + document.getElementById('preaccdur').value;
        }
    }
    if(document.getElementById('postacc'))
    {
        if(document.getElementById('postaccdur').value != '0' && document.getElementById('postaccdur').value != '' && document.getElementById('postacc').checked)
        {
            QS = QS + '&postacc=' + document.getElementById('postacc').value;
            QS = QS + '&postaccduration=' + document.getElementById('postaccdur').value;
        }
    }
    
    //Custom Headers and Footers
    if(document.getElementById('custom'))
    {
        if(document.getElementById('custom').value != '')
        {
            QS = QS + '&custom=' + document.getElementById('custom').value;
            QS = QS + '&customCode=' + document.getElementById('customCode').value;
        }
    }
    //Quote Currency
    if(document.getElementById('QC'))
    {
        if(document.getElementById('QC').value != '')
        {
            QS = QS + '&QC=' + document.getElementById('QC').value;
        }
    }
    //Book By
    if (document.getElementById('isbookby'))
    {
        if (document.getElementById('isbookby').value == 'Y')
            QS = QS + '&isbookby=Y';
    }
    
    //Shares
    //First must check if we allow shares per room or not
    if (document.getElementById('allowShares') && document.getElementById('chksharey1'))
    {
        //Allow shares per room, must build the Shares per room
        var tempShares, myShares;
        myShares = '';
        blnHasShares = false;
        for (i = 1; i <= document.main_form.numadts.length; i++)
        {
            tempShares = '';
            
            //Do we have at least 1 adult selected?
            if (document.main_form.numadts[i - 1].value > 0 || document.main_form.numchds[i - 1].value > 0)
            {
                //First, check for shares in each room
                if (document.getElementById('chksharey' + i).checked)
                {
                    blnHasShares = true;
                    if (document.getElementById('rdosharem' + i).checked)
                        tempShares = document.getElementsByName('numadts').item(i - 1).value + 'M';
                    else if (document.getElementById('rdosharef' + i).checked)
                        tempShares = document.getElementsByName('numadts').item(i - 1).value + 'F';
                }
                else //Not sharing this room, make 0
                    tempShares = '0';
                    
                if (myShares != '')
                    myShares += '/';
                myShares += tempShares;
            }
        }
        if (blnHasShares)
            QS = QS + '&Shares=' + myShares;
    }
    else if (document.getElementById('allowShares') && document.getElementById('chksharey'))
    {
        if (document.getElementById('allowShares').value == 'Y' && document.getElementById('chksharey').checked)
        {
            if (document.getElementById('rdosharem'))
            {
                if (document.getElementById('rdosharem').checked)
                {
                    if (document.getElementById('rdoshared'))
                    {
                        if (document.getElementById('rdoshared').checked)
                            QS = QS + '&Shares=' + document.getElementsByName('numspec').item(0).value + 'M';
                        else
                            QS = QS + '&Shares=' + document.getElementsByName('numadts').item(0).value + 'M';
                    }
                    else
                    {
                        QS = QS + '&Shares=' + document.getElementsByName('numadts').item(0).value + 'M';
                    }
                }
                else
                {
                    if (document.getElementById('rdoshared'))
                    {
                        if (document.getElementById('rdoshared').checked)
                            QS = QS + '&Shares=' + document.getElementsByName('numspec').item(0).value + 'F';
                        else
                            QS = QS + '&Shares=' + document.getElementsByName('numadts').item(0).value + 'F';
                    }
                    else
                    {
                        QS = QS + '&Shares=' + document.getElementsByName('numadts').item(0).value + 'F';
                    }
                }
            }
            else if (document.getElementById('rdosharemf'))
            {
                QS = QS + '&Shares=' + document.getElementsByName('numadts').item(0).value + document.getElementById('rdosharemf').value;
            }
        }
    }
    
    //Check if has PostFlex
    if (document.getElementById('haspostflex') && document.getElementById('origretdate'))
    {
        if (document.getElementById('haspostflex').value == 'Y')
        {
            var datorig = new Date(document.getElementById('origretdate').value);
            var datret = new Date(document.getElementById('airdateret').value);
            var oneday = 1000 * 60 * 60 * 24;
            
	        if (datret.getTime() > datorig.getTime())
	        {
	            //Set the post flex duration
	            QS = QS + '&PostFlexDuration=' + parseInt(((datret.getTime() - datorig.getTime()) / oneday));
	        }
	    }
	    
	}
	// Y/N tells the Res system to check ProductDetail and build FlexOverride, for all item whose ProductDetail.FlexDuration='A'
    if (document.getElementById('buildflexoverride') && document.getElementById('buildflexoverride').value.toUpperCase() == 'Y')
    {   
        QS = QS + '&buildflexoverride=' + document.getElementById('buildflexoverride').value.toUpperCase(); 
        QS = QS + '&flexcheckin=' + FormatDate(document.getElementById('flexcheckin').value);
        QS = QS + '&flexcheckout=' + FormatDate(document.getElementById('flexcheckout').value);
    }

    
    //Return the QueryString    
    return QS;
}
function BuildVacBuilder()
{
    var QS;
    var numAdts, numChds, numRooms;
    var date1, date2, date3, date4;
    var oneday;
    
    var Months;
    
    Months = new Array(12);
    Months[0]  = "Jan";
    Months[1]  = "Feb";
    Months[2]  = "Mar";
    Months[3]  = "Apr";
    Months[4]  = "May";
    Months[5]  = "Jun";
    Months[6]  = "Jul";
    Months[7]  = "Aug";
    Months[8]  = "Sep";
    Months[9]  = "Oct";
    Months[10] = "Nov";
    Months[11] = "Dec";
    
    QS = '';
    numAdts = 0;
    numChds = 0;
    numRooms = 0;
    
    //Theme
    //QS = QS + '&Theme=[Theme]';
    //Trip Type
    if (document.getElementById('chkAirY'))
    {
        if (document.getElementById('chkAirY').checked)
        {
            QS = QS + '&chkAir=Y';
            QS = QS + '&trip_type=AIRFHTL';
            //Check for a car
            if (document.getElementById('hasvacbuildercar'))
            {
                if (document.getElementById('hasvacbuildercar').value == 'Y')
                    QS += 'CAR';
            }
            
            //Set the air input fields if we have Air
	        if (document.getElementById('cbOrigCity'))
	            document.getElementById('airfromcity').value = document.getElementById('cbOrigCity').value;
	        if (document.getElementById('cbcabin'))
	            document.getElementById('aircabinclass').value = document.getElementById('cbcabin').value;
	        if (document.getElementById('cbcarrier'))
	            document.getElementById('aircarrier').value = document.getElementById('cbcarrier').value;
	        if(document.getElementById('cbairfaretype'))
	        {
	            document.getElementById('airfaretype').value = document.getElementById('cbairfaretype').value;
	        }
        }
        else
        {
            QS = QS + '&chkAir=N';
            QS = QS + '&trip_type=HTL';
            //Check for a car
            if (document.getElementById('hasvacbuildercar'))
            {
                if (document.getElementById('hasvacbuildercar').value == 'Y')
                    QS += 'CAR';
            }
        }
    }
    if (document.getElementById('airfromcity'))
        QS = QS + '&airfromcity=' + document.getElementById('airfromcity').value;
    //To and From cities should come from the actual product instead of the destination
    //QS = QS + '&airtocity=' + document.getElementById('datespeccitycode1').value;
    QS = QS + '&airtocity=' + document.getElementById('datespeccitycode1').value.split('/')[0] + '/' + document.getElementById('airtocity').value;
    //QS = QS + '&airretfromcity=' + document.getElementById('datespeccitycode' + document.getElementById('numitindest').value).value;
    QS = QS + '&airretfromcity=' + document.getElementById('datespeccitycode' + document.getElementById('numitindest').value).value.split('/')[0] + '/' + document.getElementById('airretfromcity').value;
    if (document.getElementById('airdateout'))
        QS = QS + '&airdateout=' + document.getElementById('airdateout').value;
    if (document.getElementById('aircabinclass'))
        QS = QS + '&aircabinclass=' + document.getElementById('aircabinclass').value;
    if (document.getElementById('aircarrier'))
        QS = QS + '&aircarrier=' + document.getElementById('aircarrier').value;
    if (document.getElementById('airoffset'))
        QS = QS + '&airoffset=' + document.getElementById('airoffset').value;
    if (document.getElementById('numairadts'))
        QS = QS + '&numairadts=' + document.getElementById('numairadts').value;
    if (document.getElementById('numairchds'))
        QS = QS + '&numairchds=' + document.getElementById('numairchds').value;
    if (document.getElementById('airfaretype'))
        QS = QS + '&airfaretype=' + document.getElementById('airfaretype').value;
    //ProductCode
    QS = QS + '&productcode=' + document.getElementById('productcode').value;

    //Destinations
    QS = QS + '&totaldest=' + document.getElementById('numitindest').value;
    date1 = new Date();
    
    //Get Departure date
    date1 = Date.parse(document.getElementById('txtitindepdate').value + ' 01:00:00');
    oneday = 1000 * 60 * 60 * 24;
    for (var i = 1; i <= document.getElementById('numitindest').value; i++)
    {
        //Destination should be dest/airtocity if 1st destination or dest/airretfromcity if last destination
        if (i == 1)
            QS = QS + '&destination' + i + '=' + document.getElementById('datespeccitycode' + i).value.split('/')[0] + '/' + document.getElementById('airtocity').value;
        else if (i == parseInt(document.getElementById('numitindest').value))
            QS = QS + '&destination' + i + '=' + document.getElementById('datespeccitycode' + i).value.split('/')[0] + '/' + document.getElementById('airretfromcity').value;
        else
            QS = QS + '&destination' + i + '=' + document.getElementById('datespeccitycode' + i).value;
        
        //Get the dates
        date2 = new Date();
        date4 = date1;
        date4 = date4 + (oneday * parseInt(document.getElementById('datespeconday' + i).value));
        date4 = date4 - oneday;
        date2.setTime(date4);
        
        date3 = new Date();
        date4 = date1;
        date4 = date4 + (oneday * parseInt(document.getElementById('datespeconday' + i).value)) + (oneday * parseInt(document.getElementById('datespecseldest' + i).value));
        date4 = date4 - oneday;
        date3.setTime(date4);
        
        QS = QS + '&checkin' + i + '=' + date2.getDate() + ' ' + Months[date2.getMonth()] + ' ' + date2.getFullYear();
        QS = QS + '&checkout' + i + '=' + date3.getDate() + ' ' + Months[date3.getMonth()] + ' ' + date3.getFullYear();
        
        if (i > 1)
        {
            if (document.getElementById('datespecintertype' + (i - 1)).value == 'TRA')
                QS = QS + '&radiointer' + i + '=rail';
            else if (document.getElementById('datespecintertype' + (i - 1)).value != '')
                QS = QS + '&radiointer' + i + '=' + document.getElementById('datespecintertype' + (i - 1)).value;
            else
                QS = QS + '&radiointer' + i + '=none';
        }
        if (i == document.getElementById('numitindest').value)
        {
            QS = QS + '&airdateret=' + date3.getDate() + ' ' + Months[date3.getMonth()] + ' ' + date3.getFullYear();
        }
    }
    
    //Num Rooms/Adults/Children
    for (i = 0; i < document.main_form.numadts.length; i++)
    {
        if (document.main_form.numadts[i].value != 0)
        {
            numRooms = numRooms + 1;
            QS = QS + '&NumAdts' + (i + 1) + '=' + document.main_form.numadts[i].value;
            numAdts = numAdts + ParseFloat(document.main_form.numadts[i].value);
            
            QS = QS + '&NumChds' + (i + 1) + '=' + document.main_form.numchds[i].value;
            numChds = numChds + ParseFloat(document.main_form.numchds[i].value);
            for (j = 1; j <= document.main_form.numchds[i].value; j++)
            {
                //Check that at least one adult was selected for this room
                if (document.main_form.numadts[i].value == 0)
                {
                    alert("Please select at least one adult for room #" + (i + 1));
                    return false;
                }
                if (j == 1)
                {
                    //First child
                    if (document.main_form.chd1age[i].value == "0")
                    {
                        alert("Please select child 1 age for room #" + (i + 1));
                        return false;
                    }
                    QS = QS + '&Chd1Age' + (i + 1) + '=' + document.main_form.chd1age[i].value;
                }
                else if (j == 2)
                {
                    //Second child
                    if (document.main_form.chd2age[i].value == "0")
                    {
                        alert("Please select child 2 age for room #" + (i + 1));
                        return false;
                    }
                    QS = QS + '&Chd2Age' + (i + 1) + '=' + document.main_form.chd2age[i].value;
                }
                 else if (j == 3)
                {
                    //Third child
                    if (document.main_form.chd3age[i].value == "0")
                    {
                        alert("Please select child 3 age for room #" + (i + 1));
                        return false;
                    }
                    QS = QS + '&Chd3Age' + (i + 1) + '=' + document.main_form.chd3age[i].value;
                }
            }
        }
    }
    QS = QS + '&NumRooms=' + numRooms;
    //NumAdts/NumChds
    QS = QS + '&NumAdts=' + numAdts;
    QS = QS + '&NumChds=' + numChds;
    
    //ProductCode
    if (document.getElementById('productcode'))
        QS = QS + '&productcode=' + document.getElementById('productcode').value;
    //ProductSeq
    if (document.getElementById('SelectedSeq'))
        QS = QS + '&productseq=' + document.getElementById('SelectedSeq').value;
    
    //Send the Request
    return QS;
    //document.location.href = '[ResPath]/STWMain.aspx?Action=FITSeqList' + QS;
}
function setAir(strChecked)
{
    if (strChecked == 'Y')
    {
        if (document.getElementById('Air')){ document.getElementById('Air').style.display = ''; }
        if (document.getElementById('itindepdateair'))
        {
            document.getElementById('itindepdateair').style.display = '';
            document.getElementById('itindepdatenoair').style.display = 'none';
        }
    }
    else
    {
        if (document.getElementById('Air')) {   document.getElementById('Air').style.display = 'none'; }
        if (document.getElementById('itindepdateair'))
        {
            document.getElementById('itindepdateair').style.display = 'none';
            document.getElementById('itindepdatenoair').style.display = '';
        }
    }
}

function UpdateUpgrades(strDate, strUpgradeText, strRedText, strInclText)
{
    var i, decIncludedUpgrade, decUpgrade;
    var strSeq, strSelectedSeq;
    var strUpgrades;
    
    strUpgrades = document.getElementsByName('upgrade_' + strDate);
    if (strUpgrades.length > 0)
    {
        //Do we want to keep the upgrades included (meaning whichever plan was "included" before should stay as "included" when selecting a date)
        if (document.getElementById('keepincludedupgrades'))
        {
            strSelectedSeq = document.getElementById('noselectedseq').value;
            for (i = 0; i < strUpgrades.length; i++)
            {
                strSeq = strUpgrades.item(i).id.split('_')[2];
                if (strSeq == strSelectedSeq)
                {
                    //Found the correct Seq, use this price
                    decIncludedUpgrade = ParseFloat(strUpgrades.item(i).value.replace(',',''));
                    i = strUpgrades.length;
                }
            }
        }
        else
            decIncludedUpgrade = 0;
            
        for (i = 0; i < strUpgrades.length; i++)
        {
            if (strUpgrades.item(i).id.indexOf('_') > 0)
            {
                //Get the Seq for this item first
                strSeq = strUpgrades.item(i).id.split('_')[2];
                
                if (document.getElementById('upgrade_' + strSeq))
                {
                    decUpgrade = ParseFloat(strUpgrades.item(i).value.replace(',',''));
                    decUpgrade -= decIncludedUpgrade;
                    if (decUpgrade > 0)
                    {
                        //Greater than 0, add the "+"
                        if (strUpgradeText == null)
                            document.getElementById('upgrade_' + strSeq).innerHTML = '<b class="upgradetext">Upgrade from +$' + decUpgrade + '</b>';
                        else
                            document.getElementById('upgrade_' + strSeq).innerHTML = strUpgradeText.replace('[Upgrade]', decUpgrade);
                    }
                    else if(decUpgrade < 0)
                    {
                        //Less than 0, add the "-"
                        if (strRedText == null)
                            document.getElementById('upgrade_' + strSeq).innerHTML = '<b class="upgradetext">Reduction from -$' + -decUpgrade + '</b>';
                        else
                            document.getElementById('upgrade_' + strSeq).innerHTML = strRedText.replace('[Reduction]', -decUpgrade);
                    }
                    else
                    {
                        //0 means this is included
                        if (strInclText == null)
                            document.getElementById('upgrade_' + strSeq).innerHTML = '(included)';
                        else
                            document.getElementById('upgrade_' + strSeq).innerHTML = strInclText.replace('[Price]', decUpgrade);
                    }
                    
                    //Update the date for this Upgrade
                    if (document.getElementById('upgrade_date_' + strSeq))
                    {
                        document.getElementById('upgrade_date_' + strSeq).value = strDate;
                    }
                }
            }
        }
    }
}

function UpdateOtherDate()
{
    try
    {
        var datIn;
                
        var Months;
        
        Months = new Array(12);
        
        Months[0]  = "Jan";
        Months[1]  = "Feb";
        Months[2]  = "Mar";
        Months[3]  = "Apr";
        Months[4]  = "May";
        Months[5]  = "Jun";
        Months[6]  = "Jul";
        Months[7]  = "Aug";
        Months[8]  = "Sep";
        Months[9]  = "Oct";
        Months[10] = "Nov";
        Months[11] = "Dec";
        
        datIn = new Date();
        
        datIn.setTime(Date.parse(document.getElementById('txtotherdate').value));
        //Set Other Date to correct format
        document.getElementById('txtotherdate').value = datIn.getDate() + ' ' + Months[datIn.getMonth()] + ' ' + datIn.getFullYear();
        //Set Check-In
        document.getElementById('tbCheckIn').value = Months[datIn.getMonth()] + ' ' + datIn.getDate() + ', ' + datIn.getFullYear();
        //Add the number of days to get the correct Check-Out Date
        datIn.setDate(datIn.getDate() + [ProductNumDays]);
        
        //Set Check-Out
        document.getElementById('tbCheckOut').value = Months[datIn.getMonth()] + ' ' + datIn.getDate() + ', ' + datIn.getFullYear();
        
        //alert('CheckIn: ' + document.getElementById('tbCheckIn').value);
        //alert('Checkout: ' + document.getElementById('tbCheckOut').value);
    }
    catch (ex)
    {
        //alert('Error: ' + ex.message);
    }
}
function UpdateReturnDate()
{
    if (document.getElementById('chkAirY'))
    {
        try
        {
            var dat1, dat2, oneday, airreturnoffset, airretdateoffset;
            //var dat3;
            
            var Months;
            
            Months = new Array(12);
            
            Months[0]  = "Jan";
            Months[1]  = "Feb";
            Months[2]  = "Mar";
            Months[3]  = "Apr";
            Months[4]  = "May";
            Months[5]  = "Jun";
            Months[6]  = "Jul";
            Months[7]  = "Aug";
            Months[8]  = "Sep";
            Months[9]  = "Oct";
            Months[10] = "Nov";
            Months[11] = "Dec";
            
            oneday = 1000 * 60 * 60 * 24;
            airreturnoffset = 0;
            
            dat1 = Date.parse(document.getElementById('tbCheckOut').value + ' 01:00:00');

            //Check for a return offset day
            if (document.getElementById('airreturnoffset'))
            {
                if (document.getElementById('airreturnoffset').value != '')
                {
                    airreturnoffset = parseInt(document.getElementById('airreturnoffset').value);
                    dat1 = dat1 + oneday * airreturnoffset;
                }
            }

            if (document.getElementById('postacc') != null)
            {
                if (document.getElementById('postacc') && document.getElementById('postacc').checked) //(document.getElementById('postacc').getAttribute('checked') != '')
                {
                    dat1 = dat1 + oneday * ((parseInt(document.getElementById('postaccdur').value) - 1) - airreturnoffset);
                }
            }

            //Check for a flight return date offset - KM 2011-02-15
            if (document.getElementById('airretdateoffset'))
            {
            	airretdateoffset = parseInt(document.getElementById('airretdateoffset').value);
            	dat1 = dat1 + oneday * airretdateoffset;
            }
            
            dat2 = new Date();
            dat2.setTime(dat1);

            document.getElementById('airdateret').value = dat2.getDate() + ' ' + Months[dat2.getMonth()] + ' ' + dat2.getFullYear();
        }
        catch (ex)
        {
            //alert('Error: ' + ex.message);
        }
    }
}
function UpdateOutboundDate()
{
    if (document.getElementById('chkAirY'))
    {
        try
        {
            //alert('1');
            var dat1, dat2, oneday;
            //alert('2');
            var Months;
            //alert('3');
            Months = new Array(12);
            //alert('4');
            Months[0]  = "Jan";
            Months[1]  = "Feb";
            Months[2]  = "Mar";
            Months[3]  = "Apr";
            Months[4]  = "May";
            Months[5]  = "Jun";
            Months[6]  = "Jul";
            Months[7]  = "Aug";
            Months[8]  = "Sep";
            Months[9]  = "Oct";
            Months[10] = "Nov";
            Months[11] = "Dec";
            //alert('5');
            oneday = 1000 * 60 * 60 * 24;

            //alert('tbCheckin: ' + document.getElementById('tbCheckIn').value);
            dat1 = Date.parse(document.getElementById('tbCheckIn').value + ' 01:00:00');
            
            if (document.getElementById('preacc') != null)
            {
                if (document.getElementById('preacc').checked)
                {
                    //alert('Updating the date, subtracting ' + document.getElementById('preaccdur').value + ' days to the date.');
                    dat1 = dat1 - (oneday * parseInt(document.getElementById('preaccdur').value));
                }
            }
            
            //Check if we need to subtract the air offset from the date
            if (document.getElementById('subtractairoffset'))
            {
                if (document.getElementById('subtractairoffset').value == 'Y' && document.getElementById('airoffset').value != '' && document.getElementById('airoffset').value != '0')
                    dat1 = dat1 - (oneday * parseInt(document.getElementById('airoffset').value));
            }
            
            dat2 = new Date();
            dat2.setTime(dat1);
            
            document.getElementById('airdateout').value = dat2.getDate() + ' ' + Months[dat2.getMonth()] + ' ' + dat2.getFullYear();
        }
        catch (ex)
        {
            //alert('Error: ' + ex.message);
        }
    }
}
function SetDefaultCarrier()
{
    var sdefaultcarrier;
    var sairportlist;
    var sairport;
    var i = 0;

    sdefaultcarrier = '';
    if (document.getElementById('defaultcarrier'))
        sdefaultcarrier = document.getElementById('defaultcarrier').value.toUpperCase();
    //alert('default carrier: ' + sdefaultcarrier);
    if (sdefaultcarrier == '')
    {
        return;
        //no default carrier, exit
    }
    sairport = '';
    if (document.getElementById('cbOrigCity'))
        sairport = document.getElementById('cbOrigCity').value.toUpperCase();
    //alert('selected airport: ' + sairport);
    if (sairport == '')
    {
        return;
        //no departure city selected.
    }
    sairportlist = '';
    if (document.getElementById('defaultcarriercities'))
        sairportlist = document.getElementById('defaultcarriercities').value.toUpperCase();
    //alert('default carrier cities: ' + sairportlist);
    if (sairportlist.indexOf(sairport) >= 0)
    {
    //default the carrier and exit.
        //document.getElementById('cbcarrier').options.value = sairport;
        if (document.getElementById('cbcarrier'))
        {
            for (i = 0;i < document.getElementById('cbcarrier').options.length-1; i++)
            {
                if (document.getElementById('cbcarrier').options[i].value == sdefaultcarrier)
                {
                    document.getElementById('cbcarrier').options.selectedIndex = i;
                    return;
                }
            }        
        }
        //alert('after setting airport: ' + document.getElementById('cbcarrier').value);
    }
    else
    {
        if (document.getElementById('cbcarrier'))
            document.getElementById('cbcarrier').options.selectedIndex = 0;//any
    }
    //done!
}

function GetPageHeight()
{
    try
    {
        if (window.innerHeight && window.scrollMaxY) // Firefox
        {
            pageHeight = window.innerHeight + window.scrollMaxY;
        }
        else if (document.body.scrollHeight > document.body.offsetHeight) // all but Explorer Mac
        {
            pageHeight = document.body.scrollHeight;
        }
        else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        {
            pageHeight = document.body.offsetHeight + document.body.offsetTop;
        }
        
        //Done
        return pageHeight;
    }
    catch (ex)
    {
        //There was an error
        //alert('Error: \n' + ex.description);
    }
}
function GetPageWidth()
{
    try
    {
        if (window.innerHeight && window.scrollMaxY) // Firefox
        {
            pageWidth = window.innerWidth + window.scrollMaxX;
        }
        else if (document.body.scrollHeight > document.body.offsetHeight) // all but Explorer Mac
        {
            pageWidth = document.body.scrollWidth;
        }
        else // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        {
            pageWidth = document.body.offsetWidth + document.body.offsetLeft;
        }
        
        //Done
        return pageWidth;
    }
    catch (ex)
    {
        //There was an error
        //alert('Error: \n' + ex.description);
    }
}

function ShowOverlay(tid, addToElem, bhideonbackdropclick)
{
    try
    {
        /*
            -Create the backdrop
            -Show the backdrop
            -Show the requested element
            -Center the requested element
        */
        if (bhideonbackdropclick == null || bhideonbackdropclick == 'undefined') {
            //default to true if not found...hide the popup content if clicked on backdrop (outside of content area).
            bhideonbackdropclick = true;
        }
        
        if (!document.getElementById('divbackdrop'))
        {
            //Create a new backdrop div
            var t = document.createElement('div');
            t.id = 'divbackdrop';
            t.style.opacity = '.75';
            t.style.filter = 'alpha(opacity=75)';
            t.style.position = 'absolute';
            t.style.backgroundColor = '#FFFFFF';
            t.innerHTML = '&nbsp;';
            t.style.display = 'none';
            //t.style.zIndex = 100;
            t.style.zIndex = 1001;
            if (addToElem && addToElem != null && addToElem != 'undefined')
            {
                //add the backdrop DIV to this particular element only
                addToElem.appendChild(t);
            }
            else
            {
                document.body.appendChild(t);
            }
        }
        
        var b = document.getElementById('divbackdrop')
        b.style.display = 'block';
        b.style.width = GetPageWidth() + 'px';
        b.style.height = GetPageHeight() + 'px';
        b.style.left = 0;//GetScrollX();
        b.style.top = 0; //GetScrollY();

        //Make the content disappear if the user clicks the backdrop
        if (bhideonbackdropclick) 
        {
            b.onclick = function (e) { HideOverlay(tid); }
        }
        CenterDisplay(tid);
        document.getElementById(tid).style.display = 'block';
        //document.getElementById(tid).style.zIndex = 200;
        document.getElementById(tid).style.zIndex = 1002;
        document.body.style.overflow="hidden";
        HideElement('APPLET', tid);
        HideElement('SELECT', tid);
    }
    catch (ex)
    {
        //There was an error
        //alert('Overlay(' + tid + ') Failed: \n' + ex.description);
    }
}

function ShowOverlayTop(tid, addToElem)
{
    try
    {
        /*
            -Create the backdrop
            -Show the backdrop
            -Show the requested element
            -Center the requested element
            -Set the top position to the top of the page
        */
        
        if (!document.getElementById('divbackdrop'))
        {
            //Create a new backdrop div
            var t = document.createElement('div');
            t.id = 'divbackdrop';
            t.style.opacity = '.75';
            t.style.filter = 'alpha(opacity=75)';
            t.style.position = 'absolute';
            t.style.backgroundColor = '#FFFFFF';
            t.innerHTML = '&nbsp;';
            t.style.display = 'none';
            t.style.zIndex = 100;
            if (addToElem && addToElem != null && addToElem != 'undefined')
            {
                //add the backdrop DIV to this particular element only
                addToElem.appendChild(t);
            }
            else
            {
                document.body.appendChild(t);
            }
        }
        
        var b = document.getElementById('divbackdrop')
        b.style.display = 'block';
        b.style.width = GetPageWidth() + 'px';
        b.style.height = GetPageHeight() + 'px';
        b.style.left = 0;//GetScrollX();
        b.style.top = 0; //GetScrollY();

        //Make the content disappear if the user clicks the backdrop
        b.onclick = function (e) { HideOverlay(tid); }
        
        CenterDisplay(tid);
        document.getElementById(tid).style.display = 'block';
        document.getElementById(tid).style.zIndex = 200;
        document.getElementById(tid).style.top = 50 + GetScrollY();
        document.body.style.overflow="hidden";
        HideElement('APPLET', tid);
        HideElement('SELECT', tid);
    }
    catch (ex)
    {
        //There was an error
        //alert('Overlay(' + tid + ') Failed: \n' + ex.description);
    }
}

function HideOverlay(tid)
{
    try
    {
        document.getElementById('divbackdrop').style.display = 'none';
        document.getElementById(tid).style.display = 'none';
        document.body.style.overflow="auto";
        
        ShowElement('APPLET');
        ShowElement('SELECT');
    }
    catch (ex)
    {
        //There was an error
        //alert('HideOverlay(' + tid + ') Failed: \n' + ex.description);
    }
}


/*
    HideElement:
    ------------
        Hides the specified element type if it is found under the calendar div.
        Required for IE6 (and lower) to hide Select objects
        Input:
            strElement        The tag of the elements to hide (Usually "SELECT" or "APPLET")
            strID             The ID of the elementthatis being shown above the strElement elements
        Example:
            HideElement('APPLET', 'calid')
*/
function HideElement(strElement, strId)
{
  if( ie )
  {
    if (strId == null)
        strId = calid;
    var e = document.getElementById(strId);
    var hide;
    for(i = 0; i < document.all.tags(strElement).length; i++)
    {
      obj = document.all.tags(strElement)[i];
      if(!obj || !obj.offsetParent)
      {
        continue;
      }

      //Find the element's offsetTop and offsetLeft relative to the BODY tag.
      objLeft   = obj.offsetLeft;
      objTop    = obj.offsetTop;
      objParent = obj.offsetParent;

      hide = true;
      while(objParent && objParent.tagName.toUpperCase() != "BODY" && objParent.offsetParent)
      {
        objLeft  += objParent.offsetLeft;
        objTop   += objParent.offsetTop;
        objParent = objParent.offsetParent;
        
        //Check for the ID that is being shown above the strElement elements
        //If the strElement is part of the strId then don't hide it
        if (objParent.id == strId)
        {
            //return;
            hide = false;
        }
      }

      if (hide == true)
      {
          objHeight = obj.offsetHeight;
          objWidth  = obj.offsetWidth;

          if((e.offsetLeft + e.offsetWidth) <= objLeft);
          else if((e.offsetTop + e.offsetHeight) <= objTop);
          else if(e.offsetTop >= (objTop + objHeight));
          else if(e.offsetLeft >= (objLeft + objWidth));
          else
          {
            obj.style.visibility = "hidden";
          }
      }
    }
  }
}

/*
    ShowElement:
    ------------
        Shows elements that were hidden using "HideElement".
        Input:
            strElement        The tag of the elements to show (Usually "SELECT" or "APPLET")
*/
function ShowElement(strElement)
{
  if(ie)// && document.getElementById(calid).style.display != 'none')
  {
    for(i = 0; i < document.all.tags(strElement).length; i++)
    {
      obj = document.all.tags(strElement)[i];

      if(!obj || !obj.offsetParent)
      {
        continue;
      }

      obj.style.visibility = "";
    }
  }
}



/****************************************************************************************************************8/
/*
Script Name: Javascript Cookie Script
Author: Public Domain, with some modifications
Script Source URI: http://techpatterns.com/downloads/javascript_cookies.php
Version 1.1.1
Last Update: 4 October 2007

Changes:
1.1.1 fixes a problem with Get_Cookie that did not correctly handle case
where cookie is initialized but it has no "=" and thus no value, the 
Get_Cookie function generates a NULL exception. This was pointed out by olivier, thanks

1.1.0 fixes a problem with Get_Cookie that did not correctly handle
cases where multiple cookies might test as the same, like: site1, site

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
*/

// this fixes an issue with the old method, ambiguous values 
// with this test document.cookie.indexOf( name + "=" );

// To use, simple do: Get_Cookie('cookie_name'); 
// replace cookie_name with the real cookie name, '' are required
function GetCookie( check_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 check_name
		if ( cookie_name == check_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;
	}
}

/*
only the first 2 parameters are required, the cookie name, the cookie
value. Cookie time is in milliseconds, so the below expires will make the 
number you pass in the Set_Cookie function call the number of days the cookie
lasts, if you want it to be hours or minutes, just get rid of 24 and 60.

Generally you don't need to worry about domain, path or secure for most applications
so unless you need that, leave those parameters blank in the function call.
*/
function SetCookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	// if the expires variable is set, make the correct expires time, the
	// current script below will set it for x number of days, to make it
	// for hours, delete * 24, for minutes, delete * 60 * 24
	if ( expires )
	{
		expires = expires * 1000 * 60 * 60 * 24;
	}
	//alert( 'today ' + today.toGMTString() );// this is for testing purpose only
	var expires_date = new Date( today.getTime() + (expires) );
	//alert('expires ' + expires_date.toGMTString());// this is for testing purposes only

	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + //expires.toGMTString()
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

// this deletes the cookie when called
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";
}


function QueryString(strKey){try{var qs=window.location.search.substring(1).split("&");
for(var i=0;i<qs.length;i++)if(qs[i].split("=")[0].toUpperCase()==strKey.toUpperCase())return qs[i].split("=")[1];return''}
catch(ex){return''}}


// includeURL() - Function to get the URL content using XMLHttpRequest.
//                This function will prevent the whole page to do round trip.
//          url - URL Path to request
//          req - Method Request (GET or POST)
//        param - Parameters (For POST method only) 
function includeURL(url,req,param)
{
	var urlRequest = false; //variable to hold ajax object
	if (!req){req='GET';}
	else {req=req.toUpperCase;}
	
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		urlRequest = new XMLHttpRequest()
	else if (window.ActiveXObject) // if IE
		{ 
		try {
			urlRequest = new ActiveXObject("Msxml2.XMLHTTP")
			} 
		catch (e)
			{
			try{
				urlRequest = new ActiveXObject("Microsoft.XMLHTTP")
				}
			catch (e){}
			}
		}
	else
		return false;
	if (!urlRequest && typeof XMLHttpRequest != 'undefined')
	   urlRequest = new XMLHttpRequest();

	if (urlRequest){ 
		if (req!='POST' || req=='')
		{
		   urlRequest.open('GET', url, false);  
		   urlRequest.send(null);
		}
		else
		{
		 urlRequest.open('POST', url, false);  
		 urlRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		}
	   return urlRequest;
	   }
}
//
function displayURL(request)
{
	if (request.readyState == 4 && (request.status==200 || window.location.href.indexOf("http")==-1))
        document.write(request.responseText);
}
//
function incURL_ID(url,id,mnu) //Syntax: incURL_ID(<url>,<id you want to display>,<container ID>)
{
    var nDiv=document.createElement('div');     // create dummy element
    nDiv.style.display ='none';                 // hide the element
    nDiv.setAttribute('id','idIncURL');         // set element attributes
    var s = includeURL(url,'GET','');                    // get the URL HTML content
    s=s.responseText;                           // get HTTPResponse in Text format
    nDiv.innerHTML = s;                         // get the inner HTML
    document.body.appendChild(nDiv);            // append to the body
    document.getElementById(mnu).innerHTML = document.getElementById(id).innerHTML;
    document.body.removeChild(nDiv); //remove the element
}

function removeHTMLTags(text){
 	if(text){
 		var txt = text;
 	 	txt = txt.replace(/&(lt|gt);/g, function (m, p1){
 		 	return (p1 == "lt")? "<" : ">";
 		});
 		var r = txt.replace(/<\/?[^>]+(>|$)/g, "");
 		return r;
 	}	
}

function strReplaceAll(text,r,n)
{
    return text.replace(new RegExp(r,'g'),n);
}

function trim(text)
{
	return text.replace(/^\s+|\s+$/g,'');
}

function alltrim(text)
{
	text=trim(text);
	text=text.replace(/  /g,' ');
	return text
}


function ltrim(text)
{
	return text.replace(/^\s+/,'');
}
function rtrim(text)
{
	return text.replace(/\s+$/,'');
}

function isEven(n){return !(n % 2);}
function isOdd(n) {return !isEven(n);}

function addDropListOption(id, text, value)
// Function to add OPTION element to dropdown list
{
	var eOption = document.createElement("OPTION");
	var obj=document.getElementById(id);
	eOption.text = text;
	eOption.value = value;
	obj.options.add(eOption);
}

function TravelMonths(id,num)
//Function to populate dropdown list
{
	var numMo=num;					//Number of Months
	var dat=new Date();			// Today
	var yr=dat.getFullYear();	// Current Year
	var mo=dat.getMonth();		// Current Month
	var mth=fullmonths[mo];		// Month Description
	var intStart = mo;
	var ktr=0;
	var ctr=0;
	var m=0;
	var y=0;

	for (var i=0; i < numMo;++i){
		m=ktr+intStart;
		mth=fullmonths[m];
		if (m==12){ctr=1; yr=yr+1;ktr=0;intStart=0;};
		var txt=mth + ' ' + yr;
		var val=m +'/1/'+yr;		
		addDropListOption(id, txt, val);
		++ktr;
	}

}

function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}

function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }
}

function RemoveAllChildNodes(id)
{
	var idHolder = document.getElementById(id); 
    while(idHolder.hasChildNodes()){idHolder.removeChild(idHolder.lastChild);}
}

function ShowOnCursor(strid, evt, strDirection)
{
    //Moves an element around as the mouse moves.  
    //Used to show a div pop-up on hover 
    //Pass "direction"  Right or Left to have the div open to the right or to the left
    show(strid);
    if (strDirection == 'left')
    {
       document.getElementById(strid).style.left = GetMouseX(evt) + 10;
       document.getElementById(strid).style.top = GetMouseY(evt) + 10;
    }
    else
    {
        document.getElementById(strid).style.left = GetMouseX(evt) + 10;
        document.getElementById(strid).style.top = GetMouseY(evt) + 10;
    }
}

/*
//	Embeds a media player at the location where the script is called.
//	Pass the URL to the media file to be embedded (audio or video)
*/
function embedPlayer(strMediaURL, strID, intWidth, intHeight)
{ 
    //Get Operating System 
    var isWin = navigator.userAgent.toLowerCase().indexOf("windows") != -1;
    var objTypeTag;
    
    if (isWin)
    {
		//Use MIME type application/x-mplayer2
        visitorOS = "Windows";
        //The MIME type to load the WMP plugin in non-IE browsers on Windows
		objTypeTag = "application/x-mplayer2"; 
    }
    else
    {
        //Use MIME type audio/mpeg, audio/x-wav, etc.
        visitorOS = "Other";
        //The MIME type for Macs and Linux 
        objTypeTag = "audio/mpeg"
    }
    
    //Set default height and width
    //Width 280 is the WMP minimum
    //Min Height (for audio) = 45 (WMP controls) + 24 (WMP status bar)
    if (!intWidth || intWidth < 280)
    {
		intWidth = 280;
    }
    if (!intHeight || intHeight < 69)
    {
		intHeight = 69;
    }
    
    //Set default ID
    if (!strID || strID == "")
    {
		strID = "divMediaPlayer";
    }

	//Write the embedded player in a div
    document.writeln("<div id='" + strID + "' name='" + strID + "'>");  
    document.writeln("<object width='" + intWidth + "' height='" + intHeight + "'>"); 
    document.writeln("<param name='type' value='" + objTypeTag + "'>");
    document.writeln("<param name='src' value='" + strMediaURL + "'>");
    document.writeln("<param name='autostart' value='0'>");
    document.writeln("<param name='showcontrols' value='1'>");
    document.writeln("<param name='showstatusbar' value='1'>");
    
    //Firefox and Opera for Windows require both autostart and autoplay
    //[TBD]
    document.writeln("<embed src ='" + strMediaURL + "' type='" + objTypeTag + "' autoplay='false' autostart='0' width='" + intWidth + "' height='" + intHeight + "' controller='1' showstatusbar='1' bgcolor='#ffffff'></embed>"); 

    document.writeln("</object>");
    document.writeln("</div>");
}

// addLoadEvent(): By Simon Wilson. Adds the given function as a page load 
// event.
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

function addUnLoadEvent(func) {
	var oldunonload = window.unonload;
	if (typeof window.unonload != 'function') {
		window.unonload = func;
	}
	else {
		window.unonload = function() {
			oldunonload();
			func();
		}
	}
}

// newLoadEvent() - Alternative for addLoadEvent
function newLoadEvent(func)
{
    if (window.attachEvent) {window.attachEvent('onload', func);}
	else if (window.addEventListener) {window.addEventListener('load', func, false);}
	else {document.addEventListener('load', func, false);} 
}

