/*******************************************************************************
 Author : Lea Smart
 Source : www.totallysmartit.com
 Date : 7/3/2001
 DHTML Calendar
 Version 1.2
 
 You are free to use this code if you retain this header.
 You do not need to link to my site (be nice though!)
 
 Amendments
 22 Jan 2002; Added ns resize bug code; rewrote date functions into Date 'class';
     Added support for yyyy-mm-dd date format
     Added support for calendar beginning on any day
 7th Feb 2002 Fixed day highlight when year wasn't current year bug
 9th Jun 2002 Fixed bug with weekend colour
              Amended the code for the date functions extensions.
              Shortened addDays code considerably
 10th Feb 2004 - Lance
     Added a new show_2 method where another target date textbox can be passed
     in which will updated when a new date is chosen for the original date by
     maintaining the same time difference between the two

 28th May 2004 - Nic
     Amended to fix a "Page contains non-secure items warning" caused by the
     addition of the email registration pop-up code which should not even be
     in this file.
*******************************************************************************/

var g_https = (document.URL.search(/^https/) != -1);
var form_id = ""; /* this var is like a global var that will be used to identify the formin question */

//if (!g_https)
//{
    //this file is included for email registration pop-up
  //  document.write('<SCRIPT type="text/javascript"  SRC="http' + 
    // '://www.gefx.co.uk/avro/pop/include/pop.js"></SCRIPT>');
//}

var timeoutDelay = 2000; // milliseconds, change this if you like, set to 0
                         // for the calendar to never auto disappear
var g_startDay = 1;      // 0=sunday, 1=monday

// preload images
var imgUp = new Image(8,12);
imgUp.src = s_images + '/calendar-up.gif';
var imgDown = new Image(8,12);
imgDown.src = s_images + '/calendar-down.gif';
 
// used by timeout auto hide functions
var timeoutId = false;
 
// the now standard browser sniffer class
function Browser()
{
    this.dom = document.getElementById?1:0;
    this.ie4 = (document.all && !this.dom)?1:0;
    this.ns4 = (document.layers && !this.dom)?1:0;
    this.ns6 = (this.dom && !document.all)?1:0;
    this.ie5 = (this.dom && document.all)?1:0;
    this.ok = this.dom || this.ie4 || this.ns4;
    this.platform = navigator.platform;
}

var browser = new Browser();
  
// DOM browsers require this written to the HEAD section
if (browser.dom || browser.ie4)
{
    document.writeln('<style>');
    document.writeln('#container {');
    document.writeln('position : absolute;');
    document.writeln('left : 100px;');
    document.writeln('top : 100px;');
    document.writeln('width : 124px;');;
    browser.platform=='Win32'?height=160:height=165;
    document.writeln('height : ' + height +'px;');
    document.writeln('clip:rect(0px 124px ' + height + 'px 0px);');
    //document.writeln('overflow : hidden;');
    document.writeln('visibility : hidden;');
    document.writeln('z-index : 1;');
    document.writeln('background-color : #ffffff');
    document.writeln('}');
    document.writeln('</style>')
    

    
    document.write('<div id="container"');
    if (timeoutDelay)
        document.write(' onmouseout="calendarTimeout();" onmouseover="if (timeoutId) clearTimeout(timeoutId);"');
    document.write('></div>');
}
 
    
var g_Calendar;  // global to hold the calendar reference, set by constructor
 
function calendarTimeout()
{
    if (browser.ie4 || browser.ie5)
    {
        if (window.event.srcElement && window.event.srcElement.name != 'month')
            timeoutId=setTimeout('g_Calendar.hide();', timeoutDelay);
    }
    if (browser.ns6 || browser.ns4)
    {
        timeoutId=setTimeout('g_Calendar.hide();',timeoutDelay);
    }
}
 
