﻿/* AEM CM Application
 * Written By:      Eihab El-Mahi
 * Version:         1.0.00
 * Date Created:    08 January 2007
 * Compatibility:   IE + FireFox
 */
addjQueryReference();
/***************************** Global Variables **************************************/
var iCallID;
var soapVersion  = 0; // Version 1.1
var cmNamespace  = "uri:IBE";
var ApplicationName = "";
var transportURI = "";
var PageID = 0;
var PageName = "";
var PageNum = 0;
var CheckHistory = "";
var Wait = null;
var jsonServer = null;
var selectedOffer="";
var selectedOfferName="";
var tmpContent = "";
var BookingID = "";
var BookingOpp = "";
var OffersCounter = 0;
var PageSize = 0;
var params;
var FlightsOnly = false;
var gotoBooking=false;
var IBESeachType = 0;
var originalOfferIndex = 0;
var tmpRow1 = "";
var tmpRow2 = "";
var tmpData = "";
var my_array;
/*************************************************************************************/
/************************************ Functions **************************************/
function init()
{
    try{jsonServer = new srvIBE();}catch(e){}
    GetWaitDiv(); 
     if(startupErrors!=null && startupErrors.length>0){
        for(var i=0;i<startupErrors.length;i++){
            processError(startupErrors[i].message,startupErrors[i].url,startupErrors[i].lineNumber,startupErrors[i].snippet);
        }
        startupErrors.length = 0;
    }
    
}
function GetWaitDiv()
{
    if(GetElementById('divWait') != null)
    {
        Wait = GetElementById('divWait');
        Wait.style.left = ((screen.availWidth - Wait.offsetWidth)/3)+"px";
        Wait.style.top = ((screen.availHeight - Wait.offsetHeight)/3)+"px";
    }
}
function Check(bookingid, operator, airport, selectedBoard, offer, processBooking)
{
    if(processBooking)
        gotoBooking = true;
    else
        gotoBooking = false;
    
    // for the MFP indexing 16/09/2009
    originalOfferIndex = 0;
    // EOC    
    if((WaitForCallBack) || (GetElementById('service')==null))
        return;
    if((jsonServer==null)||(jsonServer==undefined)){try{jsonServer = new srvIBE();}catch(e){}}
    WaitForCallBack = true;
    var History = GetElementById("SearchHistory");
    params = History.value;
    selectedOfferName = bookingid;
    selectedOffer = GetElementById(selectedOfferName);
    if((CheckHistory.length==0) && (GetElementById('service').innerHTML.indexOf("Unfortunately")==-1) && (GetElementById('service').innerHTML.indexOf("error")==-1))
        CheckHistory = GetElementById('service').innerHTML;
    else
        GetElementById('service').innerHTML= CheckHistory;
    CheckFields();
    // Remembering the offer index in the list
    if (GetElementById('SelectedOfferIndex')!=null)
        GetElementById('SelectedOfferIndex').value=offer;
    // Xsl files (Availabilit, InlineAvailability, and Offers List)
    if(GetElementById("AvailXsl")!=null)
        params +="|availXsl:"+GetElementById("AvailXsl").value+"|inlineXsl:"+GetElementById("InlineXsl").value+"|listXsl:"+GetElementById("ListXsl").value;

    // BookingID
    if((params.indexOf("BookingID:")==0) || (params.indexOf("|BookingID:")>-1))
    {
        pair = params.substring(params.indexOf("BookingID:"), params.indexOf('|',params.indexOf("BookingID:")+3));
        params = params.replace(pair,"BookingID:" + bookingid);
    }
    else
        params += "|BookingID:" + bookingid;
    
    // BookingOperator
    if(params.indexOf("BookingOperator:")>-1)
    {
        pair = params.substring(params.indexOf("BookingOperator:"), params.indexOf('|',params.indexOf("BookingOperator:")+3));
        params = params.replace(pair,"BookingOperator:" + operator);
    }
    else
        params += "|BookingOperator:" + operator;
    // BookingAirport
    if(params.indexOf("BookingAirport:")>-1)
    {
        pair = params.substring(params.indexOf("BookingAirport:"), params.indexOf('|',params.indexOf("BookingAirport:")+3));
        params = params.replace(pair,"BookingAirport:" + airport);
    }
    else
        params += "|BookingAirport:" + airport;
    // SelectedBoard
    if(params.indexOf("SelectedBoard:")>-1)
    {
        pair = params.substring(params.indexOf("SelectedBoard:"), params.indexOf('|',params.indexOf("SelectedBoard:")+3));
        params = params.replace(pair,"SelectedBoard:" + selectedBoard);
    }
    else
        params += "|SelectedBoard:" + selectedBoard;
     // Selected Offer
    params += "|SelectedOffer:" + offer;
    // Page Type
    params += "|PageType:" + GetElementById("PageType").value;
    // FlexiDays
    params += "|FlexiDays:" + GetElementById("FlexiDays").value;
    // WithoutAlternatives
    params += "|WithoutAlternatives:" + (GetElementById("WithoutAlternatives").checked ? "on" : "");
    //OfferGUID
    if(GetElementById("a" + bookingid))
    {
        var offerGUID = GetElementById("a" + bookingid).innerHTML;
        offerGUID = offerGUID.substring(offerGUID.indexOf("&#91;OGUID&#93;") + "&#91;OGUID&#93;".length, offerGUID.indexOf("&#91;&#47;OGUID&#93;"));
        params += "|OfferGUID:"+offerGUID;
    }
    params = params.replace(/,/g,"¬").replace(/\|/g,",")
    BookingID=bookingid;
    BookingOpp = operator;
    // Cache the Selected offer content
    if(selectedOffer!=null)
        tmpContent = selectedOffer.innerHTML;
    else
        tmpContent = "";
    // Set the wait "Div" content to the selected offer content
    if(Wait==null)
    {
        WaitForCallBack = false;
        GetWaitDiv();
        window.setTimeout('Check("'+bookingid+'", "'+operator+'", "'+airport+'", "'+selectedBoard+'", '+offer+')', 1000);
        return;
    }
    if(selectedOffer!=null)
    {
        for(i=selectedOffer.childNodes.length-1; i>=0; i--)
        {
            selectedOffer.removeChild(selectedOffer.childNodes.item(i));
        }
        for(i=0; i<Wait.childNodes.length; i++)
        {
            selectedOffer.appendChild(Wait.childNodes.item(i).cloneNode(true));
        }
    }
    jsonServer.CheckAvailability(params,UpdateContent)
}


