﻿//var baseUrl = "http://www.delfin-tour.ru/TursSearchEngine/";
var sortUp = filesUrl + "up.gif";
var sortDn = filesUrl + "dn.gif";
var colCost1 = "Цена/заезд";
//var colCost2 = "Цена/сут от (руб)";
//var defaultRegion = "1003";

var costType = "1";
var cityRegionAr, curDate, costsAr, lengtsAr;
var tbl, turName;
var roomscategory, pansion, region, city, age, freePlace, sel_length, treatment, price, notFoundPlace, multiSel, labAddParams
function initVar() {
    roomscategory = document.getElementById("selRoomscategory");
    pansion = document.getElementById("selPansion");
    region = document.getElementById("selRegion");
    city = document.getElementById("selCity");
    tbl = document.getElementById("tbl");
    freePlace = document.getElementById("radFreePlace");
    age = document.getElementById("selAge");
    treatment = document.getElementById("cheTreatment");
    sel_length = document.getElementById("selLength");
    price = document.getElementById("selPrice");
    turName = document.getElementById("txtName");
    notFoundPlace = document.getElementById("NotFoundPlace");
    multiSel = document.getElementById("tdMultiSel");
    addParamName = document.getElementById("labAddParams");
}

function getQVar(name) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "-1";
    else {
        //alert(name + " = " + results[1]);
        return results[1];
    }
}
//roomscategory, pansion, age, freePlace, length, treatment, price1, price2;
//pan=-1&rc=-1&tr=on&mest=0&age=-1&le=-1&travel_start=28.02.2009&travel_end=01.07.2009&p1=-1&p2=-1
var initRegionVal = "0";

function fillSelRegion() {
    var tempCt = getQVar("country");
    if (tempCt == "-1")
        tempCt = defaultRegion;
    fillSelect(cityRegionAr, region, tempCt);
    selRegion_onchange();
}

var curCities;
function selRegion_onchange(noBack) {
    var selIndex = region.selectedIndex;
    if (region.selectedIndex < 0)
        return;
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    if ((window.backClick) && (noBack != 1)) backClick(); //////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    costType = cityRegionAr[selIndex].Type;
    fillSelect(curCities = cityRegionAr[selIndex].Cities, city, getQVar("ct"));
    fillSelect(cityRegionAr[selIndex].Pansions, pansion, getQVar("pn"));
    fillSelect(cityRegionAr[selIndex].RoomCategories, roomscategory, getQVar("rc"));
    fillSelect(cityRegionAr[selIndex].Lengths, sel_length, getQVar("len"));
    fillSelect(cityRegionAr[selIndex].Ages, age, getQVar("age"));
    addParamName.innerHTML = "" + cityRegionAr[selIndex].AddParamName;
    if (addParamName.innerHTML.length > 0) {
        multiSel.style.display = "";
        addParamName.innerHTML += ':';
    }
    else
        multiSel.style.display = "none";
    fillSelectAddParams(cityRegionAr[selIndex].AddParams, multiSel, getQVar("addPar"));
    fillSelectsCosts(cityRegionAr[selIndex].Id, getQVar("pr"));

    ifPodMoscowCase();
    //cityChanged();
}

function ifPodMoscowCase() {
    try {
        var td = document.getElementById("countryTD2").getElementsByTagName("td")[1];
        if (region.value == "1001")//Подмосковье
            td.innerHTML = "Шоссе:";
        else
            td.innerHTML = "Города и&nbsp; регионы:";
    }
    catch (e) { }
}

function initControls() {
    if (getQVar("mest") == "1") freePlace.checked = true;
    treatment.checked = (getQVar("tr") == "1");
    if (document.URL.indexOf("&ct=") < 0) {
        city.value = defaultCity;
    }
    if (getQVar("name") != "-1") {
        document.getElementById("txtName").value = decodeURIComponent(getQVar("name"));
    }
}

var isTitle = true;
var firstLoad = true;
var isOne = false;

