﻿var searchBox;
var searchSlide;
var searchContainer;
var languagePop;
var lAlias;
var textErrorTryAgain;
var textSearch;
var textYourNumberIsAdded;
var textErrorFieldsAreFilledInIncorrectly;
var textThankYou;
var textShowSearchForm;
var textHideSearchForm;
var textAddToCart;
var textCancel;
var textBuyUpper;
var textRemoveFromCart;
var textItemRemovedFromCart;
var textCheckoutWithoutArrow;

var cnEmail;


function TextInitialize() {
    textErrorTryAgain = $('#textErrorTryAgain').val();
    textSearch = $('#textSearch').val();
    textYourNumberIsAdded = $('#textYourNumberIsAdded').val();
    textErrorFieldsAreFilledInIncorrectly = $('#textErrorFieldsAreFilledInIncorrectly').val();
    textThankYou = $('#textThankYou').val();
    textShowSearchForm = $('#textShowSearchForm').val();
    textHideSearchForm = $('#textHideSearchForm').val();
    textAddToCart = $('#textAddToCart').val();
    textCancel = $('#textCancel').val();
    textBuyUpper = $('#textBuyUpper').val();
    textRemoveFromCart = $('#textRemoveFromCart').val();
    textItemRemovedFromCart = $('#textItemRemovedFromCart').val();
    textCheckoutWithoutArrow = $('#textCheckoutWithoutArrow').val();
}

$(document).ready(function () {
    lAlias = $('#lAlias').val();
    TextInitialize();
    MainMenu();
    Boss();
    $("#aspnetForm")[0].setAttribute('autocomplete', 'off');

    searchBox = $("input[id$=searchBox]");
    searchSlide = $("#divSearchSlide");
    searchContainer = $("#tSearchSlide");
    languagePop = $("#divLanguagePop");

    $(document).click(function () {
        searchSlide.hide();
        languagePop.removeClass("open");
    });

    $(searchSlide).click(function (e) {
        e.stopPropagation();
    });
    $(searchBox).click(function (e) {
        e.stopPropagation();
    });

    $("#spanLanguageChange").unbind("click").click(function (e) {
        if (languagePop.hasClass("open")) {
            languagePop.removeClass("open");
        } else {
            languagePop.addClass("open");
        }
        e.stopPropagation();
    });

    cnEmail = $('#competitionNoticeEmail');
    cnEmail.val('');
    cnEmail.blur(function () {
        ValidCnEmail();
    });

    function ValidCnEmail() {
        var valid = true;
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test(cnEmail.val())) {
            cnEmail.removeErrorStyle();
        } else {
            cnEmail.markErrorField();
            valid = false;
        }

        return valid;
    }

    $("#aCompetitionSubscribePopup").click(function () {
        $('#divPopupCompetitionNotices').fadeIn();
        return false;
    });

    $("#competitionSubscribe").click(function () {
        if (ValidCnEmail()) {
            СompetitionSubscribe();
        }
        return false;
    });

    $(searchSlide).click(function (e) {
        e.stopPropagation();
    });
    $(searchBox).click(function (e) {
        e.stopPropagation();
    });

    $("#aCities").unbind("click").click(function () {
        if ($("#divCities").hasClass("open")) {
            $("#divCities").removeClass("open");
            $("#divCities").hide();
        }
        else {
            $("#divCities").addClass("open");
            $("#divCities").fadeIn();
        }
        return false;
    });

    CallTrack();

    $("select[id$=ddlRegion]").unbind("change").change(function () {
        var result = "";
        if ($(this).val() != "all")
            result = $(this).val();
        $("input[id$=hAlias]").val(result);
    });

    $(".more").unbind("click").click(function () {
        $("#pMoreInfo").removeClass("more-info");
        $(this).remove();
    });

    PinnedSite();
});

function GlobalSearch() {
    var tb = searchBox[0];
    var reg = /[^0-9a-zA-Zа-яА-ЯЁё.,()\-\/ ]/;
    if (tb.value.match(reg)) {
        var replaced = tb.value.split(reg).join("");
        tb.value = replaced;
    }
    GetSearchSlide();
}