// Removes leading whitespaces
function LTrim( value ) {
	
	var re = /\s*((\S+\s*)*)/;
	return value.replace(re, "$1");
	
}

// Removes ending whitespaces
function RTrim( value ) {
	
	var re = /((\s*\S+)*)\s*/;
	return value.replace(re, "$1");
	
}

// Removes leading and ending whitespaces
function trim( value ) {
	
	return LTrim(RTrim(value));
	
}


// **********// included the package ID *********//


function CheckMultipleFlightOffer(bookingid, operator, offer, packageID, airport, selectedBoard, ServiceCodes, processBooking)
{
// Generate the bookingID when getting the data from Flight Cache
    var initialOperator;
    var mfpOperator;
    if (processBooking)
    {
        gotoBooking = true;
    }
    else
    {
        gotoBooking = false;
    }
    try
    {
        mfpOperator = operator; 
        if((WaitForCallBack) || (GetElementById('service')==null))
            return;
        if((jsonServer==null)||(jsonServer==undefined)){try{jsonServer = new srvIBE();}catch(e){}}
        WaitForCallBack = true;
        var History = GetElementById("SearchHistory");
        params = History.value;
        // Changed by py
        //selectedOfferName = bookingid + '_' + offer ;
        
        // Changed to keep th same Offer ID for multiple flight Booking 
        selectedOfferName = bookingid.toString().substr(0, bookingid.toString().lastIndexOf("_")) + '_' + offer ;
        selectedOfferName = bookingid; 
        
        // Chnaged by PY for the Wait div display
        selectedOffer = GetElementById("selectedOfferName");
                
        selectedOffer = GetElementById("select_" + offer);
        ///////////////////////////////////////////////////////////////////////
        if((CheckHistory.length==0) && (GetElementById('service').innerHTML.indexOf("Unfortunately")==-1) && (GetElementById('service').innerHTML.indexOf("error")==-1))
            CheckHistory = GetElementById('service').innerHTML;
        else
            GetElementById('service').innerHTML= CheckHistory;
        CheckFields();
        // remember the original OfferIndex for the intial price check
        if ((originalOfferIndex == 0) && (GetElementById('SelectedOfferIndex')!=null))
        {   originalOfferIndex = GetElementById('SelectedOfferIndex').value; }
                
        params += "|OriginalOfferIndex:" + originalOfferIndex;
        
        // Remembering the offer index in the list
        if (GetElementById('SelectedOfferIndex')!=null)
            GetElementById('SelectedOfferIndex').value=offer;
        // Xsl files (Availabilit, InlineAvailability, and Offers List)
        if(GetElementById("AvailXsl")!=null)
            params +="|availXsl:"+GetElementById("AvailXsl").value  +"|inlineXsl:"+GetElementById("InlineXsl").value+  "|listXsl:"+GetElementById("ListXsl").value ;    
        //Commented to get the hard codes undone
            //params +="|availXsl:"+GetElementById("AvailXsl").value + "_test" +"|inlineXsl:"+GetElementById("InlineXsl").value+ "_test" + "|listXsl:"+GetElementById("ListXsl").value + "_test";    
        // BookingID
        if((params.indexOf("BookingID:")==0) || (params.indexOf("|BookingID:")>-1))
        {
            pair = params.substring(params.indexOf("BookingID:"), params.indexOf('|',params.indexOf("BookingID:")+3));
            params = params.replace(pair,"BookingID:" + selectedOfferName);
        }
        else
            params += "|BookingID:" + selectedOfferName;
         
        // BookingOperator --- Gett he original Operator and manupulate or manupulate in the XSLT
        if(params.indexOf("BookingOperator:")>-1)
        {
            pair = params.substring(params.indexOf("BookingOperator:"), params.indexOf('|',params.indexOf("BookingOperator:")+3));
            params = params.replace(pair,"BookingOperator:" + operator);
        }
        else
            params += "|BookingOperator:" + operator;
            
        // BookingAirport
        if(params.indexOf("BookingAirport:")>-1)
        {
            pair = params.substring(params.indexOf("BookingAirport:"), params.indexOf('|',params.indexOf("BookingAirport:")+3));
            params = params.replace(pair,"BookingAirport:" + airport);
        }
        else
            params += "|BookingAirport:" + airport;
        // SelectedBoard
        if(params.indexOf("SelectedBoard:")>-1)
        {
            pair = params.substring(params.indexOf("SelectedBoard:"), params.indexOf('|',params.indexOf("SelectedBoard:")+3));
            params = params.replace(pair,"SelectedBoard:" + selectedBoard);
        }
        else
            params += "|SelectedBoard:" + selectedBoard;
            
        // Selected Offer
        params += "|SelectedOffer:" + offer;
        // Page Type
        params += "|PageType:" + GetElementById("PageType").value;
        // FlexiDays
        params += "|FlexiDays:" + GetElementById("FlexiDays").value;
        // WithoutAlternatives
        
        params += "|WithoutAlternatives:" + (GetElementById("WithoutAlternatives").checked ? "on" : "");
        
        // Added for the MFP ///////////
        
        params += "|CachedOfferXml:" + GetElementById("CachedOfferXml").value;
            
        params += "|CachedAvailXml:" + GetElementById("CachedAvailXml").value;
           
        // Send a parameter recognising this a MFP Offer
        params += "|OriginalBookingID" + bookingid;
        
        if (bookingid == selectedOfferName)
        {
            params += "|MultipleFlightOffer:" + "false";
        }
        else
        {
            params += "|MultipleFlightOffer:" + "true";
        }
        params += "|ServiceCode:" + ServiceCodes ; 

        params += "|MultiFlightOfferIndex:" + offer  ;  
        
        // Pass the Package id as the parameter
        if((params.indexOf("PackageID:")==0) || (params.indexOf("|PackageID:")>-1))
        {
            pair = params.substring(params.indexOf("PackageID:"), params.indexOf('|',params.indexOf("PackageID:")+3));
            params = params.replace(pair,"PackageID:" + packageID);
        }
        else
            params += "|PackageID:" + packageID;
        
        //// End of change
        
        //OfferGUID
        if(GetElementById("a" + bookingid))
        {
        // Chnaged by PY
            var offerGUID = GetElementById("a" + BookingID).innerHTML;
            offerGUID = offerGUID.substring(offerGUID.indexOf("&#91;OGUID&#93;") + "&#91;OGUID&#93;".length, offerGUID.indexOf("&#91;&#47;OGUID&#93;"));
            params += "|OfferGUID:"+offerGUID;
        }
        
        params = params.replace(/,/g,"¬").replace(/\|/g,",")
        // Chnaged by Py for keeping MFP booking ID length always 22
        //BookingID=bookingid + '_' + offer ;;
        // Commented for the original booking id use
        //BookingID = bookingid.toString().substr(0, bookingid.toString().lastIndexOf("_")) + '_' + offer ;
        BookingID = bookingid; 
        // End of Change
        BookingOpp = operator;
    if(selectedOffer!=null)
    {
        tmpContent = selectedOffer.innerHTML;
        tmpRow1 =  GetElementById(selectedOffer.id).parentNode.parentNode;
        tmpRow2 =  GetElementById(selectedOffer.id).parentNode.parentNode.nextSibling;
        tmpData = GetElementById(selectedOffer.id).parentNode.parentNode.innerHTML;
    }
    else
    {
        tmpContent = "";
        tmpRow1 =  "";
        tmpRow2 =  "";
    }
    // Set the wait "Div" content to the selected offer content
    if(Wait==null)
    {
        WaitForCallBack = false;
        GetWaitDiv();
        //CheckMultipleFlightOffer
        window.setTimeout('CheckMultipleFlightOffer("'+bookingid+'", "'+operator+'", "'+offer+'", "'+originalOfferOperator+'" + "'+airport+'", "'+selectedBoard+'", '+ServiceCodes+')', 1000);
        //bookingid, operator, offer, originalOfferOperator, airport, selectedBoard, ServiceCodes, processBooking)
        return;
    }
    if(selectedOffer!=null)
    { 
    //variables needed for the script to work
        var selectElement = $('#' + selectedOffer.id);                         //replace select_1 with element to be selected
        var selectParent = selectElement.parent();                  //TD element
        var divHeight = selectParent.outerHeight();                 //height of TD
        var divWidth = selectParent.parent().outerWidth();    //width of TR
        var divOffset = selectParent.parent().offset();       //offset of TR
        var divContent =  $('#flightsWait').html();                 //content to be placed in loading div

        //if no element with id="flightsWait" exists, set default message
        if(!divContent){
            divContent = "Please wait while we check your flight";
        }

        //disable radio buttons while flight avail check is done
        if($('#muliple-flights table').length > 0){
            $('#muliple-flights table input').attr('disabled','disabled');
        }

        //add message div to page
        $('body').prepend(
            '<div id="flightsLoader">' +
                divContent +
            '</div>'
        );

        //position and size styles must be applied to new div
        $('#flightsLoader').css({
            'position':'absolute',
            'top':+divOffset.top+'px',
            'left':divOffset.left+'px',
            'width':divWidth+'px',
            'height':divHeight+'px',
            'z-index':'99999'});

        //if no message was given, style the message by default
        if(divContent == "Please wait while we check your flight"){
            $('#flightsLoader').css({
                'background':'#ffffff',
                'text-align':'center',
                'font-weight':'bold',
                'line-height':divHeight + 'px'
            });
        }

    }
        jsonServer.checkMFPAvailability(params,UpdateContent);
    }
    catch(e)   
    {
        alert("Parameters Passed: " + bookingid, + " operator: " + operator + " Offer Index: " +  offer + " Original TourOperator: " + originalOfferOperator  );
        return;
    }
}





