function getInfoBlock(code) {
    $("#infoBlockTitle").html(code);
    WebApplication.Services.InfoService.GetInfoBlock(code, GetInfoBlock_RequestComplete, GetInfoBlock_Error);
    return false;
}

function GetInfoBlock_RequestComplete(content) {
    $("#infoBlockContent").html(content);
}

function GetInfoBlock_Error() {
    alert("Ошибка загрузки");
}

TourDescriptions = {

    _data: {},
    _clickedId: 0,

    GetDescription: function (id) {
        this._clickedId = id;
        WebApplication.Services.InfoService.GetTourDescription(id, TourDescriptions.OnRequestComplete, TourDescriptions.OnError);
    },

    ShowDescription: function (id) {
        
        if (id in this._data) {
            this.ShowContent(id);
        }
        else {
            this.GetDescription(id);
        }

        return false;
    },

    OnRequestComplete: function (content) {
        TourDescriptions._data[TourDescriptions._clickedId] = {
            content: content,
            opened: true
        };

        TourDescriptions.ShowContent(TourDescriptions._clickedId);
    },

    OnError: function () {
        alert("Ошибка загрузки");
    },

    ShowContent: function (id) {
        $("#descr" + id).toggle();
        $("#descr" + id).html(this._data[id].content);
    }
}

function openGoogleMap(index) {
    var w = window.open("", "gmap", "width=425,height=370,statusbar=0,menubar=0,location=0,toolbar=0,scrollbars=0");
    w.document.write("<html><body style='background:#fff;margin:0;padding:0'>" + googleMaps[index] + "</body></html>");
    w.document.close();
    return false;
}

function addBookmark(url, title) {
    if (!url) url = location.href;
    if (!title) title = document.title;

    //Gecko
    if ((typeof window.sidebar == "object") && (typeof window.sidebar.addPanel == "function")) window.sidebar.addPanel(title, url, "");
    //IE4+
    else if (typeof window.external == "object") window.external.AddFavorite(url, title);
    //Opera7+
    else if (window.opera && document.createElement) {
        window.alert("Нажмите Ctrl+D для добавления в закладки");
    }
    else return false;

    return true;
}

// {{{ скрипты галереи картинок
var photoesPos = 0; // положение блока картинок относительно контейнера
var photoLeftIndex = 0; // индекс первой показанной фотографии
var PHOTO_WIDTH = 54; // ширина одной картинки
var SHOWN_PHOTOES_COUNT = 6; // число показываемых картинок
var currentShownPhotoIndex = 0;
function scrollPhotoes(direction) {
    if ((photoesPos == 0 && direction == -1)
        || (photoesPos == -(PHOTO_WIDTH * (PHOTOES_COUNT - SHOWN_PHOTOES_COUNT)) && direction == 1)
        || (SHOWN_PHOTOES_COUNT >= PHOTOES_COUNT))
        return false;
    photoesPos -= direction * PHOTO_WIDTH;
    photoLeftIndex += direction;
    
    // если на первой фотке, выключаем кнопку назад
    if (photoesPos == 0) {
        $("#photos .slides .l").addClass("hidden2");
    } else {
        $("#photos .slides .l").removeClass("hidden2");
    }

    if (photoesPos == -(PHOTO_WIDTH * (PHOTOES_COUNT - SHOWN_PHOTOES_COUNT))) {
        $("#photos .slides .r").addClass("hidden2");
    } else {
        $("#photos .slides .r").removeClass("hidden2");
    }
    
    
    
    $("#imgs-container").animate({ left: photoesPos + "px" });
    return false;
}

function showFullImage(_a) {
    $("#photos .big-photo").attr("src", _a.href);
    $("#photos .image-title").html(_a.title);
    currentShownPhotoIndex = $("#imgs-container .img").index($(_a).parent());
    return false;
}

function showFullImageNext() {
    scrollPhotoes(+1);

    if (currentShownPhotoIndex < photoLeftIndex) {
        currentShownPhotoIndex = photoLeftIndex;
    }
    else {
        currentShownPhotoIndex += currentShownPhotoIndex >= PHOTOES_COUNT - 1 ? 0 : 1;
    }

    showFullImage($($("#imgs-container .img")[currentShownPhotoIndex]).find("a")[0]);

    return false;
}
// }}}

