﻿/********************************************************************************************  
    
METHODS/VARIABLES TO STORE AND LOAD CONTROL VALUES FOR ASYNC DATA EXCHANGE 

/********************************************************************************************/
var controlValueList;
var marker_airport=new Array("a","b","c","d","e","f","g","h","i","g");
var index_airport=0;
var Tatol_airport=new Array();
var MCheck=0;
var City_Center_LaT;
var City_Center_LoN;
var Hotel_Select_LaT="";
var Hotel_Select_LoN="";
var ChecKAddAirport= true;
var Data_Airports;
var Air_Id_SelecT,Air_Name_SelecT;
var AiRSelect="";
var Data_AirportsTotal=new Array();
var Data_AirportsName=new Array();
var Air_Id_SelecTS= new Array();


var airportPopUpID;
var mpeLoader;
var mpeLoaderID;


var mapItem;
var popUpAirportDeparture = false;

function MapItem(itemId, itemDescription, itemLatitude, itemLongitude, itemSelected)
{ 
    this.id = itemId;
    this.description = itemDescription;
    this.latitude = itemLatitude;
    this.longitude = itemLongitude;
    this.selected = itemSelected;
}

function ControlValue(id, value, typeName, visible, enabled, mandatory, promptFieldId, cssValue, className)
{ 
    this.controlId = id;
    this.controlValue = value;
    this.controlTypeName = typeName;
    if (visible == undefined) 
        this.controlVisible = true
    else 
        this.controlVisible = visible; 
    this.controlEnabled = enabled;

    if (enabled == undefined) 
        this.controlEnabled = true
    else 
        this.controlEnabled = enabled; 

    this.controlMandatory = mandatory;
    this.controlPromptFieldId = promptFieldId;
    this.controlCssValue = cssValue; 
    this.controlClassName = className; 
}


function InitClientControlValues(values)
{
    var controlList = eval("(" + values + ")"); 
        
    controlValueList = new Array();
    for (var i = 0; i < controlList.controlValues.length; i++)
    {
        controlValueList.push(new ControlValue(controlList.controlValues[i].Id, 
                                               controlList.controlValues[i].Value, 
                                               controlList.controlValues[i].TypeName, 
                                               controlList.controlValues[i].Visible,
                                               controlList.controlValues[i].Enabled, 
                                               controlList.controlValues[i].Mandatory, 
                                               controlList.controlValues[i].PromptFieldId, 
                                               controlList.controlValues[i].CssValue,                                                    
                                               controlList.controlValues[i].ClassName));                                                   
        if (!controlList.controlValues[i].Visible)
        {
            var ctrl = $get(controlList.controlValues[i].Id);
            if (ctrl)
                ctrl.className = 'nungTable';
        }
        if (!controlList.controlValues[i].Enabled)
        {
            var ctrl = $get(controlList.controlValues[i].Id);
            if (ctrl)
                ctrl.disabled = true;
        }
                                               
    }
}

function FindControlPosition(id)
{
    var position = -1;
    for (var i = 0; controlValueList != null && i < controlValueList.length && position == -1; i++)
    {
        if (controlValueList[i].controlId == id)
            position = i;
    }
    return position;
}

function StoreControlValue(id, value)
{
    var position = FindControlPosition(id);
    if (position != -1)
    {
        controlValueList[position].controlValue = value;
    }
    else
    {
        if (controlValueList == null)
            InitControlValueList();
        controlValueList.push(new ControlValue(id, value));
    }
}

function GetControlValue(id)
{
    var position = FindControlPosition(id);
    if (position != -1)
       return controlValueList[position].controlValue;
    else return "";
}

function ControlValues2JSONString(ctrl)
{
    var s = "{";
    if (ctrl)
        s = s + "pbControl:" + ctrl.id + ",";
    s = s + "controlValues:[";
    for (var i = 0; i < controlValueList.length; i++)
    {
        if (i > 0) s = 
            s + ",";
        s = s + '{"Id":"' + controlValueList[i].controlId + '" '
        s = s + ',"Value":"' + controlValueList[i].controlValue + '" '
        s = s + ',"TypeName":"' + controlValueList[i].controlTypeName + '" '
        s = s + ',"Visible":"' + controlValueList[i].controlVisible + '" '
        s = s + ',"Enabled":"' + controlValueList[i].controlEnabled + '" '
        s = s + ',"Mandatory":"' + controlValueList[i].controlMandatory + '" '
        s = s + ',"PromptFieldId":"' + controlValueList[i].controlPromptFieldId + '" '
        s = s + ',"CssValue":"' + controlValueList[i].controlCssValue + '"'
        s = s + ',"ClassName":"' + controlValueList[i].controlClassName + '"}'

    }
    s = s + "]}";
    return s;
}


function GetStorageField()
{
    return FindControl(document, 'hfStorage');
}

function CombineStoredValues() // temp method to combine hiddenfield and the controlValues
{
    var s = GetStorageField().value;
    var a = s.split('|');
    
    for (var i = 0; i < controlValueList.length; i++)
    { 
        var position = -1;
        for (var j = 0; j < a.length && position == -1; j=j+2)
        {
            if (controlValueList[i].controlId == a[j])
                position = j;
        }
    
        if (position > -1)
        {
            a[position+1]= controlValueList[i].controlValue;
        }
        else {
            a.push(controlValueList[i].controlId);
            a.push(controlValueList[i].controlValue);
        }
    }

    s = "";
    for (var i = 0; i < a.length; i++)
    {
        if (s.length > 0)
            s = s + '|';
        s = s + a[i];
    }
    GetStorageField().value = s;
}
    
    


function StoreFieldValue(pobjID, value)
{
    StoreControlValue(pobjID, value, '0', ''); 

    var s = GetStorageField().value;
    var a = s.split('|');
    
    var position = -1;
    for (var i = 0; i < a.length; i=i+2)
    {
        if (pobjID == a[i])
            position = i;
    }
    
    if (position > -1)
    {
        a[position+1]= value;
    }
    else {
        a.push(pobjID);
        a.push(value);
    }

    s = "";
    for (var i = 0; i < a.length; i++)
    {
        if (s.length > 0)
            s = s + '|';
        s = s + a[i];
    }
    GetStorageField().value = s;
  //  alert(GetStorageField().value);
}

function FindPosition(a, key)
{
    var position = -1;
    for (var i = 0; i < a.length && position == -1; i=i+2)
    {
        if (key == a[i])
            position = i;
    }
    return position;
}

function GetFieldValue(pobjID)
{
    var result = GetControlValue(pobjID);
    var result2;
    var s = GetStorageField().value;
    var a = s.split('|');
        
    var position = FindPosition(a, $get(pobjID).id);
    if (position != -1)
       result2 = a[position+1];
    else result2 = "";
    return result2;
}

function GetHelperFieldValue(pobjID)
{
    var result = GetControlValue(pobjID);
    var result2;
    var s = GetStorageField().value;
    var a = s.split('|');
        
    var position = FindPosition(a, pobjID);
    if (position != -1)
       result2 = a[position+1];
    else result2 = "";
    return result2;
}



/*********************************************************************************************

FUNCTIONS TO HANDLE DATE CONTROLS DATA CHANGE

**********************************************************************************************/
function FormatDate(dt) {
    var result = "";
    if (dt)
    {
        if (dt.getDate() < 10)
            result += "0";
        result += dt.getDate().toString() + "-";
        if (dt.getMonth() < 9)
            result += "0";
        result += (dt.getMonth() + 1).toString() + "-";
        result += dt.getFullYear().toString();
    }
    return result;
}    

function ParseDate(s){
    if (s)
    {
        var parts = s.split("-");
        if (parts.length == 3)
            return new Date(parseInt(parts[2], 10),parseInt(parts[1], 10)-1,parseInt(parts[0], 10));
        else return null;
    }
    else return null;
}


function HandleDateChangeMinMax(txtDate, ceID, absMin, absMax, ctrlIDMin, ceIDMin, ctrlIDMax, ceIDMax)
{
    var dtCurrent = ParseDate(txtDate.value);
    if (dtCurrent)
    {
        var ceMin = $find(ceIDMin);
        var ceMax = $find(ceIDMax);
    
        var dtAbsMin = ParseDate(absMin);
        var dtAbsMax = ParseDate(absMax);
        var dtCtrlMin = null;
        if  (ctrlIDMin && ctrlIDMin.length > 0)
            dtCtrlMin = ParseDate($get(ctrlIDMin).value);
        var dtCtrlMax = null;
        if  (ctrlIDMax && ctrlIDMax.length > 0)
            dtCtrlMax = ParseDate($get(ctrlIDMax).value);

        if (dtAbsMin && dtCurrent < dtAbsMin)
            dtCurrent = dtAbsMin;
            
        if (dtAbsMax && dtCurrent > dtAbsMax)
            dtCurrent = dtAbsMax;

        if (dtCtrlMin && dtCurrent <= dtCtrlMin)
        {
            var ctrlMin = $get(ctrlIDMin);
            var tmpDate = new Date(dtCurrent.getFullYear(), dtCurrent.getMonth(), dtCurrent.getDate());
            tmpDate.setDate(tmpDate.getDate() - 1);
            ctrlMin.value = FormatDate(tmpDate);
            ceMin.set_selectedDate(tmpDate);
            StoreFieldValue(ctrlIDMin, ctrlMin.value);  
        }
        
        if (dtCtrlMax && dtCurrent >= dtCtrlMax)
        {
            var ctrlMax = $get(ctrlIDMax);
            var tmpDate = new Date(dtCurrent.getFullYear(), dtCurrent.getMonth(), dtCurrent.getDate());
            tmpDate.setDate(tmpDate.getDate() + 1);
            ctrlMax.value = FormatDate(tmpDate);
            ceMax.set_selectedDate(tmpDate);
            StoreFieldValue(ctrlIDMax, ctrlMax.value);  

        }
    }
    
    txtDate.value = FormatDate(dtCurrent);
    $find(ceID).set_selectedDate(dtCurrent);
    StoreFieldValue(txtDate.id, txtDate.value);  
        
    return true;
}

/**************************************************************************************/




function TestBtnDisableClick(btn)
{
    alert('test button clicked');
    return false;
}
 
function ToggleTestBtnDisableClick(chb, btnTestID)
{
    btn = $get(btnTestID);
    btn.disabled = chb.checked;
    
}

function ToggleCbxPanel(cbxID, panelID, jsIDs, cssString)
{
    var cbx = $get(cbxID);
    StoreFieldValue(cbx.id, cbx.value);
    var ids = eval("(" + jsIDs + ")"); 
    var pnl = $get(panelID);
    
    var showPanel = false;
    for (var i = 0; i < ids.keysVisible.length; i++)
      if (ids.keysVisible[i] == cbx.value)
        showPanel = true;
        
    if (showPanel)
        pnl.style.display= cssString;
    else 
        pnl.style.display= 'none';
}



function TestOKBtnClicked()
{
    alert('got you');
}

function DisableControl(ctlID)
{
    var ctl = $get(ctlID);
    ctl.disabled = true;
}    
function Visible(ctlID)
{
    var ctl = $get(ctlID);
   ctl.style.display='';
}
function InVisible(ctlID)
{
    var ctl = $get(ctlID);
   ctl.style.display='none';
}
function EnableControl(ctlID)
{
    var ctl = $get(ctlID);
    ctl.disabled = false;
}    


function ValuePairSelected(source, eventArgs)
{
        StoreFieldValue(source.get_id(), eventArgs.get_value());  
}

function LocationSelected(source, eventArgs)
{
    StoreFieldValue(source.get_id(), eventArgs.get_value());
    var data = source.get_id() + '|' + eventArgs.get_value();
    AsyncServerMessage('LocationSelected', data, ShowResponseDetails, false);
    return false;
}

function HotelSelected(source, eventArgs)
{
    StoreFieldValue(source.get_id(), eventArgs.get_value());  
}

function HandleFilterContext(cbx, acClientID, txtClientID)
{
    var ac = $find(acClientID);
    ac.set_contextKey(cbx.value);
    
    var txt = $get(txtClientID);
    txt.innerText = "";

    StoreFieldValue(cbx.id, cbx.value);  
    StoreFieldValue(txt.id, txt.innerText);  
}


var AirportPopUpTargetCtlID = '';
var AirportPopUpDistance = '50';


var marker;
var getZoom = 12;
var AirportCheck;
////******************Add-Del Marker Onclick******************//
//GEvent.addListener(map, "click", function(marker, point) {
//if (marker){map.removeOverlay(marker);}
//else {map.addOverlay(new GMarker(point));}
//});      
////******************Add-Del Marker Onclick******************
////////////// Marker With TabInfo ////////////////////
function AddAirportMarkerInfo(FillAirportLat,FillAirportLng)
{   
    var AirportSelectLat=FillAirportLat;
    var AirportSelectLng=FillAirportLng; 
    var Place = "<span style='width:50px;height:50px'>Latitude : " + AirportSelectLat + "<br/>Longitude : " + AirportSelectLng +"</span>";
    var infoTabs = [new GInfoWindowTab("Airport Info",Place)]; 
    var marker = new GMarker(new GLatLng(AirportSelectLat,AirportSelectLng));
        GEvent.addListener(marker, "click",
        function() {    
        marker.openInfoWindowTabsHtml(infoTabs);
        });      
        map.addOverlay(marker);     
        marker.openInfoWindowTabsHtml(infoTabs);     
}
////////////// Marker With TabInfo ////////////////////

