var JOURNEY_ONEWAY_TYPE = 1;
var JOURNEY_RETURN_TYPE = 2;
var JOURNEY_ROUND_TYPE  = 3;

var bPageInitStage = true;
var xmlhttp = null;
var xmlhttpReady = true;
var iframeReady = false;
var curFunc = "";
var bJourneyTypeRequest = false;
var bXmlhttpSupported = false;

var id_type = 0;
var frm_leaving_ind = 0;

//var flightsDataReceived = new Array();
var timesDataReceived = new Array();

bXmlhttpSupported = isXmlhttpSupported();

function getXmlHttp()
{
    var oXmlHttp = null;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
// JScript gives us Conditional compilation, we can cope with old IE versions.
// and security blocked creation of the objects.
    try
    {
        oXmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try
        {
            oXmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E)
        {
            oXmlHttp = null;
        }
    }
@end @*/
    if (!oXmlHttp && typeof XMLHttpRequest != 'undefined')
    {
        try
        {
            oXmlHttp = new XMLHttpRequest();
        }
        catch (e)
        {
            oXmlHttp = null;
        }
    }

    return oXmlHttp;
}

function isXmlhttpSupported()
{
    if (getXmlHttp() == null) return false;
    return true;
}

function onJourneyTypeChange(type, radio)
{
    if ((bXmlhttpSupported && !xmlhttpReady) || (!bXmlhttpSupported && !iframeReady))
    {
        return;
    }

    if(!bPageInitStage && cur_radio == radio)
    {
        return;
    }

    bPageInitStage = false;

    if (durations[radio] > 0)
    {
        setUpAccommodations(radio);
    }
    else
    {
        clearSelect(getElem("accommodation_type"));
        hide(getElem(accommodationsDiv));
    }

    var arr = new Object();
    var elDepartureCityTable = getElem("departure_city_table");

    if ((type == 27) || (type == 28))
    {
        show(elDepartureCityTable);

        clearSelect(getElem("departure_city"));

        arr[0] = new ListItem("1", "Edinburgh (departing at 09:00)");
        arr[1] = new ListItem("2", "Glasgow (departing at 10:15)");

        setupSelect(getElem("departure_city"), arr);
    }
    else if (type == 25)
    {
        hide(elDepartureCityTable);

        clearSelect(getElem("departure_city"));
        arr[0] = new ListItem("", "");

        setupSelect(getElem("departure_city"), arr);
    }
    else if (types[radio] == 3)
    {
        show(elDepartureCityTable);
    }
    else
    {
        hide(elDepartureCityTable);
        clearSelect(getElem("departure_city"));
    }

    cur_radio = radio;
    cur_type = type;
    cur_mode = types[radio];        // id_type

    var obj_leaving_text = getElem("leaving_text");
    var obj_alternative_text = getElem("alternative_text");

    if (obj_leaving_text && obj_alternative_text)
    {
        if (cur_mode == 3)
        {
            hide(obj_leaving_text);
            show(obj_alternative_text);
        }
        else
        {
            show(obj_leaving_text);
            hide(obj_alternative_text);
        }
    }

    curFunc = "getLeavingPoints";
    sendRequest("ajax_library.asp?func=" + curFunc + "&id_type=" + cur_mode + "&id_journey_type=" + cur_type + "&id_afl=" + id_afl);
}

function onLeavingPointChange(bUsrSelect, lng)
{
    flightsDataReceived = new Array();
    timesDataReceived = new Array();

    if ((bXmlhttpSupported && !xmlhttpReady) || (!bXmlhttpSupported && !iframeReady))
    {
        return;
    }

    bUsrSelect = bUsrSelect || 0;

    if(bUsrSelect)
    {
        id_leaving = frm.leaving[frm.leaving.selectedIndex].value;
    }

    if (id_leaving == "N/A" && (typeof(frm.leaving[frm.leaving.selectedIndex + 1]) != "undefined"))
    {
        id_leaving = frm.leaving[frm.leaving.selectedIndex + 1].value;  
    }

    id_leaving = id_leaving || 0;

    cur_lng = lng;
    curFunc = "getJourneysDetails";

    sendRequest("ajax_library.asp?func=" + curFunc + "&lng=" + cur_lng + "&id_type=" + cur_mode + "&id_journey_type=" + cur_type + "&id_leaving=" + id_leaving + (id_afl && Number(id_afl) ? "&id_afl=" + id_afl : ""));
}

function getExtrasBooked(departure_date, departure_time, id_extra, id_journey)
{
    curFunc = "getExtrasBooked";
    sendRequest("ajax_library.asp?func=" + curFunc + "&departure_date=" + departure_date + "&departure_time=" + departure_time + "&id_extra=" + id_extra + "&id_journey=" + id_journey, false);
}

function checkForMinSize(id_route, date, time, tickets_amount)
{
    curFunc = "checkForMinSize";
    sendRequest("ajax_library.asp?func=" + curFunc + "&departure_date=" + date + "&departure_time=" + time + "&id_route=" + id_route + "&tickets_amount=" + tickets_amount, false);
}

