/// <reference path="jquery-1.4.1-vsdoc.js"
/// <reference path="jquery.form.js"
/// <reference path="jquery.simplemodal-1.3.5.js"
/// <reference path="tools.expose-1.0.3.js"
/// <reference path="jquery.mydialogs.js"



function OnCountrySelected() {

    var elCity = document.getElementById('cityDropDown');
    var elCountry = document.getElementById('countryDropDown');

    for (var i = elCity.options.length - 1; i >= 0; i--) {
        elCity.options[i] = null;
    }
    var selectedCountry = g_countryData[elCountry.value];
    var defaultCity = "Санкт-Петербург";
    
    for (var i in selectedCountry) {

        var def = selectedCountry[i].Name == defaultCity;
        var opt = new Option(selectedCountry[i].Name, selectedCountry[i].CityId, def, def);
        elCity.options[elCity.options.length] = opt;
    }
    OnCitySelected();
}

function OnCitySelected() {
    
    var elCountry = $('#countryDropDown')[0];
    var elCity = $('#cityDropDown')[0];
    var elHotel = $('#hotelDropDown')[0];

    for (var i = elHotel.options.length - 1; i >= 0; i--) {
        elHotel.options[i] = null;
    }

    var selectedCountry = g_countryData[elCountry.value];

    var selectedCity = selectedCountry[elCity.value];

    for (var i = 0; i < selectedCity.Hotels.length; i++) {
        var opt = new Option(selectedCity.Hotels[i].Name, selectedCity.Hotels[i].HotelId, false, false);
        elHotel.options[elHotel.options.length] = opt;
    }
    elHotel.options[0].selected = true;
    
}


 

function GetSelectedTariffValue(SelectedId) {
    debugger;
    var el = document.all(SelectedId);
    return el.value;
}


function DoRequest(SelectId) {

    debugger;

    var t;
    t = document.all('selectedTeriff');
    t.value = (GetSelectedTariffValue(SelectId));
}


function closeStartDateNumberSearchCalendar(calendar) {
    var endDateTextBox = document.getElementById("endDateTextBox");
    var thisDate = calendar.date;
    var endDate = Date.parseDate(
    endDateTextBox.value || endDateTextBox.innerText, "%d.%m.%Y");

    var limit = false;
    if (endDate != null) {
        if (thisDate.getFullYear() != endDate.getFullYear()) {
            limit = (thisDate.getFullYear() > endDate.getFullYear());
        }
        else {
            if (thisDate.getMonth() != endDate.getMonth()) {
                limit = (thisDate.getMonth() > endDate.getMonth());
            }
            else {
                limit = (thisDate.getDate() >= endDate.getDate());
            }
        }
    }

    if (limit) {
        var time = (thisDate.getTime() + 2 * Date.DAY);
        var newEndDate = new Date(time);
        endDateTextBox.value = newEndDate.print("%d.%m.%Y");
    }

    calendar.hide();
}

function disallowStartNumberSearchDate(date) {
    var startDateTextBox = document.getElementById("startDateTextBox");
    var endDateTextBox = document.getElementById("endDateTextBox");
    var startDate = Date.parseDate(
    startDateTextBox.value || startDateTextBox.innerText, "%d.%m.%Y");
    var endDate = Date.parseDate(
    endDateTextBox.value || endDateTextBox.innerText, "%d.%m.%Y");
    if (date >= startDate && date <= endDate) {
        return "calendarSpecialDate";
    }

    var nowDate = new Date();
    if (date.getFullYear() != nowDate.getFullYear()) {
        return (date.getFullYear() < nowDate.getFullYear());
    }
    else {
        if (date.getMonth() != nowDate.getMonth()) {
            return (date.getMonth() < nowDate.getMonth());
        }
        else {
            return (date.getDate() < nowDate.getDate());
        }
    }
}


function closeEndDateCalendar(calendar) {
    var startDateTextBox = document.getElementById("startDateTextBox");
    var thisDate = calendar.date;
    var startDate = Date.parseDate(
    startDateTextBox.value || startDateTextBox.innerText, "%d.%m.%Y");

    var limit = false;
    if (startDate != null) {
        if (thisDate.getFullYear() != startDate.getFullYear()) {
            limit = (thisDate.getFullYear() < startDate.getFullYear());
        }
        else {
            if (thisDate.getMonth() != startDate.getMonth()) {
                limit = (thisDate.getMonth() < startDate.getMonth());
            }
            else {
                limit = (thisDate.getDate() <= startDate.getDate());
            }
        }
    }

    if (limit) {
        var tomorrow = new Date();
        var time = tomorrow.getTime() + Date.DAY;
        tomorrow = new Date(time);
        var backward = 2;
        if (thisDate.getFullYear() == tomorrow.getFullYear() && thisDate.getMonth() == tomorrow.getMonth() && thisDate.getDate() == tomorrow.getDate()) {
            backward = 1;
        }
        var time = (thisDate.getTime() - backward * Date.DAY);
        var newStartDate = new Date(time);
        startDateTextBox.value = newStartDate.print("%d.%m.%Y");
    }

    calendar.hide();
}