function HandleAirportSelected(ctlID, ctlIDText)
{

    var txtLocation = $get(ctlIDText);
    var cbxAirport = $get(ctlID);
    var airportId = cbxAirport.value;
    StoreFieldValue(ctlID, cbxAirport.value);   
    TableLoadServices.JSGetAirportCoordinates(airportId, txtLocation.value, AirportPopUpDistance, SetSelectedMarker);    
}

function HandleAirportMapSelected(cbxAirportID, cbxLocationID)
{

    var cbxAirport = $get(cbxAirportID);
    var cbxLocation = $get(cbxLocationID);
    var location = cbxLocation.options[cbxLocation.selectedIndex].text;
    StoreFieldValue(cbxAirportID, cbxAirport.value);   
    TableLoadServices.JSGetAirportCoordinates(cbxAirport.value, location, AirportPopUpDistance, SetSelectedMarker);    
}

function HandleAirportMapLocationSelected(cbxAirportID, cbxLocationID)
{
    var cbxAirport = $get(cbxAirportID);
    var cbxLocation = $get(cbxLocationID);
    StoreFieldValue(cbxLocationID, cbxLocation.value);   
    TableLoadServices.JSGetAirportCoordinates(cbxAirport.value, cbxLocation.value, AirportPopUpDistance, SetSelectedMarker); 
    
    AsyncServerMessage('getAirports', cbxLocation.selectedIndex.toString(), PopUpAirportFillTable2, false);
}


function SetSelectedMarker(result)
{

    var airports = eval("(" + result + ")"); 
    map.clearOverlays();
    for (j = 0; j < airports.id.length; j++) 
    {
        
        var FillAirportLat = airports.latitude[j];
        var FillAirportLng = airports.longitude[j];  


        var gIcon = new GIcon(G_DEFAULT_ICON);     
            gIcon.iconSize = new GSize(20,34);  
            gIcon.image = "images/red.png";
        
         if (airports.selected[j] == "Y")
            {  
                gIcon.iconSize = new GSize(32,41);              
                gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(index_airport+1)+"&MarkerName=marker_airport_select.png";
                 // map.setCenter(new GLatLng(FillAirportLat, FillAirportLng),10);
        //keru_kop select airport
            } 
        var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),{title:airports.description[j],icon:gIcon});       
        map.addOverlay(marker);    
          

     }      
}

function InitAirportPopUp(mepID, acLocationID, msgId, departure)
{
    if (GetHelperFieldValue($find(acLocationID).get_id()).length > 0)
    {
        popUpAirportDeparture = departure;
        $find(mepID).show();
        airportPopUpID = mepID;
        CombineStoredValues();
        return AsyncServerMessage(msgId, ControlValues2JSONString(), PopUpAirportFillTable3, false);
    }
    else return false;
}


//function InitAirportPopUp(acLocationID, txtLocationID, cbxLocationID, cbxAirportID, ctrlAirportIdID, cbxDistanceID, targetCtlID)
//{

////document.getElementById("ctl00_cbxAirport").style.display='none';

//    AirportPopUpTargetCtlID = targetCtlID;
//    var acLocation = $find(acLocationID);
//    var txtLocation = $get(txtLocationID); 
//    var cbxLocation = $get(cbxLocationID); 
//    var cbxDistance = $get(cbxDistanceID);
//   
//    
//    var locationKey = GetHelperFieldValue(acLocation.get_id());
//   
//   
//    return AsyncServerMessage("PopUpAirportFromSelected", GetCombinedStoredValues(), PopUpAirportFillTable3, false);
// 
//    
////    AirportPopUpDistance = cbxDistance.value;
////    var ctrlAirportId = $get(ctrlAirportIdID);
////    var selectedValue = "";
////    if (ctrlAirportId.tagName == 'INPUT')
////   
////        selectedValue = ctrlAirportId.value;
////    else selectedValue = ctrlAirportId.innerText;
////    if (txtLocation.value.length > 0)
////    {        
//// 
////    //keru_kop hide
////     document.getElementById("TdataLocal").style.display="none";
////        cbxLocation.options.length=0;
////        var option = new Option(txtLocation.value, "0");
////        cbxLocation.options[cbxLocation.options.length] = option;
////        cbxLocation.disabled = true;
////        Data_AirportsName[0]=txtLocation.value;
////      
////         index_airport=0;
////        TableLoadServices.JSGetAirportsForLocation(locationKey, cbxDistance.value, cbxAirportID, selectedValue, 
////                                                   PopUpAirportFillTable);
////    }
////    
////    return false;
//}



function InitAirportPopUpOrig(acLocationID, txtLocationID, cbxLocationID, cbxAirportID, ctrlAirportIdID, cbxDistanceID, targetCtlID)
{

//document.getElementById("ctl00_cbxAirport").style.display='none';

    AirportPopUpTargetCtlID = targetCtlID;
    var acLocation = $find(acLocationID);
    var txtLocation = $get(txtLocationID); 
    var cbxLocation = $get(cbxLocationID); 
    var cbxDistance = $get(cbxDistanceID);
   
    
    var locationKey = GetHelperFieldValue(acLocation.get_id());
    
    
    AirportPopUpDistance = cbxDistance.value;
    var ctrlAirportId = $get(ctrlAirportIdID);
    var selectedValue = "";
    if (ctrlAirportId.tagName == 'INPUT')
   
        selectedValue = ctrlAirportId.value;
    else selectedValue = ctrlAirportId.innerText;
    if (txtLocation.value.length > 0)
    {        
 
    //keru_kop hide
     document.getElementById("TdataLocal").style.display="none";
        cbxLocation.options.length=0;
        var option = new Option(txtLocation.value, "0");
        cbxLocation.options[cbxLocation.options.length] = option;
        cbxLocation.disabled = true;
      Data_AirportsName[0]=txtLocation.value;
      
         index_airport=0;
        TableLoadServices.JSGetAirportsForLocation(locationKey, cbxDistance.value, cbxAirportID, selectedValue, 
                                                   PopUpAirportFillTable);
    }
    
    return false;
}

function InitAirportPopUp2(mepID, acLocationID, txtLocationID, cbxLocationID, cbxAirportID, 
                           ctrlAirportIdID, cbxDistanceID, targetCtlID, departure)
{
    popUpAirportDeparture = departure;
    var mep = $find(mepID);
    mep.show();
    airportPopUpID = mepID;
    
    if (departure)
        msgId = "PopUpAirportFromSelected";
    else msgId = "PopUpAirportToSelected";

    CombineStoredValues();
    return AsyncServerMessage(msgId, ControlValues2JSONString(), PopUpAirportFillTable3, false);
}

function InitAirportPopUpAircraft(mepID, tableID, lbtAirport, msgId)
{
    $find(mepID).show();
    airportPopUpID = mepID;
    var table = $get(tableID);
    var selectedIndex = GetBodyRowIndex(table, lbtAirport);
    return AsyncServerMessage(msgId, selectedIndex.toString(), PopUpAirportFillTable3, false);
}

    
function AirportPopUpLocationChanged(ctrl, msg)
{
    StoreFieldValue(ctrl.id, ctrl.value);
    CombineStoredValues();

    return AsyncServerMessage(msg, ControlValues2JSONString(), PopUpAirportFillTable3, false);
}

function HandleAirportMapSelected(tableID, ctrl, numberImgID)
{
    var table = $get(tableID);
    var selectedIndex = GetBodyRowIndex(table, ctrl) + 1;
    var currentIndex = -1;
    
    for (var i=0; i < table.rows.length; i++)
        if (mapItems[i].selected)
            currentIndex = i;

    mapItems[selectedIndex].selected = true;
    var img = FindControl(table.rows[selectedIndex], numberImgID);
    img.src = "ImageMarkerOnMap.aspx?MarkerNumber=" + (selectedIndex+1).toString() + "&MarkerName=icon_number_airport_select.png"; 
    
    if (currentIndex != -1)
    {
        mapItems[currentIndex].selected = false;
        var img = FindControl(table.rows[currentIndex], numberImgID);
        img.src = "ImageMarkerOnMap.aspx?MarkerNumber=" + (currentIndex+1).toString() + "&MarkerName=icon_number_airport.png"; 
    }
            
    PlotAirportsOnMap(mapItems, false);  
}

function OkBtnAirportPopUp()
{
    var currentIndex = -1;
    for (var i=0; i < mapItems.length; i++)
        if (mapItems[i].selected)
            currentIndex = i;
    if (currentIndex != -1)
    {
       StoreFieldValue('SelectedAirportId', mapItems[currentIndex].id);
    }
    if (popUpAirportDeparture)
        StoreFieldValue('SelectedAirportType', 'D');
    else
        StoreFieldValue('SelectedAirportType', 'A');

    CombineStoredValues();
    return AsyncServerMessage("msgAirportSelected", ControlValues2JSONString(), ShowResponseDetails, false);
}



//function HandleAirportMapSelected(cbxAirportID, cbxLocationID)
//{

//    var cbxAirport = $get(cbxAirportID);
//    var cbxLocation = $get(cbxLocationID);
//    var location = cbxLocation.options[cbxLocation.selectedIndex].text;
//    StoreFieldValue(cbxAirportID, cbxAirport.value);   
//    TableLoadServices.JSGetAirportCoordinates(cbxAirport.value, location, AirportPopUpDistance, SetSelectedMarker);    
//}

    
//    var ctrlAirportId = $get(ctrlAirportIdID);
//    var selectedValue = "";
//    if (ctrlAirportId.tagName == 'INPUT')
//        selectedValue = ctrlAirportId.value;
//    else selectedValue = ctrlAirportId.innerText;

//    if (txtLocation.value.length > 0)
//    {        
//        cbxLocation.options.length=0;
//        var option = new Option(txtLocation.value, "0");
//        cbxLocation.options[cbxLocation.options.length] = option;
//        cbxLocation.disabled = true;
//     //   alert("keru---calll22")
//        TableLoadServices.JSGetAirportsForLocation(locationKey, cbxDistance.value, cbxAirportID, selectedValue, 
//                                                   PopUpAirportFillTable);
//        index_airport=1; //set index_airport ,use in get marker airport
//      Data_AirportsName[1]=txtLocation.value;
//        mep.show();
//    }
//    return false;





function ModalReservationDetailsClick(msg, mep, btn)
{
    AsyncServerMessage(msg, GetRowIndex(btn).toString(), ShowResponseDetails, false);
    mep.show();
}


function ModalAircraftClick(mep, btn)
{
    AsyncServerMessage('getImages', GetRowIndex(btn).toString(), PopUpImagesFillTable, false);
    mep.show();
}

var indexImage = -1;
var mepImage;

function LaunchModalImageSelect(mep, btn)
{
//    AsyncServerMessage('msgImageSelected', GetRowIndex(btn).toString(), DefaultServerEventResponse, false);
    mepImage = mep;
    indexImage = GetRowIndex(btn);
    mep.show();
}

function HandleUploadImageCompleted(okPressed)
{
    mepImage.hide();
    if (okPressed)
        return AsyncServerMessage("msgImageUploaded", indexImage.toString(), ShowResponseDetails, false);
    else 
        return AsyncServerMessage("msgImageUploaded", "-1", ShowResponseDetails, false);
}


function PopUpImagesFillTable()
{
    if (request.readyState == 4 && request.status == 200)
    {
        var images = eval("(" + request.responseText + ")");
        ShowControlValues(images.controlValues);
    }
}

function ModalAirportClick(mep, btn)
{
//alert("keruQQQ ")

//AsyncServerMessage('getAirportLocations', GetRowIndex(btn).toString(), PopUpAirportFillTable2, false);
AsyncServerMessage('getAirportLocations', GetRowIndex(btn).toString(), PopUpAirportFillTable3, false);
mep.show();    
    return false;
}

function PopUpAirportFillTable3()
{

    if (request.readyState == 4 && request.status == 200)
    {
        var data = eval("(" + request.responseText + ")");
        ShowControlValues(data.controlValues);
        
        var tbl = null;
        for (var i=0; i < data.controlValues.length; i++)
        {
            if (data.controlValues[i].id == "tblRepeaterAirports")
                tbl = data.controlValues[i].tableValues;
        }

        if (tbl && !tbl.isDummy)
        {
            var posDescription = -1;        
            var posLatitude = -1;        
            var posLongitude = -1;        
            var posSelected = -1;        
            var posId = -1;        
            for (var i=0; i < tbl.columns.length; i++)
            {
                if (tbl.columns[i] == "rbtSelected") posSelected = i;
                else if (tbl.columns[i] == "lblLatitude") posLatitude = i;
                else if (tbl.columns[i] == "lblLongitude") posLongitude = i;
                else if (tbl.columns[i] == "lblAirportName") posDescription = i;
                else if (tbl.columns[i] == "airportId") posId = i;
            }

            mapItems = new Array();
            for (var i=0; i < tbl.rows.length; i++)
            {
                mapItems.push(new MapItem(tbl.rows[i][posId], tbl.rows[i][posDescription], tbl.rows[i][posLatitude], 
                                          tbl.rows[i][posLongitude], tbl.rows[i][posSelected]));
            }
            PlotAirportsOnMap(mapItems, true);
        }
        else
        {
            $find(airportPopUpID).hide();
            alert('No airports found for this location !!!');    
        }
        
    }
}