function GetSearchSlide() {
    var request = searchBox[0].value;
    if (request.replaceAll(" ", "").length > 1) {
        execText(request, $("#tSearchSlide"));
    }
    else {
        $("#divSearchSlide").hide();
    }
}

function execText(cmd, container) {
    var language = '';
    if (lAlias.length > 0)
        language = '/' + lAlias;

    $.ajax({
        type: "POST",
        url: language + "/AjaxHandler.ashx",
        data: cmd,
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        timeout: 30000,
        success: function(response) { confirmTextCommand(response, container); },
        error: function (response) { $.notifier(textErrorTryAgain, "error"); }
    });
}

function confirmTextCommand(response, container) {
    var request = searchBox[0].value;

    if (response != "" && request.replaceAll(" ", "").length > 1) {
        searchContainer.html(response);
        $("#divSearchSlide").show();
    }
    else {
        $("#divSearchSlide").hide();
    }
}

function exec(cmd) {
    var sort = $("input[id $= hSort]").val();
    
    var language = '';
    if (lAlias.length > 0)
        language = '/' + lAlias;

    $.ajax({
        type: "POST",
        url: language + "/jQueryAjaxRequest.aspx/HandleCommand",
        data: "{command : '" + cmd + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) { confirmCommand(response); },
        error: function (response) { $.notifier(textErrorTryAgain, "error"); }
    });
}

function CallTrack() {
    $(document).bind('keydown', function(event) {
        if (event.ctrlKey && event.keyCode == '13') {
            $("#divPopupCallTRacker").fadeIn();
            pageTracker._trackPageview("/call_tracker");
            $(document).unbind('keydown');
        }
    });
}

$(document).ready(function() {
    $("a.bg-out").click(function(event) {
        //$("div.plus-popup").toggleClass('opened');
        $("div.plus-popup-content").toggleClass('opened');
        $("div.plus-popup").toggleClass('on');
        event.stopPropagation();
    })

    $("li[id^=liFamily_]").click(function() {
        var id = this.id.split('_')[1];
        $("li[id^=liFamily_]").removeClass("cur");
        $(this).addClass("cur");
        $("div[id^=divItms_]").hide();
        $("div[id^=divItms_" + id + "]").show();
    });

    searchBox.focus(function() {
        $("#divCallNote").hide();
        $(".search").toggleClass('active');
        if ($(this).val() == textSearch) {
            $(this).val("");
        }
        GetSearchSlide();
    });
    searchBox.blur(function() {
        $(".search").toggleClass('active');
        if ($(this).val() == "") {
            $(this).val(textSearch);
        }
    });

    $(".popup-anchor").hover(
        function() {
            //$(this).next("div").css('display', 'block').fadeIn(500);
        },
        function() {
            $(this).next("div").css('display', 'none');
        }
    );
    $(".popup-anchor").click(function() {
        $(this).next("div").css('display', 'block').fadeIn(500);
    });

    $(document).bind("click", function() {
        $("div.plus-popup").removeClass('opened');
    });

    $(".open-video-popup").click(function() {
        $(".video-link").fadeIn();
    })
    $("#aCallOpen").click(function() {
        $("#divCallMePlease").fadeIn();
        return false;
    });

    $("#aCallOpen").hover(
        function() {
            $("#aAddCallMe").show();
            $("#divCallNote").fadeIn(300);
        },
        function() {
            $("#divCallNote").hide();
        }
    );

    $("*[class*=popup-close]").click(function() {
        $("*[class*=popup-position]").fadeOut();
    })

    $("#divCallMePlease #tbPhone").mask("(999) 999-99-99");

    $("#aAddCallMe").unbind("click").click(function() {
        $(this).hide();
        var name = HtmlEncode($("#divCallMePlease #tbName").val());
        var phone = $("#divCallMePlease #tbPhone").val();
        var comment = HtmlEncode($("#divCallMePlease #tbComment").val());
        if (name != '' && phone != '') {
            $.ajax({
                type: "POST",
                url: "/jqueryajaxrequest.aspx/AddCallMe",
                data: '{name: "' + name + '", phone: "' + phone + '", comment: "' + comment + '", url: "' + top.location + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) { $('#divCallMePlease').fadeOut(); pageTracker._trackPageview("/zvonok_katerine"); gaCallMe(response.d); $.notifier(textYourNumberIsAdded, "success"); },
                error: function () { $('#divCallMePlease').fadeOut(); $.notifier(textErrorTryAgain, "error"); }
            });
        }
        else {
            $(this).show();
            $.notifier(textErrorFieldsAreFilledInIncorrectly, "error");
        }
    });

    $("#aAddErrorRequest").unbind("click").click(function() {
        $(this).hide();
        var name = HtmlEncode($("#divErrorRequest #tbNameError").val());
        var text = HtmlEncode($("#divErrorRequest #tbText").val());
        if (name != '' && text != '') {
            $.ajax({
                type: "POST",
                url: "/jQueryAjaxRequest.aspx/AddErrorRequest",
                data: '{name: "' + name + '", text: "' + text + '", url: "' + top.location + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { $('#divErrorRequest').fadeOut(); pageTracker._trackPageview("/error_request"); $.notifier(textThankYou, "success"); },
                error: function () { $('#divErrorRequest').fadeOut(); $.notifier(textErrorTryAgain, "error"); }
            });
        }
        else {
            $(this).show();
            $.notifier(textErrorFieldsAreFilledInIncorrectly, "error");
        }
    });
});