//// Commented for the Package ID Include

//function CheckMultipleFlightOffer(bookingid, operator, offer, originalOfferOperator, airport, selectedBoard, ServiceCodes, processBooking)
//{
//// Generate the bookingID when getting the data from Flight Cache
//    var initialOperator;
//    var mfpOperator;
//    if (processBooking)
//    {
//        gotoBooking = true;
//    }
//    else
//    {
//        gotoBooking = false;
//    }
//    
//    // Commented for the package ID
//    initialOperator = originalOfferOperator.toString();
//    
//    try
//    {
//        if (initialOperator.substring(0,1)== "X")
//        {
//            //mfpOperator = initialOperator.substring(0,5) + operator ;
//            operator = initialOperator.substring(0,5) + trim(operator) ;
//            mfpOperator = operator; 
//        }
//        mfpOperator = operator; 
//        //alert('New Operator: ' + operator); 
//        if((WaitForCallBack) || (GetElementById('service')==null))
//            return;
//        if((jsonServer==null)||(jsonServer==undefined)){try{jsonServer = new srvIBE();}catch(e){}}
//        WaitForCallBack = true;
//        var History = GetElementById("SearchHistory");
//        params = History.value;
//        // Changed by py
//        //selectedOfferName = bookingid + '_' + offer ;
//        selectedOfferName = bookingid.toString().substr(0, bookingid.toString().lastIndexOf("_")) + '_' + offer ;
//        
//        // Chnaged by PY for the Wait div display
//        selectedOffer = GetElementById("selectedOfferName");
//        //selectedOffer = GetElementById("BookingID");
//        
//        //selectedOffer = GetElementById("bookingid");
//        
//        selectedOffer = GetElementById("select_" + offer);
//        ///////////////////////////////////////////////////////////////////////
//        if((CheckHistory.length==0) && (GetElementById('service').innerHTML.indexOf("Unfortunately")==-1) && (GetElementById('service').innerHTML.indexOf("error")==-1))
//            CheckHistory = GetElementById('service').innerHTML;
//        else
//            GetElementById('service').innerHTML= CheckHistory;
//        CheckFields();
//        // remember the original OfferIndex for the intial price check
//        if ((originalOfferIndex == 0) && (GetElementById('SelectedOfferIndex')!=null))
//        {   originalOfferIndex = GetElementById('SelectedOfferIndex').value; }
//        
//        params += "|OriginalOfferIndex:" + originalOfferIndex;
//        
//        // Remembering the offer index in the list
//        if (GetElementById('SelectedOfferIndex')!=null)
//            GetElementById('SelectedOfferIndex').value=offer;
//        // Xsl files (Availabilit, InlineAvailability, and Offers List)
//        if(GetElementById("AvailXsl")!=null)
//            params +="|availXsl:"+GetElementById("AvailXsl").value  +"|inlineXsl:"+GetElementById("InlineXsl").value+  "|listXsl:"+GetElementById("ListXsl").value ;    
//        //Commented to get the hard codes undone
//           // params +="|availXsl:"+GetElementById("AvailXsl").value + "_MFP" +"|inlineXsl:"+GetElementById("InlineXsl").value+ "MFP" + "|listXsl:"+GetElementById("ListXsl").value + "MFP";    
//        // BookingID
//        if((params.indexOf("BookingID:")==0) || (params.indexOf("|BookingID:")>-1))
//        {
//            pair = params.substring(params.indexOf("BookingID:"), params.indexOf('|',params.indexOf("BookingID:")+3));
//            params = params.replace(pair,"BookingID:" + selectedOfferName);
//        }
//        else
//            params += "|BookingID:" + selectedOfferName;
//         
//        // BookingOperator --- Gett he original Operator and manupulate or manupulate in the XSLT
//        if(params.indexOf("BookingOperator:")>-1)
//        {
//            pair = params.substring(params.indexOf("BookingOperator:"), params.indexOf('|',params.indexOf("BookingOperator:")+3));
//            params = params.replace(pair,"BookingOperator:" + operator);
//        }
//        else
//            params += "|BookingOperator:" + operator;
//            
//        // BookingAirport
//        if(params.indexOf("BookingAirport:")>-1)
//        {
//            pair = params.substring(params.indexOf("BookingAirport:"), params.indexOf('|',params.indexOf("BookingAirport:")+3));
//            params = params.replace(pair,"BookingAirport:" + airport);
//        }
//        else
//            params += "|BookingAirport:" + airport;
//        // SelectedBoard
//        if(params.indexOf("SelectedBoard:")>-1)
//        {
//            pair = params.substring(params.indexOf("SelectedBoard:"), params.indexOf('|',params.indexOf("SelectedBoard:")+3));
//            params = params.replace(pair,"SelectedBoard:" + selectedBoard);
//        }
//        else
//            params += "|SelectedBoard:" + selectedBoard;
//            
//        // Selected Offer
//        params += "|SelectedOffer:" + offer;
//        // Page Type
//        params += "|PageType:" + GetElementById("PageType").value;
//        // FlexiDays
//        params += "|FlexiDays:" + GetElementById("FlexiDays").value;
//        // WithoutAlternatives
//        
//        params += "|WithoutAlternatives:" + (GetElementById("WithoutAlternatives").checked ? "on" : "");
//        
//        // Added for the MFP ///////////
//        
//        params += "|CachedOfferXml:" + GetElementById("CachedOfferXml").value;
//            
//        params += "|CachedAvailXml:" + GetElementById("CachedAvailXml").value;
//           
//        // Send a parameter recognising this a MFP Offer
//        params += "|OriginalBookingID" + bookingid;
//        
//        if (bookingid == selectedOfferName)
//        {
//            params += "|MultipleFlightOffer:" + "false";
//        }
//        else
//        {
//            params += "|MultipleFlightOffer:" + "true";
//        }
//        params += "|ServiceCode:" + ServiceCodes ; 
//        
//        //// End of change
//        
//        //OfferGUID
//        if(GetElementById("a" + bookingid))
//        {
//        // Chnaged by PY
//            var offerGUID = GetElementById("a" + BookingID).innerHTML;
//            offerGUID = offerGUID.substring(offerGUID.indexOf("&#91;OGUID&#93;") + "&#91;OGUID&#93;".length, offerGUID.indexOf("&#91;&#47;OGUID&#93;"));
//            params += "|OfferGUID:"+offerGUID;
//        }
//        
//        params = params.replace(/,/g,"¬").replace(/\|/g,",")
//        // Chnaged by Py for keeping MFP booking ID length always 22
//        //BookingID=bookingid + '_' + offer ;;
//        BookingID = bookingid.toString().substr(0, bookingid.toString().lastIndexOf("_")) + '_' + offer ;
//        BookingOpp = operator;
//    if(selectedOffer!=null)
//    {
//        tmpContent = selectedOffer.innerHTML;
//        tmpRow1 =  GetElementById(selectedOffer.id).parentNode.parentNode;
//        tmpRow2 =  GetElementById(selectedOffer.id).parentNode.parentNode.nextSibling;
//        tmpData = GetElementById(selectedOffer.id).parentNode.parentNode.innerHTML;
//    }
//    else
//    {
//        tmpContent = "";
//        tmpRow1 =  "";
//        tmpRow2 =  "";
//    }
//    // Set the wait "Div" content to the selected offer content
//    if(Wait==null)
//    {
//        WaitForCallBack = false;
//        GetWaitDiv();
//        //CheckMultipleFlightOffer
//        window.setTimeout('CheckMultipleFlightOffer("'+bookingid+'", "'+operator+'", "'+offer+'", "'+originalOfferOperator+'" + "'+airport+'", "'+selectedBoard+'", '+ServiceCodes+')', 1000);
//        //bookingid, operator, offer, originalOfferOperator, airport, selectedBoard, ServiceCodes, processBooking)
//        return;
//    }
//    if(selectedOffer!=null)
//    { 
//    //variables needed for the script to work
//        var selectElement = $('#' + selectedOffer.id);                         //replace select_1 with element to be selected
//        var selectParent = selectElement.parent();                  //TD element
//        var divHeight = selectParent.outerHeight();                 //height of TD
//        var divWidth = selectParent.parent().outerWidth();    //width of TR
//        var divOffset = selectParent.parent().offset();       //offset of TR
//        var divContent =  $('#flightsWait').html();                 //content to be placed in loading div