function load() {
    if (!firstLoad)
        return;
    firstLoad = false;
    try {
        if (document.URL.indexOf("www.", 0) < 0) {
            filesUrl = filesUrl.replace('www.', '');
            baseUrl = baseUrl.replace('www.', '');
        }
    }
    catch (e) { /*alert("175 " + e);*/ }
    try {
        initDate(); //////////////////////////////////////////////////////////////////////////////////////////////////

        isOne = (document.URL.indexOf("one.html", 0) > 0 || document.URL.indexOf("one=1", 0) > 0);
        if (isOne) {
            document.getElementById("countryTD1").innerHTML = 'Города и регионы:<input name="country" id="hiddenRegion" type="hidden" />';
            document.getElementById("countryTD2").innerHTML = '<select name="ct" id="selCity" style="width: 130px"><option selected="selected" value="-1">Не важно</option></select>';
            document.getElementById("countryTD3").innerHTML = '<select id="selRegion" style="visibility: hidden"></select>';
        }
        isTitle = ((RedirectPath != "") && ((getQVar("country") == "-1") && document.URL.indexOf("name") < 0));
        // if (isTitle)
        //     initRegionDelfinVal = defaultRegion;

        initVar();
        initCities();

        cityRegionAr = eval(requireText(baseUrl + "CountryCity.php"));
        var t = requireText(baseUrl + "Costs.php")
        costsAr = eval(t.substring(t.indexOf("[")));

        fillSelRegion();
        initControls();
        initSort();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        if (window.zoomClick)
            if (!zoomClick(getQVar("mapid"), 1, getQVar("country"), getQVar("ct")))
            return;

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

        //        if (!isTitle)
        //            downloadTurs(3);

        // window.
        //window.scrollTo(0, 500);
        //        document.body.scrollIntoView(true);
        //        document.getElementById("grdWithScroll").scrollTop = 1000;
        //        alert(document.getElementById("grdWithScroll").scrollTop);
    }
    catch (e) {
        //alert("197 " + e);
        //if (lastErr != "err")
        // alert('Ошибка сервиса поисковика!');
    }
}
var curDate = "";
function initDate() {
    try {
        var ts = getQVar("travel_start");
        if (curDate == "")
            curDate = eval('[' + requireText(baseUrl + 'CurDate.php') + ']')[0];
        if (ts == "-1") {
            var d1 = Date.parse(curDate.Date).add({ month: eval(curDate.DateBegAdd) }).add({ days: 1 });
            var d2 = Date.parse(curDate.Date).add({ month: eval(curDate.DateEndAdd) }).add({ days: 1 });
            document.getElementById("dateST").value = d1.toString("dd.MM.yyyy");
            document.getElementById("dateEND").value = d2.toString("dd.MM.yyyy");
        }
        else {
            document.getElementById("dateST").value = ts;
            document.getElementById("dateEND").value = getQVar("travel_end");
        }
    }
    catch (e) { }
}

function initCities() {
    try { city.onchange = cityChanged; }
    catch (e) { }
}

function cityChanged() {
    try {
        for (var i = 0; i < curCities.length; i++) {
            var t = curCities[i].DateBegAdd;
            if ((curCities[i].Id.toString() == city.value) && (curCities[i].DateBegAdd != "")) {
                var d1 = Date.parse(curDate.Date).add({ month: eval(curCities[i].DateBegAdd) }).add({ days: 1 });
                var d2 = Date.parse(curDate.Date).add({ month: eval(curCities[i].DateEndAdd) }).add({ days: 1 });
                document.getElementById("dateST").value = d1.toString("dd.MM.yyyy");
                document.getElementById("dateEND").value = d2.toString("dd.MM.yyyy");
                return;
            }
        }
        initDate();
    }
    catch (e) { }
}

function checkLen(i) {
    var s = "" + i;
    return ((s.length == 2) ? s : ("0" + s));
}

function makeUrl(findType) {

    var paramStr = "";

    if ((findType == 3) && getQVar("name") != "-1") {
        paramStr += "?name=" + encodeURIComponent(getQVar("name").replace(/[\\\?\&\/@]/g, ''));
    }
    else {
        if (findType == 1) {
            //if (turName.value != "")
            paramStr += "?name=" + encodeURIComponent(turName.value.replace(/[\\\?\&\/@]/g, ''));
            if (isOne)
                paramStr += "&region=" + region.value;
        }
        else {

            var date1 = document.getElementById("dateST").value;
            var date2 = document.getElementById("dateEND").value;
            paramStr = "?date1=" + date1 + "&date2=" + date2;

            if (city.value != -1)
                paramStr += "&city=" + city.value;
            else if (region.value != -1)
                paramStr += "&region=" + region.value;

            if (pansion.value != -1)
                paramStr += "&pansion=" + pansion.value;

            if (roomscategory.value != -1)
                paramStr += "&roomscategory=" + roomscategory.value;

            if (treatment.checked)
                paramStr += "&treatment=1";

            if (freePlace.checked)
                paramStr += "&freePlace=1";

            if (age.value != -1)
                paramStr += "&age=" + age.value;

            if (sel_length.value != -1)
                paramStr += "&length=" + sel_length.value;

            if (price.value != -1) {
                paramStr += "&price1=" + price.value;
                for (i = 0; i < costsAr.length; i++) {
                    if (costsAr[i].Id == region.value) {
                        var arr = costsAr[i].Costs;
                        for (j = 0; j < arr.length; j++)
                            if (price.value == arr[j].Cost)
                            paramStr += "&price2=" + arr[j].CostTo;
                    }
                }
            }
            var agent = parseInt(getQVar("agent"), 10);
            if (agent > 0)
                paramStr += "&agent=" + agent;
            if (multiSel.simpleSel.value != "") {
                var arr = "";
                for (var i = 0; i < multiSel.simpleSel.options.length; i++) {
                    if (multiSel.simpleSel.options[i].selected)
                        arr += multiSel.simpleSel.options[i].value + "|";
                }
                paramStr += "&addPar=" + arr;
                //alert(arr);
            }

            try {
                var tstr = "" + location.href;
                sindex = (tstr.length > 199) ? 199 : tstr.length;
                paramStr += "&curl=" + escape(tstr.substring(0, sindex));
                if (location.href != parent.location.href) {
                    tstr = "" + parent.location.href;
                    sindex = (tstr.length > 199) ? 199 : tstr.length;
                    paramStr += "&parUrl=" + escape(tstr.substring(0, sindex));
                }
            } catch (e) { }

        }
    }

    var urlText = document.getElementById("urlText"); //.value = paramStr;
    if (urlText)
        urlText.value = "FindTur.php" + paramStr;
    //alert(baseUrl + "FindTur.php" + paramStr);
    return (baseUrl + "FindTur.php" + paramStr);
}