var divPopHover = false;
function MainMenu() {
    $(document).bind("click", function() {
        $("div[id^=divPop_]").hide();
        $("*[id^=spanF_]").removeClass("onvar");
    });
    $("*[id^=spanF_]").hover(function(event) {
        var id = parseInt(this.id.split('_')[1]);
        $("*[id^=spanF_]").removeClass("onvar");
        $(this).addClass("onvar");
        $("div[id^=divPop_]").hide();
        $("div[id=divPop_" + id + "]").show();
        event.stopPropagation();
    });
    $("div[id^=divPop_]").hover(function(event) {
        divPopHover = true;
    }, function() {
        divPopHover = false;
        $("*[id^=spanF_]").removeClass("onvar");
        $("div[id^=divPop_]").hide();
    });
    $("*[id^=spanF_]").click(function(event) {
        var id = parseInt(this.id.split('_')[1]);
        $("*[id^=spanF_]").removeClass("onvar");
        $(this).addClass("onvar");
        $("div[id^=divPop_]").hide();
        $("div[id=divPop_" + id + "]").show();
        event.stopPropagation();
    });
}

function ValidateEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    return reg.test(email);
}


//notifier
(function($) {
    $.notifier = function(message, type) { notify(message, type); }

    function notify(message, type) {
        var instance = $(document.getElementById('divNoticeContainer'));
        var html = jQuery.notifier.settings.noticeTemplate;
        html = html.replace('%Message%', message);

        if (type == "success")
            html = html.replace('%CssClass%', 'b-notif-success');
        else if (type == "error")
            html = html.replace('%CssClass%', 'b-notif-error');

        var notice = $(html).hide().fadeIn(jQuery.notifier.settings.noticeFadeTimeout);

        $.notifier.settings.noticeDisplay(notice);
        instance.append(notice);

        if ($.notifier.settings.displayTimeout > 0) {
            setTimeout(function() {
                jQuery.notifier.settings.noticeRemove(notice, function() {
                    notice.remove();
                });
            }, jQuery.notifier.settings.displayTimeout);
        }
    };

    $.notifier.settings = {
        noticeTemplate: '<div class="%CssClass%">%Message%</div>',
        noticeDisplay: function(notice) {
            notice.fadeIn(jQuery.notifier.settings.noticeFadeTimeout);
        },
        noticeRemove: function(notice, callback) {
            notice.animate({ opacity: '0', height: '0px' }, { duration: jQuery.notifier.settings.noticeFadeTimeout, complete: callback });
        },
        noticeFadeTimeout: 'slow',
        displayTimeout: 5000
    };
})(jQuery);

//function pageLoad(sender, args) {
//    if (args.get_isPartialLoad()) {
//        completeNotify();
//    }
//}