function PlotAirportsOnMap(mapItems, init)
{
    var Gcenter_Lat=0;
    var Gcenter_Lon=0;
    if (mapItems.length > 0)
    {
        if (init)
            initialize();//***
        
        var maxLat = mapItems[0].latitude;
        var maxLng = mapItems[0].longitude;
        var minLat = mapItems[0].latitude;
        var minLng = mapItems[0].longitude;
        
        for (j = 0; j < mapItems.length; j++) 
        {
            var gIcon = new GIcon(G_DEFAULT_ICON);     
            gIcon.iconSize = new GSize(32,41);  
            gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(j+1)+"&MarkerName=marker_airport.png"; 
         
            if (mapItems[j].selected)
            {  
                gIcon.iconSize = new GSize(32,41);              
                gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(j+1)+"&MarkerName=marker_airport_select.png"; 
                Gcenter_Lat=mapItems[j].latitude;
                Gcenter_Lon=mapItems[j].longitude;
            }
            var FillAirportLat = mapItems[j].latitude;
            var FillAirportLng = mapItems[j].longitude;      
            var FillAirportTitle = mapItems[j].description;  
            var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),
                                        {title:mapItems[j].description, icon:gIcon});       
            map.addOverlay(marker); 
          
            maxLat = Math.max(maxLat, mapItems[j].latitude);
            maxLng = Math.max(maxLng, mapItems[j].longitude);       
            minLat = Math.min(minLat, mapItems[j].latitude);
            minLng = Math.min(minLng, mapItems[j].longitude); 
        }
        var swLatLng = new GLatLng(minLat,minLng);   
        var neLatLng = new GLatLng(maxLat,maxLng);
        var center = new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
        var getBound=new GLatLngBounds(swLatLng, neLatLng); 
        map.setCenter(center, map.getBoundsZoomLevel(getBound)-2);
     }  
     else
     {        
        if(Gcenter_Lat !=0 && Gcenter_Lon !=0)
        {
            map.setCenter(new GLatLng(Gcenter_Lat, Gcenter_Lon),map.getBoundsZoomLevel(getBound)-2) 
        }
        else
        {
            map.setCenter(center, map.getBoundsZoomLevel(getBound)-2);
        }
    }   
    try
    {
        if (map.getBoundsZoomLevel(getBound)> getZoom)
        {
            if(Gcenter_Lat !=0 && Gcenter_Lon !=0)
            {
                map.setCenter(new GLatLng(Gcenter_Lat, Gcenter_Lon),getZoom) 
            }
            else
            {
                map.setCenter(center, getZoom);
            }
        }
    }
    catch(err)     
    {
        var txtErr = err;
        alert(txtErr);
    }
}


function PopUpAirportFillTable2()
{
//keru99 click View/Change 
//_ClearTb("TbAir");
//document.getElementById("TdataAirport").style.display="none";


var Gcenter_Lat=0;
var Gcenter_Lon=0;

//if(Tatol_airport.length > 0)
//{
//document.getElementById("hid_AiR_data").value=Tatol_airport;
// initialize();//call map
// var Mpoints=[];
// var bounds = new GLatLngBounds();
// var gIcon = new GIcon(G_DEFAULT_ICON);
// var routes = new Array();  
// var AirRoutes='00';
// //var p1=0;
// //var p2=0;
//    
//  gIcon.iconSize = new GSize(20,34);  
//    for(i=0;i<Tatol_airport.length;i++)
//    {
//         gIcon.iconSize = new GSize(32,41);              
//         gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +marker_airport[i]+"&MarkerName=marker_airport_select.png"; 
//         var datas=Tatol_airport[i].split("\x09");
//         var marker = new GMarker(new GLatLng(datas[1], datas[2]),
//                                        {title:datas[0], icon:gIcon});       
//          
//          //----------//
//          AirRoutes=AirRoutes+"\x09"+datas[0];
//          
//          
//          
//        Mpoints.push(new GLatLng(datas[1],datas[2]));
//         map.addOverlay(marker); 
//         bounds.extend(marker.getPoint());
//                 
//     }
//    _SetAirRoutes(AirRoutes);
//     //----------begin set polyline-------------
//    
//    var fPoints = new Array();
//		with (Math) {
//			var lat1 = Mpoints[0].y * (PI/180);
//			var lon1 = Mpoints[0].x * (PI/180);
//			var lat2 = Mpoints[1].y * (PI/180);
//			var lon2 = Mpoints[1].x * (PI/180);

//			var d = 2*asin(sqrt( pow((sin((lat1-lat2)/2)),2) + cos(lat1)*cos(lat2)*pow((sin((lon1-lon2)/2)),2)));
//			var bearing = atan2(sin(lon1-lon2)*cos(lat2), cos(lat1)*sin(lat2)-sin(lat1)*cos(lat2)*cos(lon1-lon2))  / -(PI/180);
//			bearing = bearing < 0 ? 360 + bearing : bearing;




//			for (var n = 0 ; n < 51 ; n++ ) {
//				var f = (1/50) * n;
//				f = f.toFixed(6);
//				var A = sin((1-f)*d)/sin(d)
//				var B = sin(f*d)/sin(d)
//				var x = A*cos(lat1)*cos(lon1) +  B*cos(lat2)*cos(lon2)
//				var y = A*cos(lat1)*sin(lon1) +  B*cos(lat2)*sin(lon2)
//				var z = A*sin(lat1)           +  B*sin(lat2)

//				var latN = atan2(z,sqrt(pow(x,2)+pow(y,2)))
//				var lonN = atan2(y,x)
//				var p = new GLatLng(latN/(PI/180), lonN/(PI/180));
//				fPoints.push(p);
////				bounds.extend(p);
//			}

//		}

//		routes.push(fPoints);
//		var pLine = new GPolyline(fPoints,'#FF9601',3,1);
//		map.addOverlay(pLine);
//		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-2); 


//		var dist = d * 6378.137; // KM
//		//alert("Distance:"+dist.toFixed(2)+" km.")
//	//	oRoute.innerHTML += 'Distance: ' + dist.toFixed(2) + ' km<br>';
//	//	oRoute.innerHTML += 'Bearing: ' + bearing.toFixed(2) + '<br>\n';
//    
//    //------end polyline---------//
//      
//     // map.setZoom(map.getBoundsZoomLevel(bounds)-1);
//    // map.setCenter(bounds.getCenter());

// 
//}
//else
//{

    if (request.readyState == 4 && request.status == 200)
    {
        var airports = eval("(" + request.responseText + ")");
        ShowControlValues(airports.controlValues);
     
        if (airports.id.length > 0)
        {
            initialize();//***
            for (j = 0; j < airports.id.length; j++) 
            {
                var gIcon = new GIcon(G_DEFAULT_ICON);     
                gIcon.iconSize = new GSize(32,41);  
                gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(j+1)+"&MarkerName=marker_airport.png"; 
         
                if (airports.id[j] == airports.selectedValue)
                {  
                    gIcon.iconSize = new GSize(32,41);              
                    gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(j+1)+"&MarkerName=marker_airport_select.png"; 
                    Gcenter_Lat=airports.latitude[j];
                    Gcenter_Lon=airports.longitude[j];
                }
                var FillAirportLat = airports.latitude[j];
                var FillAirportLng = airports.longitude[j];      
                var FillAirportTitle = airports.description[j];  
                var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),
                                        {title:airports.description[j], icon:gIcon});       
                map.addOverlay(marker); 
                var x = airports.latitude[0];
                var y = airports.longitude[0];
          
                var maxLat = Math.max(x,airports.latitude[j]);
                var maxLng = Math.max(y,airports.longitude[j]);       
                var minLat = Math.min(x,airports.latitude[j]);
                var minLng = Math.min(y,airports.longitude[j]); 
            }
            var swLatLng = new GLatLng(minLat,minLng);   
            var neLatLng = new GLatLng(maxLat,maxLng);
            var center = new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
            var getBound=new GLatLngBounds(swLatLng, neLatLng); 
         }  
         else
            {        
                if(Gcenter_Lat !=0 && Gcenter_Lon !=0)
                {
                    map.setCenter(new GLatLng(Gcenter_Lat, Gcenter_Lon),map.getBoundsZoomLevel(getBound)-2) 
                }
                else
                {
                    map.setCenter(center, map.getBoundsZoomLevel(getBound)-2);
                }
              
            }   
        try
        {
            if (map.getBoundsZoomLevel(getBound)> getZoom)
            {
                if(Gcenter_Lat !=0 && Gcenter_Lon !=0)
                {
                    map.setCenter(new GLatLng(Gcenter_Lat, Gcenter_Lon),getZoom) 
                }
                else
                {
                    map.setCenter(center, getZoom);
                }
               
            }
        }
        catch(err)     
        {
            var txtErr = err;
            alert(txtErr);
        }
    }
 
//    }//keru
    
    return ;
}


function PopUpAirportFillTable(result){
//_ClearTb("TbAir");
//document.getElementById("TdataAirport").style.display=" ";
    var Pcenter_Lat=0;
    var Pcenter_Lon=0;
    
    var airports = eval("(" + result + ")");
    Data_Airports=airports;
//    cbx = $get(airports.description[0]);
//    cbx.options.length=0;
 Data_AirportsTotal[index_airport]=airports;
    if (airports.id.length > 0)
    {
        for (i = 1; i < airports.id.length; i++) 
        {
       
//            var option = new Option(airports.description[i], airports.id[i]);
//            cbx.options[cbx.options.length] = option;
//            
            if (i>1)
            {
          //  if(ChecKAddAirport){
            
//            _AddAIrPort(i-1,airports.description[i],airports.id[i],airports.latitude[i],airports.longitude[i],"TbAir")
            
           // }
            }
            
        }
        //ChecKAddAirport= false;
//        cbx.value = airports.selectedValue;
        
        
        initialize();//***
        var C=0;
        for (j = 2; j < airports.id.length; j++) 
        {

            var gIcon = new GIcon(G_DEFAULT_ICON);     
            gIcon.iconSize = new GSize(32,41);  
            gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=marker_airport.png"; 
         //if(j<10){ C=C+1;}
            if (airports.id[j] == airports.selectedValue)
            {  
                gIcon.iconSize = new GSize(32,41);              
                gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=marker_airport_select.png";
                
//                document.getElementById("RaDAir_"+airports.id[j]).checked = true;//select radio 
//                document.getElementById("MIconAir_"+airports.id[j]).src="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=icon_number_airport_select.png";//select Icon
               
                Air_Id_SelecTS[index_airport]=airports.id[j];
                Air_Id_SelecT=airports.id[j];
                Air_Name_SelecT=airports.description[j];
              
               Pcenter_Lat=airports.latitude[j] 
               Pcenter_Lon=airports.longitude[j]
            
               Tatol_airport[index_airport]=airports.description[j]+"\x09"+airports.latitude[j]+"\x09"+airports.longitude[j]
            }
            C=C+1;
        
            var FillAirportLat = airports.latitude[j];
            var FillAirportLng = airports.longitude[j];      
            var FillAirportTitle = airports.description[j];  
            var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),
                                        {title:airports.description[j], icon:gIcon});  
                               
            map.addOverlay(marker); 
//******************Add Event MouseOver******************//        
//        GEvent.addListener(marker, "mouseover", function(marker){
//        if (marker){
////      var Place = "<span style='width:50px;height:50px'>Latitude : "+ marker.lat()+"<br/>Longitude : "+ marker.lng() +"</span>";                            
//        map.openInfoWindowHtml(marker);
//        }});
//******************Add Event MouseOver******************//        
//***************Zoom-To-Fit All Markers***************//
       
        var x = airports.latitude[2];
        var y = airports.longitude[2];
          
        var maxLat = Math.max(x,airports.latitude[j]);
        var maxLng = Math.max(y,airports.longitude[j]);       
        var minLat = Math.min(x,airports.latitude[j]);
        var minLng = Math.min(y,airports.longitude[j]); 
        }
        var swLatLng = new GLatLng(minLat,minLng);   
        var neLatLng = new GLatLng(maxLat,maxLng);
           
        var center = new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
      
        var getBound=new GLatLngBounds(swLatLng, neLatLng); 
     
    try
        {
            if (map.getBoundsZoomLevel(getBound)> getZoom)
                {
              
                   //--------set center map--------
                    if (Pcenter_Lat!=0 && Pcenter_Lon!=0)
                    {
                     map.setCenter(new GLatLng(Pcenter_Lat, Pcenter_Lon),getZoom) 
                     }else
                    {
                     map.setCenter(center, getZoom);
                     }
              
                
                }
            else
                {   
                 
                //--------set center map--------
                     if (Pcenter_Lat!=0 && Pcenter_Lon!=0)
                     {
                     map.setCenter(new GLatLng(Pcenter_Lat, Pcenter_Lon),map.getBoundsZoomLevel(getBound)-2) 
                     }else
                   {
                 //  alert(map.getBoundsZoomLevel(getBound)-1)
                       map.setCenter(center, map.getBoundsZoomLevel(getBound)-2);
                     }
                  
              
                }  
                          
        }
        catch(err)
        {
        var txtErr = err;
        alert(txtErr);
        }
//***************Zoom-To-Fit All Markers***************//            
    }
    //initialize(); 
    //this you need to replace with the values from the airports   
    return ;
    
}
                

function OkBtn()
{
    return false;
}

function onOk()
{
}

function HandleTableLoad(table)
{
    alert("table load");
}