function keydown(event) {
    if (!event) var event = window.event;
    if ((13 == event.keyCode) || (13 == event.which)) {
        byNameKeydown = true;
        downloadTurs(1);
        event.cancelBubble = true;
        event.returnValue = false;
        if (event.stopPropagation) event.stopPropagation();
        if (event.preventDefault) event.preventDefault();
    }
}
var byNameKeydown = false;
function keydownAll(event) {
    if (!event) var event = window.event;
    if (((13 == event.keyCode) || (13 == event.which)) && !byNameKeydown) {
        downloadTurs(2);
        event.cancelBubble = true;
        event.returnValue = false;
        if (event.stopPropagation) event.stopPropagation();
        if (event.preventDefault) event.preventDefault();
    }
    byNameKeydown = false;
}
function getInput(name) {
    var els = document.getElementsByName(name);
    if (els.length > 0)
        return document.getElementsByName(name).item(0);
    return null;
}
function GoToAnotherRegion() {

    document.getElementById("hiddenRegion").value = region.value;

    var strUrl = document.URL;
    var exportIndex = eval(getQVar("export"));
    var isExport = ((strUrl.indexOf("/printe", 0) > 0) || (exportIndex > 0));

    if (exportIndex < 1)
        exportIndex = 1;
    if ((strUrl.indexOf("/printe3", 0) > 0))
        exportIndex = 3;
    var mapid = getInput("mapid");
    var haveMap = getQVar("map");
    var q = "country=" + getInput("country").value +
			"&ct=" + getInput("ct").value +
			"&pn=" + getInput("pn").value +
			"&rc=" + getInput("rc").value +
			"&len=" + getInput("len").value +
			"&age=" + getInput("age").value +
			"&travel_start=" + getInput("travel_start").value +
			"&travel_end=" + getInput("travel_end").value +
			"&pr=" + getInput("pr").value +
			"&tr=" + (getInput("tr").checked ? "1" : "-1") +
			"&mest=" + getInput("mest").value;
    if (price.value != -1) {
        q += "&price1=" + price.value;
        for (i = 0; i < costsAr.length; i++) {
            if (costsAr[i].Id == region.value) {
                var arr = costsAr[i].Costs;
                for (j = 0; j < arr.length; j++)
                    if (price.value == arr[j].Cost)
                    q += "&price2=" + arr[j].CostTo;
            }
        }
    }
    if (multiSel.simpleSel.value != "") {
        var arr = "";
        for (var i = 0; i < multiSel.simpleSel.options.length; i++) {
            if (multiSel.simpleSel.options[i].selected)
                arr += multiSel.simpleSel.options[i].value + "|";
        }
        q += "&addPar=" + arr;
        //alert(arr);
    }
    if (mapid != null && haveMap == "1")
        q += "&mapid=" + mapid.value + "&map=" + haveMap;

    if (isOne)
        q = q + "&one=1";
    if (isExport) {
        q = q + "&export=" + exportIndex;
        var agent = parseInt(getInput("agent").value, 10);
        if (agent > 0)
            q = q + "&agent=" + agent;
    }

    //q = q + "#FindForm";
    if (RedirectPath == "") {
        if (getQVar("id") != "-1")
            q = "id=" + getQVar("id") + "&" + q;
        if (getQVar("a") != "-1")
            q = "a=" + getQVar("a") + "&" + q;
        var i = document.URL.indexOf("?", 0);
        if (i > 0)
            window.location = document.URL.substring(0, i) + "?" + q;
        else
            window.location = document.URL + "?" + q;
    }
    else
        window.location = RedirectPathAr[getInput("country").value] + (RedirectPathAr[getInput("country").value].indexOf("?") >= 0 ? "&" : "?") + q;
}

function downloadTurs(findType) {

    //alert("" + isTitle + " " + initRegionVal + " != " + region.value + "  " + findType);
    if (/*((isTitle) || (initRegionVal != region.value)) &&*/(findType == 2) && !window.noReload) {
        GoToAnotherRegion();
        return;
    }

    if (findType == 1) {
        window.location = RedirectPathAr[region.value] + (RedirectPathAr[region.value].indexOf("?") >= 0 ? "&" : "?") + "name=" + encodeURIComponent(turName.value.replace(/[\\\?\&\/@]/g, ''));
        return;
    }
    //    if (findType == 1) costType = "1";
    //    if (getQVar("name") != "-1")
    //        findType = 1;
    //    document.getElementById("wait").style.display = "";
    //    document.getElementById("findByName").disabled = "disabled";
    //    document.getElementById("findByParam").disabled = "disabled";
    //    try {
    //        requireTextAsin(makeUrl(findType));
    //    }
    //    catch (e) {
    //        // alert("304 " + e);
    //    }
}