function completeNotify() {
    var inputs = $("input[id*=hCommandStatusMessage]");
    for (var i = 0; i < inputs.length; i++) {
        var message = inputs[i].value;
        if (message) {
            $.notifier(message);
            inputs[i].value = '';
        }
    }
}

if (Array.indexOf == "undefined" || !Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

function HtmlEncode(value) {
    return $('<div/>').text(value).html().replace(/\"/g, "&quot;");
}

function HtmlDecode(value) {
    return $('<div/>').html(value).text().replace(/&quot;/g, "\"");
}

String.prototype.replaceAll = function(search, replace) {
    return this.split(search).join(replace);
}

function gaCallMe(id) {
    var page = "/call_analytics_" + id;
    pageTracker._trackPageview(page);
}


//===Title.js===
//function Competition() {
//    var cookieName = "CompetitionVote";

    //var value = GetCookie(cookieName);
    //if (value == null) {
        //$("#divPopupCompetition").fadeIn();
        //SetCookie(cookieName, "show", new Date(new Date().getTime() + year).toUTCString());
        //pageTracker._trackPageview("/competition_promo");
    //}
//}


function SetCase(obj) {
    var toCase = obj.id.split('_')[1];
    setSwitch(toCase);

}
function setSwitch(newCase) {
    $("li[id*=liLider]:visible").fadeOut(300, function() {
        $("span[class=on]").removeClass("on");
        $("li[id=liLider_" + newCase + "]").fadeIn(300);
        $("span[id=spanCase_" + newCase + "]").addClass("on");
    });
}
function NextCase() {
    if ($("span[class=on]").size() > 0) {
        var currentCase = $("span[class=on]")[0].id.split('_')[1];
        var nextC = (parseInt(currentCase) + 1).toString();
        var nextCaseObj = $("span[id=spanCase_" + nextC + "]");
        if (nextCaseObj.length == 0) nextC = 0;
        setSwitch(nextC);
    }
}
function PrevCase() {
    if ($("span[class=on]").size() > 0) {
        var currentCase = $("span[class=on]")[0].id.split('_')[1];
        var prevC;
        if (currentCase > 0) prevC = (parseInt(currentCase) - 1).toString();
        else prevC = $("span[id*=spanCase_]:last")[0].id.split('_')[1];
        setSwitch(prevC);
    }
}

$(document).ready(function() {
    var timerName = "timer1";
    $(document).everyTime("7s", timerName, function(i) {
        NextCase();
    });
    $("div[id*=divLeaders]").bind("mouseenter", function () {
        $(document).stopTime(timerName);
    }).bind("mouseleave", function () {
        $(document).stopTime(timerName).everyTime("7s", timerName, function(i) { NextCase(); });

    });
});

//TEaser========================================
function TeaserSetCase(obj) {
    var toCase = obj.id.split('_')[1];
    setTeaserSwitch(toCase, false);

}
function setTeaserSwitch(newCase, slow) {
    var delay1 = 150;
    var delay2 = 300;
    if (slow) { delay1 = 700;delay2 = 1500; }
    $("div[id*=divTeaser_]:visible").fadeOut(delay1, function () {
        $("span[class=tcur]").removeClass("tcur");
        $("div[id=divTeaser_" + newCase + "]").show();
        $("span[id=spanT_" + newCase + "]").addClass("tcur");
    });
}
function NextTeaserCase(slow) {
    if ($("span[class=tcur]").size() > 0) {
        var currentCase = $("span[class=tcur]")[0].id.split('_')[1];
        var nextC = (parseInt(currentCase) + 1).toString();
        var nextCaseObj = $("span[id=spanT_" + nextC + "]");
        if (nextCaseObj.length == 0) nextC = 0;
        setTeaserSwitch(nextC, slow);
    }
}
function PrevTeaserCase() {
    if ($("span[class=tcur]").size() > 0) {
        var currentCase = $("span[class=tcur]")[0].id.split('_')[1];
        var prevC;
        if (currentCase > 0) prevC = (parseInt(currentCase) - 1).toString();
        else prevC = $("span[id*=spanT_]:last")[0].id.split('_')[1];
        setTeaserSwitch(prevC);
    }
}

$(document).ready(function () {
    var timerName = "timer2";
    $(document).everyTime("4s", timerName, function (i) {
        NextTeaserCase(true);
    });

    $("div[id*=_divBig]").bind("mouseenter", function () {
        $(document).stopTime(timerName);
    }).bind("mouseleave", function () {
        $(document).stopTime(timerName).everyTime("4s", timerName, function (i) { NextTeaserCase(true); });
    });
});
//TEaser========================================

$(document).ready(function () {
    var timerName = "timer3";
    $.extend($.gritter.options, {
        fade_in_speed: 1000, // how fast notifications fade in (string or int)
        fade_out_speed: 1000, // how fast the notices fade out
        time: 8000 // hang on the screen for...
    });

    $(document).oneTime("3s", timerName, function (i) {
        var msg = $("input[id$=hGritter]").val();
        if (msg != "") {
            var msgParts = msg.split('*');
            Gritter(msgParts[0], msgParts[1], msgParts[2]);
        }

        //Gritter("Добро пожаловать", "Мы рады приветствовать вас в нашем интернет-магазине", "i1");
        //Gritter("Покупка в магазине", "Пользователь и Киева только что купил ноутбук <a href='/'>Samsung R428 (NP-R428-DA02UA)</a>", "i3");
        //Gritter("Интересно", "3 пользователя вместе с вами сейчас просматривают эту страницу", "i1");
    });
});

function Gritter(title, text, image) { 
    $.gritter.add({
            title: title,
            text: text,
            image: "http://i.novatek.ua/" + image + ".png",
            sticky:false
    });
}

//===jQuery.Timers===
jQuery.fn.extend({
    everyTime: function(interval, label, fn, times, belay) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times, belay);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        guid: 1,
        global: {},
        regex: /^([0-9]+)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseInt(result[1], 10);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times, belay) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times)
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
                return;

            if (times && times.constructor != Number) {
                belay = !!times;
                times = 0;
            }

            times = times || 0;
            belay = belay || false;

            if (!element.$timers)
                element.$timers = {};

            if (!element.$timers[label])
                element.$timers[label] = {};

            fn.$timerID = fn.$timerID || this.guid++;

            var handler = function() {
                if (belay && this.inProgress)
                    return;
                this.inProgress = true;
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
                this.inProgress = false;
            };

            handler.$timerID = fn.$timerID;

            if (!element.$timers[label][fn.$timerID])
                element.$timers[label][fn.$timerID] = window.setInterval(handler, interval);

            if (!this.global[label])
                this.global[label] = [];
            this.global[label].push(element);

        },
        remove: function(element, label, fn) {
            var timers = element.$timers, ret;

            if (timers) {

                if (!label) {
                    for (label in timers)
                        this.remove(element, label, fn);
                } else if (timers[label]) {
                    if (fn) {
                        if (fn.$timerID) {
                            window.clearInterval(timers[label][fn.$timerID]);
                            delete timers[label][fn.$timerID];
                        }
                    } else {
                        for (var fn in timers[label]) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for (ret in timers[label]) break;
                    if (!ret) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for (ret in timers) break;
                if (!ret)
                    element.$timers = null;
            }
        }
    }
});

