﻿// JScript File

/* Common.js 
    JavaScript file used to encasulated commonly
    used javascript functions
    Created by A.Jason on 6 Jun 2005
*/

var highlightColor = '#bacfff';//'#f0f8ff';
var dehighlightColor = '#ffffff';

//Global variables
/* following vars for tracking mouse position
   added 04/08/2005 - w.tulloch
 */
var clickX = 0;
var clickY = 0;
var mouseTarget ;

/* this function is attached to the document mousedown event and adds
    the mouse 's x & y coords to the glabl vars clientX and clientY the target of the event
    is added to mouseTarget
    created: 04/08/2005 - w.tulloch
 */
function GlobalMouseDown(e){
var ev = window.event? window.event:e;
var target = window.event?ev.srcElement:ev.target;
clickX = ev.clientX;
clickY = ev.clientY;
mouseTarget = target;


}
function nothing()
{
}
function getAbsoluteLeft(el){

var curEl=el;
var iLeft=0;
while(curEl.tagName!="HTML"){
iLeft+=curEl.offsetLeft;
curEl=curEl.offsetParent;
if (curEl == null) break;
}

return iLeft;
}

function openHelp(){    
    window.open("RequestHelp.aspx","helpDeskform","width=550,height=450,status=no,toolbar=no,menubar=no,resizable=no,scrollbars=no,directories=no");
}


function showMenuItem(itemEl){ 
     
    //Hide main content 
    document.getElementById("content-body").style.display = "none"; 
    document.getElementById("divPageNum").style.display = "none"; 
    document.getElementById("divAd").style.display = "none"; 
     
    setupSearchEnv("empty"); 
                  
    switch (itemEl)
    {
        case "Statistics":
        {                       
            document.getElementById("Stats").style.display = "";            
            document.getElementById("News").style.display = "none";                                    
            document.getElementById("GenNews").style.display = "none";                     
            document.getElementById("Promo").style.display = "none";
            document.getElementById("Other").style.display = "none";                            
                                              
            break;
        }
        case "Fare News":
        {           
            CallbackMethods.TrackNews('Fare',null,null);              
            document.getElementById("News").style.display = "";     
            document.getElementById("Stats").style.display = "none";   
            document.getElementById("GenNews").style.display = "none";                     
            document.getElementById("Promo").style.display = "none";
            document.getElementById("Other").style.display = "none";                      
            
            break;
        }
        case "General News":
        {                                  
            CallbackMethods.GetServiceNews(ServiceNewsCallbackResultPopup);
            document.getElementById("GenNews").style.display = "";                     
            document.getElementById("News").style.display = "none";     
            document.getElementById("Stats").style.display = "none";             
            document.getElementById("Promo").style.display = "none";
            document.getElementById("Other").style.display = "none";                        
            
            break;
        }
        case "Promotions":
        {                                   
            document.getElementById("Promo").style.display = "";                       
            document.getElementById("News").style.display = "none";     
            document.getElementById("Stats").style.display = "none"; 
            document.getElementById("GenNews").style.display = "none";       
            document.getElementById("Other").style.display = "none"; 
                                      
            if (doShowAllPromo) 
            {   ShowAllPromo();}
            else
            {     doShowAllPromo = true;}  
            
            break;
        }
        case "Links":
        {           
            document.getElementById("divOtherItems").innerHTML = "";
            document.getElementById("divOtherItems").innerHTML = CallbackMethods.GetLinkContactHelpData(itemEl).value;
            document.getElementById("Other").style.display = ""; 
            document.getElementById("Promo").style.display = "none";                       
            document.getElementById("News").style.display = "none";     
            document.getElementById("Stats").style.display = "none"; 
            document.getElementById("GenNews").style.display = "none"; 
            
            break;
        }
        case "Contact":
        {
            document.getElementById("divOtherItems").innerHTML = "";
            document.getElementById("divOtherItems").innerHTML = CallbackMethods.GetLinkContactHelpData(itemEl).value;
            document.getElementById("Other").style.display = ""; 
            document.getElementById("Promo").style.display = "none";                       
            document.getElementById("News").style.display = "none";     
            document.getElementById("Stats").style.display = "none"; 
            document.getElementById("GenNews").style.display = "none"; 
            
            break;
        }
        case "Help":
        {
            document.getElementById("divOtherItems").innerHTML = "";
            document.getElementById("divOtherItems").innerHTML = CallbackMethods.GetLinkContactHelpData(itemEl).value;
            document.getElementById("Other").style.display = ""; 
            document.getElementById("Promo").style.display = "none";                       
            document.getElementById("News").style.display = "none";     
            document.getElementById("Stats").style.display = "none"; 
            document.getElementById("GenNews").style.display = "none"; 
            
            break;
        }
        default:
            break;
    }              
    
    document.getElementById("lblSearchResultsTitle").innerHTML = itemEl;
    
} 