function ImageClick(srcCtrl, targetID, pagerID)
{
    
    $get(targetID).src = srcCtrl.src;
//    target.
//    var table  = $get(tableID);
//    var cols =  table.tBodies[0].rows[0].getElementsByTagName('td').length;
//        
//    var r = GetRowIndex(source);
//    var c = GetColumnIndex(source);

//    var item = (cols * r) + c;

//    var s = PageMethods.GetImageData(pagerID, item.toString(), OnImageLoadOk, OnImageLoadError);
    return false;
}

function ButtonImageViewerClick(tableID, action, pagerID)
{
    AsyncServerMessage("getImageDetails", action, ShowResponseDetails, false);
    return false;
//    var s = PageMethods.GetImageData(pagerID, action, OnImageLoadOk, OnImageLoadError);
//    return false;
}


//function OnImageLoadOk(result)
//{
//    if (request.readyState == 4 && request.status == 200)
//    {
//        var result = eval("(" + request.responseText + ")");
//        Show


//        $get(data.imageControlId).src = data.imageURL;
//        $get(data.textControlId).innerHTML  = data.imageText;
//        var table = $get(data.tableName);
//        if (table != null)
//        {
//            var number = parseInt(data.currentImage, 10); 
//            for (var i = 0; i < table.cells.length; i++)
//            {
//                var ctrl = table.cells.item(i).childNodes[0];
//                if (ctrl != null)
//                {
//                    if (i== number)
//                        ctrl.className = 'imgSelectedImageList';
//                    else ctrl.className = 'imgImageList';
//                }
//            }
//         }
//     }
//}

function OnImageLoadError(result)
{
    alert ('Image load error' + result);
}

function ChangeCalculationTotal(ctrl, sumType, itemIndex)
{
    var data = sumType + '|' + ctrl.value + '|' + itemIndex.toString();
    AsyncServerMessage('CalculationChange', data, ShowResponseDetails, false);
    return false;
}

function StoreCbxValue(cbxID)
{
    StoreFieldValue(cbxID, $get(cbxID).value);
}

function FillCascadedControls(result){
    var options = eval("(" + result + ")");
    
    for (i = 0; i < options.dataTable.length; i++)
    {
        cbx = $get(options.dataTable[i].controlId);
        cbx.options.length=0;

        if (options.dataTable[i].rows.row.length > 0)
        {
            for (j = 0; j < options.dataTable[i].rows.row.length; j++) 
            {
                var option = new Option(options.dataTable[i].rows.row[j].val, options.dataTable[i].rows.row[j].id);
                cbx.options[cbx.options.length] = option;
            }
        }
        StoreFieldValue(options.dataTable[i].controlId, cbx.value);
        cbx.disabled = false;    
    }
    return ;
}

function CascadedChangeHandler(triggerId, functionId, jsControls)
{
    var cbx = $get(triggerId);

    if (cbx.value != GetFieldValue(triggerId))
    {
        StoreFieldValue(triggerId, cbx.value);

        var controlInfo = eval("(" + jsControls + ")");

        var cascKeys = new Array();
        var cascControlIds = new Array();
    
        for (i = 0; i < controlInfo.cascControls.length; i++)
        {
            $get(controlInfo.cascControls[i].controlID).disabled = true;
            cascKeys.push(controlInfo.cascControls[i].id);
            cascControlIds.push(controlInfo.cascControls[i].controlID);
        }

        var valKeys = new Array();
        var values = new Array();
    
        for (i = 0; i < controlInfo.valControls.length; i++)
        {
            valKeys.push(controlInfo.valControls[i].id);
            $get(controlInfo.valControls[i].controlID).value;
            values.push($get(controlInfo.valControls[i].controlID).value);
        }

        TableLoadServices.HandleCascadedControls(functionId , valKeys, values, cascKeys, 
                                                    cascControlIds, FillCascadedControls);
    }
}


// Add segments for charters alone


function AddSegmentEventResponse()
{
//alert("keru ==== AddSegmentEventResponse")
    if (request.readyState == 4 && request.status == 200)
    {
        OnTableLoadOk(request.responseText);
        return true;
    }
}

function AddSegmentButtonClickHandler(triggerId, tableID, jsControls)
{
//alert("keru ==== AddSegmentButtonClickHandler")
    var controlInfo = eval("(" + jsControls + ")");
    response = '{values:[';
    
    for (i = 0; i < controlInfo.ctrls.length; i++)
    {
        response = response + '{' + "'" + controlInfo.ctrls[i] + "'" + "," + "'" + GetFieldValue(controlInfo.ctrls[i]) + "'" + '}';
        if (i < controlInfo.ctrls.length - 1)
            response = response + ',';

    }
    response = response + ']}';

    var table = $get(tableID);
    if (table != null)
    {
        AsyncServerMessage('AddSegment', response, ShowResponseDetails, false);
        return false;
    }
    else 
    {
        AsyncServerMessage('AddSegment', response, ShowResponseDetails, true);
        return true;
    }

//    if (table != null)
//    {
//        AsyncServerMessage('AddSegment', response, AddSegmentEventResponse, false);
//        return false;
//    }
//    else 
//    {
//        AsyncServerMessage('AddSegment', response, DefaultServerEventResponse, true);
//        return true;
//    }
//ShowResponseDetails    
}

function HandleLocationAirportChange(ctrlTriggerID, ctrlTargetID, ctrlIdID)
{

//    var txtLocation = $get(ctrlTriggerID);
//    StoreFieldValue(ctrlTriggerID, txtLocation.value);

//    var lbtn = $get(ctrlTargetID);    
//    lbtn.innerText = "Select airport";   

//    var lblId = $get(ctrlIdID);    
//    lblId.innerText = "";   
//    
//    StoreFieldValue(ctrlTargetID, lbtn.innerText);
//    StoreFieldValue(ctrlIdID, lblId.innerText);

}


function LoadAirportRequest(ctlTriggerID, ctrlTargetID)
{
    lbtn.innerText = "Select airport";   
}



/************************************************************/
function HotelAvailabilityTimer(hfSessionID, hfStatusID, lblMessageID, btnRefreshID) 
{ 
//    alert('timer is started');
    var t2 = window.setInterval("CheckHotelAsyncAvailability('" + hfSessionID + "', '" + hfStatusID + "', '" +
                                 lblMessageID + "', '" + btnRefreshID + "')", 5000);
}

function CheckHotelAsyncAvailability(hfSessionID, hfStatusID, lblMessageID, btnRefreshID)
{
 //  alert('timer');
    var sessionId = $get(hfSessionID);
    var statusId =  $get(hfStatusID);

    if (sessionId != null && statusId != null)
        if (sessionId.value != "0" && statusId.value == "0") // sessionId can not be 0 for an existing session  
        {                                                    // status = 0 means not searching inactive
            statusId.value = "1";                            // status = 1 means start searching
            WSHotelsSearchProgress.GetAvailabilityUpdates(sessionId.value, hfSessionID, hfStatusID,
                                                          lblMessageID, btnRefreshID, HandleAvailabilityResponse);
        }
}

function HandleAvailabilityResponse(result) 
{
    var status = eval("(" + result + ")");
    if (status.available > 0) 
    {
        if ($get(status.btnRefreshID) != null)
            $get(status.btnRefreshID).disabled = false;
                 
        if ($get(status.lblMessageID) != null)
            $get(status.lblMessageID).innerHTML = "Press refresh to see more results!";
    }
        
    var statusId = $get(status.hfStatusID);
    if (status.completed == "Y")
    {
        statusId.value = "2";                       // set status to completed
        if (status.available == 0) 
            $get(status.lblMessageID).innerHTML = "";
    }
    else statusId.value = "0";                      // set status to idle
}



/************************************************************

FOR MANAGE FUNCTIONS

************************************************************/



/************************************************************/

var request;
var requestReady = false;



function GetNewRequest()
{
    if (window.ActiveXObject)
        request = new ActiveXObject('Msxml2.XMLHTTP');
    else request = new XMLHttpRequest();
  
//    if (window.XMLHttpRequest)
//        request = new XMLHttpRequest();
//    else if (window.ActiveXObject)
//        request = new ActiveXObject('Msxml2.XMLHTTP');
}

function FilterAircraft(ctrl)
{
    alert('filter');
}

/**************  Raising and capturing results from async server events  **************************/

/****************************************************************
Approved async request methods
*****************************************************************/
function AsyncServerMessage(id, data, myCallBackFunction, doPostback)
{

    if (request == null)
        GetNewRequest();
    request.open("POST", document.location.href, true);
    request.onreadystatechange = myCallBackFunction;
    request.setRequestHeader('asyncServerMessage', 'true');
    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    var body = id.toString() + '|' + data.toString();
    request.send(body);
    
    return doPostback;
}

function SendCommandMessage(ctrl, msg, asyncCallback)
{
    //if (asyncCallback)
    CombineStoredValues();

        return AsyncServerMessage(msg, ControlValues2JSONString(), DefaultServerEventResponse, asyncCallback);
    //else return false;
}

function SendCommandMessage3(ctrl, msg, asyncCallback)
{
    CombineStoredValues();

    AsyncServerMessage(msg, ControlValues2JSONString(ctrl), ShowResponseDetails2, asyncCallback);
    return false;
}

var postbackCtrlId;

function SendCommandMsg(ctrl, msg, asyncCallback)
{
    mpeLoader = $find('mpeLoadingBehaviorID1');
    if (mpeLoader)
        mpeLoader.show();
    if  (asyncCallback)
        return AsyncServerMessage(msg, ControlValues2JSONString(ctrl), ShowResponseDetails2, false);
    return AsyncServerMessage(msg, ControlValues2JSONString(), ShowResponseDetails2, false);
}

function SendCommandMsgTable(ctrl, msg, asyncCallback)
{
    mpeLoader = $find('mpeLoadingBehaviorID1');
    if (mpeLoader)
        mpeLoader.show();
        
    var table = GetParentTable(ctrl);
    var selectedIndex = GetBodyRowIndex(table, ctrl);
    if (table != null && selectedIndex != null)
    {
        SetRowStyles(table.id, selectedIndex);
        StoreControlValue(table.id, selectedIndex);
        
        if (asyncCallback)
            return AsyncServerMessage(msg, ControlValues2JSONString(ctrl), ShowResponseDetails2, false);
        else 
            return AsyncServerMessage(msg, ControlValues2JSONString(), ShowResponseDetails2, false);
    }
    else return false;
}

function ToggleGoogleMap()
{
    return AsyncServerMessage('msgToggleGoogleMap', '', ShowResponseDetails2, false);
}



function ChangeLanguage(ctrl, msg, asyncCallback)
{
//    return AsyncServerMessage('MsgChangeLanguage', msg, DefaultServerEventResponse, asyncCallback);
    
    postbackCtrlId = ctrl.uniqueID;    
    return AsyncServerMessage('MsgChangeLanguage', msg, PostbackServerResponse, false);
}

function ChangeCurrency(ctrl, asyncCallback)
{
    StoreFieldValue(ctrl.id, ctrl.value);

    return SendCommandMsg(ctrl, 'MsgChangeCurrency', false);
//    postbackCtrlId = ctrl.uniqueID;    
//    StoreFieldValue(ctrl.id, ctrl.value);
//    return AsyncServerMessage('MsgChangeCurrency', ctrl.value, PostbackServerResponse, false);
}


function SendCommandMessage2(ctrl, msg, asyncCallback)
{
    CombineStoredValues();
    AsyncServerMessage(msg, ControlValues2JSONString(), DefaultServerEventResponse, asyncCallback);
    return true;
}



function SendValidatedCommandMessage(ctrl, msg, asyncCallback)
{
    mpeLoader = $find('mpeLoadingBehaviorID1');
    if (mpeLoader)
        mpeLoader.show();
    CombineStoredValues();
    return AsyncServerMessage(msg, ControlValues2JSONString(), ShowValidationResponse, false);
}

function SendValidatedCommandMessage2(ctrl, msg, btn, asyncCallback)
{
    CallPostBack(btn, '');    
    CombineStoredValues();          /// requires change XXXXXX

    return AsyncServerMessage(msg, ControlValues2JSONString(), ShowValidationResponse, false);
}

function SendMenuCommandMessage(ctrl, msg, asyncCallback)
{
    CombineStoredValues();

    AsyncServerMessage(msg, ControlValues2JSONString(ctrl), DefaultServerEventResponse, asyncCallback);
    CallPostBack(ctrl.uniqueID, '');    
}

function SendManageCommandMessage(ctrl, msg, asyncCallback)
{
    //if (asyncCallback)
        CombineStoredValues();

        return AsyncServerMessage(msg, ControlValues2JSONString(), ShowResponseDetails, asyncCallback);
    //else return false;
}


function FilterAircraft(ctrl, msg, asyncCallback)
{
    //ctrl.checked = !ctrl.checked;
    StoreFieldValue(ctrl.id, ctrl.checked);   
    CombineStoredValues();

    return AsyncServerMessage(msg, ControlValues2JSONString(ctrl), ShowResponseDetails, asyncCallback);
    //else return false;
}


function SendTableCommandMessage(ctrl, msg, tableID, asyncCallback)
{    
    var table = $get(tableID);
    if (table != null)
    {
        var selectedIndex = GetBodyRowIndex(table, ctrl);
        StoreFieldValue(tableID, selectedIndex.toString());
        CombineStoredValues();
        AsyncServerMessage(msg, ControlValues2JSONString(), ShowResponseDetails, false);
        return false;
    }
    else 
    {
        CombineStoredValues();
        AsyncServerMessage(msg, ControlValues2JSONString(), ShowResponseDetails, true);
        return true;
    }
}