function downloadTursDone(text, status) {
    var Turs;
    try {
        Turs = eval("[" + text + "]")[0];
    }
    catch (e) {//alert("313 " + e);
        // if (lastErr != "err")
        //   alert('Ошибка сервиса поисковика!');
    }
    try {
        if (fillTbl(Turs))
            initSort();
    }
    catch (e) {
        //alert("322 " + e);
    }
    document.getElementById("findByName").disabled = "";
    document.getElementById("findByParam").disabled = "";
    document.getElementById("wait").style.cssText = "display:none;text-align:center";
    if ((getQVar("mapid") != "-1") && (city.value != "-1"))
        window.scrollTo(0, document.getElementById("myMap").scrollHeight - 250);
}
var NotFoundTxt = "";
function showNotFound() {
    try {
        if (NotFoundTxt == "") {
            NotFoundTxt = requireText(filesUrl + "NotFound.inc");
            if (lastErr != "err") notFoundPlace.innerHTML = NotFoundTxt;
        }
    }
    catch (e) { }

    tbl.style.display = "none";
    notFoundPlace.style.cssText = "";
}
function hideNotFound() {
    tbl.style.display = "";
    notFoundPlace.style.cssText = "display:none;";
}

function fillTbl(Turs) {
    if (Turs == null) {
        showNotFound(); return false;
    }
    if ((Turs.Rest.length + Turs.Excursion.length + Turs.HotelReservation.length + Turs.Fiery.length + Turs.Recom.length + Turs.Usual.length) <= 0) {
        showNotFound(); return false;
    }
    hideNotFound();

    document.getElementById("ColCostTH").innerText = colCost1; //(costType == "1") ? colCost1 : colCost2;

    var strUrl = document.URL;
    var exportIndex = eval(getQVar("export"));
    var isExport = ((strUrl.indexOf("/printe", 0) > 0) || (exportIndex > 0));

    if (exportIndex < 1)
        exportIndex = 1;
    if ((strUrl.indexOf("/printe3", 0) > 0))
        exportIndex = 3;

    fillTblBody(Turs.Fiery, 1, isExport, exportIndex);
    fillTblBody(Turs.Recom, 3, isExport, exportIndex);
    fillTblBody(Turs.Rest, (costType == "1") ? 7 : 5, isExport, exportIndex);
    fillTblBody(Turs.Excursion, (costType == "1") ? 5 : 7, isExport, exportIndex);
    fillTblBody(Turs.HotelReservation, 9, isExport, exportIndex);
    fillTblBody(Turs.Usual, 11, isExport, exportIndex);

    document.getElementById("group1").innerHTML = (costType == "1") ? "Экскурсионные туры" : "Отдых";
    document.getElementById("group2").innerHTML = (costType == "1") ? "Отдых" : "Экскурсионные туры";

    //	if ((Turs.Fiery.length + Turs.Recom.length) <= 0)
    //		tbl.tBodies.item(6).style.cssText = "display:none;";
    return true;
}

var sortType = ["123", "abc", "123", "123"];
function fillTblBody(Turs, index, isExport, exportIndex) {
    var tblBody = document.createElement("tbody");
    tblBody.className = tbl.tBodies.item(index).className;

    if (Turs.length <= 0)
        tbl.tBodies.item(index - 1).style.cssText = "display:none;";
    else
        tbl.tBodies.item(index - 1).style.cssText = "";

    for (j = 0; j < Turs.length; j++) {
        var tur = Turs[j];
        row = document.createElement("tr");
        row.className = (((j % 2) == 1) ? "tblEvenRow" : "tblOddRow");


        var cell;


        //row.appendChild(newElement("td", (tur.FreePlaces == "") ? "по запросу" : tur.FreePlaces));
        var k = 0;
        cell = newElement("td");
        if (tur.FreePlaces == 0) {//по запросу
            cell.className = "place_byRequest"; k = 2;
        }
        else if (eval(tur.FreePlaces) < 0) {//нет мест
            cell.className = "place_no"; k = 3;
        }
        else if (eval(tur.FreePlaces) == 1) {//одно место
            cell.className = "place_one"; k = 1;
        }
        else
            cell.className = "place_available"; //много мест
        cell.setAttribute("sorttable_customkey", "" + k);
        row.appendChild(cell);

        cell = document.createElement("td");


        var url = wwwRoot + TurPage + tur.Url;
        if (isExport) {
            url = url + "&export=" + exportIndex;
            var agent = parseInt(getQVar("agent"), 10);
            if (agent > 0)
                url = url + "&agent=" + agent;
        }

        cell.appendChild(newElement("a", tur.TurName, "href", url));
        cell.className = "turNameCol";
        row.appendChild(cell);

        var nday = eval(tur.NDay);
        row.appendChild(newElement("td", ((nday == 1) || (nday == 2)) ? "любая" : (Math.abs(nday).toString() + "д."), "sorttable_customkey",
                                         ((nday == 1) || (nday == 2)) ? "0" : Math.abs(nday).toString()));

        cell = document.createElement("td");
        if (index == 1)//старая цена для горящих туров
        {//&nbsp;&nbsp;
            var oldPrSpan = newElement("span", tur.OldFieryCost, "price", tur.OldFieryCost);
            oldPrSpan.style.textDecoration = "line-through";
            oldPrSpan.style.color = "Red";
            oldPrSpan.title = "Старая цена";
            //oldPrSpan.setAttribute("style", "text-decoration: line-through; color:Red");
            cell.appendChild(oldPrSpan);
            cell.appendChild(document.createTextNode("  "));
        }

        var el = newElement("a", null, "href", url + "#price");
        el.appendChild(newElement("span", tur.Cost, "price", tur.Cost));
        cell.appendChild(el);
        row.appendChild(cell);

        tblBody.appendChild(row);
    }
    //makeStripe(tblBody);
    tbl.replaceChild(tblBody, tbl.tBodies.item(index));
}

