///// <reference path="jquery-1.6.2.with.plugins.min.js" />
//-------------------------------------------- login.ascx
function signIn() {
    $("#loginForm").keypress(function (e) {
        if (e.which == 13) {
            $("#signIn").click();
            e.preventDefault();
        }
    });

    $("#signIn").unbind("click").bind("click", function () {
        $("#loding").show();
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=UTF-8",
            dataType: "json",
            url: '/Resources/Services/SystemService.asmx/SignIn',
            data: '{"login":"' + $("#login").val() + '","password":"' + $("#password").val() + '","remeberMe":"' + $("#rememberMe").is(':checked') + '"}',
            success: function (response) {
                $("#loding").hide();
                if (response.d) {
                    window.location.href = jQuery(location).attr('href').indexOf('#') == -1
                        ? jQuery(location).attr('href')
                        : jQuery(location).attr('href').split('#')[0];
                }
                else {
                    $("#error").show();
                }
            }
        });
    });
}

function closeLoginForm() {
    $("#loding").hide();
    $("#error").hide();

    $('#loginForm :input').each(function () {
        switch (this.type) {
            case 'checkbox':
                this.checked = false;
                break;
            case 'text':
            case 'password':
                $(this).val('');
                break;
        }
    });
};


// ------------------------------------- extend
var localPopupIsReload = false;

(function ($) {
    $.fn.extend({
        limit: function (limit, element) {
            var interval, f;
            var self = $(this);
            self.focus(function () {
                interval = window.setInterval(substring, 100);
            });
            self.blur(function () {
                clearInterval(interval);
                substring();
            });

            substringFunction = "function substring(){ var val = $(self).val();var length = val.length;";
            if (typeof element != 'undefined')
                substringFunction += "if($(element).html() != limit-length){$(element).html(limit-length == 0 ? '0' : limit-length); if(limit-length<0){$(element).css('color','red');}else{$(element).css('color','black');}}";
            substringFunction += "}";
            eval(substringFunction);
            substring();
        },
        getSelectedText: function () {
            var select_list_field = this[0];
            var select_list_selected_index = select_list_field.selectedIndex;
            if (select_list_selected_index >= 0) {
                return select_list_field.options[select_list_selected_index].text;
            } else {
                return undefined;
            }
        }
    });
})(jQuery);

$.urlParam = function (name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) return 0;
    return results[1] || 0;
};

function updateBasket() {
    var control = $("#basketContent ul.user_menu");
    $.post('/Resources/Services/BasketService.svc/GetBasketShortInfo', function (data) {
        $("#basketCount").text(data.GoodsQuantity);
        $("#basketTotalPrice").text(data.TotalGoodsPrice);
        control.html(data.AuthControls);
    }, 'json');
}

function updateVisitedGoods(countParam) {
    var count = $("#hfCountVisibleItemStatic").val();
    var contanier = $("#visitedGoodsContanier");

    if (!count || count == 0)
        count = countParam;
    
    $.get("/visitedgoods.aspx", { v: Math.random(), count: count }, function (data) {
        contanier.html(data);
    });
}

function InitializeNewReceiptsCarousel() {
    var scrollNew = $(".scrollNew");
    var itemCount = $(".scrollNew ul li").length;
    var visibleCount = document.getElementById("mainPage") ? 5 : 7;
    visibleCount = itemCount < visibleCount && itemCount != 0 ? itemCount : visibleCount;

    if (typeof (scrollNew.jCarouselLite) == 'function' && scrollNew.length != 0) { //Дополнительно проверяем, доступна ли карусель.
        scrollNew.jCarouselLite({
            btnNext: ".nextNew",
            btnPrev: ".prevNew",
            visible: visibleCount,
            speed: 500
        });
    }
}

(function ($) {
    $.fn.extend({
        InitializeBigBannerCarousel: function () {
            var $this = $(this);
            if ($this.find('li').length != 0) {
                $this.jCarouselLite({
                    btnNext: "#next",
                    btnPrev: "#prev",
                    visible: 1,
                    width: 700,
                    height: 341,
                    auto: 7000,
                    beforeStart: function (a) {
                        var nextImg = a.next().find('img');
                        copyOrigToSrc(nextImg);
                        a.parent().fadeTo(500, 0);
                        var bg = a.find('img').attr('src');
                        $this.css({ backgroundImage: "url(" + bg + ")" });
                    },
                    afterEnd: function (a) {
                        var $a = $(a);
                        copyOrigToSrc($a.find('img'));
                        $a.parent().fadeTo(500, 1);
                    }
                });
            }
            function copyOrigToSrc(img) {
                if (img != null && img.attr('original') != '') {
                    img.attr('src', img.attr('original'));
                    img.attr('original', '');
                    img.css({ 'visibility': '' });
                }
            }
        }
    });
})(jQuery);

// -------------------------------- gogo.js
$().ready(function () {

    $(".login .close").click(function () {
        $(".login").css("display", "none");
        $(".blank").css("visibility", "hidden");
        if (jQuery.browser.msie && jQuery.browser.version.charAt(0) == '6') {
            $("#filter").css("visibility", "visible");
            $("#ctl00_ctl00_ctl00_ContentPlaceHolder_ContentPlaceHolder_ctl03_PagerRS1_PageSizeList").css("visibility", "visible");
        }
        return false;
    });

    $(".openPopup").click(function (event) {
        event.preventDefault();
        event.stopPropagation ? event.stopPropagation() : window.event.cancelBubble = true;
        var rel = $(this).attr("rel");
        var attrs = rel.split("_");
        var dceId = 0;
        var rowID = 0;
        var isReload = false;

        if (attrs.length > 0) {
            dceId = attrs[0];
        }
        if (attrs.length > 1) {
            rowID = attrs[1];
        }
        if (attrs.length > 2) {
            isReload = attrs[3];
        }
        if (dceId > 0) {
            OpenNewPopup(dceId, rowID, isReload);
        }
    });

    $(".openPopup2").click(function () {

        $(".photo-container .bigimg").attr("src", '');

        $("#descr-container .photodescription").text("");
        $("#descr-container .name").text("");
        $("#descr-container .votes").text("");

        var photoId = $(this).attr("photoId");
        var concursId = $(this).attr("concursId");
        var urlphoto = $(this).attr("urlphoto");

        $("#photo-dialog .voting").attr('photoId', photoId);


        if ($.browser.msie && $.browser.version <= 7) {
            $(".trunkOld").css("position", "static");
        }
        $(".blank").css({ "height": document.documentElement.scrollHeight + "px", "visibility": "visible" });
        $(".photo-dialog").show();

        $(".photo-container .bigimg").attr("src", urlphoto + photoId + '.jpg');

        $.ajax({
            type: "POST",
            url: "/Resources/Services/SystemService.asmx/GetPhotoByConcursId",
            data: "{ 'photoId': '" + photoId + "', 'concursId':" + concursId + "}",
            contentType: "application/json; charset=UTF-8",
            success: function (concursPhoto) {
                var data = eval("[" + concursPhoto.d + "]")[0];

                $("#descr-container .photodescription").text(data.Description);
                $("#descr-container .name").text(data.UserName);
                $("#descr-container .votes").text(data.Votes);
            }
            ,
            dataType: "json"
        });

    });

    $("#photo-dialog .voting").click(function () {
        var photoId = $(this).attr("photoId");
        var concursId = $(this).attr("concursId");

        $.ajax({
            type: "POST",
            url: "/Resources/Services/SystemService.asmx/VotingFoPhoto",
            data: "{ 'photoId': '" + photoId + "', 'concursId':" + concursId + "}",
            contentType: "application/json; charset=UTF-8"
        });


        $("#photo-dialog .cart-button").hide();
        $("#photo-dialog .votcomplete").show();
    });
});