function getRouteTimes(route_data, id_journey, date, id_season)
{
    id_season = id_season || 0;

    var requestData = route_data + "_" + id_journey + "_" + id_season + "_" + date;

    if (!inArr(timesDataReceived, requestData))
    {
        timesDataReceived.push(requestData);
        curFunc = "getRouteTimesForAllDates";
        sendRequest("ajax_library.asp?func=" + curFunc + "&route_data=" + route_data + "&id_journey=" + id_journey + "&id_season=" + id_season + "&date=" + date, false);
    }
}
/*
function getNextAvailableDate(routeData, idJourney, date)
{
    curFunc = "getNextAvailableDate";
    sendRequest("ajax_library.asp?func=" + curFunc + "&route_data=" + routeData + "&id_journey=" + idJourney + "&date=" + date, false);
}
*/
function getRouteFlights(route_data, id_journey, id_season, date)
{
    id_season = id_season || 0;

    curFunc = "getRouteFlights";
    sendRequest("ajax_library.asp?func=" + curFunc + "&route_data=" + route_data + "&id_journey=" + id_journey + "&id_season=" + id_season + "&date=" + date, false);
}

function getDiscountBooked(id_discount, id_journey, departure_date, departure_time, id_route, id_leaving, id_season)
{
    if (id_discount == 57)
    {
        curFunc = "getDiscountsBooked";
        var url = "ajax_library.asp?func=" + curFunc + "&id_discount=" + id_discount + "&id_journey=" + id_journey +
                  "&departure_date=" + departure_date + "&departure_time=" + departure_time + "&id_route=" + id_route + "&id_leaving=" + id_leaving + "&id_season=" + id_season;
        var async = true;
        var get = true;
        var postPayload = null;
        var span_id = null;

        sendAjaxRequest(url, procDiscountsBookedResponseData, async, get, postPayload, span_id);
    }
}

function getProviderCurrentTime()
{
    curFunc = "getProviderCurrentTime";
    sendRequest("ajax_library.asp?func=" + curFunc, false);
}

function sendRequest(url, async)
{
    url += "&randomnumber=" + new Date().getTime();

    if ((bXmlhttpSupported && !xmlhttpReady) || (!bXmlhttpSupported && !iframeReady))
    {
        return;
    }

    if (async == null)
    {
        async = true;
    }

    try
    {
        if (bXmlhttpSupported)
        {
            xmlhttp = getXmlHttp();
            xmlhttp.open("GET", url, async);

            try
            {
                if (xmlhttpReady == true)
                {
                    if (async)
                    {
                        xmlhttp.onreadystatechange = responseHandler;
                    }
                    else
                    {
                        xmlhttpReady = false;
                    }

                    xmlhttp.send(null);

                    if (!async)
                    {
                        xmlhttpReady = true;
                        eval(xmlhttp.responseText);
                    }
                }
            }
            catch(ex)
            {
            }
        }
        else if (iframeReady == true)
        {
            setIFrameReadyState(false);
            window.ifr.location.href = url;
        }
    }
    catch (e)
    {
    }
}

function responseHandler()
{
    if(xmlhttp.readyState == 4)
    {
        if (xmlhttp.status != 200)
        {
            xmlhttpReady = true;
            return;
        }

        if (xmlhttp.responseText == "")
        {
            xmlhttpReady = true;
            return;
        }

        var responseData = xmlhttp.responseText;

        eval(responseData);

        switch(curFunc)
        {
            case "getLeavingPoints":
            {
                procLeavingPointsResponseData(cur_type);

                curFunc = "";
                xmlhttpReady = true;
                bJourneyTypeRequest = true;

                onLeavingPointChange(0, cur_lng);
                hide(getElem("departure_points_loading_image"));
                break;
            }
            case "getJourneysDetails":
            {
                curFunc = "";
                xmlhttpReady = true;

                procJourneyDetailsResponseData();
                break;
            }
        }

        if(!bJourneyTypeRequest)
        {
            curFunc = "";
            xmlhttpReady = true;
        }
    }
    else
    {
        if (xmlhttp.readyState >= 0 && xmlhttp.readyState <= 3)
        {
            showWaitMessage();
        }

        xmlhttpReady = false;
    }
}