if (jQuery.browser.msie)
    jQuery(window).one("unload", function() {
        var global = jQuery.timer.global;
        for (var label in global) {
            var els = global[label], i = els.length;
            while (--i)
                jQuery.timer.remove(els[i], label);
        }
    });

    //==ParametersFilter.js===
    $(function() {
        if ($("input[id$=hShowFilter]").val() != "1") {
            $("#divSearchForm").hide();
            $("#pTab").removeClass("search_tab_open");
            $("#pTab").addClass("search_tab_close");
            $("#spanTabButton").html(textShowSearchForm);
        }
        else {
            $("#divSearchForm").slideDown("normal");
            $("#pTab").removeClass("search_tab_close");
            $("#pTab").addClass("search_tab_open");
            $("#spanTabButton").html(textHideSearchForm);
        }

        $("#pTab").unbind("click").click(function() {
            if (!$("#pTab").hasClass("search_tab_close")) {
                $("#divSearchForm").slideUp();
                $("#pTab").removeClass("search_tab_open");
                $("#pTab").addClass("search_tab_close");
                $("#spanTabButton").html(textShowSearchForm);
                $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&showfilter=0");
            }
            else {
                $("#divSearchForm").slideDown("normal");
                $("#pTab").removeClass("search_tab_close");
                $("#pTab").addClass("search_tab_open");
                $("#spanTabButton").html(textHideSearchForm);
                $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&showfilter=1");
            }
        });
        $("a[id$=btnFilterSubmit]").unbind("click").click(function() {
            var result = "";
            if ($("select[id*=selectManufacturer]").val() != "0")
                result += "m=" + $("select[id*=selectManufacturer]").val() + "~";
            var singleValues = $("select[id*=selectSingle]");
            for (var i = 0; i < singleValues.length; i++) {
                if ($(singleValues[i]).val() != "0")
                    result += singleValues[i].id.split("_")[1] + "=" + $(singleValues[i]).val() + "~";
            }
            var minValues = $("select[id*=selectFrom]");
            for (var j = 0; j < minValues.length; j++) {
                var minVal = $("select[id*=" + minValues[j].id + "]").val();
                var maxVal = $("select[id*=" + minValues[j].id.replace("From", "To") + "]").val();
                if (minVal != "0" || maxVal != "0") {
                    result += minVal + "," + maxVal + "~";
                }
            }
            $("input[id$=hParameters]").val(result);
        });
        $("select[id*=selectFrom]").unbind("change").change(function() {
            var toId = this.id.replace("From", "To");
            var toValue = $("option[value=" + $("select[id*=" + toId + "]").val() + "]").html();
            var fromValue = $("option[value=" + $(this).val() + "]").html();
            if ($(this).val() != "0" && $("select[id*=" + toId + "]").val() != "0" && parseFloat(toValue.split(' ')[0]) < parseFloat(fromValue.split(' ')[0])) {
                $("select[id*=" + toId + "]").val($(this).val());
            }
        });
        $("select[id*=selectTo]").unbind("change").change(function() {
            var fromId = this.id.replace("To", "From");
            var fromValue = $("option[value=" + $("select[id*=" + fromId + "]").val() + "]").html();
            var toValue = $("option[value=" + $(this).val() + "]").html();
            if ($(this).val() != "0" && $("select[id*=" + fromId + "]").val() != "0" && parseFloat(fromValue.split(' ')[0]) > parseFloat(toValue.split(' ')[0])) {
                $("select[id*=" + fromId + "]").val($(this).val());
            }
        });
    });
	
	//Say with boss
	var textFormSubmitErrorMessage;