function loginOpen() {
    if (jQuery.browser.msie && jQuery.browser.version <= 7) {
        $("#blank").insertBefore(".header .login");
    }
    if (jQuery.browser.msie && jQuery.browser.version.charAt(0) == '6') {
        $("#filter").css("visibility", "hidden");
        $("#ctl00_ctl00_ctl00_ContentPlaceHolder_ContentPlaceHolder_ctl03_PagerRS1_PageSizeList").css("visibility", "hidden");
    }
    $(".blank").css({ "height": document.documentElement.scrollHeight + "px", "visibility": "visible" });
    $(".login").css("display", "block");
    $(".login input")[0].focus();

    return false;
}

function inArray(elem, array) {
    for (var i = 0, length = array.length; i < length; i++) {
        if (array[i].indexOf(elem) == 0) {
            return i;
        }
    }
    return -1;
}

function getClientWidth() { return document.compatMode == 'CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth; }
function getClientHeight() { return document.compatMode == 'CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight; }


//--------------------------------- getWidth.js

var IE = (document.all); // Internet Explorer?
var NC = (document.layers); // Netscape?
var Opera = (document.getElementById); // Opera?

function getHeight() { // Получаем высоту рабочей области браузера
    //    if (IE || Opera) send = document.body.clientHeight;
    //    if (NC) send = window.innerHeight;
    return getClientHeight();
}

function getWidth() { // Получаем ширину рабочей области браузера
    //    if (IE || Opera) send = document.body.clientWidth;
    //    if (NC) send = window.innerWidth;
    return getClientWidth();
}


// --------------------------------- BasketTools.js

var pg_src = '';
var loc_div = '';

function Search(e) {
    var evt = window.event || e;
    if (evt.keyCode == 13) {
        StartSearch();
    }
}

var GlobalIFrOpenFlag = true;

function OpenNewPopup(dceId, rowID, isReload) {
    var url = '/catalog/' + dceId + '/popup.aspx?v=' + Math.random();
    if (rowID && rowID > 0) {
        url += "&rowID=" + rowID;
    }
    var popup = $("#popup");


    popup.jqm({
        toTop: true,
        ajax: url,
        modal: false,
        onLoad: function (hash) {
            InitializePopup(hash, rowID);
        },
        onHide: function (hash) {
            $("#popup #TableSizes").die();
            $("#popup #sizePopup .close").die();
            var popup = $("#popup");
            if ($.browser.msie && $.browser.version == '9.0') //Убираем загадочный глюк в IE9 при кнопке +1 от гугла                            
                $('.share-google-box').find('iframe').attr('src', ''); //IE9 не нравится столь изощренный src от гугла
            popup.html('');
            popup.attr('style', '');
            hash.o.remove();
            updateVisitedGoods();
            if (isReload && localPopupIsReload) {
                location.reload();
            }
            pop = '';
            $("#GotoBasket").hide();
            $("#AddToBasket").show();
        }
    });

    var halfScreen = ((document.documentElement.offsetHeight || document.body.clientHeight) / 2);
    var top = (document.documentElement.scrollTop || document.body.scrollTop) + Math.round(halfScreen < 340 ? 340 : halfScreen);

    popup.css("top", top + 'px');
    popup.jqmShow();
}

function OpenBigProductCard(el) {
    $(".openPopup", ".catalog_main_table").hide();
    var href = $(el.parentNode).children('a').attr('href');
    if (href) navigateWithReferrer(href); //window.location = href;
}

function StartSearch() {
    var obj = document.getElementById(loc_div);
    if (obj != null && obj.value.length > 0) {
        parent.location.href = pg_src + obj.value;
    }
}

function ShowAction() {
    document.getElementById('ifr').className = 'visible';

    document.getElementById('ifr').style.left = (getClientWidth() - 900) / 2 + "px";
    document.getElementById('ifr').style.top = (getClientHeight() - 600) / 2 + "px";
    document.getElementById('ifr').style.width = 900 + "px";
    document.getElementById('ifr').style.height = 600 + "px";
    document.getElementById('frame').style.width = 900 + "px";
    document.getElementById('frame').style.height = 600 + "px";
}

//Обход бага с IE6-IE8, при котором UrlReferrer всегда null
//см. http://dotnetefectivecoding.blogspot.com/2009/08/requesturlreferrer-is-null-in-ie-60.html
function navigateWithReferrer(url) {
    var fakeLink = document.createElement("a");
    if (typeof (fakeLink.click) == 'undefined')
        location.href = url; // sends referrer in FF, not in IE
    else {
        fakeLink.href = url;
        document.body.appendChild(fakeLink);
        fakeLink.click(); // click() method defined in IE only
    }
}

// ------------------------------------- action_ajax.js

$().ready(function () {
    if (typeof (Sys) != 'undefined') {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        var act = "";

        prm.add_initializeRequest(InitializeRequest);
        prm.add_endRequest(EndRequest);
    }
});

function InitializeRequest(sender, args) {
    act = document.forms[0].action;
}

function EndRequest(sender, args) {
    document.forms[0].action = act;
}

// ------------------------------------- UserDetailEdit.ascx ----------------------------

function InitializeUserDetailEdit() {
    var cityField = $('#cityInput');
    var streetField = $('#streetInput');
    var houseField = $('#houseInput');
    var streetAutoCompl;
    var separator = '|';
    cityField.available(function () {
        cityField.autocomplete({
            serviceUrl: '/ServiceApps/MainService.svc/SearchCityByString',
            minChars: 2,
            maxHeight: 400,
            width: 237,
            zIndex: 9999,
            deferRequestBy: 500,
            noCache: false,
            onSelect: function (value, data) { onObjectSelected(value, data, cityField, streetField); streetAutoCompl.setOptions({ params: { id: data} }); },
            fnFormatResult: function (value, data, currentValue) {
                var t = value.split(separator); return t.shift() + '<br /><span style="font-size: smaller; color: gray;">' + t.join(', ') + '</span>';
            }
        });
        cityField.focus(function () {
            SetText2(this, false, streetField);
        });

        cityField.blur(function () {
            SetText2(this, true, streetField);
        });
    });

    streetField.available(function () {
        streetAutoCompl = streetField.autocomplete({
            serviceUrl: '/ServiceApps/MainService.svc/SearchStreetInCity',
            minChars: 2,
            maxHeight: 400,
            width: 237,
            zIndex: 9999,
            deferRequestBy: 500,
            noCache: false,
            onSelect: function (value, data) { onObjectSelected(value, data, streetField, houseField); $('#streetInputHidden').val(data); } //,
            //            fnFormatResult: function (value, data, currentValue) {
            //                var t = value.split(separator); return t[0] + '<br /><span style="font-size: smaller; color: gray;">Индекс: ' + t[1] + '</span>';
            //            }
        });
        streetField.focus(function () {
            SetText2(this, false, null, cityField);
        });

        streetField.blur(function () {
            SetText2(this, true, null, cityField);
        });
    });

    function onObjectSelected(value, data, caller, setFocusOn) {

        var u = value.split(separator)[0];
        caller.val(u).data('id', data).data('selectedName', u);
        if (setFocusOn) setFocusOn.focus();
    }
    $('[data-next-input]').keyup(function () {
        var $this = $(this);
        if ($this.val().length == $this.attr('maxlength'))
            $('#' + $this.data('nextInput')).focus();
    })
        .keydown(function (event) {
            // Allow only backspace and delete 
            if (event.keyCode == 46 || event.keyCode == 8) {
                // let it happen, don't do anything 
            }
            else {
                // Ensure that it is a number and stop the keypress 
                if ((event.keyCode < 48 || event.keyCode > 105) || (event.keyCode < 96 && event.keyCode > 57)) {
                    event.preventDefault();
                }
            }
        });
}

function SetText2(obj, isOut, descendant, ancestor) {
    if (ancestor && !ancestor.data('id')) {
        ancestor.focus();
    } else {
        if (obj != null) {
            var o = $(obj);
            if ((o.val().length == 0 && isOut) || (o.val() != o.data('selectedName'))) {
                o.val('');
                o.data('selectedName', null);
                o.data('id', null);
                if (descendant) { descendant.val('').data('selectedName', null).data('id', null); }
            }
        }
    }
}

// ------------------------------------- SearchControl.ascx ----------------------------

var pre_src = 'Воспользуйтесь поиском';
var textBox;
var button;

function searchPreInit() {
    textBox = $('#tbSearch');
    button = $('#btnSearch');

    textBox.val(pre_src);
    textBox.attr('title', pre_src);
    button.attr('title', pre_src);

    textBox.available(function () {
        textBox.autocomplete({
            serviceUrl: '/Resources/Services/SystemService.asmx/GetSearchCompletionList',
            minChars: 2,
            maxHeight: 400,
            width: 237,
            zIndex: 9999,
            deferRequestBy: 500,
            noCache: false,
            onSelect: function (value, data) { searchRedirect(); }
        });

        textBox.keypress(function (e) {
            if (e.which == 13) {
                if (checkSearch())
                    searchRedirect();
                e.preventDefault();
            }
        });

        textBox.focus(function () {
            SetText(this, false);
        });

        textBox.blur(function () {
            SetText(this, true);
        });

        button.click(function (e) {
            if (checkSearch())
                searchRedirect();
            e.preventDefault();
        });
    });
}

function SetText(obj, isOut) {
    if (obj != null) {
        if (obj.value.length == 0 && isOut) obj.value = pre_src;
        if ((obj.value.length == 0 || obj.value == pre_src) && !isOut) obj.value = '';
    }
}

function checkSearch() {
    if ($.trim(textBox.val()) == "" || textBox.val() == pre_src)
        return false;
    return true;
}

function searchRedirect() {
    var query = $.trim(makeSafeString(textBox.val()));
    var fullUrl = '/catalog/0/search.aspx?brand=' + query;
    window.location.href = $.browser.msie ? fullUrl : encodeURI(fullUrl);
}

function makeSafeString(string) {
    return string.replace(/<\/?[^>]+>/gi, '').replace(/\\/g, '').replace(/\//g, '');
}
// --------------------------------конец SearchControl.ascx ----------------------------


// ------------------------------------- VisitedGoods.ascx
function scrollVisitedGoods(count) {
    var scrollNew = $(".scrollVisitedGoods");
    if (scrollNew.length != 0) {
        scrollNew.jCarouselLite({
            btnNext: ".nextNew",
            btnPrev: ".prevNew",
            visible: count,
            speed: 500
        });
    }
}

function scrollBuyGoods() {
    $().ready(function () {
        var scrollNew = $(".scrollBuyGoods");
        if (scrollNew.length != 0) {
            scrollNew.jCarouselLite({
                btnNext: ".nextNew",
                btnPrev: ".prevNew",
                visible: 4,
                speed: 500
            });
        }
    });
}

// ------------------------------------- MenuForService.ascx
$(document).ready(function () {
    var url = window.location.pathname;
    $.each($(".lft_menu_for_service ul a"), function () {
        if (url.indexOf(this.pathname) != -1) {
            var jThis = $(this);
            jThis.parent().addClass('selected');
            jThis.parent().parent().attr('class', 'display_block');
            if (jThis.parent().parent().parent()[0].tagName == 'LI') {
                jThis.parent().parent().parent().attr('class', 'active');
            }
        };
    });
});

function ShowElement(element) {
    var el = $(element);
    if (el.next().attr('class') == 'display_none') {
        el.parent().addClass('active');
        el.children().attr('class', 'arrow_dsmall_down');
        el.next().attr('class', 'display_block');
        return true;
    }
    else {
        el.parent().removeClass('active');
        el.children().attr('class', 'arrow_dsmall_right');
        el.next().attr('class', 'display_none');
        return false;
    }
}

// ------------------------------------- AbcIndex.ascx
$(document).ready(function () {
    $('#AbcIndexLinks a').each(function () {
        if (document.location.href.indexOf($(this).attr('href')) != -1) {
            $(this).parent().addClass('selected');
        }
    });
});


// ------------------------------------- accessories.aspx, child.aspx, men.aspx, shoes.aspx, women.aspx
$(document).ready(function () {
    if ($.browser.msie && parseInt($.browser.version) == 6) {
        if (typeof document.body.style.maxHeight === 'undefined') {
            $('.tb_ramka tbody tr, .tb_ramka2 tr tr').hover(
                    function () {
                        $(this).addClass('tr_over');
                    },
                    function () {
                        $(this).removeClass('tr_over');
                    }
                );
        }
    }
});

// ------------------------------------- tkani.aspx
function tkaniPopup() {
    var popup = document.getElementById('popup'),
			  lists = document.getElementsByTagName('dl');

    function closePopup() {
        $('.blank').css('visibility', 'hidden');
        popup.style.display = 'none';
        document.onkeyup = null;
    }
    for (var i = 0; i < popup.getElementsByTagName('a').length; i++) {
        (function (i) {
            popup.getElementsByTagName('a')[i].onclick = function () {
                if (this.href.indexOf('#close')) {
                    closePopup();
                    return false;
                }
            };
        })(i);
    }
    for (var j = 0; j < lists.length; j++) {
        if (lists[j].className.indexOf('list', 99)) {
            for (var i = 0; i < lists[j].getElementsByTagName('a').length; i++) {
                (function (i) {
                    lists[j].getElementsByTagName('a')[i].onclick = function () {
                        popup.getElementsByTagName('h4')[0].innerHTML = this.innerHTML;
                        document.getElementById('popup-content').innerHTML = this.parentNode.parentNode.getElementsByTagName('dd')[i].innerHTML;

                        $('#blank').css({ 'height': document.documentElement.scrollHeight + 'px', 'visibility': 'visible' });
                        $('#popup').insertAfter('#blank').show();

                        document.onkeyup = function (e) {
                            if (!e) e = window.event;
                            if (e.keyCode == 27) closePopup();
                        };
                        return false;
                    };
                })(i);
            }
        }
    }
    if (typeof (document.body.style.maxHeight) == 'undefined') { // lte IE6
        var ie6 = true;
        $('#popup').css('position', 'absolute');
        $('.conventional-signs').css('margin-left', '3px');
        $('.conventional-signs:first').css('margin-left', '0');
        $('.conventional-signs td:empty').css({ 'width': '50px', 'background-image': 'url(/Resources/Images/textile.png)', 'background-repeat': 'no-repeat' });
    };
}


// ------------------------------------- user_menu.ascx
$(document).ready(function () {
    var url = window.location;
    $.each($("#left_menu ul a"), function () {
        if ((url.pathname.indexOf(this.pathname) != -1) && (url.search.indexOf("Default=1") == -1)) {
            $(this).parent().addClass('selected');
        };
    });
});



// ------------------------------------- mark.ascx
function starSwitch(numStar, state) {
    var rat = document.getElementById(document.getElementById('hfClientIDhfRaiting').value).value;
    if (rat == "") {
        for (var i = 1; i <= numStar; i++) {
            ChangeImg('star' + i, GetMarkIamgeUrl(state));
        }
    }
}

function setRaiting(rat, idhf) {
    var theform = document.getElementById(idhf);
    theform.value = rat;
    var rating = parseInt("0" + rat);
    for (var i = 1; i <= 5; i++) {
        ChangeImg('star' + i, GetMarkIamgeUrl((i <= rating) ? "ON" : "OFF"));
    }
}

function GetMarkIamgeUrl(imageSuffix) {
    return "http://images.wildberries.ru/other/star" + imageSuffix + ".gif";
}

function preload() {
    if (document.images) {
        var imgsrc = preload.arguments;
        arr = new Array(imgsrc.length);
        for (var j = 0; j < imgsrc.length; j++) {
            arr[j] = new Image;
            arr[j].src = imgsrc[j];
        }
    }
}

function ChangeImg() {
    if (document.images) {
        eval("document." + ChangeImg.arguments[0] + ".src=('" + ChangeImg.arguments[1] + "')");
    }
}

// ------------------------------------- UserGoods.ascx
function GetIMG(imgPath, id) {
    var obj = document.getElementById('preview_' + id);
    if (obj != null) {
        obj.innerHTML = "<img src='images/small/" + imgPath + "'>";
    }
}

// ------------------------------------- shop/Order/Order.ascx
function SetInputBackground(param) {
    $(param).click(function () {
        $(".registered span:visible").each(
            function () {
                if (jQuery.css(this, 'visibility') == 'visible') {
                    $('#' + $(this).attr('class')).css('background-color', '#F8D0F8');
                }
                if (jQuery.css(this, 'visibility') == 'hidden') {
                    $('#' + $(this).attr('class')).css('background-color', '#ffffff');
                }
            }
        );
    });
}


// ------------------------------------- Posted.ascx

function ClickAll(obj) {
    var checked = obj.checked ? true : false;
    var objs = document.getElementsByName('idss');
    if (objs != null) {
        for (var i = 0; i < objs.length; i++) {
            objs[i].checked = checked;
        }
    }
}

function RefreshRowIds(isDelete, rids) {
    var objs = document.getElementsByName('idss');
    var hfield = document.getElementById(rids);
    var retval = '';

    if (objs != null) {
        for (var i = 0; i < objs.length; i++) {
            if (objs[i].checked == true) {
                retval = objs[i].value + '_' + retval;
            }
        }
    }

    if (retval.length > 3 && hfield != null) {
        hfield.value = retval;
        return confirm(isDelete ? 'Удалить выбранные товары?' : 'Переместить выбранные товары в корзину?');
    }

    return false;
}


// ------------------------------------- AbcBrandsFilter

function GetBrandListByLetter(letter, sender, id) {
    $('#dLetters a').removeClass("selected");
    $("#" + sender).addClass("selected");

    $.ajax({
        type: 'POST',
        url: "/ServiceApps/MainService.svc/GetBrandListByLetter",
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify({ letter: letter, id: id }),
        dataType: "json",
        success: function (response) {
            var brands;
            if (response != '{}') {
                brands = eval('(' + response + ')');
                var brandList = $('.brand-list');
                var brandListInner = '';
                brandList.empty();
                $.each(brands, function (index, brand) {
                    if (brand.Selected)
                        brandListInner += '<span class="selected" title="' + brand.Name + '">' + brand.Name + '</span>';
                    else
                        brandListInner += '<a title="' + brand.Name + '" href="' + brand.Link + '">' + brand.Name + '</a>';
                });
                brandList.html(brandListInner);
            }
        },
        failure: function (msg) {
            $('.brand-list').text("none");
        }
    });
}

function SetOnclick(letter, sender, id) {
    $("#" + sender).removeAttr("onclick").click(function () {
        GetBrandListByLetter(letter, sender, id);
        return false;
    });
}

// ----------------------------------- Tabs
$.fn.tabs = function () {
    var jThis = $(this);
    jThis.children('div').hide();
    jThis.find('div:first').show();
    jThis.find('ul li:first').addClass('current');

    jThis.find('ul li a').click(jThis, function (e) {
        e.data.find('ul li').removeClass('current');
        jThis.parent().addClass('current');
        var currentTab = $(jThis.attr('href'));
        e.data.children('div').hide();
        currentTab.show();
        return false;
    });
}
// ------------------------------------- GoodComments.ascx discussion

function EnableAnswerText(txt) {
    $('#Answer' + txt).val('');
    $('.error-msg').hide();
    if (txt == "") return;
    $('#txt' + txt).toggle();
    $('.comment-form').hide();
}

function answerAction(branch) {
    $('.confirm').hide();
    $('.error-msg').hide();
    $('.success-msg').hide();
    $('.reply-form').hide();
    $('#txt').hide();
    $('#DeleteDialog' + branch).hide();
    $('#txt' + branch).show();
    $('#Answer' + branch).val('').focus();
    $('.comment-form').hide();

    if (branch == ' ') {
        $('.comment-form').show();
        $('#txt' + branch).show();
        $('#Answer' + branch).val('').focus();
    }
}

function deleteAction(branch) {
    $('.confirm').hide();
    $('.error-msg').hide();
    $('.success-msg').hide();
    $('.reply-form').hide();
    $('#txt' + branch).hide();
    $('#DeleteDialog' + branch).show();
}

function containerToggle(container) {
    $('#' + container).toggle();
}

function validateMessageLength(branch, text) {
    $('.error-msg').hide();
    $('#Answer' + branch).focus();
    if (text.length < 10) {
        $('#errMin' + branch).show();
        return false;
    }

    if (text.length > 300) {
        $('#errMax' + branch).show();
        return false;
    }

    $('#errMin' + branch).hide();
    $('#errMax' + branch).hide();

    return true;
}

function addPostMessage(textId, branch, dceId) {
    $('#cmt').empty();

    var text = $("#" + textId).val().replace(/<\/?[^>]+>/gi, '');
    var valid = validateMessageLength(branch, text);
    if (valid) {
        $.ajax({
            type: 'POST',
            url: '/Resources/Services/SystemService.asmx/AddGoodsForumItem',
            contentType: "application/json; charset=UTF-8",
            data: '{"dceId":"' + dceId + '","message":"' + text + '","postBranch":"' + branch + '"}',
            success: function (response) {
                EnableAnswerText(branch);
                $('<div id="cmt" class="comment"/>').insertBefore('#Answer');
                $('#postedTemplate').tmpl(null).appendTo('#cmt' + branch);
                $('.commentsArea').text('300');
            },
            dataType: "json"
        });
    }
}

function GetGoodsForum(dceId, page) {
    $('#dAnswers').empty();
    $("#forumPage").text(page);

    selectForumPagerPage(page);
    $.ajax({
        type: 'POST',
        url: '/Resources/Services/SystemService.asmx/GetGoodsForum',
        contentType: "application/json; charset=UTF-8",
        data: '{"dceId":"' + dceId + '","page":"' + page + '"}',
        success: function (response) {
            $.each(response.d, function (index, answer) {
                $('#summaryTemplate').tmpl(answer).appendTo('#dAnswers');
            });
            $.scrollTo("#dvcmm", { duration: 0 });
        },
        dataType: "json"
    });
}

function RemoveForumItem(dceId, branch, dt) {
    var page = $("#forumPage").text() != 0
        ? page = $("#forumPage").text()
        : ($.urlParam('page') != 0 ? $.urlParam('page') : 1);

    $.ajax({
        type: 'POST',
        url: '/Resources/Services/SystemService.asmx/RemoveForumItem',
        contentType: "application/json; charset=UTF-8",
        data: '{"dceId":"' + dceId + '","page":"' + page + '","postBranch":"' + branch + '"}',
        success: function (response) {
            $("#container" + branch).addClass('deleted');
            $("#container" + branch).html('<div class="meta"><span class="time">' + dt + '</span>Комментарий был удален</div>');
        },
        dataType: "json"
    });
}

function selectForumPagerPage(page) {
    $("#divForumPager a").each(function (item) {
        $(this).removeClass("active");
        if ($(this).text() == page) {
            $(this).addClass("active");
        }
    });
}

function displayBranch(branch) {
    $("#dAnswers #container .comment").each(function () {
        if ($(this).attr('id').substring(0, branch.length) == branch && branch != $(this).attr('id'))
            $(this).parent().toggle('slow');
    });
}

$().ready(function () {
    $("#Answer").each(function () {
        $(this).limit('300', $('.commentsArea'));
    });
});

function selectTab(item, content) {
    $("#tabs-content > div").hide();
    $(".tabs .tab").removeClass('active');
    item.parent().addClass('active');
    $(content).show();

    if (content != '#discussion' && window.location.hash == '#discussion')
        window.location.hash = '';
}

function addSubscribe(sender, goodId, cod1s) {
    if (sender.checked) {
        $.ajax({
            type: 'POST',
            url: '/Resources/Services/SystemService.asmx/AddSubscribe',
            contentType: "application/json; charset=UTF-8",
            data: '{"goodId":"' + goodId + '","cod1s":"' + cod1s + '"}',
            dataType: "json",
            success: function (response) {
                $("#cmt-subscribe-container").html("Подписка оформлена.");
            }
        });
    }

    return false;
}

function setFocusDiscussion() {
    $.scrollTo("#dvcmm", { duration: 0 });
    return false;
}

// ------------------------------------- ShipmentMaps.ascx карта для пунктов самовывоза

function addAddress(value, address, drivingDirections, phones, samaWork, id, isOur) {
    if ($.browser.msie && $.browser.version == '6.0')
        return addAddressHttp(value, address, drivingDirections, phones, samaWork, id, key);

    var geocoder = new YMaps.Geocoder(value, { results: 1, boundedBy: map.getBounds() });

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            geoResult = this.get(0);

            var point = geoResult.getCoordPoint();
            var s = new YMaps.Style("default#violetPoint");
            s.iconStyle = new YMaps.IconStyle();

            s.iconStyle.href = "http://images.wildberries.ru/interface/wb2.png";
            s.iconStyle.size = new YMaps.Point(27, 26);

            var placemark = new YMaps.Placemark(point, { style: s });

            //вешаем свой обработчик нажатия мышки по метке
            YMaps.Events.observe(placemark, placemark.Events.Click, function () {
                showPickupPopup(id);
            });
            //блокируем показ балуна, делаем видимой метку
            YMaps.Events.observe(placemark, placemark.Events.BalloonOpen, function () {
                $(".YMaps-balloon").hide();
                $(".YMaps-placemark").removeClass("YMaps-Hidden");
                return false;
            });

            map.addOverlay(placemark);
        } else {
            alert("Ничего не найдено");
        }

        return true;
    });

    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) {
        showAddress($("#currentCity").text());
        return false;
    });
}

