﻿var experience;
var price;
var destination;
var tip;
var selectedTours;
var stars;
var hotelType;
var priceMin;
var priceMax;
var comments;
var insurance;
var courier;
var newsEmail;
var city = 0, family = 0, beach = 0, ski = 0, christmas = 0, romantic = 0;
//var luxury = 0, standard = 0, budget = 0;
var middlesea = 0, north_europe = 0, egypt_turkey = 0, east = 0, thailand_indonesia = 0, south_east_asia = 0, africa_indian_ocean = 0, caribbean = 0, south_america = 0, north_america = 0;
var currentToolTip = null;

Ext.onReady(function ()
{
    /* create tooltip for each tour */
    for (i = 1; i <= document.getElementById('toursCount').value; i++)
    {
        tip = new Ext.ToolTip({
            id: 'tTip' + i,
            target: 'imgDiv' + i,
            showDelay: 0, //(Ext.isIE ? 0 : 80),
            closable: true,
            autoHide: false,
            baseCls: 'tipinset',
            width: 520,
            anchor: 'bottom',
            anchorToTarget: true,
            shadow: true,
            border: false,
            bodyBorder: false,
            contentEl: 'tipinset' + i // load content from the page
        });
        tip.on('show', function () { if (this.target.findParent("li", 2, true).hasClass('disabledthumb')) { this.hide(); return; } else { if (currentToolTip != null) { currentToolTip.hide(); currentToolTip = null } else { currentToolTip = this; } } });
        if (i == 1)
        {
            currentToolTip = tip;
        }
    }

    Ext.getBody().on('click', function (e, t) { if (currentToolTip != null) { currentToolTip.hide(); } });
    Ext.getBody().on('mousemove', function (e, t) { if (t.id == 'aspnetForm' || t.id == 'and-finally' || t.id == 'ext-gen3') { if (currentToolTip != null) { currentToolTip.hide(); } } });

    countFilters();

    experience = new Ext.form.ComboBox({
        transform: 'experience',
        editable: false,
        triggerAction: 'all',
        width: 196,
        height: 50,
        style: { color: '#404041' },
        fieldClass: 'select-field',
        triggerConfig: { tag: "img", src: './img/new/select-arrow2.gif', cls: "x-form-trigger" }
    });
    experience.getEl().applyStyles("border-top:1px solid #73a82d; border-bottom:1px solid #73a82d; border-left:1px solid #73a82d;");
    if (navigator.userAgent.indexOf("MSIE 7") != -1)
    {
        experience.getEl().applyStyles("margin-top:0px;");
    }

    price = new Ext.form.ComboBox({
        transform: 'price',
        editable: false,
        triggerAction: 'all',
        width: 196,
        fieldClass: 'select-field',
        style: { color: '#404041' },
        triggerConfig: { tag: "img", src: './img/new/select-arrow2.gif', cls: "x-form-trigger " + this.triggerClass }
    });
    price.getEl().applyStyles("border-top:1px solid #73a82d; border-bottom:1px solid #73a82d; border-left:1px solid #73a82d;");
    if (navigator.userAgent.indexOf("MSIE 7") != -1)
    {
        price.getEl().applyStyles("margin-top:0px;");
    }

    destination = new Ext.form.ComboBox({
        transform: 'destination',
        editable: false,
        triggerAction: 'all',
        width: 196,
        fieldClass: 'select-field',
        style: { color: '#404041' },
        triggerConfig: { tag: "img", src: './img/new/select-arrow2.gif', cls: "x-form-trigger " + this.triggerClass }
    });
    destination.getEl().applyStyles("border-top:1px solid #73a82d; border-bottom:1px solid #73a82d; border-left:1px solid #73a82d;");
    if (navigator.userAgent.indexOf("MSIE 7") != -1)
    {
        destination.getEl().applyStyles("margin-top:0px;");
    }

//    experience.on('select', function () { price.reset(); destination.reset(); search(this.getValue()); });
//    price.on('select', function () { experience.reset(); destination.reset(); search(this.getValue()); });
//    destination.on('select', function () { price.reset(); experience.reset(); search(this.getValue()); });

    experience.on('select', function () { search(this.getValue()); });
    price.on('select', function () { search(this.getValue()); });
    destination.on('select', function () { search(this.getValue()); });

    //    if(navigator.userAgent.indexOf("MSIE 8")!=-1)
    if (Ext.isIE8)
    {
        var temp = new Ext.form.ComboBox({
            transform: 'temp'
        });
        temp.destroy();

        $('newsEmailGoDiv').style.height = '22px';
    }

    document.getElementById('_flightsSearchForm').src = './Forms/SearchFlight.html?ver=1.1';
    document.getElementById('_hotelsSearchForm').src = './Forms/SearchHotels.html';

    newsEmail = new Ext.form.TextField({
        applyTo: 'newsEmail',
        width: 174,
        emptyText: 'Введите Ваш email...',
        allowBlank: false,
        fieldClass: 'login-text-field',
        preventMark: true,
        style: { verticalAlign: 'top', paddingBottom: '2px' },
        regex: /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z]{2,4}$/,
        regexText: "Некорректный адрес"
    });

    Ext.get('headerToursSearchDiv').removeClass('mainSearchFormDisabled').addClass('mainSearchFormEnabled');
    Ext.get('headerToursSearchDiv').applyStyles('background:url("./img/new/header-searchlinks-tours-en.gif") no-repeat;');

    onloadSearchForm();
});