function SendEditTableCommandMessage(ctrl, msg, tableID, asyncCallback)
{    
    var table = $get(tableID);
    var selectedIndex = GetBodyRowIndex(table, ctrl);
    StoreFieldValue(tableID, selectedIndex.toString());
    CombineStoredValues();
    AsyncServerMessage(msg, ControlValues2JSONString(), ShowResponseDetails, false);
    return false;
}


function SendTabChangeMessage(sender, msg, asyncCallback)
{
    if (asyncCallback)
        return AsyncServerMessage(msg, sender.get_activeTab().get_tabIndex(), DefaultServerEventResponse, asyncCallback);
    else return false;
}

function SendMsgActiveStepChangeTable(ctrl, eventName)
{
    postbackCtrlId = ctrl.id;//ctrl.uniqueID;    
    var table = GetParentTable(ctrl);
    var selectedIndex = GetBodyRowIndex(table, ctrl);
    if (table != null && selectedIndex != null)
    {
        SetRowStyles(table.id, selectedIndex);
        return AsyncServerMessage(eventName, selectedIndex, PostbackServerResponse, false);
    }
    else return false;
}

function SendMsgActiveStepChange(ctrl, eventName)
{
    postbackCtrlId = ctrl.uniqueID;    
    CombineStoredValues();                      ///  requires change XXXXXX
    return AsyncServerMessage(eventName, ControlValues2JSONString(), PostbackServerResponse, false);
}


function HandleMenuItemClick()
{ alert('menu item click');}


/**********  Async Response Handling Methods *******************************************************/

function DefaultServerEventResponse()
{
    if (request.readyState == 4 && request.status == 200)
    {
    }
}

function PostbackServerResponse()
{
    if (request.readyState == 4 && request.status == 200)
    {
        CallPostBack(postbackCtrlId, '');    
    }
}

function CallPostBack(eventTarget, eventArgument)
{
    if (window.navigator.appName.toLowerCase().indexOf("microsoft") > -1)
    {
        __doPostBack(eventTarget, eventArgument);
    }
    else 
    {    
        var theForm;
        theForm = document.forms["Form1"];
        theForm.__EVENTTARGET.value = eventTarget.split("$").join(".");
        theForm.__EVENTARGUMENT.value = eventArgument;
        theForm.submit();
    }
}

function ShowValidationResponse() 
{
    if (request.readyState == 4 && request.status == 200)
    {
        
        var result = eval("(" + request.responseText + ")");
        
        if (result.validationError == 'N')
            CallPostBack(result.triggerControlID, '');  
        else 
        {
            if (result.mandatoryFields)
            {
                for (var i = 0; i < result.mandatoryFields.length; i++)
                {
                    var ctl = $get(result.mandatoryFields[i].id);
                    if (ctl)
                        ctl.className = result.mandatoryFields[i].value;
                }
            }
            if (result.businessRules)
            {
                for (var i = 0; i < result.businessRules.length; i++)
                {
                    var ctl = $get(result.businessRules[i].id);
                    if (ctl)
                        ctl.innerHTML = result.businessRules[i].value;
                    else alert(result.businessRules[i].value);
//                        ctl.value = result.businessRules[i].value;
                }
            }
        }
        if (mpeLoader)
            mpeLoader.hide();
    }
}            


 
function ShowResponseDetails2() 
{
    if (request.readyState == 4 && request.status == 200)
    {
        try
        {
           
        
            var result = eval("(" + request.responseText + ")");
           
            var x = result.pbControl;
            var y = result.error;
            
            if (!result.error && result.pbControl)
            {
              //  ShowControlValues2(result.controlValues) 
                CallPostBack(result.pbControl, ControlValues2JSONString());
          //      mpeLoader = $find('mpeLoadingBehaviorID1');
            }
            else 
            {
                try {
                    ShowControlValues2(result.controlValues) 
  //        window.scrollBy(0, 500000);
  
                }
                catch (errorShow)
                {
                }
                try {
                    ShowStatusMessages(result.statusMessages) 
                }
                catch (errorShow)
                {
                }
            }
            if (mpeLoader)
                mpeLoader.hide();
        }
        catch (error)
        {
        }
    }
}



function ShowResponseDetails() 
{
    if (request.readyState == 4 && request.status == 200)
    {
        try
        {
            var result = eval("(" + request.responseText + ")");
            try {
                ShowControlValues(result.controlValues) 
            }
            catch (errorShow)
            {
            }
            try {
                ShowStatusMessages(result.statusMessages) 
            }
            catch (errorShow)
            {
            }
            
        }
        catch (error)
        {
        }
    }
}

function ShowControlValues(controlValues) 
{
    for (var i = 0; i < controlValues.length; i++)
    {
        StoreFieldValue(controlValues[i].id, controlValues[i].value);
        var ctl = $get(controlValues[i].id);
        if (ctl)
        {
            if  (ctl.tagName == 'TEXTAREA')
                ctl.value = controlValues[i].value;
            else 
                if  (ctl.tagName == 'SPAN' || ctl.tagName == 'A') 
                    ctl.innerHTML = controlValues[i].value;
                else     
                    if (ctl.tagName == 'INPUT')
                    {
                        if (ctl.type == 'text')
                        {
                            ctl.value = controlValues[i].value;
                        }
                        else if (ctl.type == 'checkbox')
                        {
                            ctl.checked = (controlValues[i].value.toString().toUpperCase() == "TRUE");
                        }
                        else if (ctl.type == 'radio')
                        {
                            ctl.checked = (controlValues[i].value.toString().toUpperCase() == "TRUE");
                        }
                        else if (ctl.type == 'submit')
                        {
                        }
                    }
                    else 
                    if (ctl.tagName == 'SELECT')
                    {
                        if (controlValues[i].hasData)
                        {
                            UpdateOptionList(ctl, controlValues[i].cbxValues);
                        }

                        ctl.value = controlValues[i].value;
                    }
                    else 
                    if  (ctl.tagName == 'IMG')
                    {
                        ctl.src = controlValues[i].value;
                    }
                    else 
                    if (ctl.tagName == 'TABLE')
                    {
                        ShowTable(controlValues[i].tableValues);
                    }
                    else if (ctl.tagName == 'DIV')
                    {
                        if (controlValues[i].value == 'hidePanel')
                            ctl.className = 'nungTable';
                        else if (controlValues[i].value == 'showPanel')
                                ctl.className= '';
                            else
                            {
                                    var ctl2 = $find(controlValues[i].id);
                                    ctl2.set_activeTabIndex(controlValues[i].value);
                            }
                    }
                    
            ctl.disabled = (controlValues[i].status & 1 == 1);
        }
    }         
}

function ShowControlValues2(controlValues) 
{
    for (var i = 0; i < controlValues.length; i++)
    {
        StoreFieldValue(controlValues[i].Id, controlValues[i].Value);
        var ctl = $get(controlValues[i].Id);
        if (!ctl)
            ctl = $find(controlValues[i].Id);
            
        if (ctl)
        {
            ctl.disabled = !controlValues[i].Enabled;
                            
            if  (ctl.tagName == 'TEXTAREA')
                ctl.value = controlValues[i].Value;
            else 
                if  (ctl.tagName == 'SPAN' || ctl.tagName == 'A') 
                {
                    ctl.innerHTML = controlValues[i].Value;
                    if (controlValues[i].Visible)
                        ctl.className = controlValues[i].CssClass;
                    else ctl.className = 'nungTable';
                }
                else     
                    if (ctl.tagName == 'INPUT')
                    {
                        if (ctl.type == 'text')
                        {
                            ctl.value = controlValues[i].Value;
                        }
                        else if (ctl.type == 'checkbox')
                        {
                            ctl.checked = (controlValues[i].Value.toString().toUpperCase() == "TRUE");
                            ctl.disabled = !controlValues[i].Enabled;
                        }
                        else if (ctl.type == 'radio')
                        {
                            ctl.checked = (controlValues[i].Value.toString().toUpperCase() == "TRUE");
                        }
                        else if (ctl.type == 'submit')
                        {
                            if (controlValues[i].Visible)
                                ctl.className = controlValues[i].ClassName;
                            else ctl.className = 'nungTable';
                        }
                    }
                    else 
                    if (ctl.tagName == 'SELECT')
                    {
                        if (controlValues[i].JSONData)
                            UpdateCbxData(ctl, controlValues[i].JSONData);

                        ctl.value = controlValues[i].Value;
                    }
                    else 
                    if  (ctl.tagName == 'IMG')
                    {
                        ctl.src = controlValues[i].Value;
                    }
                    else 
                    if (ctl.tagName == 'TABLE')
                    {
                        if (controlValues[i].JSONData)
                            ShowTable(controlValues[i].JSONData);
                    }
                    else if (ctl.tagName == 'DIV')
                    {
                        if (controlValues[i].TypeName == 'panel')
                        {
                            if (controlValues[i].Visible) 
                            {
                                ctl.className= '';
                            }
                            else    ctl.className = 'nungTable';
                        }
                        
                        else
                        {
                            try {
                            var ctl2 = $find(controlValues[i].Id);
                            ctl2.set_activeTabIndex(controlValues[i].Value);
                            }
                            catch (err) {}
                        }
                    }
                    else 
                    if (controlValues[i].TypeName == 'collapsiblepanelextender')
                    {
                        if (controlValues[i].Value == 'FALSE')
                            ctl.set_Collapsed(false);
                        else ctl.set_Collapsed(false);
                    }

                    
        }
        else 
        if (controlValues[i].TypeName == 'wugmap')
        {
            if (controlValues[i].JSONData)
            {
                try {
                    SetMarkersOnMap(controlValues[i].JSONData);
                    }
                catch (error)
                {
                }
            }
        }
    }         
}


function ShowStatusMessages(statusMessages) 
{
    for (var i = 0; i < statusMessages.length; i++)
    {
        alert(statusMessages[i].msgText);
    }
}

function UpdateCbxData(cbx, data)
{
    if (cbx == null){
        return ;
    }

    cbx.options.length=0;

    if (data.cbxValues.length > 0){
        for (i = 0; i < data.cbxValues.length; i++) {
            var option = new Option(data.cbxValues[i].value, data.cbxValues[i].id);
            cbx.options[cbx.options.length] = option;
        }
    }
}





function UpdateOptionList(cbx, data)
{
    if (cbx == null){
        return ;
    }

    cbx.options.length=0;

    if (data.length > 0){
        for (i = 0; i < data.length; i++) {
            var option = new Option(data[i].value, data[i].id);
            cbx.options[cbx.options.length] = option;
        }
    }
    cbx.disabled = false;
}


function OnLoadError(error)
{
    alert(error.get_message());
}


/****************************************************************************
    Approved table methods
****************************************************************************/

function FindControl(ctrl, key) //finds a control in a table
{
   var result;

   if (ctrl.id && ctrl.id.length >= key.length && key == ctrl.id.substr(ctrl.id.length - key.length))
        result = ctrl;

   for (var i = 0; i < ctrl.childNodes.length && !result; i++)
        result = FindControl(ctrl.childNodes[i], key)        
   return result;
}

function FirstDataRow(table)
{
    if (table.tHead != null)
        return 1;
    else return 0;
}

function LastDataRow(table)
{
    if (table.tFoot != null)
        return table.rows.length - 1;
    else return table.rows.length;
}

function GetParentTable(ctrl)
{
    var parent = ctrl.parentNode;
    while (parent.tagName != 'TABLE')
        parent = parent.parentNode;
    return parent;    
}

function HandleListRbtCheck(triggerRbt, btnId, message)
{   
    var table = GetParentTable(triggerRbt);
    
    var startIndex = FirstDataRow(table);
    var endIndex = LastDataRow(table);
    var itemIndex = GetRowIndex(triggerRbt);
    
    
    for (var i = startIndex; i < endIndex; i++)
    {
        var rbt = FindControl(table.rows[i], btnId);
        if (rbt != null)
        {
           rbt.checked = (i == itemIndex);
           StoreFieldValue(rbt.id, rbt.checked.toString());
        }
    }
    
    AsyncServerMessage(message, itemIndex.toString(), DefaultServerEventResponse, false);    
    return true;
}

function GetRowIndex(ctrl)
{
    try {
    var parent = ctrl.parentNode;
    while (parent.tagName != 'TR')
        parent = parent.parentNode;
    return parent.rowIndex;    
    }
    catch (err) 
    {
    return 0;
    }    
}

function GetColumnIndex(ctrl)
{
    var parent = ctrl.parentNode;
    while (parent.tagName != 'TD')
        parent = parent.parentNode;
    return parent.cellIndex;    
}


function GetBodyRowIndex(table, ctrl)
{
    var index = GetRowIndex(ctrl);
    if (table.tHead != null)
        return index - 1;    
    else return index;    
}

function HandleListSelect(ctrl, eventName, asyncCallback)
{
    var table = GetParentTable(ctrl);
    var selectedIndex = GetBodyRowIndex(table, ctrl);
    if (table != null && selectedIndex != null)
    {
        SetRowStyles(table.id, selectedIndex);
        if (asyncCallback)
            return AsyncServerMessage(eventName, selectedIndex, DefaultServerEventResponse, asyncCallback);
        else return false;
    }
    else return false;
}