//Получаем точки из JSON посредством запроса к серваку. Для IE6
function addAddressHttp(value, address, drivingDirections, phones, samaWork, id, key) {
    $.ajaxSetup({ cache: false });
    $.getJSON('http://geocode-maps.yandex.ru/1.x/?callback=?', { key: key, geocode: value, format: 'json' }, function (data, status) {
        if (status == 'success') {
            drivingDirections = drivingDirections.length > 0 ? '<strong>Проезд:</strong> ' + drivingDirections + '<br />' : '';
            phones = phones.length > 0 ? '<strong>Телефоны:</strong> ' + phones + '<br />' : '';

            var style = new YMaps.Style("default#violetPoint");
            style.iconStyle = new YMaps.IconStyle();
            style.iconStyle.href = "http://images.wildberries.ru/interface/wb2.png";
            style.iconStyle.size = new YMaps.Point(27, 26);

            var position = data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos;

            var point = YMaps.GeoPoint.fromString(position.replace(' ', ','));

            var placemark = new YMaps.Placemark(point, { style: style });

            //вешаем свой обработчик нажатия мышки по метке
            YMaps.Events.observe(placemark, placemark.Events.Click, function () {
                showPickupPopup(id);
            });
            //блокируем показ балуна, делаем видимой метку
            YMaps.Events.observe(placemark, placemark.Events.BalloonOpen, function () {
                $(".YMaps-balloon").hide();
                $(".YMaps-placemark").removeClass("YMaps-Hidden");
                return false;
            });

            map.addOverlay(placemark);
        }
    });
}