var textFieldsErrorMessage;

function Boss() {
    var swbName = $("#divSayWithBoss #swbName");
    var swbEmail = $("#divSayWithBoss #swbEmail");
    var swbMessage = $("#divSayWithBoss #swbMessage");

    $("#swbPhone").mask("(999) 999-99-99");

    swbName.blur(function () {
        ValidSwbName();
    });

    swbEmail.blur(function () {
        ValidSwbEmail();
    });

    swbMessage.blur(function () {
        ValidSwbMessage();
    });

    $("#aSayWithBoss").click(function () {
        $("#divSayWithBoss").fadeIn();
        $("#aSayToBoss").show();
        return false;
    });

    function IsValid() {
        var valid = true;
        if (!ValidSwbName())
            valid = false;
        if (!ValidSwbEmail())
            valid = false;
        if (!ValidSwbMessage())
            valid = false;
        return valid;
    }

    function ValidSwbName() {
        var valid = true;
        if (HtmlEncode(swbName.val().trim()).length > 0) {
            swbName.removeErrorStyle();
        } else {
            swbName.markErrorField();
            valid = false;
        }

        return valid;
    }

    function ValidSwbEmail() {
        var valid = true;
        var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
        if (reg.test(swbEmail.val())) {
            swbEmail.removeErrorStyle();
        } else {
            swbEmail.markErrorField();
            valid = false;
        }

        return valid;
    }

    function ValidSwbMessage() {
        var valid = true;
        if (HtmlEncode(swbMessage.val().trim()).length > 0) {
            swbMessage.removeErrorStyle();
        } else {
            swbMessage.markErrorField();
            valid = false;
        }

        return valid;
    }

    $("#aSayToBoss").unbind("click").click(function () {
        $(this).hide();
        var name = HtmlEncode(swbName.val());
        var phone = $("#divSayWithBoss #swbPhone").val();
        var email = swbEmail.val();
        var message = HtmlEncode(swbMessage.val());
        var messageType = $("#divSayWithBoss #swbMessageType option:selected").val();
        if (IsValid()) {
            $.ajax({
                type: "POST",
                url: "/jQueryAjaxRequest.aspx/SayToBoss",
                data: '{name: "' + name + '", phone: "' + phone + '", email: "' + email + '", message: "' + message + '", messageType: "' + messageType + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { $('#divSayWithBoss').fadeOut(); gaCallMe(response.d); $.notifier(textFormSubmitErrorMessage, "success"); },
                error: function () { $('#divSayWithBoss').fadeOut(); $.notifier('<%= Rg("FormSubmitErrorMessage")%>', "error"); }
            });
        }
        else {
            $(this).show();
            $.notifier(textFieldsErrorMessage, "error");
        }
    });

    $.fn.markErrorField = function () {
        return this.css('border', 'solid 1px #d22333');
    };

    $.fn.removeErrorStyle = function () {
        return this.removeAttr('style');
    };
}