function procLeavingPointsResponseData(type)
{
    clearSelect(frm.leaving);

    var arr  = new Object();
    var vals = String(data[type].start_points).split(',');

    if(vals.length == 0)
    {
        return;
    }

    var enabled = new Object();
    var tmp_arr = String(data[type].enabled_points).split(',');

    for(var i in tmp_arr)
    {
        enabled[tmp_arr[i]] = true;
    }

    var count = 0;
    var flag = false;
    var b = false;

    for (var i in vals)
    {
        if (inArr(hiddenPoints, vals[i]))
        {
            continue;
        }

        if (vals[i].indexOf('**') == -1)
        {
            if(typeof(enabled[vals[i]]) != 'undefined')
            {
                var point_name = points[vals[i]] || pickup_points[vals[i]];

                arr[count]  = new ListItem(vals[i], unescapeHTML(unescape(point_name)));
                flag        = true;

                if(!b)
                {
                    id_leaving = vals[i];
                    b = true;
                }
            }
        }
        else if (vals[i] != '**null')
        {
            vals[i] = vals[i].substring(2,vals[i].length);
            arr[count] = new ListItem("-1", unescapeHTML(separators[vals[i]]));
        }
        else if (flag)
        {
            arr[count] = new ListItem("-1", unescapeHTML(separators[-1]));
        }

        count++;
    }

    if (st_point)
    {
        for(var i in arr)
        {
            if(arr[i].id == st_point)
            {
                id_leaving = arr[i].id;
                break;
            }
        }
    }

    setupSelect(frm.leaving, arr, (show_NA_by_deafult && getArrayLength(arr) > 1));
    enable(frm.leaving);

    if (st_point)
    {
        setSelected(frm.leaving, st_point);
        st_point = 0;
    }

    makeHighlighted(frm.leaving);
}

function procJourneyDetailsResponseData()
{
    if(bJourneyTypeRequest)
    {
        updatePage(cur_type, cur_radio);
        bJourneyTypeRequest = false;
    }
    else
    {
        switch(Number(cur_mode))
        {
            case 1:
            case 2:
            {
                updateTo(frm.going, frm.leaving);
                break;
            }
            case 3:
            {
                updateT3(frm.departure_time, frm.leaving, frm.departuring);
                break;
            }
        }
    }
}

function procDiscountsBookedResponseData(request)
{
    if (parseInt(request.responseText, 10) > 0)
    {
        try
        {
            getElem("frogbusTicketsAvailable").innerHTML = (parseInt(request.responseText, 10) >= 60 ? "" : request.responseText + " ");
            show(getElem("frogbus_special_fare"));
            hide(getElem("enter_discount_form"));
            getElem("discount").value = "Special fare";
        }
        catch(e)
        {
        }
    }
    else
    {
        try
        {
            getElem("frogbusTicketsAvailable").innerHTML = 0;
            hide(getElem("frogbus_special_fare"));
            show(getElem("enter_discount_form"));
            getElem("discount").value = "";
        }
        catch(e)
        {
        }
    }
}

function showWaitMessage()
{
    var arr = new Array();
    arr[0] = new ListItem("0", msg_loading);

    switch(cur_mode)
    {
        case 1:
        {
            show(getElem('table_1'));
            hide(getElem('f_returning'));
            hide(getElem('f_description'));
            show(getElem('f_going'));

            if (curFunc == "getLeavingPoints")
            {
                show(getElem("departure_points_loading_image"));
                clearSelect(frm.leaving);
                setupSelect(frm.leaving, arr);
            }

            show(getElem("destination_points_loading_image"));
            clearSelect(frm.going);
            setupSelect(frm.going, arr);
            break;
        }
        case 2:
        {
            show(getElem('table_1'));
            hide(getElem('f_description'));
            show(getElem('f_going'));
            show(getElem('f_returning'));

            if (curFunc == "getLeavingPoints")
            {
                show(getElem("departure_points_loading_image"));
                clearSelect(frm.leaving);
                setupSelect(frm.leaving, arr);
            }

            show(getElem("destination_points_loading_image"));
            clearSelect(frm.going);
            setupSelect(frm.going, arr);
            break;
        }
        case 3:
        {
            show(getElem('table_1'));
            hide(getElem('f_description'));
            hide(getElem('f_going'));
            hide(getElem('f_returning'));

            if (curFunc == "getLeavingPoints")
            {
                show(getElem("departure_points_loading_image"));
                clearSelect(frm.leaving);
                setupSelect(frm.leaving, arr);
            }
            break;
        }
    }
}

function callInProgress(xmlhttp)
{
    switch ( xmlhttp.readyState )
    {
        case 1, 2, 3:
            return true;
        break;

        // Case 4 and 0
        default:
            return false;
        break;
    }
}

function updateXmlHttpStatus()
{
    xmlhttpReady = !callInProgress(xmlhttp);
    //return callInProgress(xmlhttp);
}

function setIFrameReadyState(state)
{
    if (bXmlhttpSupported) return;

    iframeReady = state;
    if (iframeReady)
    {
        if (bPageInitStage)
        {
            onJourneyTypeChange(cur_type, cur_mode);
//            bPageInitStage = false;
        }
        else
        {
            var responseData = window.ifr.document.body.innerHTML;
            responseData = responseData.replace(/\n/g,"");

            if (responseData == "")
            {
                return;
            }

            eval(responseData);

            switch(curFunc)
            {
                case "getLeavingPoints":
                {
                    procLeavingPointsResponseData(cur_type);
                    curFunc = "";
//                    iframeReady = true;
                    bJourneyTypeRequest = true;

                    onLeavingPointChange(0, cur_lng);

                    break;
                }

                case "getJourneysDetails":
                {
                    procJourneyDetailsResponseData();
                    break;
                }
            }

            if (!bJourneyTypeRequest)
            {
                curFunc = "";
//                iframeReady = true;
            }
        }
    }
    else
    {
        showWaitMessage();
    }
}