function addCityMark(city) {

    if ($.browser.msie && $.browser.version == '6.0')
        return addCityMarkHttp(city, key);

    var geocoder = new YMaps.Geocoder(city.Name, { results: 1, boundedBy: map.getBounds() });

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            geoResult = this.get(0);

            var point = geoResult.getCoordPoint();
            var s = new YMaps.Style("default#violetPoint");
            s.iconStyle = new YMaps.IconStyle();

            s.iconStyle.href = "http://images.wildberries.ru/interface/wb2.png";
            s.iconStyle.size = new YMaps.Point(27, 26);

            var placemark = new YMaps.Placemark(point, { style: s });

            //вешаем свой обработчик нажатия мышки по метке
            YMaps.Events.observe(placemark, placemark.Events.Click, function () {
                selectCityForYMap(city.Id);
            });
            //блокируем показ балуна, делаем видимой метку
            YMaps.Events.observe(placemark, placemark.Events.BalloonOpen, function () {
                $(".YMaps-balloon").hide();
                $(".YMaps-placemark").removeClass("YMaps-Hidden");
                return false;
            });

            map.addOverlay(placemark);

        } else {
            alert("Ничего не найдено");
        }

        return true;
    });

    YMaps.Events.observe(geocoder, geocoder.Events.Fault, function (geocoder, error) {
        return false;
    });
}