var selectedPopUpEl;
var doShowAllPromo = true;

function openPop(itemEl){     
    closePopWindows();
    var divPopUp = document.getElementById("divPop");  
    var divPopItem = document.getElementById("divPopItem");
    document.getElementById("divPop").style.display = "";
    itemEl.style.color = '#ffcc99';
    selectedPopUpEl = itemEl;

    switch (itemEl.value)
    {
        case "My Fare Library":
        {
            
            document.getElementById("popFareLib").style.display = "";
            setNormalSize(divPopUp,divPopItem);
            break;
        }
        case "Statistics":
        {
            document.getElementById("popStat").style.display = "";
            setNormalSize(divPopUp,divPopItem);
            break;
        }
        case "Fare News":
        {
            CallbackMethods.TrackNews('Fare',null,null);
            document.getElementById("popFareNews").style.display = "";
            setNormalSize(divPopUp,divPopItem);
//            divPopUp.style.width = '400px';
//            divPopItem.style.width = '395px';   
//            divPopUp.style.height = '330px';
//            divPopItem.style.height = '295px';
            break;
        }
        case "General News":
        {   
            //CallbackMethods.TrackNews('ExceptFare',null,null);
            document.getElementById("popGeneralNews").style.display = "";
            CallbackMethods.GetServiceNews(ServiceNewsCallbackResultPopup);
            //setNormalSize(divPopUp,divPopItem);
            break;
        }
         case "Promotions":
        {
            document.getElementById("popPromotions").style.display = "";
            setNormalSize(divPopUp,divPopItem);
            if (doShowAllPromo) 
            {   ShowAllPromo();}
            else
            {     doShowAllPromo = true;}    
            
            break;
        }
        default:
            break;
    }
    var elBody = document.getElementById("content-body");  
    var elBodyLeft =  getAbsoluteLeft(elBody);
    var leftPos = getAbsoluteLeft(itemEl);
     if (leftPos < (elBodyLeft)) //should not be less than the body left
        leftPos = elBodyLeft ;
     //Testing Far Right   
    var elBodyFarLeft = elBodyLeft+ elBody.offsetWidth;
    var divPopUpWidth = divPopUp.offsetWidth;
    if (divPopUpWidth == 0)  divPopUpWidth = 300; //patch
    if ((leftPos + divPopUpWidth) >= elBodyFarLeft-50)
         leftPos = elBodyFarLeft - divPopUpWidth- 10;
   
    divPopUp.style.left = leftPos + 'px';
  
    var elTitle = document.getElementById("popTitle");
    elTitle.style.display = "";
    elTitle.innerHTML =itemEl.value ;

}
function setNormalSize(divPopUp,divPopItem)
{
    divPopUp.style.width = '300px';
    divPopItem.style.width = '295px';   
    divPopUp.style.height = '240px';
    divPopItem.style.height = '205px';
}
function closePop(){
    
    closePopWindows();
    
    document.getElementById("divPop").style.display="none";
    
}
function closePopWindows()
{
    if (selectedPopUpEl != null) selectedPopUpEl.style.color = '#ffffff';
    document.getElementById("popFareLib").style.display = "none";
    document.getElementById("popStat").style.display = "none";
    document.getElementById("popFareNews").style.display = "none";
    document.getElementById("popGeneralNews").style.display = "none";
    document.getElementById("popPromotions").style.display = "none";
    /*document.getElementById("popServiceNews").style.display = "none";*/
}


function ShowPromo(fareId, agentCode)
{
    doShowAllPromo = false;
    //openPop(document.getElementById('cmdPromotions'));
    var elPopPromo = document.getElementById("Promotions_pnlItems");
    var el = document.getElementById(ddlFareGroupId);
    var OverrideFG;
    if (el != null)
        OverrideFG = el.value;
    if (OverrideFG == null) OverrideFG = '';
    ShowLoadingGraphic(elPopPromo, '100px');
    CallbackMethods.GetPromo(fareId, agentCode, OverrideFG, ShowPromoCallbackHandler,elPopPromo);
}

function ShowAllPromo()
{
    var elPopPromo = document.getElementById("Promotions_pnlItems");
    ShowLoadingGraphic(elPopPromo, '100px');
    CallbackMethods.GetAllPromo(ShowPromoCallbackHandler,elPopPromo);
}

function ShowPromoCallbackHandler(res)
{
    res.context.innerHTML = "";
    if (res.error != null){
        ShowDialogBox("Error", errorMessage + ' ' + res.error);
    }else{
   
        if (res.value.DisplayInfoHTML != ""){
            document.getElementById('Promotions_lblNewsHeader').innerHTML = res.value.DisplayInfoHTML;
            res.context.innerHTML = res.value.PromoHTML;               
            if (res.value.PopUpUrl != "") window.open(res.value.PopUpUrl,"_blank","top=300px");  
        }else{
                              
             ShowDialogBox("Error", errorMessage + ' ' + res.error);
        }
    }
 }
 