function disallowEndNumberSearchDate(date) {
    var startDateTextBox = document.getElementById("startDateTextBox");
    var endDateTextBox = document.getElementById("endDateTextBox");
    var startDate = Date.parseDate(
    startDateTextBox.value || startDateTextBox.innerText, "%d.%m.%Y");
    var endDate = Date.parseDate(
    endDateTextBox.value || endDateTextBox.innerText, "%d.%m.%Y");
    if (date >= startDate && date <= endDate) {
        var today = new Date();
        if (date.getFullYear() != today.getFullYear() || date.getMonth() != today.getMonth() || date.getDate() != today.getDate()) {
            return "calendarSpecialDate";
        }
    }
    var tomorrowDate = new Date();
    var time = tomorrowDate.getTime() + Date.DAY;
    tomorrowDate = new Date(time);
    if (date.getFullYear() != tomorrowDate.getFullYear()) {
        return (date.getFullYear() < tomorrowDate.getFullYear());
    }
    else {
        if (date.getMonth() != tomorrowDate.getMonth()) {
            return (date.getMonth() < tomorrowDate.getMonth());
        }
        else {
            return (date.getDate() < tomorrowDate.getDate());
        }
    }
    return result;
}



var g_popup;
var g_popupContent;


function GetOffsetTop(el) {
    if (el.parentElement != null) {
        return el.offsetTop + GetOffsetTop(el.parentElement);
    }
    return el.offsetTop;
}



function addEvent(el, evname, func) {
    if (el.attachEvent) { // IE
        el.attachEvent("on" + evname, func);
    } else if (el.addEventListener) { // Gecko / W3C
        el.addEventListener(evname, func, true);
    } else {
        el["on" + evname] = func;
    }
};

function removeEvent(el, evname, func) {

    if (el.attachEvent) { // IE
        el.detachEvent("on" + evname, func);
    } else if (el.addEventListener) { // Gecko / W3C
        el.removeEventListener(evname, func, true);
    } else {
        el["on" + evname] = null;
    }

};




function Popup_HideHandler(ev) {
    if (typeof g_popup != "undefined") {
        g_popup.style.visibility = "hidden";
        //    ev.cancelBubble = true;
        //    ev.returnValue = false;
        //    ev.preventDefault();
        //    ev.stopPropagation();
        //    return false;
    }
    return true;
}

function ShowPopup(PopupText, PopupOnElement) {
    if (g_popup == null) {
        g_popup = document.createElement('div');
        g_popup.Id = 'popup';
        g_popup.className = 'popupControl';

        document.body.appendChild(g_popup);

        g_popup.innerHTML = '<table cellpadding="7" ><tr><td id="popupContent"></td></tr></table>';

        g_popupContent = document.getElementById('popupContent');

        addEvent(document, "keydown", Popup_HideHandler);
        addEvent(document, "keypress", Popup_HideHandler);
        addEvent(document, "mousedown", Popup_HideHandler);
    }

    var el = document.getElementById(PopupOnElement);


    var x;
    var y;

    x = 0;
    y = 0;

    for (var p = el; p != document.body; p = p.offsetParent) {
        if (p.style.position != 'absolute') {
            x += p.offsetLeft;
            y += p.offsetTop;
        }
    }

    y = y + el.offsetHeight + 5;
    //y=y+5;
    g_popup.style.top = y + 'px'; //el.offsetTop;
    g_popup.style.left = x + 'px';
    g_popupContent.innerHTML = PopupText;


    g_popup.style.visibility = "visible";

}


function changePrice(dayPrice, totalPrice, select) {
    var dayPriceEl = document.getElementById(dayPrice);
    var totalPriceEl = document.getElementById(totalPrice);
    var selectEl = document.getElementById(select);

    var v = selectEl.value;
    var values = v.split(";");

    dayPriceEl.innerText = values[0]; //IE
    dayPriceEl.textContent = values[0]; //MOZILLA
    totalPriceEl.innerText = values[1]; //IE
    totalPriceEl.textContent = values[1]; //MOZILLA
}

function DoSearch() {
    debugger;

/* var form=document.getElementById('form1');
    form.submit();*/

}