//Получаем точки из JSON посредством запроса к серваку. Для IE6
function addCityMarkHttp(city, key) {
    $.ajaxSetup({ cache: false });
    $.getJSON('http://geocode-maps.yandex.ru/1.x/?callback=?', { key: key, geocode: city.Name, format: 'json' }, function (data, status) {
        if (status == 'success') {

            var style = new YMaps.Style("default#violetPoint");
            style.iconStyle = new YMaps.IconStyle();
            style.iconStyle.href = "http://images.wildberries.ru/interface/wb2.png";
            style.iconStyle.size = new YMaps.Point(27, 26);

            var position = data.response.GeoObjectCollection.featureMember[0].GeoObject.Point.pos;

            var point = YMaps.GeoPoint.fromString(position.replace(' ', ','));

            var placemark = new YMaps.Placemark(point, { style: style });

            //вешаем свой обработчик нажатия мышки по метке
            YMaps.Events.observe(placemark, placemark.Events.Click, function () {
                selectCityForYMap(city.Id);
            });
            //блокируем показ балуна, делаем видимой метку
            YMaps.Events.observe(placemark, placemark.Events.BalloonOpen, function () {
                $(".YMaps-balloon").hide();
                $(".YMaps-placemark").removeClass("YMaps-Hidden");
                return false;
            });

            map.addOverlay(placemark);
        }
    });
}

function showAddress(value) {
    if ($.browser.msie && $.browser.version == '6.0')
        return showAddressHttp(value, key);

    var geocoder = new YMaps.Geocoder(value);

    YMaps.Events.observe(geocoder, geocoder.Events.Load, function () {
        if (this.length()) {
            geoResult = this.get(0);
            map.setBounds(geoResult.getBounds());
        } else {
            alert("Ничего не найдено");
        }
    });
}

//Снова получаем точки через json.  Для IE6
function showAddressHttp(value, key) {
    $.ajaxSetup({ cache: false });
    $.getJSON('http://geocode-maps.yandex.ru/1.x/?callback=?', { key: key, geocode: value, format: 'json' }, function (data, status) {
        if (status == 'success') {
            var lowerCorner = data.response.GeoObjectCollection.featureMember[0].GeoObject.boundedBy.Envelope.lowerCorner;
            var lowerPoint = YMaps.GeoPoint.fromString(lowerCorner.replace(' ', ','));
            var upperCorner = data.response.GeoObjectCollection.featureMember[0].GeoObject.boundedBy.Envelope.upperCorner;
            var upperPoint = YMaps.GeoPoint.fromString(upperCorner.replace(' ', ','));
            var bounds = new YMaps.GeoBounds(lowerPoint, upperPoint);
            map.setBounds(bounds);
        }
    });
}

function initMap() {
    map = new YMaps.Map(YMaps.jQuery("#YMapsID")[0]);
    map.enableScrollZoom();

    var toolbar = new YMaps.ToolBar();
    var button = new YMaps.ToolBarToggleButton({
        icon: "http://api.yandex.ru/i/maps/icon-fullscreen.png",
        hint: "Разворачивает карту на весь экран"
    });

    YMaps.Events.observe(button, button.Events.Select, function () {
        setSize(960, 540, 0);
        $('#info_menu').hide();
    });

    YMaps.Events.observe(button, button.Events.Deselect, function () {
        setSize(761, 400, 0);
        $('#info_menu').show();
    });

    function setSize(newWidth, newHeight, marginLeft) {
        YMaps.jQuery("#YMapsID").css({
            width: newWidth,
            height: newHeight
        });

        $("#YMapsID").css("width", newWidth + "px");
        $("#YMapsID").css("height", newHeight + "px");
        $("#YMapsID").css("margin-left", marginLeft + "px");

        map.redraw();
    }

    toolbar.add(button);
    map.addControl(toolbar);
    map.addControl(new YMaps.Zoom());

    /* поиск
    var searchControl = new YMaps.SearchControl({
    resultsPerPage: 5,
    useMapBounds: 1
    });

    map.addControl(searchControl, new YMaps.ControlPosition(YMaps.ControlPosition.TOP_RIGHT, new YMaps.Point(10, 5)));
    */

    map.addControl(new YMaps.MiniMap());
}