function initAdSpace(expand)
{
    var el= document.getElementById('divAd');
    if (expand) 
        el.style.display = "";
    else
        el.style.display = "none";
}
/* Created JASOA - 12/01/2006 */
function initScreen()
{
    
    var elCon = document.getElementById("container");
    var elConBody= document.getElementById("content-body");
    var elPages = document.getElementById("divPageNum");
    var el= document.getElementById('divAd');
    
    /* COMMENTED OUT DUE TO STYLE CHANGE - DO NOT UNCOMMENT.
    if (screen.height <= 600)
            {
                elCon.style.height = "590px";
               //elConBody.style.height = "400px";
                adjustContainerBodyTopAndHeight(elConBody,400,165,el.offsetHeight, (el.style.display == "none"));
            }
            else if (screen.height <= 768)
            {
                elCon.style.height = "590px";
               //elConBody.style.height = "400px";
               adjustContainerBodyTopAndHeight(elConBody,400,165,el.offsetHeight, (el.style.display == "none"));
            }
            else
            {
               elCon.style.height = "835px"; 
              // elConBody.style.height = "645px";
               adjustContainerBodyTopAndHeight(elConBody,645,165,el.offsetHeight, (el.style.display == "none"));
            }  
     elPages.style.top = (elConBody.offsetTop + elConBody.offsetHeight ) + 'px';
     */
}

function adjustContainerBodyTopAndHeight(elConBody, normalHeight, normalTop, adSpaceHeight, adSpaceExpand)
{
    if (!adSpaceExpand)
    {
        elConBody.style.height = (normalHeight - adSpaceHeight) + "px";
        elConBody.style.top = (normalTop + adSpaceHeight) + "px";
    }
    else
    {    
        elConBody.style.height = normalHeight + "px";
        elConBody.style.top = (normalTop - adSpaceHeight) + "px";
    }
}
/*
Function for changing an object's  style class
*/
function ChangeStyleClass(obj, className){
obj.className = className;
}

function GlobalKeyPress(e){
    var key;
	var keychar;
	var pattern;
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode; 
	}
	else if(e.which) {
		// netscape & FireFox
		key = e.which; 
		
	}
	else {
		// browser doesn't support event, allow any char
		return true;
	}
    
    if (key == 13) 
    {
        switch (activeSection)
        {
            case "FastFind":
            {
                fareFastFind();
                break;
            }
            case "FareSearch":
            {
                var el;
                el = document.getElementById(cmdSearchId);       
                //el.focus();               
                if (el.disabled == false)
                    searchFares();
                break;
            }
            case "TicketSearch":
            {
                searchTicket();
                break;
            }
            case "IndexSearch":
                break;
            case "Tools":
                break;
            
        }
        return false;
    }
 	return true;
}

function fareFastFind()
{
    var elValue = new String();
    var elFastFind = document.getElementById('txtFastFind');
    elValue =  trim(elFastFind.value);
    elValue = elValue.replace(/\s/g,"")
    elFastFind.value = elValue;
    if (elValue.length == 0 )
    {
        ShowDialogBox("Fare Fast Find","Please enter a fare reference or a pricecode"); 
        elFastFind.focus();
        return;
    }
    else
    {
        
        var str = elValue.split("/");
        var ref = new String();
        ref = str[0];
        ref = ref.toUpperCase();
        var code;
        code = '';
        var el = document.getElementById(ddlFareGroupId);
        if (el != null)
            code = el.value;
        if (code == null) code = '';
      
        if (str.length < 2)
        getFareSheet(ref,0,0,0,code,true); 
        else //By Price Code
        getFareSheet(ref,0,0,str[1],code,true);    
    }
   
}
/* This var is used to generalised the error message, used in the callback*/
var errorMessage = 'Please log out and try to relogin.';
var disabledBC = '#c0c0c0';
/*  
    This function will add an event handler to the passed object
    Created by A.Jason on 7 Jun 2005
*/
function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		alert("Handler could not be attached");
	}
} 


function removeEvent(obj, evType, fn, useCapture){
  if (obj.removeEventListener){
    obj.removeEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.detachEvent){
    var r = obj.detachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be removed");
  }
} 


function enableElement(el,enable)
{
    
      el.disabled = (!enable);
      if (enable == false)
        el.style.background = disabledBC;
      else
        el.style.background = '#ffffff';
}