function TextInitialize() {
    textFormSubmitErrorMessage = $('#textFormSubmitErrorMessage').val();
    textFieldsErrorMessage = $('#textFieldsErrorMessage').val();
}


//Masked input
/*
Masked Input plugin for jQuery
Copyright (c) 2007-2009 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) 
Version: 1.2.2 (03/09/2009 22:39:06)
*/
(function (a) { var c = (a.browser.msie ? "paste" : "input") + ".mask"; var b = (window.orientation != undefined); a.mask = { definitions: { "9": "[0-9]", a: "[A-Za-z]", "*": "[A-Za-z0-9]"} }; a.fn.extend({ caret: function (e, f) { if (this.length == 0) { return } if (typeof e == "number") { f = (typeof f == "number") ? f : e; return this.each(function () { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(e, f) } else { if (this.createTextRange) { var g = this.createTextRange(); g.collapse(true); g.moveEnd("character", f); g.moveStart("character", e); g.select() } } }) } else { if (this[0].setSelectionRange) { e = this[0].selectionStart; f = this[0].selectionEnd } else { if (document.selection && document.selection.createRange) { var d = document.selection.createRange(); e = 0 - d.duplicate().moveStart("character", -100000); f = e + d.text.length } } return { begin: e, end: f} } }, unmask: function () { return this.trigger("unmask") }, mask: function (j, d) { if (!j && this.length > 0) { var f = a(this[0]); var g = f.data("tests"); return a.map(f.data("buffer"), function (l, m) { return g[m] ? l : null }).join("") } d = a.extend({ placeholder: "_", completed: null }, d); var k = a.mask.definitions; var g = []; var e = j.length; var i = null; var h = j.length; a.each(j.split(""), function (m, l) { if (l == "?") { h--; e = m } else { if (k[l]) { g.push(new RegExp(k[l])); if (i == null) { i = g.length - 1 } } else { g.push(null) } } }); return this.each(function () { var r = a(this); var m = a.map(j.split(""), function (x, y) { if (x != "?") { return k[x] ? d.placeholder : x } }); var n = false; var q = r.val(); r.data("buffer", m).data("tests", g); function v(x) { while (++x <= h && !g[x]) { } return x } function t(x) { while (!g[x] && --x >= 0) { } for (var y = x; y < h; y++) { if (g[y]) { m[y] = d.placeholder; var z = v(y); if (z < h && g[y].test(m[z])) { m[y] = m[z] } else { break } } } s(); r.caret(Math.max(i, x)) } function u(y) { for (var A = y, z = d.placeholder; A < h; A++) { if (g[A]) { var B = v(A); var x = m[A]; m[A] = z; if (B < h && g[B].test(x)) { z = x } else { break } } } } function l(y) { var x = a(this).caret(); var z = y.keyCode; n = (z < 16 || (z > 16 && z < 32) || (z > 32 && z < 41)); if ((x.begin - x.end) != 0 && (!n || z == 8 || z == 46)) { w(x.begin, x.end) } if (z == 8 || z == 46 || (b && z == 127)) { t(x.begin + (z == 46 ? 0 : -1)); return false } else { if (z == 27) { r.val(q); r.caret(0, p()); return false } } } function o(B) { if (n) { n = false; return (B.keyCode == 8) ? false : null } B = B || window.event; var C = B.charCode || B.keyCode || B.which; var z = a(this).caret(); if (B.ctrlKey || B.altKey || B.metaKey) { return true } else { if ((C >= 32 && C <= 125) || C > 186) { var x = v(z.begin - 1); if (x < h) { var A = String.fromCharCode(C); if (g[x].test(A)) { u(x); m[x] = A; s(); var y = v(x); a(this).caret(y); if (d.completed && y == h) { d.completed.call(r) } } } } } return false } function w(x, y) { for (var z = x; z < y && z < h; z++) { if (g[z]) { m[z] = d.placeholder } } } function s() { return r.val(m.join("")).val() } function p(y) { var z = r.val(); var C = -1; for (var B = 0, x = 0; B < h; B++) { if (g[B]) { m[B] = d.placeholder; while (x++ < z.length) { var A = z.charAt(x - 1); if (g[B].test(A)) { m[B] = A; C = B; break } } if (x > z.length) { break } } else { if (m[B] == z[x] && B != e) { x++; C = B } } } if (!y && C + 1 < e) { r.val(""); w(0, h) } else { if (y || C + 1 >= e) { s(); if (!y) { r.val(r.val().substring(0, C + 1)) } } } return (e ? B : i) } if (!r.attr("readonly")) { r.one("unmask", function () { r.unbind(".mask").removeData("buffer").removeData("tests") }).bind("focus.mask", function () { q = r.val(); var x = p(); s(); setTimeout(function () { if (x == j.length) { r.caret(0, x) } else { r.caret(x) } }, 0) }).bind("blur.mask", function () { p(); if (r.val() != q) { r.change() } }).bind("keydown.mask", l).bind("keypress.mask", o).bind(c, function () { setTimeout(function () { r.caret(p(true)) }, 0) }) } p() }) } }) })(jQuery);