function setCenter() {
    map.setCenter(new YMaps.GeoPoint(87.363281, 55.2627), 3);
}

function renderPoligons(poligons) {

    var style = new YMaps.Style("default#greenPoint");

    style.polygonStyle = new YMaps.PolygonStyle();
    style.polygonStyle.fill = 1;
    style.polygonStyle.outline = 1;
    style.polygonStyle.strokeWidth = 2;
    style.polygonStyle.strokeColor = "ffff0088";
    style.polygonStyle.fillColor = "ff000055";

    YMaps.Styles.add("polygon#Example", style);

    $.each(poligons, function (index, item) {

        var polygon = YMaps.Polygon.fromEncodedPoints(item.base64Poligon, "", {
            style: "polygon#Example",
            hasHint: 1,
            hasBalloon: 0
        });

        polygon.name = item.name;
        polygon.description = item.description;

        map.addOverlay(polygon);
    });
}


/* --------------------------- Albums */
function showAlbumDialog(visible, dialog, clear) {
    if (visible) {
        $(".blank").css({ "height": document.documentElement.scrollHeight + "px", "visibility": "visible" });
        $("#" + dialog).show();
        if ($.browser.msie && $.browser.version <= 7) {
            $(".trunkOld").css({ "position": "static", "margin-top": $(".trunkOld").css("top"), "margin-bottom": "0" });
        }
    }
    else {
        $(".blank").css("visibility", "hidden");
        $(".album-dialog").hide();
        $("#" + dialog).hide();
        $(".upload-dialog-error-message").hide();
        $('.error-message').html('');
    }

    return false;
}

function closeDialog(dialogClassName) {
    $(".blank").css("visibility", "hidden");
    $(dialogClassName).hide();
}

/* --------------------------- Albums View */
function showPhoto(index) {
    if (index == -1) index = photos.length - 1;
    if (index >= photos.length) index = 0;

    cur = parseInt(index);

    $(".photo-count").text("Фотография " + (parseInt(index) + 1) + " из " + photos.length);

    var path = photos[index].src.replace("ms_", "fs_");
    var comment = comments[index];
    $(".photo-container img")[0].src = path;
    $("#photo-dialog .description").text(comment);
    $("#photo-dialog").show();
}

/* --------------------------- Albums Edit */
function setCover(sender) {
    $('.photo-edit-list input:radio').attr('checked', false);
    $('#' + sender.id).attr('checked', true);
}


/*------------------------- UploadDialog */
var files = [];

function validateFileUpload(sender) {
    var filename = sender.value;
    var extension = filename.substr(filename.length - 3, 3);
    var validExtensions = new Array("jpg", "png", "gif");
    var flag = false;
    for (var index = 0; index < validExtensions.length; index++) {
        if (extension.toLowerCase() == validExtensions[index].toString().toLowerCase()) {
            flag = true;
            break;
        }
    }

    if (flag == false) {
        $('.error-message').html('Невозможно загрузить файл ' + filename + '. \r\nРазрешается загрузка файлов с расширениями ' + validExtensions);
        if (!$.browser.msie)
            $('#' + sender.id).val('');
        else {
            $('#' + sender.id).parent().html($('#' + sender.id).parent().html());
        }
        return false;
    }
    else {
        $('.error-message').html('');
        files.push(true);
        return true;
    }
}

function checkUploadExists() {
    if (files.length > 0)
        return true;
    else
        showAlbumDialog(false);
    return false;
}

/*-----PhotoConcurse----*/


/*--- Бесплатная доставка ---*/

function getCityServices(cityName) {

    var id = cityName ? -1 : $("#cityId").val();
    var name = cityName ? cityName : $("#cityName").val();
    var data = { cityName: cityName, cityId: id };

    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        url: '/ServiceApps/MainService.svc/GetServicesByCity',
        data: JSON.stringify(data),
        success: function (response) {
            var result = eval('(' + response + ')');
            if (result.error) {
                alert(result.message);
                return;
            }
            prepareHolders();
            renderResponse(result);
            $("#foundCityName").text(name);
        }
    });
}

function getPickupCities() {

    // если список городов уже заполнен
    if (cityList != null && cityList != undefined) {
        prepareCitySelector();
        createCitySelector(cityList);
        return;
    }
    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        url: '/ServiceApps/MainService.svc/GetPickupCities',
        data: JSON.stringify({}),
        success: function (response) {

            cityList = eval(response);
            prepareCitySelector();
            createCitySelector(cityList);
        }
    });
}

function prepareCitySelector() {
    try {
        map.removeAllOverlays();
    } catch (e) { };

    $("#citySelectorLink").hide();
    $("#citySelectorNoLink").show();
    $("#addressList ul").html("");
    $("#cityPickupList").html("");
    $("#currentCity").text("Россия");

    try {
        map.setMaxZoom(6);
    } catch (e) { };
}

function createCitySelector(response) {
    hideCityList();
    var cityPickupL = $("#cityPickupList");
    cityPickupL.append("<div class='allCities' onclick='javascript:getPickupCities()'><strong>Вся Россия</strong></div>");
    cityPickupL.append("<div class='delimiter'></div>");

    var cityPickupTmpl = $("#cityPickupTemplate");
    var cityMenuTmpl = $("#cityMenuTemplate");
    var cityListCap = new Array();
    var cityListExcl = new Array();

    for (var j = 0; j < response.length; j++) {
        var item = response[j];
        if (item.Id == moscowId || item.Id == sankPeterId) {
            cityListCap.push(item);
        } else {
            cityListExcl.push(item);
        }
        try {
            addCityMark(item);
        } catch (e) { };
    }

    cityPickupTmpl.tmpl(cityListCap).appendTo(cityPickupL);
    cityMenuTmpl.tmpl(cityListCap).appendTo("#addressList ul");

    $("#addressList ul li div.region-name").hide();
    $("#addressList ul").append("<li class='delimiter'><div></div></li>");
    cityPickupL.append("<div class='delimiter'></div>");

    cityPickupTmpl.tmpl(cityListExcl).appendTo(cityPickupL);
    cityMenuTmpl.tmpl(cityListExcl).appendTo("#addressList ul");

    try {
        map.setZoom(4, { position: new YMaps.GeoPoint(57, 55.5), centering: true });
    }
    catch (e) { };
}

function selectCityForYMap(id) {

    $.ajax({
        type: 'POST',
        contentType: "application/json; charset=UTF-8",
        dataType: "json",
        url: '/ServiceApps/MainService.svc/GetServicesByCity',
        data: JSON.stringify({ cityId: id }),
        success: function (response) {
            $("#citySelectorNoLink").hide();
            $("#citySelectorLink").show();
            try {
                map.removeAllOverlays();
                map.setMaxZoom(20);
                fillYMapData(eval(response));
            }
            catch (e) { };
        }
    });
    hideCityList();
}

function fillYMapData(response) {
    $("#addressList ul li").remove();
    pickUplist = response;

    for (var i = 0; i < response.length; i++) {
        switch (response[i].Type) {
            case 1:
                addPickupToYMap(response[i]);
                break;
        }
    }
    $("#addressList ul").append("<li><a class='allCities' onclick='javascript:getPickupCities()'>Вся Россия</a></li>");

    showAddress($("#currentCity").text());
}