function calcPrices(priceType) {
    try {
        var imgs = document.getElementById("currencies").getElementsByTagName("img");
        for (var i = 0; i < imgs.length; i++) { imgs[i].height = 11; imgs[i].width = 16; }
        imgs[priceType + 1].height = 20; imgs[priceType + 1].width = 29;
        var priceSpans = document.getElementById("tbl").getElementsByTagName("span");
        if (priceType == -1)
            document.getElementById("currencyVal").innerHTML = " (конвертирование по курсу: <b>1</b> RUR/RUR)";
        else
            document.getElementById("currencyVal").innerHTML = " (конвертирование на " + currencies[priceType].Date + " по курсу ЦБ РФ-1%: <b>" + currencies[priceType].Value + " </b> " + currencies[priceType].Code + "/RUR)";

        var cur = (priceType == -1) ? 1.0 : eval(currencies[priceType].Value);
        for (var i = 0; i < priceSpans.length; i++) {
            var price = eval(priceSpans[i].getAttribute("price"));
            if (price)
                priceSpans[i].innerHTML = "" + parseInt(price / cur);
        }
    }
    catch (e) {
        //alert(e);
    }
}
var currencies;
function initCurrencies() {
    try {
        var currenciesDiv = document.getElementById("currencies");
        for (var i = 0; i < currencies.length; i++) {
            var el = newElement("img", null, "src", baseUrl + currencies[i].ImgUrl);
            el.setAttribute("title", currencies[i].Name);
            el.style.cursor = "pointer";
            eval("el.onclick = function() { calcPrices(" + i + "); };");
            currenciesDiv.appendChild(document.createTextNode("  "));
            currenciesDiv.appendChild(el);
        }
        var el = newElement("span", null, "id", "currencyVal");
        el.innerHTML = " (конвертирование по курсу: <b>1</b> RUR/RUR)";
        currenciesDiv.appendChild(el);
        currenciesDiv.style.display = "";
    }
    catch (e) {
        //alert(e);
    }
}

function newElement(type, text, attrName, attrVal) {
    var cell = document.createElement(type);
    if (text != null)
        cell.appendChild(document.createTextNode(text))
    if (attrName != null)
        cell.setAttribute(attrName, attrVal);
    return cell;
}

var initSelectHtml = "";
function fillSelectAddParams(arr, sel, ids) {
    if (initSelectHtml == "")
        initSelectHtml = sel.innerHTML;
    else
        sel.innerHTML = initSelectHtml;
    sel.simpleSel = sel.getElementsByTagName("select")[0];
    for (i = 0; i < arr.length; i++) {
        addOption(sel.simpleSel, arr[i].Name, arr[i].Id, compareIds(arr[i].Id, ids));
    }
    a$.multiSelectCreate(sel.simpleSel);
}

function compareIds(id, ids) {
    try {
        var idsAr = unescape(ids).split('|');
        for (var j = 0; j < idsAr.length; j++) {
            if (idsAr[j] == id)
                return true;
        }
    }
    catch (e) {
        //alert(e);
    }
    return false;
}

function fillSelect(arr, sel, id) {
    clearSelect(sel);
    for (i = 0; i < arr.length; i++) {
        addOption(sel, arr[i].Name, arr[i].Id, (arr[i].Id == id));
    }
}

function fillSelectsCosts(IdReg, cost) {
    try {
        for (i = 0; i < costsAr.length; i++) {
            if (costsAr[i].Id == IdReg) {
                clearSelect(price);
                var arr = costsAr[i].Costs;
                for (j = 0; j < arr.length; j++)
                    addOption(price, arr[j].Name, arr[j].Cost, (arr[j].Cost == cost));
            }
        }
    }
    catch (e) {
        // alert("462 " + e);
    }
}

function addOption(oListbox, text, value, isSelected) {
    var oOption = document.createElement("option");
    oOption.appendChild(document.createTextNode(text));
    oOption.setAttribute("value", value);
    if (isSelected) oOption.selected = true;
    oListbox.appendChild(oOption);
}

function clearSelect(oListbox) {
    try {
        for (var i = oListbox.options.length - 1; i >= 1; i--)
            oListbox.remove(i);
    }
    catch (e) { /*alert("479 " + e);*/ }
};