//        //if no element with id="flightsWait" exists, set default message
//        if(!divContent){
//            divContent = "Please wait while we check your flight";
//        }

//        //disable radio buttons while flight avail check is done
//        if($('#muliple-flights table').length > 0){
//            $('#muliple-flights table input').attr('disabled','disabled');
//        }

//        //add message div to page
//        $('body').prepend(
//            '<div id="flightsLoader">' +
//                divContent +
//            '</div>'
//        );

//        //position and size styles must be applied to new div
//        $('#flightsLoader').css({
//            'position':'absolute',
//            'top':+divOffset.top+'px',
//            'left':divOffset.left+'px',
//            'width':divWidth+'px',
//            'height':divHeight+'px',
//            'z-index':'99999'});

//        //if no message was given, style the message by default
//        if(divContent == "Please wait while we check your flight"){
//            $('#flightsLoader').css({
//                'background':'#ffffff',
//                'text-align':'center',
//                'font-weight':'bold',
//                'line-height':divHeight + 'px'
//            });
//        }

//    }
//        jsonServer.checkMFPAvailability(params,UpdateContent);
//    }
//    catch(e)   
//    {
//        alert("Parameters Passed: " + bookingid, + " operator: " + operator + " Offer Index: " +  offer + " Original TourOperator: " + originalOfferOperator  );
//        return;
//    }
//   
//    //////////////////////////////////////////////////////////////////////////////////
//    
//    ///alert('Hello CheckMultipleFlightOffer called');
//}