function addPickupToYMap(deliveryService) {
    $("#currentCity").text(deliveryService.CityName);

    try {
        addAddress(deliveryService.CityName + ", " + deliveryService.Address, deliveryService.Address, deliveryService.WayInfo, deliveryService.Phones, deliveryService.WorkTime, deliveryService.Id, deliveryService.OurOffice);
    } catch (e) { };

    deliveryService.CustomAddress = deliveryService.Address.replace(deliveryService.Address.split(',')[0], "<strong>" + deliveryService.Address.split(',')[0] + "</strong>");

    $("#pickupMenuTemplate").tmpl(deliveryService).appendTo("#addressList ul");

    $("#address_" + deliveryService.Id).click(function () {
        try {
            showAddress(deliveryService.CityName + ", " + deliveryService.Address);
        } catch (exp) { };
    });
}

function showCityList() {
    $("#cityPickupList").show();
}

var registerAutoHide = function (event, buttonId, dropdownId) {
    if (!$((event.target) ? event.target : event.srcElement).parents().andSelf().is("#" + buttonId + ", #" + dropdownId) &&
                    !$((event.target) ? event.target : event.srcElement).is("#" + buttonId))
        $("#" + dropdownId).hide();
};

function hideCityList() {
    $("#cityPickupList").hide();
}

function prepareHolders() {

    $("#citySearchResult").hide();
    $("#pickupsResult").hide();

    $("#courierServiseResult").html("");
    $("#pickupsList").html("");
}

function renderResponse(response) {

    for (var i = 0; i < response.length; i++) {
        switch (response[i].Type) {
            case 0:
                addCourierServise(response[i]);
                break;
            case 1:
                addPickup(response[i], response.length);
                break;
        }
    }

    if (response.length > 0)
        $("#citySearchResult").show();

    $(".list-header").each(function () {
        var obj = $(this);
        obj.unbind("click").bind("click", function () {
            obj.parent().toggleClass("list-container-hide");
        });
    });
}

function addCourierServise(deliveryService) {

    switch (deliveryService.DeliveryTime) {
        case 0:
            deliveryService.DeliveryTimeStr = "в день заказа";
            break;

        case 1:
            deliveryService.DeliveryTimeStr = "на следующий день";
            break;

        case 21, 31, 41, 51, 61:
            deliveryService.DeliveryTimeStr = deliveryService.DeliveryTime + " день";
            break;

        case 2, 3, 4, 22, 23, 24, 32, 33, 34, 42, 43, 44:
            deliveryService.DeliveryTimeStr = deliveryService.DeliveryTime + " дня";
            break;

        default:
            deliveryService.DeliveryTimeStr = deliveryService.DeliveryTime + " дней";
    }

    $("#courierTemplate").tmpl(deliveryService).appendTo("#courierServiseResult");
}

function addPickup(deliveryService, countServices) {

    deliveryService.LargeImagePath = baseImagePath + deliveryService.ImageLocationPath + "_" + largePreffix + extension;
    deliveryService.SmallImagePath = baseImagePath + deliveryService.ImageLocationPath + "_" + smallPreffix + extension;
    deliveryService.AddressTitle = deliveryService.Address.split(',')[0];

    // если 1 курьерский сервис и больше одного самовывоза то берем другой template
    if (countServices > 2) {
        $("#manyPickupTemplate").tmpl(deliveryService).appendTo("#pickupsList");
    }
    else {
        $("#simplePickupTemplate").tmpl(deliveryService).appendTo("#pickupsList");
    }

    $("#pickupsResult").show();
}

function onSelectCity(value, data) {

    $("#cityId").val(data.Id);
    $("#cityName").val(data.Name);
    getCityServices(false);
}

var reEscape = new RegExp('(\\' + ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'].join('|\\') + ')', 'g');

function myfnFormatResult(value, data, currentValue) {
    var pattern = '(' + currentValue.replace(reEscape, '\\$1') + ')';
    return value.replace(new RegExp(pattern, 'gi'), '<strong>$1<\/strong>') + '<div class="region-name">' + data.RegionName + '</div>';
}

function drawDeliveryMap() {
    try {
        map = new YMaps.Map(YMaps.jQuery("#YMapsID")[0]);
        map.setCenter(new YMaps.GeoPoint(57, 55.5), 10);
        map.setZoom(4);
        map.setMaxZoom(6);
        map.setMinZoom(2);

        map.enableScrollZoom();

        var toolbar = new YMaps.ToolBar();
        var button = new YMaps.ToolBarToggleButton({
            icon: "http://api.yandex.ru/i/maps/icon-fullscreen.png",
            hint: "Разворачивает карту на весь экран"
        });

        YMaps.Events.observe(button, button.Events.Select, function () {
            setSize(920, 540, 0);
            $('#search_menu').hide();
        });

        YMaps.Events.observe(button, button.Events.Deselect, function () {
            setSize(670, 400, 0);
            $('#search_menu').show();
        });

        function setSize(newWidth, newHeight, marginLeft) {
            YMaps.jQuery("#YMapsID").css({
                width: newWidth,
                height: newHeight
            });

            $("#YMapsID").css("width", newWidth + "px");
            $("#YMapsID").css("height", newHeight + "px");
            $("#YMapsID").css("margin-left", marginLeft + "px");

            map.redraw();
        }

        toolbar.add(button);

        map.addControl(toolbar);
        map.addControl(new YMaps.Zoom());

        setSize(670, 400, 0);
        setCenter();
    } catch (e) { };
}

function showPickupPopup(id) {

    var h = 0;

    if ($.browser.msie && $.browser.version <= 7) {
        //$(".trunkOld").css("position", "static");
        $('.popup.jqmWindow').insertAfter('#blank');
        h = 161;
    }
    $('#blank').css({ 'height': document.documentElement.scrollHeight + 'px', 'visibility': 'visible' });
    $('.popup').show();

    $('.popup.jqmWindow').css({ 'top': ($(window).height() - $('.popup').height()) / 2 - $('.trunkOld').offset().top + $(window).scrollTop() + h + 'px' });
    $(document).bind('keydown', function (e) {
        if (!e) e = window.event;
        if (e.keyCode == 27) {
            closePickupPopup();
        }
    });

    $("#pickupPopup").html("");
    for (var i = 0; i < pickUplist.length; i++) {
        if (pickUplist[i].Id == id) {
            var deliveryService = pickUplist[i];

            deliveryService.SmallPhotos = new Array();
            deliveryService.BigPhotos = new Array();

            deliveryService.LargeImagePath = baseImagePath + deliveryService.ImageLocationPath + "_" + largePreffix + extension;

            deliveryService.SmallPhotos.push(baseImagePath + deliveryService.ImageLocationPath + "_" + previewPreffix + extension);
            deliveryService.BigPhotos.push(baseImagePath + deliveryService.ImageLocationPath + "_" + largePreffix + extension);

            if (deliveryService.ImagesCount == null || deliveryService.ImagesCount == undefined)
                deliveryService.ImagesCount = 0;

            if (deliveryService.ImagesCount > 0) {
                for (var j = 0; j < deliveryService.ImagesCount; j++) {
                    deliveryService.SmallPhotos.push(baseImagePath + deliveryService.ImageLocationPath + "_" + previewPreffix + photoPreffix + j + extension);
                    deliveryService.BigPhotos.push(baseImagePath + deliveryService.ImageLocationPath + "_" + photoPreffix + j + extension);
                }
            }

            $("#pickupPopupTemplate").tmpl(deliveryService).appendTo("#pickupPopup");
        }
    }
    $("button.disabled").live('click', function (e) {
        e.preventDefault();
        return false;
    });
    var scrollNew = $("#scrollImage");
    if (scrollNew.length != 0) {
        scrollNew.jCarouselLite({
            btnNext: "#scroller-next",
            btnPrev: "#scroller-prev",
            width: 106,
            circular: false,
            visible: 4
        });
    }
    scrollNew.show();

    $("ul.carousel li a").click(function (e) {
        $("#photo_big").attr("src", $(this).attr("rev"));
        $("ul.carousel li img").removeClass("selected");
        $("img", $(this)).addClass("selected");
        return false;
    });

    $(".print-image").unbind("click").click(function () {

        if ($("#popupPrint").length == 0)
            $("body").append("<div id='popupPrint' />");

        $("#popupPrint").html("");
        $("#pickupPopup").clone().appendTo("#popupPrint");
        $("#carousel, .print-image", $("#popupPrint")).remove();
        window.print();
        return false;
    });

    return false;
}