function requireText(url) {
    res = "";
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest;
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("MSXML2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                document.getElementById("NoActiveX").style.cssText = "";
            }
        }
    } else {
        //alert("Your browser doesn't support AJAX1");
        return;
    }

    if (req) {
        req.open("GET", url, false);
        req.send(null);
        res = req.responseText;
        lastErr = "ok";
    }
    if (req.status != 200) {
        // alert('Сервис поисковика "' + url + '" недоступен1!');
        lastErr = "err";
    }
    return res;
}
var lastErr = "ok";

function requireTextAsin(url) {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest;
    } else if (window.ActiveXObject) {
        try {
            req = new ActiveXObject("MSXML2.XMLHTTP");
        } catch (e) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) { }
        }
    } else {
        //alert("Your browser doesn't support AJAX2");
        return;
    }

    // Create a function that will receive data sent from the server
    req.onreadystatechange = function() {
        if (req.readyState == 4) {
            lastErr = "ok";
            if (req.status != 200) {
                // alert('Сервис поисковика недоступен2!');
                lastErr = "err";
            }
            downloadTursDone(req.responseText, req.status);
        }
    }
    req.open("GET", url, true);
    req.send(null);
}

var stIsIE = /*@cc_on!@*/false;

var first = true;
function initSort() {
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;
    sorttable.makeSortable(document.getElementById('tbl'));
}