// constructor for calendar class
function Calendar()
{
    g_Calendar = this;
    // some constants needed throughout the program
    this.daysOfWeek = new Array("S", "M", "T", "W", "T", "F", "S");
    this.months = new Array(
      "January", "February", "March", "April", "May", "June",
      "July","August","September","October","November","December");
    this.daysInMonth = new Array(
      31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
    if (browser.ns4)
    {
        var tmpLayer = new Layer(127);
        if (timeoutDelay)
        {
            tmpLayer.captureEvents(Event.MOUSEOVER | Event.MOUSEOUT);
            tmpLayer.onmouseover = function(event) {
              if (timeoutId) clearTimeout(timeoutId); };
            tmpLayer.onmouseout = function(event) {
              timeoutId=setTimeout('g_Calendar.hide()',timeoutDelay);};
        }
        tmpLayer.x = 100;
        tmpLayer.y = 100;
        tmpLayer.bgColor = "#ffffff";
   }
   if (browser.dom || browser.ie4)
   {
       var tmpLayer = browser.dom ? document.getElementById('container') :
         document.all.container;
   }
   this.containerLayer = tmpLayer;
   if (browser.ns4 && browser.platform == 'Win32')
   {
       this.containerLayer.clip.height=134;
       this.containerLayer.clip.width=127;
   }
}
 
Calendar.prototype.getFirstDOM = function() {
    var thedate = new Date();
    thedate.setDate(1);
    thedate.setMonth(this.month);
    thedate.setFullYear(this.year);
    return thedate.getDay();
    
}

Calendar.prototype.getDaysInMonth = function () {
    if (this.month!=1)
        return this.daysInMonth[this.month]
    else
    {
        // is it a leap year
        if (Date.isLeapYear(this.year))
        {
            return 29;
        }
        else
        {
            return 28;
        }
    }
}
  
Calendar.prototype.buildString = function() {
    var tmpStr = '<form onSubmit="this.year.blur();return false;"><table width="100%" border="0" cellspacing="0" cellpadding="2" class="calBorderColor"><tr><td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="1" class="calBgColor">';
    tmpStr += '<tr>';
    tmpStr += '<td width="60%" class="cal" align="left">';
    if (this.hasDropDown)
    {
        tmpStr += '<select class="month" name="month" onchange="g_Calendar.selectChange();">';
        for (var i = 0; i < this.months.length; i++)
        {
            tmpStr += '<option value="' + i + '"';
            if (i == this.month)
                tmpStr += ' selected';
            tmpStr += '>' + this.months[i] + '</option>';
        }
        tmpStr += '</select>';
    }
    else
    {
        tmpStr += '<table border="0" cellspacing="0" cellpadding="0" color="red"><tr><td><a href="javascript: g_Calendar.changeMonth(-1);"><img name="calendar" src="' + s_images + '/calendar-down.gif" width="8" height="12" border="0" alt=""></a></td><td class="cal" width="100%" align="center">' + this.months[this.month] + '</td><td class="cal"><a href="javascript: g_Calendar.changeMonth(+1);"><img name="calendar" src="' + s_images + '/calendar-up.gif" width="8" height="12" border="0" alt=""></a></td></tr></table>';
    }
    tmpStr += '</td>';
    /* observation : for some reason if the below event is changed to 'onChange' rather than 'onBlur' it totally crashes IE (4 and 5)!
   */
    tmpStr += '<td width="40%" align="right" class="cal">';
   
    if (this.hasDropDown)
    { 
        tmpStr += '<input class="year" type="text" size="';
        // get round NS4 win32 lenght of year input problem
        (browser.ns4 && browser.platform == 'Win32')? tmpStr += 1: tmpStr += 4;
        tmpStr += '" name="year" maxlength="4" onBlur="g_Calendar.inputChange();" value="' + this.year + '">';
    }
    else
    {
        tmpStr += '<table border="0" cellspacing="0" cellpadding="0"><tr><td class="cal"><a href="javascript: g_Calendar.changeYear(-1);"><img name="calendar" src="' + s_images + '/calendar-down.gif" width="8" height="12" border="0" alt=""></a></td><td class="cal" width="100%" align="center">' + this.year + '</td><td class="cal"><a href="javascript: g_Calendar.changeYear(+1);"><img name="calendar" src="' + s_images + '/calendar-up.gif" width="8" height="12" border="0" alt=""></a></td></tr></table>'
    }
    tmpStr += '</td>';
    tmpStr += '</tr>';
    tmpStr += '</table>';
    var iCount = 1;

    var iFirstDOM = (7+this.getFirstDOM()-g_startDay)%7; // to prevent calling it in a loop

    var iDaysInMonth = this.getDaysInMonth(); // to prevent calling it in a loop
   
    tmpStr += '<table width="100%" border="0" cellspacing="0" cellpadding="1" class="calBgColor">';
    tmpStr += '<tr>';
    for (var i = 0; i < 7; i++)
    {
        tmpStr += '<td align="center" class="calDaysColor">' + this.daysOfWeek[(g_startDay+i)%7] + '</td>';
    }
    tmpStr += '</tr>';
    var tmpFrom = parseInt('' + this.dateFromYear + this.dateFromMonth + this.dateFromDay,10);
    
    tmpFrom +=0;  //changed back to todays date. LEft it at zero so the next person knows where to change it in the future
    
    var tmpTo = parseInt('' + this.dateToYear + this.dateToMonth + this.dateToDay,10);
    var tmpCompare;
    for (var j = 1; j <= 6; j++)
    {
        tmpStr += '<tr>';
        for (var i = 1; i <= 7; i++)
        {
            tmpStr += '<td width="16" align="center" '
            if ((7 * (j - 1) + i) >= iFirstDOM + 1 && iCount <= iDaysInMonth)
            { //for the colour change of todays date
                if (iCount == this.day &&
                  this.year == this.oYear &&
                  this.month == this.oMonth)
                    tmpStr += 'class="calHighlightColor"';
                else
                {
                    if (i == 7 - g_startDay || i == ((7 - g_startDay) % 7) + 1)
                        tmpStr += 'class="calWeekend"';
                    else tmpStr += 'class="cal"';
                }
                tmpStr += '>';
                /* could create a date object here and compare that but probably more efficient to convert to a number and compare number as numbers are primitives */
                tmpCompare = parseInt('' + this.year + padZero(this.month) + padZero(iCount), 10);
                if (tmpCompare >= tmpFrom && tmpCompare <= tmpTo)
                {
                    tmpStr += '<a class="cal" href="javascript: g_Calendar.clickDay(' + iCount + ');">' + iCount + '</a>';
                }
                else
                {
                    tmpStr += '<span class="disabled">' + iCount + '</span>';
                }
                iCount++;
            }
            else
            {
                if  (i == 7 - g_startDay || i == ((7 - g_startDay) % 7) + 1)
                    tmpStr += 'class="calWeekend"'; else tmpStr +='class="cal"';
                tmpStr += '>&nbsp;';
            }
            tmpStr += '</td>'
        }
        tmpStr += '</tr>'
    }
    tmpStr += '</table></td></tr><tr><td class="calClose" align="right"><a href="javascript:g_Calendar.hide();"  class="calClose">close</a></td></tr></table></form>'
    return tmpStr;
}
 
Calendar.prototype.selectChange = function() {
    this.month = browser.ns6?this.containerLayer.ownerDocument.forms[0].month.selectedIndex:this.containerLayer.document.forms[0].month.selectedIndex;
    this.writeString(this.buildString());
}
 
Calendar.prototype.inputChange = function() {
    var tmp = browser.ns6?this.containerLayer.ownerDocument.forms[0].year:this.containerLayer.document.forms[0].year;
    if (tmp.value >= 1900 || tmp.value <= 2100) {
        this.year = tmp.value;
        this.writeString(this.buildString());
    }
    else
    {
        tmp.value = this.year;
    }
}

Calendar.prototype.changeYear = function(incr) {
    (incr == 1) ? this.year++ : this.year--;
    this.writeString(this.buildString());
}

Calendar.prototype.changeMonth = function(incr) {
    if (this.month == 11 && incr == 1)
    {
        this.month = 0;
        this.year++;
    }
    else
    {
        if (this.month == 0 && incr == -1)
        {
            this.month = 11;
            this.year--;
        }
        else
        {
            (incr == 1) ? this.month++ : this.month--;
        }
    }
    this.writeString(this.buildString());
}
 
var DAY = 1000 * 60 * 60 * 24;
Date.prototype.addDays = function(num) {
    return new Date((num * DAY) + this.valueOf());
} 
   
/*******************************************************************************
* Changed this method to allow another textbox's date to be updated by maintaing
* the time difference.
* this.target2 and this.timeDiff are set in the showUpdate method, if called
* Lance
*******************************************************************************/
Calendar.prototype.clickDay = function(day) {
    var value = this.formatDateAsString(day, this.month, this.year);
    
	
		
	
	this.target.value = value;
    if (this.target2 && this.timeDiff)
    {
       dd = new Date(this.year, this.month, day);
       dd.setTime(dd.getTime() + this.timeDiff);
       this.target2.value = this.formatDateAsString(
         dd.getDate(), dd.getMonth(), dd.getFullYear());
    }
    if (browser.ns4)
        this.containerLayer.hidden = true;
    if (browser.dom || browser.ie4)
        this.containerLayer.style.visibility = 'hidden';

	//Method to checkif the value of the return date is the same as the dep_date and if so take relevant action
	validate_duration(this.target);
	var target_identifier = this.target.name.substr(0, 3);
	if ((target_identifier == 'dep') || (target_identifier == 'ret'))
	{
		// fire the hidden date field's onchange event to trigger the update of the date menus
		//text_field = document.getElementById(target_identifier + '_date_hidden');
		//if (typeof(text_field.onchange) == 'function') text_field.onchange();
    	eval('document.flight_search.' + target_identifier + '_date_hidden.' + 'onchange()');
	}
}

Calendar.prototype.formatDateAsString = function(day, month, year) { 
    var delim = eval('/\\' + this.dateDelim + '/g');      
    switch (this.dateFormat.replace(delim,""))
    {
        case 'ddmmmyyyy':
            return padZero(day) + this.dateDelim + this.months[month].substr(0,3) + this.dateDelim + year;
        case 'ddmmyyyy':
            return padZero(day) + this.dateDelim + padZero(month+1) + this.dateDelim + year;
        case 'ddmmyy':
            return padZero(day) + this.dateDelim + padZero(month+1) + this.dateDelim + padZero(year - 2000);
        case 'mmddyyyy':
            return padZero((month+1)) + this.dateDelim + padZero(day) + this.dateDelim + year;
        case 'yyyymmdd':
            return year + this.dateDelim + padZero(month+1) + this.dateDelim + padZero(day);
        default:
            alert('unsupported date format');
    }
}




Calendar.prototype.writeString = function(str) {    
	if (browser.ns4)
    {
        this.containerLayer.document.open();
        this.containerLayer.document.write(str);
        this.containerLayer.document.close();
    } 
    if (browser.dom || browser.ie4)
    {
        this.containerLayer.innerHTML = str;
    }
}

/*******************************************************************************
* Thsi method is extracted from the original show method so that any date string
* can be split into an array of parts, i.e. (day, month and year) and returned
* Lance
*******************************************************************************/
Calendar.prototype.getDateParts = function(value) {
		var re = /(\d{1,2})[^\d]*(\d{1,2}|\w{3})[^\d]*(\d{1,4})/;
        var atmp = re.exec(value);
        var day, month, year;
        day = month = year = -1;

		if (value==""){ /*implemented due to errors when value is passed as null solution : default to today*/
			if(document.forms['flight_search'].date){
				
				value = replaceSubstring(new String(document.forms['flight_search'].date.value), "/", ",");
				
			}else{
				
				var today = new Date()
				  var month = today.getMonth()+1
				  var year = today.getYear()
				  var day = today.getDate()
				  if(day<10) day = "0" + day
				  if(month<10) month= "0" + month 
				  if(year<1000) year+=1900
				  value = month + "/" + day + "/" + (year+"").substring(2,4);
				  atmp = re.exec(value);
			}
		}

		
		
		if (value!=""){
			atmp.shift();
		}
		

        switch (this.dateFormat)
        {
            case 'dd-mmm-yyyy':
            case 'dd/mmm/yyyy':
                for (var i = 0; i < this.months.length; i++)
                {
                    if (atmp[1].toLowerCase() ==
                      this.months[i].substr(0, 3).toLowerCase())
                    {
                        month = i;
                        break;
                    }
                }
                day = parseInt(atmp[0], 10);
                year = parseInt(atmp[2], 10);
                break;
            case 'dd/mm/yyyy':
            case 'dd-mm-yyyy':
            case 'dd/mm/yy':
            case 'dd-mm-yy':
                month = parseInt(atmp[1] - 1, 10); 
                day = parseInt(atmp[0], 10);
                if (parseInt(atmp[2], 10) < 2000)
                    year = (parseInt(atmp[2], 10) + 2000);
                else
                    year = parseInt(atmp[2], 10);
                break;
            case 'mm/dd/yyyy':
            case 'mm-dd-yyyy':
                month = parseInt(atmp[0] - 1, 10);
                day = parseInt(atmp[1], 10);
                year = parseInt(atmp[2], 10);
                break;
            case 'yyyy-mm-dd':
                month = parseInt(atmp[1] - 1, 10);
                day = parseInt(atmp[2], 10);
                year = parseInt(atmp[0], 10);
                break;
        }
    if (day != -1 && month != -1 && year != -1)
        return new Array(day, month, year);
}

Calendar.prototype.show = function(event, target, bHasDropDown, dateFormat, dateFrom, dateTo) {
     // calendar can restrict choices between 2 dates, if however no
     // restrictions are made, let them choose any date between 1900 and 3000
    
	this.dateFrom = dateFrom || new Date(1900, 0, 1);
    this.dateFromDay = padZero(this.dateFrom.getDate());
    this.dateFromMonth = padZero(this.dateFrom.getMonth());
    this.dateFromYear = this.dateFrom.getFullYear();
    this.dateTo = dateTo || new Date(3000, 0, 1);
    this.dateToDay = padZero(this.dateTo.getDate());
    this.dateToMonth = padZero(this.dateTo.getMonth());
    this.dateToYear = this.dateTo.getFullYear();
    this.hasDropDown = bHasDropDown;
    this.dateFormat = dateFormat || 'dd-mmm-yyyy';
    switch (this.dateFormat)
    {
        case 'dd-mmm-yyyy':
        case 'dd-mm-yyyy':   
        case 'dd-mm-yy':   
        case 'yyyy-mm-dd':
            this.dateDelim = '-';
            break;
        case 'dd/mm/yyyy':
        case 'dd/mm/yy':
        case 'mm/dd/yyyy':
        case 'dd/mmm/yyyy':
            this.dateDelim = '/';
            break;
    }
    // alert(browser.toSource());
    if (browser.ns4)
    {
        if (!this.containerLayer.hidden)
        {
            this.containerLayer.hidden = true;
            return;
        }
    }
    if (browser.dom || browser.ie4)
    {
        if (this.containerLayer.style.visibility == 'visible')
        {
            this.containerLayer.style.visibility='hidden';
            return;
        }  
    }
    if (browser.ie5 || browser.ie4)
    {
         var event = window.event;
    }
    if (browser.ns4)
    {
         this.containerLayer.x = event.x + 10;
         this.containerLayer.y = event.y - 5;
    }
    if (browser.ie5 || browser.ie4)
    {
        var obj = event.srcElement;
        x = 0;
        while (obj.offsetParent != null)
        {
            x += obj.offsetLeft;
            obj = obj.offsetParent;
        }
        x += obj.offsetLeft;
        y = 0;
        var obj = event.srcElement;
        while (obj.offsetParent != null)
        {
            y += obj.offsetTop;
            obj = obj.offsetParent;
        }
        y += obj.offsetTop;
        // Display to right of image...
        // this.containerLayer.style.left = x + 35;
        // if (event.y>0)
        //   this.containerLayer.style.top = y;
        // Display above image...
        this.containerLayer.style.left = x + 120;
        if (event.y > 0)
            this.containerLayer.style.top = y - 7; // + 30;
    } // if (browser.ie5 || browser.ie4)

    if (browser.ie6)
    {
    	//this.containerLayer.style.left = x + 135;
    }
    
    if (browser.ns6)
    {
        this.containerLayer.style.left = event.pageX + 10;
        this.containerLayer.style.top = event.pageY - 5;
    }

    this.target = eval('document.' + target);

    var value = this.target.value;

    if (value)
    {
        // This scope has been changed in that most of the code that was in it
        // is now in the getDateParts method.

        // Parse value into an array of date parts
        var dateObj = this.getDateParts(value);
        this.day = dateObj[0];
        this.month = this.oMonth = dateObj[1];
        this.year = this.oYear = dateObj[2];
        if (this.target2)
        {
            from = new Date(this.year, this.month, this.day);
            to = this.getDateParts(this.target2.value);
            to = new Date(to[2], to[1], to[0]);
            // Save the current difference between the two dates
            this.timeDiff = to.getTime() - from.getTime();
        }
    }
    else
    { 
        // no date set, default to today
        var theDate = new Date();
        this.year = this.oYear = theDate.getFullYear();
        this.month = this.oMonth = theDate.getMonth();
        this.day = this.oDay = theDate.getDate();
    }
    this.writeString(this.buildString());
    // and then show it!
    if (browser.ns4)
    {
        this.containerLayer.hidden = false;
    }
    if (browser.dom || browser.ie4)
    {
        this.containerLayer.style.visibility = 'visible';
    }
	//DivSetVisible(true);
	//implemented to hide or show form objects based on the visibility of the dhtml form
	toggleobj_css('hide');
}
/*******************************************************************************
* New method to allow another date in another textbox (target2) to be updated by
* maintaining the difference between the 2 dates - Lance
*******************************************************************************/
Calendar.prototype.showUpdate = function(event, target, bHasDropDown, dateFormat, dateFrom, target2) { 
	this.target2 = eval('document.' + target2);
    var tmp_str = "";	
	var tmp_arr = new Array();
		tmp_str = target;
		tmp_arr = tmp_str.split(".");
		form_id = document.forms[tmp_arr[0]].id;			
	this.show(event, target, bHasDropDown, dateFormat, dateFrom);
    return true;
};

// calendar can restrict choices between 2 dates, if however no
Calendar.prototype.hide = function() {
   if (browser.ns4)
       this.containerLayer.hidden = true;
   if (browser.dom || browser.ie4)
   {
       this.containerLayer.style.visibility='hidden';
   }  
  toggleobj_css('show');
}
 
function handleDocumentClick(e)
{
    if (!g_Calendar || !g_Calendar.containerLayer)
        return;
    if (browser.ie4 || browser.ie5)
        e = window.event;
    if (browser.ns6)
    {
        var bTest =
          (e.pageX > parseInt(g_Calendar.containerLayer.style.left,10) &&
           e.pageX < (parseInt(g_Calendar.containerLayer.style.left,10)+125) &&
           e.pageY < (parseInt(g_Calendar.containerLayer.style.top,10)+125) &&
           e.pageY > parseInt(g_Calendar.containerLayer.style.top,10));
        if (e.target.name != 'imgCalendar' &&
            e.target.name != 'month' &&
            e.target.name != 'year' &&
            e.target.name != 'calendar' && !bTest)
        {
            g_Calendar.hide(); 
        }
    }
    if (browser.ie4 || browser.ie5)
    {
        // extra test to see if user clicked inside the calendar but not on a
        // valid date, we don't want it to disappear in this case
        var bTest =
          (e.x > parseInt(g_Calendar.containerLayer.style.left,10) &&
          e.x < (parseInt(g_Calendar.containerLayer.style.left,10)+125) &&
          e.y < (parseInt(g_Calendar.containerLayer.style.top,10)+125) &&
          e.y > parseInt(g_Calendar.containerLayer.style.top,10));
        if (e.srcElement.name != 'imgCalendar' &&
           e.srcElement.name != 'month' &&
           e.srcElement.name != 'year' &&
           !bTest & typeof(e.srcElement)!='object')
        {
            g_Calendar.hide(); 
        }
    }
    if (browser.ns4)
         g_Calendar.hide();
}
 
// utility function
function padZero(num)
{
    return ((num <= 9) ? ("0" + num) : num);
}

// Finally licked extending  native date object;
Date.isLeapYear = function(year) {
     if (year % 4 == 0 && ((year % 100 != 0) || (year % 400 ==0)))
         return true;
     else
         return false;
}

Date.daysInYear = function(year) {
    if (Date.isLeapYear(year))
        return 366;
    else
        return 365;
}
// events capturing, careful you don't overwrite this by setting something in
// the onload event of  the body tag
window.onload = function() { 

   // if (!g_https)
        //checkDMDPopUp('pop.cgi','UK','1'); //open email registration pop-up
    new Calendar(new Date());
    if (browser.ns4)
    {
        if (typeof document.NSfix == 'undefined')
        {
            document.NSfix = new Object();
            document.NSfix.initWidth=window.innerWidth;
            document.NSfix.initHeight=window.innerHeight;
        }
    }
}

if (browser.ns4)
    window.onresize = function() {
        if (document.NSfix.initWidth != window.innerWidth ||
          document.NSfix.initHeight != window.innerHeight)
            window.location.reload(false);
    } // ns4 resize bug workaround
    window.document.onclick=handleDocumentClick;
//     window.onerror = function(msg,url,line){
//    alert('******* an error has occurred ********' +
//    '\n\nPlease check that' + 
//    '\n\n1)You have not added any code to the body onload event,'
//    +  '\nif you want to run something as well as the calendar initialisation'
//    + '\ncode, add it to the onload event in the calendar library.'
//    + '\n\n2)You have set the parameters correctly in the g_Calendar.show() method '
//    + '\n\nSee www.totallysmartit.com\\examples\\calendar\\simple.asp for examples'
//    + '\n\n------------------------------------------------------'
//    + '\nError details'
//    + '\nText:' + msg + '\nurl:' + url + '\nline:' + line);
//  }
function toggleobj_css(cse){
//alert("function called case : " + cse);
/* Function designed to hide / show objects based on the status of the container div */
//use some form of marker to identify the troublesome form

switch(form_id){
	//Array of objects to be hidden in the event of the calendar being opened / closed
		case 'flight_search':
			//initialize vars for this form			
			var arr_inc_objs = new Array()
				 //this.status = "form id " + form_id + " | ";
				 var inputClassname  = "input";
				 var hiddenClassname = "hideall";
		break;
		case 'panel':
			//initialize vars for this form
			var arr_inc_objs = new Array()				 
				 var inputClassname  = "input";
				 var hiddenClassname = "hideall";			
		break;
	}//switch	
	
	if(arr_inc_objs){
		var arr_size = arr_inc_objs.length;
	}else{
		var arr_size = 0;
	}
	switch (cse){
			case 'show': 
				//check that objects are hidden and if so then show them
				for (u=0; u < arr_size; u++){
					if (arr_inc_objs[u].className == hiddenClassname){

						arr_inc_objs[u].className = inputClassname;						
					}
				}
			break;
			case 'hide': 
				//check that objects are visible and if so then hide them
				for (u=0; u < arr_size; u++){
					if (arr_inc_objs[u].className == inputClassname){
						
						arr_inc_objs[u].className = hiddenClassname;												
					}
				}
			break;
			default:	
			//do nothing right now	
		}

}
/* Method to clear duration field if the user decides to enter the return date rather the duration*/
function clear_duration(){	
	//document.forms['flight_search'].nights.value='';
}

/* Method used to check whether or not the flight should be one way only */
function validate_duration(curr_target){
	
	return_field_name = 'rtn_date';
	departure_field_name = 'date';
	duration_field_name = 'nights';
	
	switch (curr_target.name){
		case return_field_name:
			//action for return date
			if (curr_target.value == document.forms['flight_search'].date.value){
				
				document.forms['flight_search'].oneWayDirection.checked = true;
				
			}else{
				
				if (document.forms['flight_search'].oneWayDirection.checked == true){
				
					document.forms['flight_earch'].oneWayDirection.checked = false;
				
				}
				
			}			
		break;
		case duration_field_name:
			//action if the user has entered 0 / 00 for the duration in the duration text field
			if ((document.forms['flight_search'].nights.value == 0) || (document.forms['search'].nights.value == 00)){
				
				document.forms['flight_search'].oneWayDirection.checked = true;
				
			}else{
				
				if (document.forms['flight_search'].oneWayDirection.checked == true){
				
					document.forms['flight_search'].oneWayDirection.checked = false;
				
				}
				
			}
		break;
		
		default:
			//do nothing
	}
}

function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	


function replaceSubstring(inputString, fromString, _toString) {
   // Goes through the inputString and replaces every occurrence of fromString with _toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (_toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + _toString + toTheRight;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";
      // Find a string that doesn't exist in the inputString to be used
      // as an "inbetween" string
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist
      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }
      // Next, replace the "inbetween" string with the "_toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + _toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function