function initGallery() {


    var x = 0;
    var imgs = $(".scroll div img");

    var scrollSize = 105;
    var maxScroll = (imgs.length - 5) * scrollSize;

    maxScroll = maxScroll > 0 ? maxScroll : 0;


    var manageControls = function() {
        $(".imagesSelect .controlLeft").toggleClass("controlLeftActive", x != 0);
        $(".imagesSelect .controlRight").toggleClass("controlRightActive", x != -maxScroll);
    };

    var scrollGallery = function(direction) {



        var scroll = $(".scroll");

        if (direction == "left") {
            x += scrollSize;
            x = x > 0 ? 0 : x;
        };

        if (direction == "right") {
            x -= scrollSize;
            x = x < -maxScroll ? -maxScroll : x;
        };

        scroll.stop(true, false);
        scroll.animate({ "marginLeft": x }, "slow", "swing");

    };



    $(".imagesSelect .controlLeft").click(function(e) {
        e.preventDefault();
        scrollGallery("left");
        manageControls();
    });


    $(".imagesSelect .controlRight").click(function(e) {
        e.preventDefault();
        scrollGallery("right");
        manageControls();
    });

    manageControls();

    $(".scroll a").click(function(e) {
        e.preventDefault();
        var lnk = $(this);

        var title = lnk.attr("title");
        if (title != "")
            $("#title").text(title);
        else
            $("#title").html("&nbsp");
        $("#comment").text(lnk.attr("comment"));
        //$("#bigimg").attr("src", "images/loader.gif");
        $("#bigimg").attr("src", lnk.attr("href"));
    });

    $("#bigimg").bind("load", null, function() {
        $("#galleryDialog").centerDialogs();
    });

};

$(document).ready(function() {


    var SortBy = 'name';
    var Page = 1;
    var HotelsOnPage = 10;

    var mainForm = $('#form1');


    mainForm.submit(function(ev) {
        ev.preventDefault();

        var sel = $("#HotelsPerPage select");
        if (sel == null || sel.length == 0)
            HotelsOnPage = 10;
        else
            HotelsOnPage = sel.val();

        $("#loader").modal({
            overlayCss: { backgroundColor: "black" },
            opacity: 30,
            escClose: false,
            close: false
        });

        //$("#numberTypeResultsUpdatePanel").html("");

        mainForm.ajaxSubmit({
            'target': '#numberTypeResultsUpdatePanel',
            'url': 'SearchHandler.php',
            'data':
            {
                'Page': Page,
                'HotelsOnPage': HotelsOnPage,
                'SortBy': SortBy
            },
            'success': function() {

                $.modal.close();

                $('.pagelink').click(function(e) {
                    e.preventDefault();
                    Page = $(this).attr("rel");
                    mainForm.submit();
                    return false;

                })


                $('a.sort').click(function(e) {
                    e.preventDefault();
                    SortBy = $(this).attr("rel");
                    mainForm.submit();
                    //return false;
                })



                $("#HotelsPerPage select").change(function(e) {
                    e.preventDefault();
                    mainForm.submit();
                    return false;
                })

                $('a.reserve').click(function(e) {
                    e.preventDefault();
                    var descriptor = $(this).find('input').val();
                    $('#selectedTeriff').val(descriptor);
                    $('#main').submit();
                });

                $('.gallery').click(function(e) {
                    e.preventDefault();
                    var gd = $("#galleryDialog");
                    gd.html($("#galleryDialogDummy").html());
                    gd.showDialog().centerDialogs();
                    gd.load($(this).attr('href'), {}, function() {
                        initGallery();
                    });


                });


            }

        });
        return false;
    });



    $("#searchLinkButton").click(function(e) {
        e.preventDefault();
        mainForm.submit();
        return false;
    })

    $(".popup_how_to_get").live("click", function(e) {
        e.preventDefault();
        var lnk = $(this);
        var id = lnk.attr("rel");
        var selector = "#how_to_get_" + id;
        var popupDiv = $(selector);
        popupDiv.load("HowToGetHandler.php", { "HotelId": id }, function() {
            $(".popup").hide();
            var o = lnk.offset();
            popupDiv.css("top", o.top + lnk.outerHeight());
            popupDiv.css("left", o.left);
            popupDiv.show();
            popupDiv.click(function() {
                $(this).hide();
            });

        });
    });


    $(".popup_services").live("click", function(e) {
        e.preventDefault();
        var lnk = $(this);
        var id = lnk.attr("rel");
        var selector = "#services_" + id;
        var popupDiv = $(selector);
        popupDiv.load("GetAdditionalInfoHandler.php", { "HotelId": id }, function() {
            $(".popup").hide();
            var o = lnk.offset();
            popupDiv.css("top", o.top + lnk.outerHeight());
            popupDiv.css("left", o.left);
            popupDiv.show();
            popupDiv.click(function() {
                $(this).hide();
            });

        });
    });



    Calendar.setup({
        inputField: "startDateTextBox",
        ifFormat: "%d.%m.%Y",
        showsTime: false,
        timeFormat: "24",
        firstDay: 1,
        onClose: closeStartDateNumberSearchCalendar,
        dateStatusFunc: disallowStartNumberSearchDate
    });

    Calendar.setup({
        inputField: "endDateTextBox",
        ifFormat: "%d.%m.%Y",
        showsTime: false,
        timeFormat: "24",
        firstDay: 1,
        onClose: closeEndDateCalendar,
        dateStatusFunc: disallowEndNumberSearchDate
    });

    $("#countryDropDown").change(OnCountrySelected);
    $("#countryDropDown").change();

    $("#cityDropDown").change(OnCitySelected);


});