// {{{ скрипты галереи видео
var videoPos = 0;
var PREVIEW_WIDTH = 54; // ширина одной превью
var SHOWN_PREVIEWS_COUNT = 6; // число показываемых картинок - превью
function scrollVideos(direction) {
    if ((videoPos == 0 && direction == -1)
        || (videoPos == -(PREVIEW_WIDTH * (VIDEOS_COUNT - SHOWN_PREVIEWS_COUNT)) && direction == 1)
        || (SHOWN_PREVIEWS_COUNT >= VIDEOS_COUNT))
        return false;
    videoPos -= direction * PREVIEW_WIDTH;

    // если на первой фотке, выключаем кнопку назад
    if (videoPos == 0) {
        $("#videos .slides .l").addClass("hidden2");
    } else {
        $("#videos .slides .l").removeClass("hidden2");
    }

    if (videoPos == -(PREVIEW_WIDTH * (VIDEOS_COUNT - SHOWN_PREVIEWS_COUNT))) {
        $("#videos .slides .r").addClass("hidden2");
    } else {
        $("#videos .slides .r").removeClass("hidden2");
    }



    $("#video-container").animate({ left: videoPos + "px" });
    return false;
}
function showVideo(a) {
    $("#" + videoContainerId).html(decodeURIComponent(a.title));
    $("#videos .image-title").html(a.childNodes[0].title);
    return false;
}
// }}}

function checkDate(source, clientside_arguments) {
    var reDate = /^[0-9]{1,2}\.[0-9]{1,2}\.[0-9]{4}$/;
    clientside_arguments.IsValid = reDate.test(clientside_arguments.Value);
}

function EnableTab(id, tabText) {
    var tabStrip = $find(id);
    var tab = tabStrip.findTabByText(tabText);
    tab.select();
}

var PositionUtils = {
    
    // определение видимой части окна
    GetScreenSize: function() {
        var w, h;
        w = (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth));
        h = (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight));
        return { w: w, h: h };
    },

    // определение скролла окна
    GetScroll: function() {
        var x = y = 0;
        x = (window.scrollX) ? window.scrollX : document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft;
        y = y = (window.scrollY) ? window.scrollY : document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
        return { x: x, y: y };
    } 
}


// {{{ выбор города
var currentTownShown = false;
function currentTown_Click() {
    alert($("#citypick"));
    $("#citypick").show();
    currentTownShown = true;
    return false;
}
$(function() {
    $(document).click(function(obj) {
        if (obj.target.id != "A1") { // && currentTownShown) {
            //currentTownShown = false;
            $("#citypick").hide();
        }
    });

    var waitPanelObj = document.getElementById("waitPanel");
    var waitPanelIEObj = document.getElementById("waitPanelIE");

    if (waitPanelObj) {
        window.setInterval(function() {
            var _screenSize = PositionUtils.GetScreenSize();
            var _scroll = PositionUtils.GetScroll();
            var y = _scroll.y + _screenSize.h / 2;
            var x = _scroll.x + _screenSize.w / 2;

            waitPanelObj.style.top = y + "px";
            waitPanelObj.style.left = x + "px";

            if (waitPanelIEObj) {
                waitPanelIEObj.style.top = y + "px";
                waitPanelIEObj.style.left = x + "px";
            }
        }, 100);
    }

});
// }}}

// инициализация сворачивания каталога по регионам
//$(document).ready(function () {

//    $(".accordion h3").click(function () {
//        $(this).next("div").slideToggle("slow")
//					.siblings("div:visible").slideUp("slow");
//        $(this).toggleClass("active");
//        $(this).siblings("h3").removeClass("active");
//    });
//    $(".accordion h3 a").click(function (e) {
//        e.stopPropagation();
//    });

//});

// overridden function
function ValidationSummaryOnSubmit(validationGroup) {
    if (typeof (Page_ValidationSummaries) == "undefined")
        return;
    var summary, sums, s;
    for (sums = 0; sums < Page_ValidationSummaries.length; sums++) {
        summary = Page_ValidationSummaries[sums];
        summary.style.display = "none";
        if (!Page_IsValid && IsValidationGroupMatch(summary, validationGroup)) {
            var i;
            if (summary.showsummary != "False") {
                summary.style.display = "";
                if (typeof (summary.displaymode) != "string") {
                    summary.displaymode = "BulletList";
                }
                switch (summary.displaymode) {
                    case "List":
                        headerSep = "<br>";
                        first = "";
                        pre = "";
                        post = "<br>";
                        end = "";
                        break;
                    case "BulletList":
                    default:
                        headerSep = "";
                        first = "<ul>";
                        pre = "<li>";
                        post = "</li>";
                        end = "</ul>";
                        break;
                    case "SingleParagraph":
                        headerSep = " ";
                        first = "";
                        pre = "";
                        post = " ";
                        end = "<br>";
                        break;
                }
                s = "";
                if (typeof (summary.headertext) == "string") {
                    s += summary.headertext + headerSep;
                }
                s += first;
                for (i = 0; i < Page_Validators.length; i++) {
                    if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string") {
                        s += pre + Page_Validators[i].errormessage + post;
                    }
                }
                s += end;
                summary.innerHTML = s;
                //window.scrollTo(0, 0);
            }
            if (summary.showmessagebox == "True") {
                s = "";
                if (typeof (summary.headertext) == "string") {
                    s += summary.headertext + "\r\n";
                }
                var lastValIndex = Page_Validators.length - 1;
                for (i = 0; i <= lastValIndex; i++) {
                    if (!Page_Validators[i].isvalid && typeof (Page_Validators[i].errormessage) == "string") {
                        switch (summary.displaymode) {
                            case "List":
                                s += Page_Validators[i].errormessage;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "BulletList":
                            default:
                                s += "- " + Page_Validators[i].errormessage;
                                if (i < lastValIndex) {
                                    s += "\r\n";
                                }
                                break;
                            case "SingleParagraph":
                                s += Page_Validators[i].errormessage + " ";
                                break;
                        }
                    }
                }
                alert(s);
            }
        }
    }
}