/********///////////////////////////

/*************************************************************************************/
/******************************** Service Callbacks **********************************/
function UpdateContent(response) {
    var offerGUID = '';
    if(response.error)
    {
//        if(window.confirm("Error when checking availability. Please refresh the page."))
//            GetElementById('frmIBEMainForm').submit();
        if(FlightsOnly)
            GetElementById('FlightBookingID').value = BookingID;
        else
            GetElementById('BookingID').value = BookingID;
        GetElementById('frmIBEMainForm').submit();
        if(selectedOffer)
            PopulateInlineContent(tmpContent);
        //alert(response.error.stackTrace);
    }
    else
    {
        // Updated list
        GetElementById('offers_list').innerHTML=response.result.offersListHTML;
        GetElementById("CachedOfferXml").value = response.result.offerDataXML;
        GetElementById("CachedAvailXml").value = response.result.availDataXML;
//        if (response.result.multiFlight){
//            GetElementById("CachedMultiFlightXml").value = response.result.ukFlightDataXML; 
//            }
        GetElementById("txtTimeout").value = response.result.checkTime;
        offerGUID = response.result.offerGUID;
        
        // Changed for the bookind Change:
        //if(GetElementById("a" + BookingID))
        if(GetElementById("a" + BookingID))
        {
            if((response.result.inlineDataHTML.indexOf("Unfortunately")==-1)&&(response.result.availDataHTML.indexOf("error")==-1))
            {
                GetElementById("a" + BookingID).style.display="block";
                if (!response.result.multiFlight)
                {
                    GetElementById("a" + BookingID).innerHTML = response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut][CachedMultiFlightXml]" + response.result.ukFlightDataXML + "[CachedMultiFlightXml]-->";
                    GetElementById("a" + BookingID).style.display="block";
                    CheckHistory = GetElementById('service').innerHTML;
                }
                else
                {
                    GetElementById("a" + BookingID).innerHTML= "";
                    CheckHistory = "<div id=\"a" + BookingID + "\">" + response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut]--></div>";
                    //GetElementById("a" + BookingID).style.display="block";
                    GetElementById('service').innerHTML = CheckHistory.replace('\n', '');
                }
            }
            else
            {
                    GetElementById('service').innerHTML = CheckHistory.replace('\n','');
                    GetElementById("a" + BookingID).innerHTML= "";
                    GetElementById("a" + BookingID).style.display="none";
                    GetElementById('service').removeChild(GetElementById("a" + BookingID));
            }
        }
        // Added for OfferID change
        else
        {
        // Changed by PY for the multi Flight
            if (((response.result.inlineDataHTML.length > 0) && (response.result.inlineDataHTML.indexOf("Unfortunately") == -1) && (response.result.availDataHTML.indexOf("error") == -1)) || (response.result.multiFlight)) {
                if (response.result.multiFlight){CheckHistory="";}
                //CheckHistory += "<div id=\"a" + BookingID + "\">" + response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut][CachedMultiFlightXml]" + response.result.ukFlightDataXML + "[CachedMultiFlightXml]--></div>";
                CheckHistory += "<div id=\"a" + BookingID + "\">" + response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut]--></div>";
                //CheckHistory += "<div id=\"a" + BookingID + "\"" + " name=\"a" + BookingID +  "\">" + response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut]--></div>";
                GetElementById('service').innerHTML = CheckHistory.replace('\n', '');
            }
            else if ((response.result.inlineDataHTML.length > 0) && (response.result.isdatamixOffer) && (response.result.statusCode.match("450") != null)){ //|| (response.result.multiFlight)) #
                //CheckHistory += "<div id=\"a" + BookingID + "\">" + response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut][CachedMultiFlightXml]" + response.result.ukFlightDataXML + "[CachedMultiFlightXml]--></div>";
                CheckHistory += "<div id=\"a" + BookingID + "\">" + response.result.availDataHTML + "<!--[CachedOfferXml]" + response.result.offerDataXML + "[/CachedOfferXml][CachedAvailXml]" + response.result.availDataXML + "[/CachedAvailXml][TimeOut]" + response.result.checkTime + "[/TimeOut]--></div>";
                GetElementById('service').innerHTML = CheckHistory.replace('\n', '');
            }
            else
                GetElementById('service').innerHTML = CheckHistory.replace('\n', '');
        }
        selectedOffer = GetElementById(selectedOfferName);
        
        if(response.result.inlineDataHTML.length>0)
        {
            PopulateInlineContent(response.result.inlineDataHTML);
        }
        else if(selectedOffer)
        {
            if(selectedOffer.hasChildNodes())
            {
                for(i=selectedOffer.childNodes.length-1; i>=0; i--)
                {
                    selectedOffer.removeChild(selectedOffer.childNodes.item(i));
                }
            }
            PopulateInlineContent(tmpContent);
        }
        var ShowAvialDiv = false;
        if(GetElementById('service').hasChildNodes() && (GetElementById('service').childNodes.length>1))
        {
            var counter = 0;
            var div = GetElementById('service').childNodes;
            for(i=0; i<div.length;i++)
            {
                if(div[i].nodeName!="#text")
                    counter++;
            }
            if(counter<=1)
                ShowAvialDiv=false;
            else
                ShowAvialDiv=true;
        }
        if(ShowAvialDiv)
        {
//            if (response.result.multiFlight)
//            {
//                try{
//                    $('#flightsLoader').remove();
//                    if($('#muliple-flights table').length > 0){
//                        $('#muliple-flights table input').removeAttr('disabled');
//                    }
//                }
//                catch(e){
//                    alert("Jquery Failed");
//                }
//            }
//            else
//            {
                GetElementById('service').style.visibility="visible";
                GetElementById('service').style.display="block";
//            }
        }
        else
        {
              if (response.result.multiFlight)
            {
                try{
                    $('#flightsLoader').remove();
                    if($('#muliple-flights table').length > 0){
                        $('#muliple-flights table input').removeAttr('disabled');
                    }
                }
                catch(e){
                    alert("Jquery Failed");
                }
            }
          GetElementById('service').style.visibility="hidden";
          GetElementById('service').style.display="none";
        }
        if (window.OnAfterPriceCheck) { window.OnAfterPriceCheck(response); }
    }
    WaitForCallBack = false;
    if(FlightsOnly)
    {
        offerCheckCallbackFunction(response, offerGUID);
    }
    else
    {
        if ((gotoBooking) && (response.result) && (response.result.inlineDataHTML.indexOf("Unfortunately") == -1))
        {
            var Form = GetElementById('frmIBEMainForm');
            Book(BookingID, BookingOpp, "", "", "");
                
         Form.submit();
        }
    }
}
function PopulateContent(tmpContent)
{
    var node = document.createElement("div");
    node.innerHTML = tmpContent;
    for(i=0; i<node.childNodes.length; i++)
    {
        selectedOffer.appendChild(node.childNodes.item(i).cloneNode(true));
    }
}