function search(val)
{
    Ext.select("li", true).addClass('disabledthumb').removeClass('selected');
    Ext.select("div.disabledthumb", true).show();
    
//    if ((val == '') || (val == 'all'))
//    {
//        Ext.select("li", true).removeClass('disabledthumb').removeClass('selected');
//    }
//    else
//    {
//        Ext.each(Ext.query("li"), function (item){var el = Ext.get(item); if (el.hasClass(val)) {el.removeClass('disabledthumb').addClass('selected'); }});
    //    }

    var trigger = createTrigger();

    Ext.each(Ext.query("li"), function (item) { var itemToCheck = Ext.get(item); checkItem(itemToCheck, trigger); });
}

function filterPrices(val)
{
    Ext.select("li", true).addClass('disabledthumb').removeClass('selected');

    if ((val == '') || (val == 'all'))
    {
        Ext.select("li", true).removeClass('disabledthumb').removeClass('selected');
    }
    else
    {
        Ext.each(Ext.query("li"), function (item) { var el = Ext.get(item); var els = Ext.query("div.tourprice", item); for (i = 0; i < els.length; i++) { if (Ext.get(els[i]).hasClass(val)) { el.removeClass('disabledthumb').addClass('selected'); return; } } });
    }
}

/* build trigger for search */
function createTrigger()
{
    var tempTrigger;
    if (experience.value == '' || experience.value == 'all')
    {
        tempTrigger = '0';
    }
    else
    {
        tempTrigger = '1';
    }

    if (price.value == '' || price.value == 'all')
    {
        tempTrigger += '0';
    }
    else
    {
        tempTrigger += '1';
    }

    if (destination.value == '' || destination.value == 'all')
    {
        tempTrigger += '0';
    }
    else
    {
        tempTrigger += '1';
    }
    return tempTrigger;
}