function HandleListDelete(ctrl, eventName, asyncCallback)
{
    var table = GetParentTable(ctrl);
    var selectedIndex = GetBodyRowIndex(table, ctrl);
    
    if (table != null && selectedIndex != null)
    {
        AsyncServerMessage(eventName, selectedIndex.toString(), ShowResponseDetails, false);
        return false;
    }
    else return false;
}


function HandleManageSelect(ctrl, eventName, asyncCallback)
{
    var table = GetParentTable(ctrl);
    var selectedIndex = GetBodyRowIndex(table, ctrl);
    if (table != null && selectedIndex != null)
    {
        SetRowStyles(table.id, selectedIndex);
        return AsyncServerMessage(eventName, selectedIndex, ShowResponseDetails, asyncCallback);
    }
    return asyncCallback;
}




function SetFooterData(id, currentPage, numberOfPages, numberOfItems)
{
    var table = $get(id);
    if (table != null && table.tFoot != null && table.tFoot.rows.length > 0)
    {
        cbx = FindControl(table.tFoot, 'cbxPager');
        while (cbx.options.length < numberOfPages)
        {
            var pageNumber = cbx.options.length + 1;
            var option = new Option(pageNumber.toString(), pageNumber.toString());
            cbx.options[cbx.options.length] = option;
        }
        var index = currentPage + 1;
        cbx.value = index.toString();
        cbx.disabled = (numberOfPages <= 1);
        lblCurrentPage = FindControl(table.tFoot, 'lblCurrentPage');
        lblCurrentPage.innerHTML = index.toString();
        lblNumberOfPages = FindControl(table.tFoot, 'lblPages');
        lblNumberOfPages.innerHTML = numberOfPages.toString();
        lblNumberOfItems = FindControl(table.tFoot, 'lblItems');
        lblNumberOfItems.innerHTML = numberOfItems.toString();
        
        FindControl(table.tFoot, 'btnNext').disabled = (index == numberOfPages);
        FindControl(table.tFoot, 'btnEnd').disabled = (index == numberOfPages);
        FindControl(table.tFoot, 'btnPrev').disabled = (index == 1);
        FindControl(table.tFoot, 'btnStart').disabled = (index == 1);
    }
}

function InitPagedTable(id, pagerId, selectedIndex, currentPage, numberOfPages, numberOfItems, isDummy)
{
    var table = $get(id);
    if (isDummy)
        table.className = 'nungTable';

    var hfPager = FindControl($get(id).tFoot, 'hfPagerId');
    hfPager.value = pagerId;

    SetRowStyles(id, selectedIndex);
    SetFooterData(id, currentPage, numberOfPages, numberOfItems);
}

function SetTableStyle(tableId, tableClass, isDummy)
{
    var table = $get(tableId);
    if (isDummy)
        table.className = 'nungTable';
    else table.className = tableClass;
}

function InitTable(id, selectedIndex)
{
    SetRowStyles(id, selectedIndex);
}

function SetRowStyles(id, selectedIndex)
{
    var table = $get(id);
    if (table != null)
    {
        var tbody = table.tBodies[0];
        
        for (var i=0; i < tbody.rows.length; i++)
        {
            if (selectedIndex != null && i == selectedIndex)
                tbody.rows[i].className = 'tablerow selectedrow';
            else 
                if ((i%2)!=0)
                {
                    tbody.rows[i].className = 'tablerow alternate';
                }
                else 
                    tbody.rows[i].className = 'tablerow';

        }   
    }
}

function AdjustNumberOfRows(tbody, count, columns)
{
    if (tbody.rows.length < count)
    {
        var counter = tbody.rows.length;
        while (tbody.rows.length < count)
        {
            counter++;
            var row = tbody.rows[0];
            var clone = row.cloneNode(true);
            var ctlNumber = counter.toString();
            if (ctlNumber.length == 1) 
                ctlNumber = '0' + ctlNumber;
            
            for (var i = 0; i < columns.length; i++)
            {
                var z = FindControl(clone, columns[i]);
                if (z)
                {
                    var c = z.id;
                    z.id = z.id.replace('01_' + columns[i], ctlNumber + '_' + columns[i].toString());
                    var tmp = 4;
                }
            }
            tbody.appendChild(clone); 
            
        }
    }
    else 
        if (tbody.rows.length > count)
        {
            while (tbody.rows.length > count)
            {
                var row = tbody.rows[tbody.rows.length - 1];
                while (row.firstChild != null)
                  row.removeChild(row.firstChild);
                tbody.deleteRow(tbody.rows.length - 1);
            }
        }
//    for (var i = 0; i < tbody.rows.length; i++)
//    {
//                var z = FindControl(tbody.rows[i], columns[1]);
//                if (z)
//                {
//                    var c = z.id;
//                }
//    
//    
//    }
}


function OnTableLoadOk(result)
{
    var data = eval("(" + result + ")");
    ShowTable(data);
}

function ShowTable(data)
{

    var table = $get(data.tableName);
    if (table != null)
    {
        table.className = data.className;
        
        var tbody = table.tBodies[0];
        AdjustNumberOfRows(tbody, data.rows.length, data.columns);
        for (var i=0; i < data.rows.length; i++)
        {
            for (var j = 0; j < data.columns.length; j++)
            {
              //  StoreFieldValue(tbody.rows[i], data.columns[j]);
            
                var ctl = FindControl(tbody.rows[i], data.columns[j]);
                
                
                if (ctl)
                {
                    
                    if  (ctl.tagName == 'SPAN' || ctl.tagName == 'A')
                    {
                        ctl.innerHTML = data.rows[i][j];
                    }
                    else                    
                        if  (ctl.tagName == 'TEXTAREA')
                            ctl.value = data.rows[i][j];

                    else     
                    if (ctl.tagName == 'INPUT')
                    {
                        var z = data.rows[i];
                        var z1 = data.rows[i][j];
                        StoreControlValue(ctl.id, data.rows[i][j].toString(), '0', ''); 
                        //StoreFieldValue(ctl.id, data.rows[i][j].toString());
                        if (ctl.type == 'text')
                            ctl.value = data.rows[i][j];
                        else if (ctl.type == 'checkbox' || ctl.type == 'radio' )
                            ctl.checked = data.rows[i][j];
                        else if (ctl.type == 'image')
                        {
                                ctl.src = data.rows[i][j].toString();
                                var x = 4;
                        }
                        else if (ctl.type == 'submit')
                        {
//                            try {
//                                if (data.rows[i][j].toString() == 'FALSE')
//                                    ctl.disabled= true;
//                                else ctl.disabled= false;
//                            }
//                            catch(err) {}
                        }
                    }
                    else 
                    if (ctl.tagName == 'SELECT')
                    {
                        ctl.value = data.rows[i][j];
                    }
                    else 
                    if  (ctl.tagName == 'IMG')
                    {
                        ctl.src = data.rows[i][j];
                    }
                }

            }
        }
            
        SetTableStyle(data.tableName, data.className, data.isDummy);
        SetRowStyles(table.id, parseInt(data.selectedIndex, 10));
        SetFooterData(table.id, parseInt(data.currentPage, 10), parseInt(data.numberOfPages, 10), 
                      parseInt(data.numberOfItems, 10))
    }   
}



function HandlePagingButton(ctrl, item) {
    var c = ctrl.parentNode;
    while (c.id != 'tblFooter')
        c = c.parentNode;
    var hfPager = FindControl(c, 'hfPagerId');
    c = c.parentNode;
    while (c.tagName != 'TABLE')
        c = c.parentNode;
//    while (c.tagName != 'TABLE')
//        c = c.parentNode;
//    var hfPager = FindControl(c.tFoot, 'hfPagerId');


    var s = PageMethods.GetTableData(c.id, hfPager.value, item, OnTableLoadOk, OnLoadError);
    return false;
}

function HandlePagerChange(cbxPager)
{
    var c = cbxPager.parentNode;
    while (c.id != 'tblFooter')
        c = c.parentNode;
    var hfPager = FindControl(c, 'hfPagerId');
    c = c.parentNode;
    while (c.tagName != 'TABLE')
        c = c.parentNode;

    var pageNumber = cbxPager.value;
    var s = PageMethods.GetTableData(c.id, hfPager.value, pageNumber.toString(), OnTableLoadOk, OnLoadError);
}

function HandleListSortCommand(lbtSort, message)
{
    var c = lbtSort.parentNode;
    while (c.tagName != 'TABLE')
        c = c.parentNode;
    var s = PageMethods.GetTableData(c.id, c.id, 'sort' + message, OnTableLoadOk, OnLoadError);
    return false;
}



/************ End of the table related javascript functions **************************/

function HandleCopyButton(item) {
    var table = $get("tblRepeater");
    var row   = table.rows[1];
    var parent   = row.parentNode; 
    var clone = row.cloneNode(true);
    var btn = FindControl(clone, "btn1");
    btn.id = "dataListItem_ctl11_btn1";
    parent.appendChild(clone); 
    var btn = FindControl(clone, "btn1");
    var btn2 = FindControl(table.rows[2], "btn1");
    
//    alert("hallo");
    return false;
}

function UpdateList(result){
    var options = eval("(" + result + ")");
    if (options.description.length < 1){
        return ;
    }

    var cbxID = options.description[0];
    var cbx = $get(cbxID);
    if (cbx == null){
        return ;
    }

    cbx.disabled = true;
    cbx.options.length=0;

    if (options.id.length > 1){
        for (i = 1; i < options.id.length; i++) {
            var option = new Option(options.description[i], options.id[i]);
            cbx.options[cbx.options.length] = option;
        }
    }
    cbx.disabled = false;
}



//function OnTestDataOk(result)
//{
//    var data = eval("(" + result + ")");
//    var table = 7;
//}

//function HandleJSONTest()
//{
//    var s = PageMethods.JSTestTableData('1', '2', OnTestDataOk, OnLoadError);
//}

//function HandleAddSegmentRequest()
//{
//    FunctionCallback('AddSegment', 'hallo', true);
//    return false;


//}





function GetSSRRateValue(ctrl, key)
{
    var tmpLbl = FindControl(ctrl, key);
    if (tmpLbl)  
        return parseFloat(tmpLbl.innerText);
    else return 0; 
}

function HandleRentalCarSSRChbChange(chbID, dlSSRID, dlMandatoryID, itemRateID, itemRateReqCurID,
                                     rateID, ssrTotalID, totalID, rateReqCurID, ssrTotalReqCurID, totalReqCurID) 
{
    var rate = parseFloat($get(rateID).innerText);
    var rateReqCur = parseFloat($get(rateReqCurID).innerText);
    
    var mandatoryRate = 0;
    var mandatoryRateReqCur = 0;
    
    var dlMandatory = $get(dlMandatoryID);
    var r = dlMandatory.rows[0];
    var r2 = dlMandatory.rows[1];
    for (var i = 0; i < dlMandatory.rows.length; i++)
    {
        mandatoryRate += GetSSRRateValue(dlMandatory.rows[i], itemRateID);
        mandatoryRateReqCur += GetSSRRateValue(dlMandatory.rows[i], itemRateReqCurID);
    }
        
    var ssrRate = mandatoryRate;
    var ssrRateReqCur = mandatoryRateReqCur;

    var dlSSR = $get(dlSSRID);
    
    for (var i = 0; i < dlSSR.rows.length; i++)
    {
        var chb = FindControl(dlSSR.rows[i], chbID);
        if (chb && chb.checked) 
        {
            ssrRate += GetSSRRateValue(dlSSR.rows[i], itemRateID);
            ssrRateReqCur += GetSSRRateValue(dlSSR.rows[i], itemRateReqCurID);
        }
    }
    
    var totalRate = rate + ssrRate;
    var totalRateReqCur = rateReqCur + ssrRateReqCur;
    
    var txtSSR = $get(ssrTotalID);
    txtSSR.innerText = ToMoneyString(ssrRate);
    
    var txtSSRReqCur = $get(ssrTotalReqCurID);
    txtSSRReqCur.innerText = ToMoneyString(ssrRateReqCur);

    var txtTotal = $get(totalID);
    txtTotal.innerText = ToMoneyString(totalRate);

    var txtTotalReqCur = $get(totalReqCurID);
    txtTotalReqCur.innerText = ToMoneyString(totalRateReqCur);
}


function SSRSelectionChangeHandler(pObjID) 
{
    var pObj = $get(pObjID);
    StoreFieldValue(pObj, pObj.value);
    var s = "{'index':'" + GetRowIndex(pObj).toString() + "', 'value': '" + pObj.value + "'}";
   
    AsyncServerMessage('ssrSelected', s, ShowResponseDetails, false);
}




var filePath;

function HandleBtnAddImageClick(btn, ctlID)
{
    var obj = $get(ctlID);
    var filePath = obj.value;
    CallServer(obj.value, '');

    return false;    
}




/* GOOGLE MAP RELATED SCRIPTS   */
var map = null;
var Hmap = null;
var BMhotelDetail ;
var BMhotelCenter;


function initialize()
{
    if (GBrowserIsCompatible()) 
    {
   
        map = new GMap2(document.getElementById("map"));      
        var mapControl = new GMapTypeControl();
		    map.addControl(mapControl);
		    //map.addControl(new GLargeMapControl());
		    map.addControl(new GMapTypeControl(true));
           map.setUIToDefault();

        GEvent.addListener(map, "moveend",
        function()
        {
            var center = map.getCenter();
            }
        );
        map.setCenter(new GLatLng(52.373056, 4.892222),13);
        //keru_kop
    }
}