// Added on date 05/08/2009 to fix the single cell inline availability
function checkifSingleCell(content) {
    // Check if the html content is a single cell or not
    var singlecell = true;
    if (content.split('<td').length > 0) {
        var closing = 0;

        var nodeCount = content.split('<td').length - 1;
        var cnt = 0;
        // Get the cells in the HTML
        for (i = 0; i < content.split('<td').length; i++) {
            if (content.split('<td')[i].split('</td>').length > 0) {
                // if the node is not null
                if (content.split('<td')[i].replace(/ /g, '').length > 0) {
                    cnt = cnt + 1;
                    var inrString = content.split('<td')[i];
                    // Check if there is a corresponding closing </td> 
                    if (inrString.search('</td>') > 0) {
                        closing = closing + 1;
                    }
                    // if in each <td> row for the corresponding </td>  
                    // is available then it is not a single cell else 
                    // it is single cell (if the <td> count and </td>  
                    // count matches at the last node - it is a single cell
                    if ((closing == cnt) && i != nodeCount) {
                        singlecell = false;
                    }
                }
            }
        }
    }
    return singlecell;
}

function PopulateInlineContent(content) {
    if (!selectedOffer)
        return;
    var pos = content.indexOf("<", 0);
    var nodeCount = content.split('<td').length - 1;
    // Clear existing content
    if (selectedOffer.hasChildNodes()) {
        for (i = selectedOffer.childNodes.length - 1; i >= 0; i--) {
            selectedOffer.removeChild(selectedOffer.childNodes.item(i));
        }
    }
    // setting new content
    if (selectedOffer.nodeName.toUpperCase() == "TR") {
        while (pos > -1) {
            if (content.substring(pos, pos + 4) != "<!--") {

                if (content.split('<td').length > 0) 


                {
                    if (checkifSingleCell(content)) 
                    {
                        var startPosition = -1;
                        var endPosition;

                        var node = selectedOffer.insertCell(-1);

                        if (content.split('(<td.>.</td>')[0].replace(/ /g, '').length > 0) 
                        {
                            (startPosition == content.split('(<td.>.</td>')[0].indexOf("class=\"", 0)) ? startPosition = 0 : startPosition = content.split('(<td.>.</td>')[0].indexOf("class=\"", 0) + 7;
                            endPosition = content.split('(<td.>.</td>')[0].indexOf("\"", startPosition);
                            if (startPosition > 0) 
                            {
                                node.className = content.split('(<td.>.</td>')[0].substring(startPosition, endPosition);
                            }
                            // colspan
                            startPosition = -1;
                            //
                            (startPosition == content.split('(<td.>.</td>')[0].indexOf("colspan=", 0)) ? startPosition = 0 : startPosition = content.split('(<td.>.</td>')[0].indexOf("colspan=", 0) + 9;
                            endPosition = content.split('(<td.>.</td>')[0].indexOf(">", 0);
                            var tst = content.split('(<td.>.</td>')[0].indexOf(" ", startPosition);
                            if (tst < endPosition) 
                            {
                                endPosition = tst; 
                            }
                            if ((startPosition > 8) && (endPosition > startPosition)) 
                            {
                                node.colSpan = parseInt(content.split('(<td.>.</td>')[0].substring(startPosition, endPosition).replace('"', '').replace("'", ""));
                            }
                            // td content
                            startPosition = content.split('(<td.>.</td>')[0].indexOf(">", endPosition) + 1;
                            endPosition = content.toString().length - '</td>'.length; //content.split('(<td.>.</td>')[0].indexOf("</td", startPosition);
                            //if ((pos2 > 0 ) && (t != nodeCount))
                            //{
                            node.innerHTML = content.split('(<td.>.</td>')[0].substring(startPosition, endPosition);
                            //}
                        }
                    }
                    else {

                        for (t = 0; t < content.split('<td').length; t++) {
                            if (content.split('<td')[t].replace(/ /g, '').length > 0) {
                                var n = selectedOffer.insertCell(-1);
                                // class
                                // Changed by PY for the not available class name in the cell
                                var pos1 = -1;
                                //pos1 = content.split('<td')[t].indexOf("class=\"", 0) + 7;
                                (pos1 == content.split('<td')[t].indexOf("class=\"", 0))? pos1 = 0 : pos1 = content.split('<td')[t].indexOf("class=\"", 0) + 7;
                                var pos2 = content.split('<td')[t].indexOf("\"", pos1);

                                if (pos1 > 0) {
                                    n.className = content.split('<td')[t].substring(pos1, pos2);
                                }
                                // colspan
                                // Commented by Py for the class and position changes
                                // not available colspan
                                //pos1 = content.split('<td')[t].indexOf("colspan=", 0) + 9;
                                pos1 = -1;
                                (pos1 == content.split('<td')[t].indexOf("colspan=", 0))? pos1 = 0 : pos1 = content.split('<td')[t].indexOf("colspan=", 0) + 9;
                                pos2 = content.split('<td')[t].indexOf(">", 0);
                                var tst = content.split('<td')[t].indexOf(" ", pos1);
                                if (tst < pos2) { pos2 = tst; }
                                if ((pos1 > 8) && (pos2 > pos1)) {
                                    n.colSpan = parseInt(content.split('<td')[t].substring(pos1, pos2).replace('"', '').replace("'", ""));
                                }
                                // td content
                                pos1 = content.split('<td')[t].indexOf(">", pos2) + 1;
                                pos2 = content.split('<td')[t].indexOf("</td", pos1);
                                //if ((pos2 > 0 ) && (t != nodeCount))
                                //{
                                    n.innerHTML = content.split('<td')[t].substring(pos1, pos2);
                                //}
                                //else 
                                //{
                                //    n.innerHTML = content.split('<td')[t].substring(pos1);
                                //}
                            }
                        }
                    }
                }
                pos = -1;
                break;
            }
            else {
                pos = content.indexOf("<", pos + 1);
            }
        }
    }
    else
        PopulateContent(content);
}