sorttable = {

    makeSortable: function(table) {
        // Safari doesn't support table.tHead, sigh
        if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];

        sortbottomrows = [];
        for (var i = 0; i < table.rows.length; i++) {
            if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {
                sortbottomrows[sortbottomrows.length] = table.rows[i];
            }
        }
        if (sortbottomrows) {
            if (table.tFoot == null) {
                // table doesn't have a tfoot. Create one.
                tfo = document.createElement('tfoot');
                table.appendChild(tfo);
            }
            for (var i = 0; i < sortbottomrows.length; i++) {
                tfo.appendChild(sortbottomrows[i]);
            }
            delete sortbottomrows;
        }

        headrow = table.tHead.rows[0].cells;

        for (var i = 0; i < headrow.length; i++) {
            // manually override the type with a sorttable_type attribute
            if (!headrow[i].className.match(/\bsorttable_nosort\b/)) { // skip this col
                mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);
                if (mtch) { override = mtch[1]; }
                if (mtch && typeof sorttable["sort_" + override] == 'function') {
                    headrow[i].sorttable_sortfunction = sorttable["sort_" + override];
                } else {
                    headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);
                }
                // make it clickable to sort
                headrow[i].sorttable_columnindex = i;
                headrow[i].sorttable_tbody = table.tBodies[2];
                headrow[i].sorttable_tbody1 = table.tBodies[4];
                headrow[i].sorttable_tbody2 = table.tBodies[6];
                headrow[i].sorttable_tbody3 = table.tBodies[8];
                headrow[i].sorttable_tbody4 = table.tBodies[10];
                headrow[i].sorttable_tbody5 = table.tBodies[12];
                if (first)
                    dean_addEvent(headrow[i], "click", cellClick);
            }
        }
        first = false;
    },

    guessType: function(table, column) {
        // guess the type of a column based on its first non-blank row
        sortfn = sorttable.sort_alpha;
        //for (var i = 0; i < table.tBodies[1].rows.length; i++) {
        text = sortType[column]; //sorttable.getInnerText(table.tBodies[1].rows[i].cells[column]);
        if (text != '') {
            if (text.match(/^-?[Ј$¤]?[\d,.]+%?$/)) {
                return sorttable.sort_numeric;
            }
            // check for a date: dd/mm/yyyy or dd/mm/yy 
            // can have / or . or - as separator
            // can be mm/dd as well

            possdate = text.substr(0, 5).match(sorttable.DATE_RE)
            if (possdate) {
                // looks like a date
                first = parseInt(possdate[1]);
                second = parseInt(possdate[2]);
                if (first > 12) {
                    // definitely dd/mm
                    return sorttable.sort_ddmm;
                } else if (second > 12) {
                    return sorttable.sort_mmdd;
                } else {
                    // looks like a date, but we can't tell which, so assume
                    // that it's dd/mm (English imperialism!) and keep looking
                    sortfn = sorttable.sort_ddmm;
                }
            }
        }
        //}
        return sortfn;
    },

    getInnerText: function(node) {
        // gets the text we want to use for sorting for a cell.
        // strips leading and trailing whitespace.
        // this is *not* a generic getInnerText function; it's special to sorttable.
        // for example, you can override the cell text with a customkey attribute.
        // it also gets .value for <input> fields.

        hasInputs = (typeof node.getElementsByTagName == 'function') &&
                 node.getElementsByTagName('input').length;

        if (node.getAttribute("sorttable_customkey") != null) {
            return node.getAttribute("sorttable_customkey");
        }
        else if (typeof node.textContent != 'undefined' && !hasInputs) {
            return node.textContent.replace(/^\s+|\s+$/g, '');
        }
        else if (typeof node.innerText != 'undefined' && !hasInputs) {
            return node.innerText.replace(/^\s+|\s+$/g, '');
        }
        else if (typeof node.text != 'undefined' && !hasInputs) {
            return node.text.replace(/^\s+|\s+$/g, '');
        }
        else {
            switch (node.nodeType) {
                case 3:
                    if (node.nodeName.toLowerCase() == 'input') {
                        return node.value.replace(/^\s+|\s+$/g, '');
                    }
                case 4:
                    return node.nodeValue.replace(/^\s+|\s+$/g, '');
                    break;
                case 1:
                case 11:
                    var innerText = '';
                    for (var i = 0; i < node.childNodes.length; i++) {
                        innerText += sorttable.getInnerText(node.childNodes[i]);
                    }
                    return innerText.replace(/^\s+|\s+$/g, '');
                    break;
                default:
                    return '';
            }
        }
    },

    reverse: function(tbody) {
        // reverse the rows in a tbody
        newrows = [];
        for (var i = 0; i < tbody.rows.length; i++) {
            newrows[newrows.length] = tbody.rows[i];
        }
        for (var i = newrows.length - 1; i >= 0; i--) {
            tbody.appendChild(newrows[i]);
        }
        delete newrows;
    },

    /* sort functions
    each sort function takes two parameters, a and b
    you are comparing a[0] and b[0] */
    sort_numeric: function(a, b) {
        aa = parseFloat(a[0].replace(',','.').replace(/[^0-9.-]/g, ''));
        if (isNaN(aa)) aa = 0;
        bb = parseFloat(b[0].replace(',', '.').replace(/[^0-9.-]/g, ''));
        if (isNaN(bb)) bb = 0;
        return aa - bb;
    },
    sort_alpha: function(a, b) {
        if (a[0] == b[0]) return 0;
        if (a[0] < b[0]) return -1;
        return 1;
    },
    sort_ddmm: function(a, b) {
        mtch = a[0].match(sorttable.DATE_RE);
        y = mtch[3]; m = mtch[2]; d = mtch[1];
        if (m.length == 1) m = '0' + m;
        if (d.length == 1) d = '0' + d;
        dt1 = y + m + d;
        mtch = b[0].match(sorttable.DATE_RE);
        y = mtch[3]; m = mtch[2]; d = mtch[1];
        if (m.length == 1) m = '0' + m;
        if (d.length == 1) d = '0' + d;
        dt2 = y + m + d;
        if (dt1 == dt2) return 0;
        if (dt1 < dt2) return -1;
        return 1;
    },
    sort_mmdd: function(a, b) {
        mtch = a[0].match(sorttable.DATE_RE);
        y = mtch[3]; d = mtch[2]; m = mtch[1];
        if (m.length == 1) m = '0' + m;
        if (d.length == 1) d = '0' + d;
        dt1 = y + m + d;
        mtch = b[0].match(sorttable.DATE_RE);
        y = mtch[3]; d = mtch[2]; m = mtch[1];
        if (m.length == 1) m = '0' + m;
        if (d.length == 1) d = '0' + d;
        dt2 = y + m + d;
        if (dt1 == dt2) return 0;
        if (dt1 < dt2) return -1;
        return 1;
    },

    shaker_sort: function(list, comp_func) {
        // A stable sort function to allow multi-level sorting of data
        // see: http://en.wikipedia.org/wiki/Cocktail_sort
        // thanks to Joseph Nahmias
        var b = 0;
        var t = list.length - 1;
        var swap = true;

        while (swap) {
            swap = false;
            for (var i = b; i < t; ++i) {
                if (comp_func(list[i], list[i + 1]) > 0) {
                    var q = list[i]; list[i] = list[i + 1]; list[i + 1] = q;
                    swap = true;
                }
            } // for
            t--;

            if (!swap) break;

            for (var i = t; i > b; --i) {
                if (comp_func(list[i], list[i - 1]) < 0) {
                    var q = list[i]; list[i] = list[i - 1]; list[i - 1] = q;
                    swap = true;
                }
            } // for
            b++;

        } // while(swap)
    }
}

function dean_addEvent(element, type, handler) {
    var c = document.createElement("center");
    c.innerHTML = '<img src="' + sortUp + '" title="В алфавитном порядке"/><img src="' + sortDn + '" title="В обратном порядке"/>';
    element.appendChild(c);
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    } else {
        // assign each event handler a unique ID
        if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;
        // create a hash table of event types for the element
        if (!element.events) element.events = {};
        // create a hash table of event handlers for each element/event pair
        var handlers = element.events[type];
        if (!handlers) {
            handlers = element.events[type] = {};
            // store the existing event handler (if there is one)
            if (element["on" + type]) {
                handlers[0] = element["on" + type];
            }
        }
        // store the event handler in the hash table
        handlers[handler.$$guid] = handler;
        // assign a global event handler to do all the work
        element["on" + type] = handleEvent;
    }
};
// a counter used to create unique IDs
dean_addEvent.guid = 1;