function TestTT()
{
alert("keru_kop")
}

function LoadMapHoteldetail(data,Hotel_Lat,Hotel_Lon)//Load Hotel detail
{

try
{
Hotel_Select_LaT=Hotel_Lat;
Hotel_Select_LoN=Hotel_Lon;
 var hotelInfo=data;
 ew = new EWindow(map, E_STYLE_7);      
      map.addOverlay(ew);
      
    
        
        
    for (var i = 0; i < hotelInfo.hotels.length; i++)
    {
        if(Hotel_Lat==hotelInfo.hotels[i].latitude && Hotel_Lon==hotelInfo.hotels[i].longitude)
        {
         AddHotelMarker(hotelInfo.hotels[i],"ImageMarkerOnMap.aspx?MarkerNumber=" +(i+1)+"&MarkerName=marker_hotel_select.png");
         
        }else
        {
         AddHotelMarker(hotelInfo.hotels[i],"ImageMarkerOnMap.aspx?MarkerNumber=" +(i+1)+"&MarkerName=marker_hotel.png");
         
        }
        
    
        var x = hotelInfo.hotels[0].latitude;
        var y = hotelInfo.hotels[0].longitude;
          
        var maxLat = Math.max(x,hotelInfo.hotels[i].latitude);
        var maxLng = Math.max(y,hotelInfo.hotels[i].longitude);       
        var minLat = Math.min(x,hotelInfo.hotels[i].latitude);
        var minLng = Math.min(y,hotelInfo.hotels[i].longitude);    
    }        
        
        var swLatLng = new GLatLng(minLat,minLng);   
        var neLatLng = new GLatLng(maxLat,maxLng);
           
        var center = new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
      
      BMhotelCenter=new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
      
        var getBound=new GLatLngBounds(swLatLng, neLatLng); 
 
        if (map.getBoundsZoomLevel(getBound)> getZoom)
                {
                
                map.setCenter(center, getZoom);
                }
            else
                {        
                map.setCenter(center, map.getBoundsZoomLevel(getBound));
                } 
                
             _CheckMapHoteL();//Check display map
           //   City_Center_LaT=hotelInfo.cityCentreLatitude;
             //  City_Center_LoN=hotelInfo.cityCentreLongitude;
       } catch (err) {}    

}

function _loadBMapHotel()
{
/*
 if (GBrowserIsCompatible()) 
    {
   
        Hmap = new GMap2(document.getElementById("GMap_hotel"));      
        var mapControl = new GMapTypeControl();
		    Hmap.addControl(mapControl);
		    //map.addControl(new GLargeMapControl());
		    Hmap.addControl(new GMapTypeControl(true));
            Hmap.setUIToDefault();

        GEvent.addListener(Hmap, "moveend",
        function()
        {
            var center = Hmap.getCenter();
            }
        );
        Hmap.setCenter(new GLatLng(52.373056, 4.892222),13);
        //keru_kop
    }
      */  
}


/*****************************************/
//function _CallBmap()
//{
//parent._ShowBmap();
//}



//var toggleState = 1;
//function _ShowMap()
//{

//    try {
//    if (toggleState == 1) 
//	   {
//  	  
//  	         document.getElementById("_BMap").style.display="";
//  	         document.getElementById("Detail_IcoN").style.display="";
//  	         document.getElementById("LinkMaP").innerHTML="CloseMap";
//  	         toggleState = 0;
//  	      
//  	   } 

//	 else 
//	    {
//   		
//             document.getElementById("_BMap").style.display="none";
//             document.getElementById("Detail_IcoN").style.display="none";
//  	         document.getElementById("LinkMaP").innerHTML="ShowMap";
//             toggleState = 1;
//  	  
//	    }
//    }
//    catch (err) {}

//}

//function ChecKStatEMaP(Mdata)
//{
//        if(Mdata.value=='Hotel')
//            {
//             document.getElementById("LinkMaP").innerHTML="ShowMap";
//             toggleState = 1;
//            }
//}

//function _ShowBmap()
//{
//_ShowMap();

//}

//function RE_ShowBmap()
//{
//_ShowBmap()

//}

//function _CheckMapHoteL()
//{

//   if(document.getElementById('Check_Itemp').value=="PrivatAir")
//   {
//   document.getElementById("_BMap").style.display="";//Big Map
//   document.getElementById("Detail_IcoN").style.display="";
//   document.getElementById("IFr_SMap").style.display="none";//Small Map
//   }
//   else if(document.getElementById('Check_Itemp').value=="Plan2Go")
//   {
//   document.getElementById("_BMap").style.display="none";
//   document.getElementById("Detail_IcoN").style.display="none";
//   document.getElementById("IFr_SMap").style.display="";

//   }

//}


function ShowGoogleMiniMap(result)
{
    info = eval("(" + result + ")");
    document.getElementById('SMap_1');
}


function SetMarkersOnMap(hotelInfo) 
{
    if (hotelInfo)
    {
    initialize();
    for (var i = 0; i < hotelInfo.hotels.length; i++)
    {
        if(Hotel_Select_LaT==hotelInfo.hotels[i].latitude && Hotel_Select_LoN==hotelInfo.hotels[i].longitude)
        {
            AddHotelMarker(hotelInfo.hotels[i], "ImageMarkerOnMap.aspx?MarkerNumber=" +(i+1)+"&MarkerName=marker_hotel_select.png"); 
        }
        else
        {
            AddHotelMarker(hotelInfo.hotels[i], "ImageMarkerOnMap.aspx?MarkerNumber=" + (i+1)+"&MarkerName=marker_hotel.png");  
        }
        
         var Latitude = hotelInfo.hotels[0].latitude;
         var Longitude = hotelInfo.hotels[0].longitude;
          
        var maxLatitude = Math.max(Latitude,hotelInfo.hotels[i].latitude);
        var maxLongitude = Math.max(Longitude,hotelInfo.hotels[i].longitude);       
        var minLatitude = Math.min(Latitude,hotelInfo.hotels[i].latitude);
        var minLongitude = Math.min(Longitude,hotelInfo.hotels[i].longitude);    
        
        
        }
      var swLatLng = new GLatLng(minLatitude,minLongitude);   
      var neLatLng = new GLatLng(maxLatitude,maxLongitude);
      var center = new GLatLng((maxLatitude+minLatitude)/2,(maxLongitude+minLongitude)/2);
      var getBound=new GLatLngBounds(swLatLng, neLatLng); 
      BMhotelCenter=new GLatLng((maxLatitude+minLatitude)/2,(maxLongitude+minLongitude)/2);
      
    if (map.getBoundsZoomLevel(getBound)> getZoom)
    {
        map.setCenter(center, getZoom);
    }
    else
    {        
        map.setCenter(center, map.getBoundsZoomLevel(getBound)-1);
    } 
           
    City_Center_LaT=hotelInfo.cityCentreLatitude;
    City_Center_LoN=hotelInfo.cityCentreLongitude;
    }
}


function InitGoogleMap(result)
{

    if (result)
    {    
        var hotelInfo = eval("(" + result + ")");
        BMhotelDetail=hotelInfo;
        initialize();//new GLatLng(hotelInfo.cityCentreLatitude, hotelInfo.cityCentreLongitude));
        //alert("keru_hotel")
        // Create an EWindow
        ew = new EWindow(map, E_STYLE_7);      
        map.addOverlay(ew);
        
        for (var i = 0; i < hotelInfo.hotels.length; i++)
        {
             if(Hotel_Select_LaT==hotelInfo.hotels[i].latitude && Hotel_Select_LoN==hotelInfo.hotels[i].longitude)
                {
                    
                     AddHotelMarker(hotelInfo.hotels[i], "ImageMarkerOnMap.aspx?MarkerNumber=" +(i+1)+"&MarkerName=marker_hotel_select.png"); 
                 }
                 else{
                     AddHotelMarker(hotelInfo.hotels[i], "ImageMarkerOnMap.aspx?MarkerNumber=" + (i+1)+"&MarkerName=marker_hotel.png");  
                     }
            
        
            var x = hotelInfo.hotels[0].latitude;
            var y = hotelInfo.hotels[0].longitude;
              
            var maxLat = Math.max(x,hotelInfo.hotels[i].latitude);
            var maxLng = Math.max(y,hotelInfo.hotels[i].longitude);       
            var minLat = Math.min(x,hotelInfo.hotels[i].latitude);
            var minLng = Math.min(y,hotelInfo.hotels[i].longitude);    
        }        
            
            var swLatLng = new GLatLng(minLat,minLng);   
            var neLatLng = new GLatLng(maxLat,maxLng);
               
            var center = new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
          
          BMhotelCenter=new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
          
            var getBound=new GLatLngBounds(swLatLng, neLatLng); 
     
            if (map.getBoundsZoomLevel(getBound)> getZoom)
                    {
                    
                    map.setCenter(center, getZoom);
                    }
                else
                    {        
                    map.setCenter(center, map.getBoundsZoomLevel(getBound));
                    } 
                    
                //  _CheckMapHoteL();//Check display map
                  City_Center_LaT=hotelInfo.cityCentreLatitude;
                   City_Center_LoN=hotelInfo.cityCentreLongitude;
                 //  GetCity_Map(hotelInfo.cityCentreLatitude,hotelInfo.cityCentreLongitude)
    }
    else 
    {
        BMhotelDetail=hotelInfo;
        initialize();
        ew = new EWindow(map, E_STYLE_7);      
        map.addOverlay(ew);
    }
                 
}

function AddHotelMarker(hotelInfo,HotelIcoN)
{
    var lat = hotelInfo.latitude;
    var lng = hotelInfo.longitude;
    var price = hotelInfo.price + " " + hotelInfo.currencyId;
    var hName = hotelInfo.hotelName;
    var addr = hotelInfo.address;
    var gPic = document.location.src=("<img src='"+ hotelInfo.imageUrl +"' width='80'height='55'/>"); 
    
    var infoLatLong = "<div style='width:360px;height:226px;'>Latitude : " + lat + "<br/>Longitude :" + lng +"</div>";
   // var infoTabs = [new GInfoWindowTab("Place's Info",Place)]; 
    var hIcon = new GIcon(G_DEFAULT_ICON);                 
        hIcon.iconSize = new GSize(30,39);
        hIcon.image =  HotelIcoN;     
   // var marker = new PdMarker(new GLatLng(hotelInfo.latitude, hotelInfo.longitude),{icon:hIcon});       
     //  marker.setTooltip(Place);

       
      //  map.addOverlay(marker);
             
      // Set up three markers with EWindows 
      var point = new GLatLng(hotelInfo.latitude,hotelInfo.longitude);
      var html = pretty(hName,gPic,addr,price,hotelInfo.hotelId); 
      var marker = createMarker_Hotel(point,html,hIcon,hName);
      map.addOverlay(marker);
      
    

}

function createMarker_Hotel(point,html,icon,title) {
var marker = new GMarker(point,{title:title,icon:icon});
      GEvent.addListener(marker, "click", function() {
          ew.openOnMarker(marker,html);
        });
        return marker;
      }


 // This function just makes a pretty table for the EWindow contents
      function pretty(Hname,Hpic,Haddr,Hprice,Hid) {
     //alert(Hpic)
     return "<div><table class='TbpopupHotel'>"+
    "<tr ><td style='width:60px'></td> <td style='width:10px'></td><td style='width:170px;'align='right'></td></tr>"+
    "<tr ><td colspan='3'class='TrHotelnam'><table style='width:240px'border='0'><tr><td style='width:230px' align='center'>"+Hname+"</td><td style='width:10px' align='right'><label  onclick='javascript:ew.hide();' >X</label></td></tr></table></td></tr>"+
    "<tr><td ><table class='tbHotelPic'><tr><td>"+Hpic+"</td> </tr></table></td>"+
    "<td ></td><td><table border='0'><tr align='left'><td>"+Haddr+"</td></tr><tr></tr><tr align='left'><td>"+Hprice+"</td></tr>"+
    "<tr height='5'></tr><tr align='center'  ><td> <button type='Button' class='Btbook'  Onclick='javascript:return HandleMapSelect(this, " + Hid + ");'>Book hotel</button></td></tr>"+
    "</table></td></tr></table></div>";
     
      }



function HandleMapSelect(ctrl, key)
{
    AsyncServerMessage("hotelMarkerSelected", key, DefaultServerEventResponse, true);
    
    CallPostBack(ctrl.uniqueID, '');
    
   
    return true;
}

/* END OF GOOGLE MAP RELATED SCRIPTS   */

Sys.Application.add_load(function pageLoad(){});
Sys.Application.add_unload(function pageUnload(){});



//--------------------------------------------------------------------------------------------//


//function _ClearTb(TbName)//Clear Table
//{
//while (document.getElementById(TbName).rows.length > 0)
//	{
//	    document.getElementById(TbName).deleteRow(0); 
//	}

//}

// add value in table
//function _AddAIrPort(Count,name,IDAirport,AirLaT,AirLoN,TbName)
//{ 
//     var mtable = document.getElementById(TbName)
//    var Newrow = mtable.insertRow(mtable.rows.length)  
//   
//    //Newrow.id = Count-1;
//    Newrow.id = Count;