//function PopulateInlineContent(content)
//{
//    if(!selectedOffer)
//        return;
//    var pos = content.indexOf("<",0); 
//    // Clear existing content
//    if(selectedOffer.hasChildNodes())
//    {
//        for(i=selectedOffer.childNodes.length-1; i>=0; i--)
//        {
//            selectedOffer.removeChild(selectedOffer.childNodes.item(i));
//        }
//    }
//    // setting new content
//    if(selectedOffer.nodeName.toUpperCase()=="TR")
//    {
//        while(pos>-1)
//        {
//            if(content.substring(pos, pos+4)!="<!--")
//            {
//                if(content.split('<td').length>0)
//                {
//                    for(t=0;t<content.split('<td').length; t++)
//                    {
//                        if(content.split('<td')[t].replace(/ /g, '').length>0)
//                        {
//                            var n = selectedOffer.insertCell(-1);
//                            // class
//                            var pos1 = content.split('<td')[t].indexOf("class=\"", 0) + 7;
//                            var pos2 = content.split('<td')[t].indexOf("\"", pos1);
//                            n.className = content.split('<td')[t].substring(pos1, pos2);
//                            // colspan
//                            pos1 = content.split('<td')[t].indexOf("colspan=", 0) + 9;
//                            pos2 = content.split('<td')[t].indexOf(">", 0);
//                            var tst = content.split('<td')[t].indexOf(" ", pos1);
//                            if(tst<pos2){pos2=tst;}
//                            if((pos1>8)&&(pos2>pos1))
//                            {
//                                n.colSpan = parseInt(content.split('<td')[t].substring(pos1, pos2).replace('"','').replace("'",""));
//                            }
//                            // td content
//                            pos1 = content.split('<td')[t].indexOf(">", pos2) + 1;
//                            pos2 = content.split('<td')[t].indexOf("</td", pos1);
//                            n.innerHTML = content.split('<td')[t].substring(pos1, pos2);
//                        }
//                    }
//                }
//                pos=-1;
//                break;
//            }
//            else
//            {
//                pos = content.indexOf("<", pos+1);
//            }
//        }
//    }
//    else
//        PopulateContent(content);
//}