//function for getting position
function getPos(el,sProp){
	//sProp is the property we  want to check is "Left" or "Top"
	var iPos = 0;
	while (el!=null){
	    switch(sProp)
	    {
	        case "Left":
	            iPos += el.offsetLeft;
	            el = el.offsetParent;
	            break;
	        case "Top":
	            iPos += el.offsetTop;
		        el = el.offsetParent;
	            break;
	    }
		
	}
	
	return iPos;
}


function trim(str)
{
    return str.replace(/^\s*|\s*$/g,"");
} 


/*  
    This function is used to block the invalid key
    Created by A.Jason on 7 Jun 2005
*/
function isValidCharForType(e, testType)
{
  
  
    var key;
	var keychar;
	var pattern;
	if(window.event) {
		// for IE, e.keyCode or window.event.keyCode can be used
		key = e.keyCode; 
	}
	else if(e.which) {
		// netscape & FireFox
		key = e.which; 
		if (key == 8) //Allow Backspace
		{
		    return true;
		}
	}
	else {
		// browser doesn't support event, allow any char
		return true;
	}
    
 	keychar = String.fromCharCode(key);
    	
	switch(testType)
	{
	    case "decimal":
	        pattern = /[0-9.]/;
	        break;
	    case "numeric":
	        pattern = /[0-9]/;
	        break;
	    case "bookingName":
	        pattern = /[A-Za-z\/]/;
	        break;
	    case "fareRef":
	        pattern = /[0-9A-Za-z\/]/;
	        break;
	    case "name":
	        pattern = /[a-zA-Z\s']/;
	        break;
        case "normalDate","date":
            pattern = /[0-9a-zA-Z/]/;
            break;
        case "citysearch":
            if (key == 32) //Allow space
    	        return true;
    	    pattern = /[A-Za-z]/;
	        break;  
	    case "carriersearch":
	        if (key == 32) //Allow space
    	        return true;
    	   
    	    pattern = /[A-Za-z0-9]/;
	        break;  
	    case "citycode":
	        pattern = /[A-Za-z]/;
	        break;
	    case "carrier","fastticketsearchnumber":
	        pattern = /[A-Za-z0-9]/;
	        break;
	    default:
	        pattern = /[A-Za-z0-9]/;
	        break;
	}
	if (key != 13)
	{
        e.cancelBubble = true;
	}
	return pattern.test(keychar);
}


function getMonthName(month)
{
    switch(month + 1)
    {
        case 1:
            return "JAN";
        case 2:
            return "FEB";
        case 3:
            return "MAR";
        case 4:
            return "APR";
        case 5:
            return "MAY";
        case 6:
            return "JUN";
        case 7:
            return "JUL";
        case 8:
            return "AUG";
        case 9:
            return "SEP";
        case 10:
            return "OCT";
        case 11:
            return "NOV";
        case 12:
            return "DEC";
    }
}

/*	This function return current time string
  	Created on 23 Sept 2005 - A. Jason */
function getCurrentTime()
{
    var dt = new Date();
    var minutes = new String();
    minutes = minutes.concat(dt.getMinutes());
    var hours = new String();
    hours = hours.concat(dt.getHours());
    
    if (hours.length < 2) 
    {
        var temp1 = hours.toString();
        hours = new String();
        hours = hours.concat('0' + temp1);

    }
    if (minutes.length < 2) 
    {      
        var temp2 = minutes.toString();
        minutes = new String();
        minutes = minutes.concat('0' + temp2);   
    }
    return hours.toString() + ':' + minutes.toString();
}



/*  
    This function is used to disabled and enabled radio
    Note: Don't use set attribute for setting the radio button
    because it doesn't work on FireFox!
    Created by A.Jason on 7 Jun 2005
*/
function enableRadioButton(radioToEnable,radioToDisable)
{
    
    if (radioToDisable != null)
    {
        radioToDisable.checked = false;   
    }
    radioToEnable.checked = true;
}

/*  
    This function is used to remove item from select element
    Created by A.Jason on 23/09/2005
*/
function removeItem(selectElId,valueToRemove)
{
	var dl = document.getElementById(selectElId);
	var col = dl.childNodes;
	var el;
	for (i=0; i<=col.length -1;i++)
	{
		el = col[i];
		if (el.value == valueToRemove)
		{
			dl.removeChild(el);
			return;
		}
	}
}

function clearItems(dl)
{
    dl.options.length = 0; 
}
/*  
    This function is used to add item from select element
    Created by A.Jason on 23/09/2005
*/
function addItem(selectElId, value, text)
{

   	var dl = document.getElementById(selectElId);
   	var col = dl.childNodes;
	var el;
	var exist = false;
	for (i=0; i<=col.length -1;i++)
	{
		el = col[i];
		if (el.value == value)
		{
			exist = true;
			break;
		}
	}
	if (exist == false)
	{
          dl.appendChild(createOptionEl(text,value));
    }
    
}
function createOptionEl(text,value)
{
    var newEl = document.createElement("option");
    newEl.innerHTML = text;
    newEl.value = value;
    return newEl;
}
//temp function to handle opening the feedback form
function OpenFeedbackForm()
{
var winParams = "width=510,height=440";
window.open("feedbackform.aspx","feedbackform",winParams);
}


//functions for the View rules requirement
// 10/08/2005 - modified so that the Viewrules box is opened first before calling back to the server - wt
function getRules(caller,code,group){
    var theView = document.getElementById("elRules");
      	var theTarget = document.getElementById("elRulesContent");
	   
    var cLeft = clickX;
    var cTop = clickY;
    var cHeight = caller.clientHeight;
    var rWidth = theView.clientWidth;
	var rLeft =  (getPos(caller,"Left") + caller.clientWidth) - rWidth;
    var rTop = cTop + cHeight;
   
	theView.style.left = rLeft + "px";
    theView.style.top = (rTop + 2) + "px";
    
    var codes = code.split('/');
	document.getElementById('elRulesHeader').innerHTML = 'Key Fare Rules - ' + code;
		     
	var body = document.getElementById("elRulesContent");
	ShowLoadingGraphic(theTarget);
	theView.style.visibility = "";

    document.getElementsByTagName("body")[0].style.cursor = "wait";
    CallbackMethods.GetRules(codes[1],group,GetFareRulesResults,caller);
}

// 10/08/2005 modified. Removed code for displaying the rule view since it is now done GetFareRules()
function GetFareRulesResults(res){
 document.getElementsByTagName("body")[0].style.cursor = "default";
   var theView = document.getElementById("elRules");
   var body = document.getElementById("elRulesContent");
   body.innerHTML = "";
  if (res.error != null){
        theView.visibility = "hidden";
        ShowDialogBox("Error", res.error);
        
    }else{
    
    if (res.value != ""){
        var e = window.event;
        var theCaller = res.context;
	      
	    body.style.overflow = 'auto';
		body.innerHTML = res.value;
	 
	    
	   }else{
	   theView.visibility = "hidden";
	   ShowDialogBox("Show Rules Error", "No rules were found to display");
	   }
	}
} 
function closeRule() { var el = document.getElementById('elRules'); el.style.visibility='hidden'; el = document.getElementById('elRulesContent'); el.style.overflow='hidden';}

/*
10/08/2005 created
*/

function ShowLoadingGraphic(target, width){
if (width== null)
    width = '200px';
var dummyText = "<div style='position:relative;top:100px;margin-left:auto;margin-right:auto;width:" + width + ";text-align:center'><span style='font-size:14px;font-weight:bold'>Loading</span>&nbsp;<img src='Images/AniPlanes-BlueSmall.gif' /></div>";

target.innerHTML = dummyText;

}
function timeoutHandler()
{
    alert("Time out");
}
//This method is callback method, result will be returned by the server .
//Modified 15/11/2007 by VICAS - added server-side error message
function searchResultHandler(res)
{
    //var el = document.getElementById("content-body");
    res.context.innerHTML = "";
   
     
    if (res.error != null){
        if(res.error != null && res.error.Status == 12002) { 
            ShowDialogBox("Error", "Your web browser's RequestTimeout is too small." + res.error);
        } 
        else{
        ShowDialogBox("Error", errorMessage + ' ' + res.error);}
        
    }else{
   
        if (res.value.ResultsHTML != ""){
        
           // res.context.className="FareResults";
            res.context.innerHTML = res.value.ResultsHTML;
            var pages = document.getElementById("divPageNum");
            pages.innerHTML = res.value.PagesHTML;
            var prevSearches = document.getElementById("cellPrevSearches");
            prevSearches.innerHTML = res.value.PreviousSearchesHTML;
            var display = document.getElementById("displayInfo");
            display.innerHTML = res.value.DisplayInfoHTML;
            var ad = document.getElementById("divAd");
            if (res.value.AdHTML == "")
            {
                initAdSpace(false);
                initScreen();       
            }
            else
            {  
                ad.innerHTML = res.value.AdHTML;
                initAdSpace(true);
                initScreen();          
            }
        }else{
            var title = getDialogBoxTitle(res.value.SearchTypeString);
            var error;
            if (res.value.ErrorMessage == "")
            {   
                // Not an error, just no results
                error = "No fares were found that matched your requirements.";
                switch (res.value.SearchTypeString)
                {
                    case "TicketSearch":
                        error = "No tickets were found that matched your requirements.";
                        break;
                    default:
                        break;    
                }
            }else{
                // Server-side error message
                title = title + " Error";
                error = res.value.ErrorMessage;
            } 
            ShowDialogBox(title,error); 
        }
    }
    if (res.value != null)
    {
        if (res.value.SearchTypeString != null)
        {
            switch (res.value.SearchTypeString)
            {
                case "FareSearch":
                    //el = document.getElementById(pnlLoadingId);
                    //el.style.visibility = "hidden";
                    el = document.getElementById(cmdSearchId);      
                    el.disabled = false;
                    break;
                case "IndexSearch":
                    //el = document.getElementById(pnlIXLoadingId);
                    //el.style.visibility = "hidden";
                    loadingIndexFares = false;
                    break;
                case "TicketSearch":
                    //el = document.getElementById(pnlTSLoadingId);
                    //el.style.visibility = "hidden";
                    el = document.getElementById(cmdTicketSearchId);      
                    el.disabled = false;
                    break;
                default:
                    break;
                    
            }
        }
    }
}

function getDialogBoxTitle(searchTypeString)
{
    var title;
    switch (searchTypeString)
            {
                case "FareSearch":
                    title = "Fare Search";
                    break;
                case "IndexSearch":
                   title = "Index Search";
                    break;
                case "TicketSearch":
                   title = "Ticket Search";
                    break;
                default:
                    break;
                    
            }
              
    return title;
}
/* Setup environment for given search type 
    [JASOA] 27/01/2006 Created  Localized environment setup for ALL search Type
*/

var prevSearchType;
function setupSearchEnv(searchType)
{

    closeDialog();
    document.getElementById('displayInfo').innerHTML = '';
    document.getElementById('cellPrevSearches').innerHTML = '';
    document.getElementById('divPageNum').innerHTML = '';
    var ruleView = document.getElementById("elRules");

    if (ruleView != null){
        ruleView.style.visibility = "hidden";
    }
    var visibilityValue;
    var sortVisibilityValue;
    var printVisibilityValue;
    var selectAllVisibilityValue;
    var buttonVisibilityValue;
    
    var cmdPrint = document.getElementById('cmdPrint');
    var cmdCompare = document.getElementById('cmdCompare')
    var ddlSortBy = document.getElementById('ddlFareSortById');
    var selectAllEl = document.getElementById('chkSelectAll');
    var lblSearchResultsTitle = document.getElementById('lblSearchResultsTitle');
    var initItems = false;
    
    var SearchTicket = document.getElementById('TSPC1');
    
    if (prevSearchType == null)
        initItems = true;
    else
        if (prevSearchType != searchType)
            initItems = true;
  
    prevSearchType = searchType;
    if (initItems)
    {
        clearItems(ddlSortBy);
        removeEvent(cmdPrint,'click',printFareResults,false);                       
        removeEvent(ddlSortBy,'change',searchFares,false);
        removeEvent(cmdCompare,'click',compareFareResults,false);
        
        if (SearchTicket != null)
        {
            removeEvent(cmdPrint,'click',printTicketResults,false);
            removeEvent(ddlSortBy,'change',searchTicket,false);
        }    
       
        initAdSpace(false);
        initScreen();
    }
    selectAllEl.checked = false;
    lblSearchResultsTitle.innerHTML = 'Search Results';
 
    switch (searchType)
    {
        case 'empty':
            lblSearchResultsTitle.innerHTML = 'Welcome';
            visibilityValue= "hidden"; 
            sortVisibilityValue = "hidden";
            printVisibilityValue = "hidden";
            selectAllVisibilityValue = "hidden";
            // added to hide buttons
            buttonVisibilityValue= "hidden";
            break;
        case 'fareSearch':
            visibilityValue= "visible"; 
            sortVisibilityValue = "visible";
            printVisibilityValue = "visible";
            selectAllVisibilityValue = "visible";
            buttonVisibilityValue= "visible";
          
            if (initItems)
            {
                ddlSortBy.appendChild(createOptionEl("Price","Price"));
                ddlSortBy.appendChild(createOptionEl("Departure Date","DateFrom"));
                ddlSortBy.appendChild(createOptionEl("Airline","MarketCarrier"));
                ddlSortBy.appendChild(createOptionEl("Min Stay","MinStay"));
                ddlSortBy.appendChild(createOptionEl("Max Stay","MaxStay"));
                ddlSortBy.appendChild(createOptionEl("PassengerType","PaxType"));
                ddlSortBy.appendChild(createOptionEl("Ticketing","TicketDateTo"));
                ddlSortBy.appendChild(createOptionEl("Reference","Reference"));
                addEvent(ddlSortBy,'change',searchFares,false);
                addEvent(cmdPrint,'click',printFareResults,false);
                addEvent(cmdCompare,'click',compareFareResults,false);
            }
            break;
    /*    case 'travelSearch':
            visibilityValue= "hidden"; 
            sortVisibilityValue = "visible";
            printVisibilityValue = "visible";
            selectAllVisibilityValue = "hidden";
          
            if (initItems)
            {
                ddlSortBy.appendChild(createOptionEl("Price","Price"));
                ddlSortBy.appendChild(createOptionEl("Departure Date","DateFrom"));
                ddlSortBy.appendChild(createOptionEl("Min Stay","MinStay"));
                ddlSortBy.appendChild(createOptionEl("Max Stay","MaxStay"));
                ddlSortBy.appendChild(createOptionEl("Ticketing","TicketDateTo"));
                ddlSortBy.appendChild(createOptionEl("Reference","Reference"));
                addEvent(ddlSortBy,'change',searchFares,false);
                addEvent(cmdPrint,'click',printFareResults,false);
            }
            break;  */
        case 'ticketSearch':
             visibilityValue= "hidden"; 
            sortVisibilityValue = "visible";
            printVisibilityValue = "visible";
            selectAllVisibilityValue = "visible";
            buttonVisibilityValue= "visible";
            if (initItems)
            {
                ddlSortBy.appendChild(createOptionEl("Booking Name","Booking Name"));
                ddlSortBy.appendChild(createOptionEl("Relocator","Relocator"));
                ddlSortBy.appendChild(createOptionEl("Booking Date","Booking Date"));
                ddlSortBy.appendChild(createOptionEl("Departure Date","Departure Date"));
                ddlSortBy.appendChild(createOptionEl("No. Tickets","No. Tickets"));
                addEvent(ddlSortBy,'change',searchTicket,false);
                addEvent(cmdPrint,'click',printTicketResults,false);
            }
            break;
        case 'indexSearch':
            visibilityValue= "hidden"; 
            sortVisibilityValue = "hidden";
            printVisibilityValue = "visible";
            selectAllVisibilityValue = "hidden";
            buttonVisibilityValue= "hidden";
            if (initItems)addEvent(cmdPrint,'click',printFareResults,false);
            if (initItems)addEvent(cmdCompare,'click',compareFareResults,false);
            break;
        default:
            break;
    }
      
    ddlSortBy.style.visibility = sortVisibilityValue;
    document.getElementById('ddlPage').style.visibility = visibilityValue;
    document.getElementById('lblSortBy').style.visibility  = sortVisibilityValue;
    document.getElementById('lblPerPage').style.visibility = visibilityValue;
    document.getElementById('lblSelectAll').style.visibility = selectAllVisibilityValue;
    document.getElementById('cmdCompare').style.visibility = buttonVisibilityValue;
    document.getElementById('cmdPrint').style.visibility = buttonVisibilityValue;
    selectAllEl.style.visibility = selectAllVisibilityValue;
}

function printFareResults()
{
    var cfi = getCheckedFareInfo();
    var ddlSortBy = document.getElementById('ddlFareSortById');
    if (cfi.selectedIds.length == 0)
    {
        ShowDialogBox("Print Selected Fares","Please select one or more fares to print."); 
    }
    else
    {
        window.open('PrintSearchResults.aspx?farePrintIds=' + cfi.selectedIds + '&unfarePrintIds=' + cfi.unselectedIds + '&printType=' + prevSearchType + '&printSort=' + ddlSortBy.value, 'printWindow');
    }

}

function compareFareResults()
{
    var cfi = getCheckedFareInfo();
    if (cfi.selectedIds.indexOf(',') == -1)
    {
        ShowDialogBox("Fare Compare","Please select two or more fares to compare."); 
    }
    else
    {
        window.open('compare.aspx?compareIds=' + cfi.selectedIds + '&uncompareIds=' + cfi.unselectedIds, 'comparewindow');
    }
}


/**************** FARE LIBRARY ******************/

/*  function fareLibrary Code 
    Add fare code to the library
    Created by A. Jason on 22/09/2005*/
function addFareRef(el, code,fzid, agentGroupName)
{

    var stat = document.getElementById('lblFareLibStatus');
    stat.innerHTML = 'adding fare ...';
    CallbackMethods.AddFareRef(code, fzid, agentGroupName, addFareRefCallback,stat);
}


/*  call back from adding the fare Library 
    at the same time refreshing the library
    Created by A. Jason on 22/09/2005 */
function addFareRefCallback(res)
{
    res.context.innerHTML = "";
    if (res.error != null){
   
        ShowDialogBox("Error", errorMessage);
    }else{
        if (res.value != ""){                         
                var elFareLib = document.getElementById(pnlFareLibId);
                elFareLib.innerHTML = res.value;                     
        }else{
        
            ShowDialogBox("Fare library","There is an error when adding fare to the library"); 
        }
    }
}

/*  removing the fare code from the library
    Created by A. Jason on 22/09/2005 */
function removeFareRef(el,code)
{
    var stat = document.getElementById('lblFareLibStatus');
    stat.innerHTML = 'removing fare ...';
    CallbackMethods.RemoveFareRef(code, removeFareRefCallback,stat);
}


/*  removing the fare code from the library's call back
    This will also refresh the fare library
    Created by A. Jason on 22/09/2005 */
function removeFareRefCallback(res)
{
    res.context.innerHTML = "";
    if (res.error != null){
   
        ShowDialogBox("Error", errorMessage);
    }else{
         var elFareLib = document.getElementById(pnlFareLibId);
         elFareLib.innerHTML = res.value;  
    }
}

function highlight(el)
{
    el.style.backgroundColor = highlightColor;
}
function dehighlight(el)
{
    el.style.backgroundColor = dehighlightColor;
}

/**************** END FARE LIBRARY ******************/

function isValidDate(dateStr) {
   var ucaseDateStr;
   ucaseDateStr = trim(dateStr).toUpperCase();
   
   var slashIdx = ucaseDateStr.indexOf("/");
   if (slashIdx < 0)
   {
       var dates = new Array("", "JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC")

       var datePat = /^(\d{1,2})(-||'')(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)(-||'')(\d{2,4})$/;

       var matchArray = ucaseDateStr.match(datePat); // is the format ok?
       if (matchArray == null) {
   	    return false;
       }

       day = matchArray[1];
       monthStr = matchArray[3];
       for (i = 1; i <=dates.length; i++) {if (dates[i] == monthStr) month = i}
       year = matchArray[5];

       if (day < 1 || day > 31) {
   	    return false;
       }
       if ((month==4 || month==6 || month==9 || month==11) && day==31) {
   	    return false;
       }
       //add check year
       var isValidYear = validateYear(year);
       if (isValidYear == false)
            return false;
       
       if (month == 2) { // check for february 29th
   	    var isleap1 = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
   	    if (day>29 || (day==29 && !isleap1)) {
   		    return false;
          }
       }
   }
   else
   {
        var splitted;
        splitted = ucaseDateStr.split("/");
        if (splitted.length != 3)
        {
            return false;
        }
        else
        {
            day = splitted[0];
            month = splitted[1];
            year = splitted[2];
            if ((day > 0 && day <= 31) && (month > 0 && month <= 12))
            {
                if ((month==4 || month==6 || month==9 || month==11) && day==31) {
   	                return false;
                }
                if (month == 2) { // check for february 29th
   	                var isleap2 = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
   	                if (day>29 || (day==29 && !isleap2)) {
   		                return false;
                    }
                }
                return validateYear(year);
            }
            else
                return false;           
        }
   }
   return true;  // date is valid
}

function validateYear(strYear)
{
    if (strYear.length == 2) //Validate 2 digits year 
    {
        if (strYear >= 7 && strYear<= 99)
            return true;
        }
    else if (strYear.length == 4) //Validate 4 digits year 
    {
        if (strYear >= 2007)
            return true;   
    }   
    return false;
}

function isValidDecimal(value)
{
    var ValidChars = "0123456789.";
    var IsDecimal=true;
    var Char;

    for (i = 0; i < value.length && IsDecimal == true; i++) 
    { 
        Char = value.charAt(i); 
        if (ValidChars.indexOf(Char) == -1) 
        {
            IsDecimal = false;
        }
    }
    return IsDecimal;
}


/********************** SERVICE NEWS SECTION **********************************************/

/*  Shows service news on home page (ie when QF first loads) 
  	Created on 13 October 2008 - VICAS
*/
function DisplayServiceNewsOnHomePage()
{
    setupSearchEnv("empty");
    CallbackMethods.GetServiceNews(ServiceNewsCallbackResultHomePage);
}
function ServiceNewsCallbackResultHomePage(res)
{
    var el;
    el = document.getElementById("content-body")
    if (res.value != "") {
        DisplayServiceNews(res, el);
        el.innerHTML = "<br/><b>News and Notices</b><br/><br/>" + el.innerHTML;
    }
}
function ServiceNewsCallbackResultPopup(res)
{
    var el;
    el = document.getElementById("divServiceNewsItems");
    // Force the height, fixes display/hide problem in IE6
    //el.style.height = "195px" //commenting out to avoid short box
    if (res.value =="") {
        res.value="<br/>No General News at this time, check back soon.";
    }
    DisplayServiceNews(res, el);
}
/*	This function is a callback function that will handle the results for service news 
    which are returned by the server
  	Created on 13 October 2008 - VICAS */  
function DisplayServiceNews(ServiceNews, displayElement)
{
    displayElement.style.display = "";
    if (ServiceNews != null) {
        displayElement.innerHTML = ServiceNews.value;
    }
}