function checkItem(itemToCheck, trigger)
{
    var item = Ext.get(itemToCheck);

    switch (trigger)
    {
        case '100':
            if (item.hasClass(experience.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '010':
            if (item.hasClass(price.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '001':
            if (item.hasClass(destination.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '110':
            if (item.hasClass(experience.value) && item.hasClass(price.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '101':
            if (item.hasClass(experience.value) && item.hasClass(destination.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '011':
            if (item.hasClass(price.value) && item.hasClass(destination.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '111':
            if (item.hasClass(experience.value) && item.hasClass(price.value) && item.hasClass(destination.value))
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
        case '000':
            {
                item.removeClass('disabledthumb');
                item.first().hide();
            }
            break;
    }

    return true;
}

function $(id)
{
    return document.getElementById(id);
}

//function tourInfo(tourId, thumbId)
//{
//    if (!Ext.get('thumb' + thumbId).hasClass('disabledthumb'))
//    {
//        document.location.href="./tour.aspx?tour_id=" + tourId;
//    }
//}

function tourInfo(destCountryId, destCitiesIDs, thumbId)
{
    if (!Ext.get('thumb' + thumbId).hasClass('disabledthumb'))
    {
        var queryString = ""; // = CreateQueryString(object);
        queryString += "?departureCity_sm=1";
        queryString += "&destinationCountry_sm=" + destCountryId;
        queryString += "&destinationCities_sm=" + destCitiesIDs;
        queryString += "&hotels_sm=";
        queryString += "&meals_sm=";
        queryString += "&stars_sm=";
        queryString += "&adultsCount_sm=2";
        queryString += "&childrenCount_sm=0";
        queryString += "&checkinDateFrom_sm=" + document.getElementById('DateFromTextBox').value;
        queryString += "&checkinDateTo_sm=" + document.getElementById('DateToTextBox').value;
        queryString += "&currency_sm=-1";
        queryString += "&nightsFrom_sm=6";
        queryString += "&nightsTo_sm=12";
        document.location.href = './SearchTour/Html/Results.aspx' + queryString;
    }
}

function SearchTours()
{
    var queryString = ""; // = CreateQueryString(object);
    queryString += "?departureCity_sm=" + document.getElementById('DepartureCityComboBox_hidden').value;
    queryString += "&destinationCountry_sm=" + document.getElementById('DestinationCountryComboBox_hidden').value;
    queryString += "&destinationCities_sm=";
    queryString += "&hotels_sm=";
    queryString += "&meals_sm=";
    queryString += "&stars_sm=";
    queryString += "&adultsCount_sm=" + document.getElementById('AdultTextBox').value;
    queryString += "&childrenCount_sm=" + document.getElementById('ChildTextBox').value;
    queryString += "&checkinDateFrom_sm=" + document.getElementById('DateFromTextBox').value;
    queryString += "&checkinDateTo_sm=" + document.getElementById('DateToTextBox').value;
    queryString += "&currency_sm=-1";
    queryString += "&nightsFrom_sm=" + document.getElementById('NightsFromTextBox').value;
    queryString += "&nightsTo_sm=" + document.getElementById('NightsToTextBox').value;
//    queryString += "&windowWidth_sm=" + resultsPageWidth + "";
//    queryString += "&windowHeight_sm=" + resultsPageHeight + "";
    //    window.open('./SearchTour/Html/Results.aspx' + queryString, '', "width=1024,height=600,fullscreen=yes,resizable=yes,scrollbars=yes,status=yes,toolbar=yes,menubar=yes,location=yes,directories=yes");
    document.location.href = './SearchTour/Html/Results.aspx' + queryString;
}

function countFilters()
{
    Ext.each(Ext.query("li"), function (item) {
        var el = Ext.get(item);
        if (el.hasClass("city")) { city++; }
        if (el.hasClass("family")) { family++; }
        if (el.hasClass("beach")) { beach++; }
        if (el.hasClass("ski")) { ski++; }
        if (el.hasClass("christmas")) { christmas++; }
        if (el.hasClass("romantic")) { romantic++; }

        if (el.hasClass("middlesea")) { middlesea++; }
        if (el.hasClass("north-europe")) { north_europe++; }
        if (el.hasClass("egypt-turkey")) { egypt_turkey++; }
        if (el.hasClass("east")) { east++; }
        if (el.hasClass("thailand-indonesia")) { thailand_indonesia++; }
        if (el.hasClass("south-east-asia")) { south_east_asia++; }
        if (el.hasClass("africa-indian_ocean")) { africa_indian_ocean++; }
        if (el.hasClass("caribbean")) { caribbean++; }
        if (el.hasClass("south-america")) { south_america++; }
        if (el.hasClass("north-america")) { north_america++; }
    });



    $("_experience").innerHTML = '<select id="experience"><option value="" selected="selected">по типу отдыха...</option>' +
                                 (city > 0 ? '<option value="city">Сити-туры (' + city + ')</option>' : '') +
                                 (family > 0 ? '<option value="family">Отдых с детьми (' + family + ')</option>' : '') +
                                 (beach > 0 ? '<option value="beach">Пляж (' + beach + ')</option>': '') +
                                 (ski > 0 ? '<option value="ski">Горные лыжи (' + ski + ')</option>' : '') +
                                 (christmas > 0 ? '<option value="christmas">Новогодние (' + christmas + ')</option>' : '') +
                                 (romantic > 0 ? '<option value="romantic">Романтические (' + romantic + ')</option>' : '') +
                                 '</select>';
    
//    $("_price").innerHTML = '<select id="price"><option value="all" selected="selected">По стоимости...</option><option value="luxury">больше $2000 (' + luxury + ')</option>' +
//                                 '<option value="standard">до $2000 (' + standard + ')</option>' +
    //                                 '<option value="budget">до $1000 (' + budget + ')</option></select>';
    $("_price").innerHTML = '<select id="price"><option value="" selected="selected">по стоимости на человека...</option><option value="under300">до $300 (' + document.getElementById('_under300').value + ')</option>' +
                                 '<option value="under500">до $500 (' + document.getElementById('_under500').value + ')</option>' +
                                 '<option value="under800">до $800 (' + document.getElementById('_under800').value + ')</option>' +
                                 '<option value="under1000">до $1000 (' + document.getElementById('_under1000').value + ')</option>' +
                                 '<option value="under1500">до $1500 (' + document.getElementById('_under1500').value + ')</option>' +
                                 '<option value="under2000">до $2000 (' + document.getElementById('_under2000').value + ')</option>' +
                                 '<option value="over2000">больше $2000 (' + document.getElementById('_over2000').value + ')</option></select>';
                                 
    $("_destination").innerHTML = '<select id="destination"><option value="" selected="selected">по направлению...</option>' +
                             (middlesea > 0 ? '<option value="middlesea">Средиземноморье (' + middlesea + ')</option>' : '') +
                             (north_europe > 0 ? '<option value="north-europe">Северная Европа (' + north_europe + ')</option>' : '') +
                             (egypt_turkey > 0 ? '<option value="egypt-turkey">Египет, Турция (' + egypt_turkey + ')</option>' : '') +
                             (east > 0 ? '<option value="east">Ближний восток (' + east + ')</option>' : '') +
                             (thailand_indonesia > 0 ? '<option value="thailand-indonesia">Таиланд и Индонезия (' + thailand_indonesia + ')</option>' : '') +
                             (south_east_asia > 0 ? '<option value="south-east-asia">Юго-восточная Азия (' + south_east_asia + ')</option>' : '') +
                             (africa_indian_ocean > 0 ? '<option value="africa-indian_ocean">Африка и Индийский океан (' + africa_indian_ocean + ')</option>' : '') +
                             (caribbean > 0 ? '<option value="caribbean">Карибы (' + caribbean + ')</option>' : '') +
                             (south_america > 0 ? '<option value="south-america">Южная Америка (' + south_america + ')</option>' : '') +
                             (north_america > 0 ? '<option value="north-america">Северная Америка (' + north_america + ')</option>' : '') +
                             '</select>';
}

function showSearchForm(id)
{
    $('toursSearchForm').style.display = 'none';
    $('hotelsSearchForm').style.display = 'none';
    $('flightsSearchForm').style.display = 'none';
    $(id + 'SearchForm').style.display = 'block';

    $('toursSearchDiv').className = 'mainSearchFormDisabled';
    $('hotelsSearchDiv').className = 'mainSearchFormDisabled';
    $('flightsSearchDiv').className = 'mainSearchFormDisabled';
    $(id + 'SearchDiv').className = 'mainSearchFormEnabled';
}

function subscribe()
{
    var val = newsEmail.getValue();
    if (val == null || val == '' || !newsEmail.isValid(true))
    {
        Ext.get('newsEmail').applyStyles('background-color:#fcb6b6; border-color:Red;');
        return;
    }

    Ext.get('newsEmail').applyStyles('background-color:White; border-color:#73a82d;');

    $('emailDiv').style.display = 'none';
    $('waitingAnimationDiv').style.display = 'block';

    try
    {
        xmlRequest = new XMLHttpRequest();
    }
    catch (ex)
    {
        xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }

    var url = "./services/Subscribe.ashx";
    xmlRequest.open("POST", url, true);
    xmlRequest.onreadystatechange = subscribe_applyUpdate;
    xmlRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlRequest.send("email=" + escape(newsEmail.getValue()));
}

function subscribe_applyUpdate()
{
    if (xmlRequest.readyState == 4)
    {
        if (xmlRequest.status == 200)
        {
            $('waitingAnimationDiv').style.display = 'none';

            var response = xmlRequest.responseText.split('!');
            if (response[1] == "ok")
            {
                $('subscribeSuccessDiv').style.display = 'block';
            }
            else
            {
                $('emailDiv').style.display = 'block';
                alert('Произошла ошибка. Пожалуйста, повторите попытку.');
            }
        }
    }
}