//    var Newcell = Newrow.insertCell(0)
//    
//    if(TbName == 'TbAir')
//    {
//    Newcell.width = '250px'
//	Newcell.align = 'left';
//    Newcell.innerHTML = "<table cellspacing = 0 cellpadding = 0 width='250px' border ='0'><td id='Air_cell_0_"+Newrow.id+"' align ='left' width='25'><img id='MIconAir_"+IDAirport+"' src='ImageMarkerOnMap.aspx?MarkerNumber=" +Newrow.id+"&MarkerName=icon_number_airport.png' /></td><td id='Air_cell_1_"+Newrow.id+"' align ='left' width='20'><input type='radio'id='RaDAir_"+IDAirport+"' "+name+" name='RaDAir' onclick='javascript:ClicKAirPort("+IDAirport+");'/></td><td align ='left' width='160px'>"+name+"<input type='hidden' id='hidAirID_"+IDAirport+
//                        "' value='"+IDAirport+"' /><input type='hidden' id='hidAirLaT_"+IDAirport+"' value='"+AirLaT+"' /><input type='hidden' id='hidAirLoN_"+IDAirport+"' value='"+AirLoN+"' /><input type='hidden' id='hidAirName_"+IDAirport+"' value='"+name+"' /></td></table>"
//    
//    }else
//        {
//        Newcell.width = '200px'
//	    Newcell.align = 'left';
//         Newcell.innerHTML = "<table cellspacing = 0 cellpadding = 0 width='200px' border ='0'><td id='Air_cell_0_"+Newrow.id+"' align ='left' width='25'><img id='_MIconAir_"+IDAirport+"' src='ImageMarkerOnMap.aspx?MarkerNumber=" +Newrow.id+"&MarkerName=icon_number_airport.png' /></td><td id='Air_cell_1_"+Newrow.id+"' align ='left' width='20'><input type='radio'id='RaDAir_"+IDAirport+"' "+name+" name='RaDAir' onclick='javascript:_ClicKAirPort("+IDAirport+");'/></td><td align ='left' width='160px'>"+name+"<input type='hidden' id='hidAirID_"+IDAirport+
//                        "' value='"+IDAirport+"' /><input type='hidden' id='hidAirLaT_"+IDAirport+"' value='"+AirLaT+"' /><input type='hidden' id='hidAirLoN_"+IDAirport+"' value='"+AirLoN+"' /><input type='hidden' id='hidAirName_"+IDAirport+"' value='"+name+"' /></td></table>"
//       
//        }
//    
//        if(Air_Id_SelecTS.length >0 )
//        {
//            for(var i=0;i< Air_Id_SelecTS.length;i++)
//            {
//                if (Air_Id_SelecTS[i]==IDAirport)
//                {
//                    document.getElementById("RaDAir_"+IDAirport).checked = true;
//          
//                }
//            }
//            
//        }

//}

//function ClicKAirPort(_Id)
//{
////alert("_IdAiR:"+document.getElementById("hidAirID_"+_Id).value+"|NameAiR:"+document.getElementById("hidAirName_"+_Id).value+"|AiR_LaT:"+document.getElementById("hidAirLaT_"+_Id).value+"|AiR_LoN:"+document.getElementById("hidAirLoN_"+_Id).value)
//_AddPointAiR(_Id);
//}
function _AddPointAiR(_Id)
{

     var airports = Data_Airports; 
    // alert("airports.id.length:"+airports.id.length)
    map.clearOverlays();
    for (j = 0; j < airports.id.length; j++) 
    {
       
        var FillAirportLat = airports.latitude[j];
        var FillAirportLng = airports.longitude[j];  


        var gIcon = new GIcon(G_DEFAULT_ICON);     
            gIcon.iconSize = new GSize(32,41);  
          if(j >1){
                    gIcon.image = "ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=marker_airport.png";
                    document.getElementById("MIconAir_"+airports.id[j]).src="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=icon_number_airport.png";
                    }
                 
         if (airports.id[j] == _Id)
            {  
                gIcon.iconSize = new GSize(32,41);              
                gIcon.image = "ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=marker_airport_select.png";
                document.getElementById("MIconAir_"+_Id).src="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=icon_number_airport_select.png";
              // alert("BB:"+marker_airport[j-2]+"||_Id:"+_Id)
              
               Air_Id_SelecT=airports.id[j];
              Air_Name_SelecT=airports.description[j];
              Air_Id_SelecTS[index_airport]=airports.id[j];
             
            
              Tatol_airport[index_airport]=airports.description[j]+"\x09"+FillAirportLat+"\x09"+FillAirportLng;
            
             
            }
           
            
            
        var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),{title:airports.description[j],icon:gIcon});       
        map.addOverlay(marker);       

     }            

     
}



function Checkgooglemap()
{
    document.getElementById("IFr_SMap").style.display="none";
    document.getElementById("Detail_IcoN").style.display="none";
}

function GetCity_Map(Lat,Lon)
{
    document.getElementById('SMap_1').contentWindow.Msubmit(Lat,Lon);
}

function _ReturnIFr()
{
    if(City_Center_LaT !="" || City_Center_LoN !="")
    {
    document.getElementById('SMap_1').contentWindow.Msubmit(City_Center_LaT,City_Center_LoN);
    }
    else
    {
     document.getElementById('SMap_1').contentWindow.Msubmit("52.373056","4.892222");
    }
}

function GetHotel_Map(Lat,Lon)
{
try{

initialize();
LoadMapHoteldetail(BMhotelDetail,Lat,Lon)
//set buttom
toggleState=1;
document.getElementById("LinkMaP").innerHTML="ShowMap";
document.getElementById('SMap_1').contentWindow.SelectIcon();
document.getElementById('SMap_1').contentWindow.Msubmit(Lat,Lon);
    if(document.getElementById('Check_Itemp').value =='PrivatAir')
      {document.getElementById('map').style.display="none"; }
 }
 catch(err)
        {
        
        }
 
}

function Check_hide()
{
//cbxAirport.style.display='none';
}

function _SetAirRoutes(mAirRoutes)
{
    if(mAirRoutes!=''){
    var datas=mAirRoutes.split("\x09");
    document.getElementById("TAirRoutes").style.display="";
    document.getElementById("AirRoutes_Strat").innerHTML=datas[1];
    document.getElementById("AirRoutes_End").innerHTML=datas[2];

    }
  if(document.getElementById("LoCalAir").options.length==0){LoadCbOLocal();}
}

function LoadCbOLocal()
{
document.getElementById("TdataLocal").style.display="none";
document.getElementById("LoCalAir").options[document.getElementById("LoCalAir").options.length] = new Option("",0);
if (Data_AirportsName.length>0 )
    {
         for(var i=0;i<Data_AirportsName.length;i++)
        {
           var option = new Option(Data_AirportsName[i], i+1);
           document.getElementById("LoCalAir").options[document.getElementById("LoCalAir").options.length] = option;
        } 
    }
     
   
      
}

function ChanGLocal()
{

 _ClearTb("TbAirFroM");
 _ClearTb("TbAirTo");
    if(Data_AirportsTotal.length >0)
    {
        if( document.getElementById("LoCalAir").value ==1)
        {
           document.getElementById("DAirFroM").style.display="";
           document.getElementById("DAirTo").style.display="none";
           Data_AiR=Data_AirportsTotal[0];
           LocalNamE="AirRoutes_Strat";
           LoadData_Airport(Data_AirportsTotal[0],"TbAirFroM");
        
        }else if(document.getElementById("LoCalAir").value ==2)
            {
              document.getElementById("DAirTo").style.display="";
              document.getElementById("DAirFroM").style.display="none";
               Data_AiR=Data_AirportsTotal[1];
               LocalNamE="AirRoutes_End";
              LoadData_Airport(Data_AirportsTotal[1],"TbAirTo");
            }
            else if(document.getElementById("LoCalAir").value ==0)
            {
              document.getElementById("DAirFroM").style.display="none";
              document.getElementById("DAirTo").style.display="none";
              PopUpAirportFillTable2();
            }
    
    }
    
}


function LoadData_Airport(Mdata,Tbname)
{

    var Pcenter_Lat=0;
    var Pcenter_Lon=0;
    
    var airports = Mdata ;
    initialize();//***
    var C=0;
    
    if (airports.id.length > 0)
    {
        for (i = 1; i < airports.id.length; i++) 
        {
       
           
            if (i>1)
            {
            _AddAIrPort(i-1,airports.description[i],airports.id[i],airports.latitude[i],airports.longitude[i],Tbname)
         
             }
         }
             
                    for (j = 2; j < airports.id.length; j++) 
                    {

                    var gIcon = new GIcon(G_DEFAULT_ICON);     
                    gIcon.iconSize = new GSize(32,41);  
                    gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(C+1)+"&MarkerName=marker_airport.png"; 
                        
                        
                        if(Air_Id_SelecTS.length >0 )
                             {
                                
                                        if (Air_Id_SelecTS[0]==airports.id[j]||Air_Id_SelecTS[1]==airports.id[j])
                                            {
                                           
                                                 gIcon.iconSize = new GSize(32,41);              
                                                 gIcon.image ="ImageMarkerOnMap.aspx?MarkerNumber=" +(C+1)+"&MarkerName=marker_airport_select.png";  
                    
                                                 document.getElementById("RaDAir_"+airports.id[j]).checked = true;//select radio 
                                                 document.getElementById("_MIconAir_"+airports.id[j]).src='ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=icon_number_airport_select.png';//select Icon
                   
                                                // Air_Id_SelecTS[index_airport]=airports.id[j];
                                                 Air_Id_SelecT=airports.id[j];
                                                 Air_Name_SelecT=airports.description[j];
              
                                                 Pcenter_Lat=airports.latitude[j] 
                                                 Pcenter_Lon=airports.longitude[j]
                                                 Tatol_airport[index_airport]=airports.description[j]+"\x09"+airports.latitude[j]+"\x09"+airports.longitude[j]
             
          
                                            }
                                   
            
                              }
                        
                        
                         
                        C=C+1;
        
                         var FillAirportLat = airports.latitude[j];
                         var FillAirportLng = airports.longitude[j];      
                         var FillAirportTitle = airports.description[j];  
                         var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),
                                        {title:airports.description[j], icon:gIcon});  
                               
            map.addOverlay(marker); 

       
        var x = airports.latitude[2];
        var y = airports.longitude[2];
          
        var maxLat = Math.max(x,airports.latitude[j]);
        var maxLng = Math.max(y,airports.longitude[j]);       
        var minLat = Math.min(x,airports.latitude[j]);
        var minLng = Math.min(y,airports.longitude[j]); 
        }
        var swLatLng = new GLatLng(minLat,minLng);   
        var neLatLng = new GLatLng(maxLat,maxLng);
           
        var center = new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2);
      
        var getBound=new GLatLngBounds(swLatLng, neLatLng); 
     
    try
        {
            if (map.getBoundsZoomLevel(getBound)> getZoom)
                {
              
                   //--------set center map--------
                    if (Pcenter_Lat!=0 && Pcenter_Lon!=0)
                    {
                     map.setCenter(new GLatLng(Pcenter_Lat, Pcenter_Lon),getZoom) 
                     }else
                    {
                     map.setCenter(center, getZoom);
                     }
              
                
                }
            else
                {   
                 
                //--------set center map--------
                     if (Pcenter_Lat!=0 && Pcenter_Lon!=0)
                     {
                     map.setCenter(new GLatLng(Pcenter_Lat, Pcenter_Lon),map.getBoundsZoomLevel(getBound)-2) 
                     }else
                   {
                 //  alert(map.getBoundsZoomLevel(getBound)-1)
                       map.setCenter(center, map.getBoundsZoomLevel(getBound)-2);
                     }
                  
              
                }  
                          
        }
        catch(err)
        {
        var txtErr = err;
        alert(txtErr);
        }
//***************Zoom-To-Fit All Markers***************//            
    }
             
             
        return ;
     }
     
     
     function _ClicKAirPort(_Id)
{

     var airports = Data_AiR; 
    // alert("airports.id.length:"+airports.id.length)
    map.clearOverlays();
    for (j = 0; j < airports.id.length; j++) 
    {
       
        var FillAirportLat = airports.latitude[j];
        var FillAirportLng = airports.longitude[j];  


        var gIcon = new GIcon(G_DEFAULT_ICON);     
            gIcon.iconSize = new GSize(32,41);  
          if(j >1){
                    gIcon.image = "ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=marker_airport.png";
                    document.getElementById("_MIconAir_"+airports.id[j]).src="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=icon_number_airport.png";
                  
                    }
                 
         if (airports.id[j] == _Id)
            {  
                gIcon.iconSize = new GSize(32,41);              
                gIcon.image = "ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=marker_airport_select.png"; 
                document.getElementById("_MIconAir_"+_Id).src="ImageMarkerOnMap.aspx?MarkerNumber=" +(j-1)+"&MarkerName=icon_number_airport_select.png";
                if(LocalNamE !=""){ document.getElementById(LocalNamE).innerHTML=airports.description[j];}
              Air_Id_SelecT=airports.id[j];
              Air_Name_SelecT=airports.description[j];
             // Air_Id_SelecTS[index_airport]=airports.id[j];
              
            Tatol_airport[index_airport]=airports.description[j]+"\x09"+FillAirportLat+"\x09"+FillAirportLng;
           
             
            }
           
            
            
        var marker = new GMarker(new GLatLng(FillAirportLat, FillAirportLng),{title:airports.description[j],icon:gIcon});       
        map.addOverlay(marker);       

     }            

     
}


function refesh_Clear_Image()
            {
             
                   var f = document.getElementById('Iframe1');
                  f.contentWindow.location.reload(true);
            }

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();