function handleEvent(event) {
    var returnValue = true;
    // grab the event object (IE uses a global event object)
    event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
    // get a reference to the hash table of event handlers
    var handlers = this.events[event.type];
    // execute each event handler
    for (var i in handlers) {
        this.$$handleEvent = handlers[i];
        if (this.$$handleEvent(event) === false) {
            returnValue = false;
        }
    }
    return returnValue;
};

function fixEvent(event) {
    // add W3C standard event methods
    event.preventDefault = fixEvent.preventDefault;
    event.stopPropagation = fixEvent.stopPropagation;
    return event;
};
fixEvent.preventDefault = function() {
    this.returnValue = false;
};
fixEvent.stopPropagation = function() {
    this.cancelBubble = true;
}


// array-like enumeration
if (!Array.forEach) { // mozilla already supports this
    Array.forEach = function(array, block, context) {
        for (var i = 0; i < array.length; i++) {
            block.call(context, array[i], i, array);
        }
    };
}

// generic enumeration
Function.prototype.forEach = function(object, block, context) {
    for (var key in object) {
        if (typeof this.prototype[key] == "undefined") {
            block.call(context, object[key], key, object);
        }
    }
};

// character enumeration
String.forEach = function(string, block, context) {
    Array.forEach(string.split(""), function(chr, index) {
        block.call(context, chr, index, string);
    });
};

// globally resolve forEach enumeration
var forEach = function(object, block, context) {
    if (object) {
        var resolve = Object; // default
        if (object instanceof Function) {
            // functions have a "length" property
            resolve = Function;
        } else if (object.forEach instanceof Function) {
            // the object implements a custom forEach method so use that
            object.forEach(block, context);
            return;
        } else if (typeof object == "string") {
            // the object is a string
            resolve = String;
        } else if (typeof object.length == "number") {
            // the object is array-like
            resolve = Array;
        }
        resolve.forEach(object, block, context);
    }
};
function cellClick(e) {
    if (this.className.search(/\bsorttable_sorted\b/) != -1) {

        reverseAndStripe(this.sorttable_tbody);
        reverseAndStripe(this.sorttable_tbody1);
        reverseAndStripe(this.sorttable_tbody2);
        reverseAndStripe(this.sorttable_tbody3);
        reverseAndStripe(this.sorttable_tbody4);
        reverseAndStripe(this.sorttable_tbody5);

        this.className = this.className.replace('sorttable_sorted',
                                                    'sorttable_sorted_reverse');
        return;
    }
    if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {

        reverseAndStripe(this.sorttable_tbody);
        reverseAndStripe(this.sorttable_tbody1);
        reverseAndStripe(this.sorttable_tbody2);
        reverseAndStripe(this.sorttable_tbody3);
        reverseAndStripe(this.sorttable_tbody4);
        reverseAndStripe(this.sorttable_tbody5);

        this.className = this.className.replace('sorttable_sorted_reverse',
                                                    'sorttable_sorted');
        return;
    }

    sortTbody(this, this.sorttable_tbody);
    sortTbody(this, this.sorttable_tbody1);
    sortTbody(this, this.sorttable_tbody2);
    sortTbody(this, this.sorttable_tbody3);
    sortTbody(this, this.sorttable_tbody4);
    sortTbody(this, this.sorttable_tbody5);
}

function reverseAndStripe(sort_tbody) {
    if (sort_tbody) {
        sorttable.reverse(sort_tbody);
        makeStripe(sort_tbody);
    }
}

function sortTbody(obj, sort_tbody) {
    // remove sorttable_sorted classes
    theadrow = obj.parentNode;
    forEach(theadrow.childNodes, function(cell) {
        if (cell.nodeType == 1) { // an element
            cell.className = cell.className.replace('sorttable_sorted_reverse', '');
            cell.className = cell.className.replace('sorttable_sorted', '');
        }
    });
    obj.className += ' sorttable_sorted';

    // build an array to sort. This is a Schwartzian transform thing,
    // i.e., we "decorate" each row with the actual sort key,
    // sort based on the sort keys, and then put the rows back in order
    // which is a lot faster because you only do getInnerText once per row
    row_array = [];
    col = obj.sorttable_columnindex;
    rows = sort_tbody.rows;
    for (var j = 0; j < rows.length; j++) {
        row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];
    }
    /* If you want a stable sort, uncomment the following line */
    //sorttable.shaker_sort(row_array, this.sorttable_sortfunction);
    /* and comment out this one */
    row_array.sort(obj.sorttable_sortfunction);

    tb = sort_tbody;
    for (var j = 0; j < row_array.length; j++) {
        tb.appendChild(row_array[j][1]);
    }
    delete row_array;
    makeStripe(sort_tbody);
}

function makeStripe(tBody) {
    var rows = tBody.rows;
    if (!rows)
        return;
    for (var i = 0; i < rows.length; i++)
        rows[i].className = (((i % 2) == 1) ? "tblEvenRow" : "tblOddRow");
}

///////////////////////////////////load///////////////////////////////////////////////
/* for Mozilla/Opera9 */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", load, false);
}

/* for Internet Explorer */
/*@cc_on@*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
    if (this.readyState == "complete") {
        load(); // call the onload handler
    }
};
/*@end@*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            load(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = load;