/***************************************************************************************/
var targetPage;
function CheckFlightOffer(bookingid,operator,offer, TargetPageName,processBooking){
    FlightsOnly=true;
    targetPage = TargetPageName;
    Check(bookingid, operator, GetElementById("DLC").value, "", offer, processBooking);
    return;
}

function offerCheckCallbackFunction(response, offerGUID) {
    if(response.result.resultCode!=-1){
        GetElementById('FlightBookingID').value = response.result.bookingID;

        GetElementById('OfferGUID').value = offerGUID;
        GetElementById('PageNum').value = "1";
        
        for(var i=0; i<GetElementById('Duration').options.length;i++)
            if(GetElementById('Duration').options[i].value==6)
                GetElementById('Duration').selectedIndex = i; 
        GetElementById('DurationDays').value = response.result.duration;
        GetElementById('FromDate').value = response.result.fromDate;
        GetElementById('ToDate').value = response.result.toDate;
        GetElementById('FlightDataXML').value = response.result.offerDataXML;
        
        CheckFields();
        GetElementById('Target').value = targetPage;
        
        if(gotoBooking){
            var Form = GetElementById('frmIBEMainForm');
            var secure = GetElementById("SecureSite");
            Form.action = secure.value.replace(/;/g, ':');  
           Form.submit();
        }
    }
}
/***************************************************************************************/
function ChangeSearchType(searchType){
if(IBESeachType==parseInt(searchType,10)){return false;}
if((jsonServer==null)||(jsonServer==undefined)){try{jsonServer = new srvIBE();}catch(e){}}
if(GetElementById('SearchHistory').value.indexOf("ibeSearchType:"+IBESeachType)>-1)
    GetElementById('SearchHistory').value = GetElementById('SearchHistory').value.replace("ibeSearchType:"+IBESeachType,"ibeSearchType:"+searchType);
IBESeachType= parseInt(searchType,10);
GetElementById('ibeSearchType').value = IBESeachType.toString();
/*********** Displaying "Updating..." on all dropdowns ******************/
GroupsList = new Array('0:Updating...');
RegionsList =  new Array('0:1:Updating...');
AllResortsList = new Array('1:Updating...');
ResortsList = new Array('1:Updating...');
OperatorsList = new Array(':Updating...');
UpdateGroups();UpdateRegions();UpdateResorts();UpdateOperators();
/************************************************************************/
jsonServer.ChangeSearchType(searchType,GetElementById('SessionGUID').value,UpdateSearchFields);
return true;
}
function UpdateSearchFields(response){
if(!response.error)
{
GroupsList = response.result.groupsList;
RegionsList = response.result.regionsList;
OperatorsList = response.result.operatorsList;
AllResortsList = response.result.allResortsList;
ResortsList = response.result.resortsList;
InitDates();UpdateDate();UpdateGroups();UpdateRegions();UpdateResorts();UpdateOperators();CheckFields();CheckDuration(GetElementById("Duration"));SetSearchPage();UpdateRegions();
if(window.OnPageLoad){window.OnPageLoad();}
}
}
/*************************************************************************************/

function addjQueryReference(){
    if(window.jQuery==null){
        var e = document.createElement("script");
        e.src = "http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js";
        e.type="text/javascript";
        if(document.getElementsByTagName("head").length>0)
            document.getElementsByTagName("head")[0].appendChild(e);
        else if(document.getElementsByTagName("body").length>0){
            var bodyTag = document.getElementsByTagName("body")[0];
            if(bodyTag.hasChildNodes())
                bodyTag.insertBefore(e,bodyTag.firstChild);
            else
                bodyTag.appendChild(e);
        }
    }
}