function changeBigPhoto(obj, url) {

    $("#pickupPopup li img").removeClass("selected");
    $(obj).addClass("selected");
    $("#photo_big").attr("src", url);
}

function closePickupPopup() {
    $('.popup').hide();
    $('#blank').css({ 'visibility': 'hidden', 'display': 'block' });
    $(document).unbind('keydown');
}

function clickOnTab(tabId) {
    $('.delivery-terms').hide();
    $('.tab').removeClass('active');
    if (tabId && !tabId.type) {
        $("#b-" + tabId.replace('#', '')).show();
        $(tabId).parent().addClass('active');
    } else {
        $($(this).attr('href')).show();
        $(this).parent().addClass('active');
    }
    try {
        map.redraw();
    } catch (e) { };

    return false;
}

function deliveryInit() {
    var ancor = this.location.hash;
    if (ancor && ancor != "") {
        clickOnTab(ancor);
    }

    $($("#b-services .list-header").parent()).each(function (index) {
        if (index != 0)
            $(this).addClass("list-container-hide");
    });

    $('.popup .close').click(function () {
        closePickupPopup();
        return false;
    });

    $('.tabs a').click(clickOnTab);

    var cityName = $('#cityName');
    // добавление watermark на textbox
    if (cityName.val() == '') {
        cityName.val(enterCityMessage);
        cityName.addClass('citySearch');
    }

    cityName.keyup(function (event) {
        var code;
        if (!e) var e = event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;

        if (code == 13)
            return false;
        if (code == 27)
            cityName.val('');
    });

    cityName.focus(function () {
        cityName.removeClass('citySearch');

        if (cityName.val() == enterCityMessage)
            cityName.val('');
    });

    cityName.blur(function () {
        if (cityName.val() == '')
            setTimeout("$('#cityName').addClass('citySearch'); $('#cityName').val(enterCityMessage);", 100);
    });

    cityName.keydown(function (event) {
        var code;
        if (!e) var e = event;
        if (e.keyCode) code = e.keyCode;
        else if (e.which) code = e.which;


        if (code == 13) {
            var cityNameVal = cityName.val();
            if (cityNameVal != "" && cityNameVal != enterCityMessage) {
                getCityServices(cityNameVal);
                autoComplete.hide();
            }
            // блокируем при нажатии на enter общий поиск по сайту
            return false;
        }
    });

    autoComplete = cityName.autocomplete({
        serviceUrl: '/ServiceApps/MainService.svc/FindCity',
        minChars: 2,
        width: 450,
        zIndex: 9999,
        maxHeight: 185,
        deferRequestBy: 500,
        noCache: false,
        fnFormatResult: myfnFormatResult,
        onSelect: onSelectCity
    });

    $("#submitBtn").bind("click", function () {
        var cityNameVal = cityName.val();
        if (cityNameVal != "" && cityNameVal != enterCityMessage) {
            getCityServices(cityNameVal);
            autoComplete.hide();
        }
    });

    $(".list-header").each(function () {
        var obj = $(this);
        obj.unbind("click").bind("click", function () {
            obj.parent().toggleClass("list-container-hide");
        });
    });

    getPickupCities();

    $(document).click(function (event) {
        registerAutoHide(event, "citySelectorLink", "cityPickupList");
    });

    $("a.region-link").bind("click", function () {
        $($(this).attr("href")).toggle();
        return false;
    });

}

/*--- Бесплатная доставка ---*/

/*--- Выпадающий список для выбора способа доставки, начало ---*/

function ViewDiv(id) {
    var dropList = document.getElementsByName(nameDropList);
    var obj = document.getElementById(id);
    for (var i = 0; i < dropList.length; i++) {
        if (dropList[i].id != obj.id) {
            dropList[i].style.display = 'none';
        }
    }
    if (obj != null) {
        if (obj.style.display != 'block') {
            obj.style.display = 'block';
        }
        else {
            obj.style.display = 'none';
        }
    }
    obj = null;
    i = null;
    dropList = null;
}

//функция отображения/ передачи данных из DIV`а
function selectItem(itemText, lblID, vhfId, divID, hfId, val) {
    var lbl = document.getElementById(lblID);
    var vhf = document.getElementById(vhfId);
    var hf = document.getElementById(hfId);
    var str;
    var str2;
    if (lbl != null && vhf != null && hf != null && divID != null) {
        // удаление HTML тегов из строки 			 	
        var space = $.browser.msie && ($.browser.version >= 6 && $.browser.version <= 8) ? ' ' : '';
        str2 = itemText.replace(/<\/?[^>]+>/gi, space).replace('  ', ' ');

        lbl.innerHTML = str2;
        vhf.value = str2;
        hf.value = val;

        ViewDiv(divID);
        var textArea = document.getElementById('ctl00_ctl00_ContentPlaceHolder_ContentPlaceHolder_devOrder_ADRES');
        if (textArea != undefined) {
            textArea.value = str2;
        }
    }
    lbl = null;
    vhf = null;
    hf = null;
}

function hideMyDiv(e) {
    var e;
    if (!e) e = window.event;
    var tg = (window.event) ? e.srcElement : e.target;

    if (tg.getAttribute('name') == nameLabel || tg.getAttribute('name') == nameButton || tg.getAttribute('id') == 'pseudoselect-back') {
        return;
    }

    //var dropList = document.getElementsByName(nameDropList); 
    //getElementsByTagName('DIV')[i]
    var IE = '\v' == 'v';
    if (IE || navigator.userAgent.indexOf('MSIE 9.0') != -1) {
        var dropList = document.getElementsByTagName('div');
        for (var i = 0; i < dropList.length; i++) {
            if (dropList[i].getAttribute('name') == nameDropList) {
                dropList[i].style.display = 'none';
            }

        }
    }
    else {
        var dropList = document.getElementsByName(nameDropList);
        for (var i = 0; i < dropList.length; i++) {

            dropList[i].style.display = 'none';
        }
    }

    e = null;
    i = null;
    tg = null;
    dropList = null;
    IE = null;
}




function ViewEvents() {
    if (window.addEventListener) {
        window.addEventListener('click', hideMyDiv, false);
    }
    else if (document.addEventListener) {
        document.addEventListener('click', hideMyDiv, false);
    }
    else if (document.attachEvent) {
        document.attachEvent('onclick', hideMyDiv);
    }
}

// Предотвращение выпадения списка из декоративного <select>
function selectOnclick(e, sender) {
    e = e || window.event;
    e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
    setTimeout(function () { sender.disabled = false; }, 10);
}

//  Проверка версии браузера. 
function checkBrowser(sender) {
    if ($.browser.msie)
        if ($.browser.version == '9.0') {
            return false;
        }
        else {
            sender.disabled = true;
            selectOnclick(e, sender);
        }
}
/*--- конец ---*/


/*--- topmenu.js start ---*/
$(document).ready(function () {
    $(".menu_topjs li.category").hoverIntent({
        over: show,
        out: hide,
        interval: 30,
        timeout: 30,
        sensitivity: 4
    });

    function show() {
        var current = $(this);
        if (current.attr('id') == "beauty-link") return false;
        var ulWrapper = current.find("ul.wrapper");
        $("#ie6iframe").css({ "width": ulWrapper.width(), "height": ulWrapper.height(), "left": ulWrapper.css("left"), "right": ulWrapper.css("right") }).show();
        if (current.attr("class") != "category selected") {
            current.find("a").first().addClass("unfolded");
        }
        current.find("ul.wrapper").show();
    }

    function hide() {
        $("#ie6iframe").hide();
        if ($(this).attr("class") != "category selected") {
            $(this).find("a").first().removeClass("unfolded");
        }
        $(this).find("ul.wrapper").hide();
    }

});
/*--- topmenu.js end ---*/