function PinnedSite() {
    try {
        if (window.external.msIsSiteMode()) {
            window.external.msSiteModeCreateJumplist('Информация');
            window.external.msSiteModeAddJumpListItem('Доставка', '/dostavka/', 'favicon.ico');
            window.external.msSiteModeAddJumpListItem('О магазине', '/o-magazine/', 'favicon.ico');
            /*window.external.msSiteModeCreateJumplist('Категории');
            window.external.msSiteModeAddJumpListItem('Софт', '/catalog/software/', 'favicon.ico');
            window.external.msSiteModeAddJumpListItem('Аксессуары', '/catalog/accessories/', 'favicon.ico');
            window.external.msSiteModeAddJumpListItem('Планшеты', '/catalog/tablets/', 'favicon.ico');
            window.external.msSiteModeAddJumpListItem('Нетбуки', '/catalog/netbooks/', 'favicon.ico');
            window.external.msSiteModeAddJumpListItem('Ноутбуки', '/catalog/notebook/', 'favicon.ico');*/
            window.external.msSiteModeShowJumplist();
            window.external.msSiteModeActivate();
        }
    }
    catch (ex) {
        return;
    }
}

function СompetitionSubscribe() {
    $.ajax({
        type: "POST",
        url: "/jQueryAjaxRequest.aspx/CompetitionSubscribe",
        data: '{competitionNoticeEmail: "' + cnEmail.val() + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) { $('#divPopupCompetitionNotices').fadeOut(); $.notifier(response.d, "success"); cnEmail.val(''); },
        error: function () { $('#divPopupCompetitionNotices').fadeOut(); $.notifier(response.d, "error"); }
    });
}