function wopen(wurl, wname, w, h) {
    window.open(wurl, wname, 'height=' + h + ',width=' + w + ',resizable=1,scrollbars=yes,menubar=no,status=no');
}

String.prototype.format = function () {
    var str = this;
    for (var i = 0; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}

// {{{ инициализация каталогов в подвале
function initGroundFloorItems() {
    $("#ground-floor-container .catalog-list").hide();
    $("#ground-floor-container .catalog-item-container").removeClass("catalog-white-corner");
    $("#ground-floor-container .btn-catalog").removeClass("btn-cls-catalog");
}

function getDimensionsForGroundFloorPopup(left0, bottom0) {
    var isIE6 = String(window.navigator.appVersion).indexOf("MSIE 6") != -1;
    return {
        left: left0 - 6,
        bottom: bottom0 + (isIE6 ? 0 : 1),
        width: isIE6 ? "100%" : "15.5%"
    }
}

function showGroundFloorPopup(sender, parentItem, popUp) {
    var left_arr_pos = $(sender).offset().left - parentItem.parent().parent().parent().offset().left;
    var divDimensions = getDimensionsForGroundFloorPopup(left_arr_pos, $("#ground-floor-container").height());

    popUp.css("width", divDimensions.width);
    popUp.css('left', divDimensions.left);
    popUp.css('bottom', divDimensions.bottom);
    popUp.show();
}


$(document).click(function (obj) {
    if (obj.target.className.indexOf("btn-exp-catalog") == -1) {
        initGroundFloorItems();
    }
});

$(document).ready(function () {
    $("#ground-floor-container .btn-exp-catalog").click(function () {

        var parentItem = $(this).parent();
        var popUp = parentItem.next();
        var isPopupDisplayed = popUp.css("display") == "block";

        initGroundFloorItems();

        if (isPopupDisplayed) return;

        showGroundFloorPopup(this, parentItem, popUp);

        $(this).addClass("btn-cls-catalog");
        //parentItem.addClass("catalog-white-corner");

    });
});

// }}}
function getElementsByClass(searchClass, node, tag) {
    var classElements = new Array();
    if (node == null)
        node = document;
    if (tag == null)
        tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;

    var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if (pattern.test(els[i].className)) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

$(document).ready(function () {
    loadTooltips('');
});

function pageLoad(sender, args) {
    if (args.get_isPartialLoad()) {
        loadTooltips(".tour ");

        if (window.PIE) {
            $('#tooltip').each(function () {
                PIE.attach(this);
            });
            $('.timeToDieTimer').each(function () {
                PIE.attach(this);
            });
            $('.needPie').each(function () {
                PIE.attach(this);
            });
            $('.pad').each(function () {
                PIE.attach(this);
            });
        }
    }
}

function loadTooltips(sel) {
    if (sel == null)
        sel == '';
    $(sel + '.megatooltip').tooltip({
        track: true,
        delay: 0,
        showURL: false,
        opacity: 0.95,
        left: -50
    });
    $(".actionCountdown").each(function (i) {
        $(this).countdown({ prefix: '', finish: '' })
    });
}


$(document).ready(function () {
    $("#blockAuthorizationFormLoginID").keypress(loginForm_OnClientKeyPressing);
    $("#blockAuthorizationFormPasswordID").keypress(loginForm_OnClientKeyPressing);
    $("#codeForPaymentID").keypress(cardForm_OnClientKeyPressing);
    $("#codeForOrderShowID").keypress(orderForm_OnClientKeyPressing);
});


function loginForm_OnClientKeyPressing(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
        bA_Authorize();
        return false;
    }
}

function cardForm_OnClientKeyPressing(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
        paymentOrder();
        $("#codeForPaymentID").keypress(cardForm_OnClientKeyPressing);
        return false;
    }
}

function orderForm_OnClientKeyPressing(e) {
    var keyCode = e.keyCode || e.which;
    if (keyCode == 13) {
        showOrder();
        $("#codeForOrderShowID").keypress(orderForm_OnClientKeyPressing);
        return false;
    }
}
