﻿var searchBox;
var searchSlide;
var searchContainer;

$(document).ready(function() {
    MainMenu();
    $("#aspnetForm")[0].setAttribute('autocomplete', 'off');

    searchBox = $("input[id$=searchBox]");
    searchSlide = $("#divSearchSlide");
    searchContainer = $("#tSearchSlide");

    $(document).click(function() {
        searchSlide.hide();
    });

    $(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();
});

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("getSearch_" + request, $("#tSearchSlide"));
    }
    else {
        $("#divSearchSlide").hide();
    }
}

function execText(cmd, container) {
    $.ajax({
        type: "POST",
        url: "/AjaxHandler.ashx",
        data: cmd,
        contentType: "application/x-www-form-urlencoded",
        dataType: "text",
        timeout: 30000,
        success: function(response) { confirmTextCommand(response, container); },
        error: function(response) { $.notifier("Произошла ошибка. Попробуйте снова.", "error"); }
    });
}

function confirmTextCommand(response, container) {
    var request = searchBox[0].value;

    if (response != "" && request.replaceAll(" ", "").length > 1) {
        searchContainer.html(response);
        $("#divSearchSlide").slideDown();
    }
    else {
        $("#divSearchSlide").hide();
    }
}

function exec(cmd) {
    var sort = $("input[id $= hSort]").val();
    $.ajax({
        type: "POST",
        url: "/jQueryAjaxRequest.aspx/HandleCommand",
        data: "{command : '" + cmd + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) { confirmCommand(response); },
        error: function(response) { $.notifier("Произошла ошибка. Попробуйте снова.", "error"); }
    });
}

function confirmCommand(response) {
    var result = eval('(' + response.d + ')');
    if (result.IsSuccess) {
        switch (result.Command.split("_")[0]) {
            case "getModificationsAddBasket":
                $("#tModsData").html(result.Message);
                $("#h3Title").html(result.Message2);
                $("#divPopupModifications").fadeIn();
                Basket();
                break;
            case "getModificationsAddReview":
                $("#tModsData").html(result.Message);
                $("#h3Title").html(result.Message2);
                $("#divPopupModifications").fadeIn();
                break;
        }
    }
    else {
        $.notifier("Произошла ошибка. Попробуйте снова.", "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() == "Поиск") {
            $(this).val("");
        }
        GetSearchSlide();
    });
    searchBox.blur(function() {
        //        if (allowClose) {
        //            alert("2");
        //            searchSlide.hide();
        //        }
        $(".search").toggleClass('active');
        if ($(this).val() == "") {
            $(this).val("Поиск");
        }
    });

    $(".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();
        }
    );
    
    $(".tip").hover(
        function() {
            $("#divPhoneNote").fadeIn(300);
        },
        function() {
            $("#divPhoneNote").hide();
        }
    );

    $("*[class*=popup-close]").click(function() {
        $("*[class*=popup-position]").fadeOut();
    })

    $("#divCallMePlease #tbPhone1").unbind("keyup").keyup(function() {
        $(this).val($(this).val().replace(/[^0-9+\-() ]/g, ""));
    });
    $("#divCallMePlease #tbPhone2").unbind("keyup").keyup(function() {
        $(this).val($(this).val().replace(/[^0-9+\-() ]/g, ""));
    });

    $("#aAddCallMe").unbind("click").click(function() {
        $(this).hide();
        var name = HtmlEncode($("#divCallMePlease #tbName").val());
        var phone1 = $("#divCallMePlease #tbPhone1").val();
        var phone2 = $("#divCallMePlease #tbPhone2").val();
        var comment = HtmlEncode($("#divCallMePlease #tbComment").val());
        if (name != '' && phone1 != '' && phone2 != '') {
            $.ajax({
                type: "POST",
                url: "/jQueryAjaxRequest.aspx/AddCallMe",
                data: '{name: "' + name + '", phone: "' + phone1 + "-" + phone2 + '", comment: "' + comment + '", url: "' + top.location + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(response) { $('#divCallMePlease').fadeOut(); pageTracker._trackPageview("/zvonok_katerine"); $.notifier("Ваш номер добавлен.", "success"); },
                error: function() { $('#divCallMePlease').fadeOut(); $.notifier("Ошибка. Попробуйте еще раз.", "error"); }
            });
        }
        else {
            $(this).show();
            $.notifier("Ошибка. Поля заполнены неверно", "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("Спасибо. Вы нам очень помогли.", "success"); },
                error: function() { $('#divErrorRequest').fadeOut(); $.notifier("Ошибка. Попробуйте еще раз.", "error"); }
            });
        }
        else {
            $(this).show();
            $.notifier("Ошибка. Поля заполнены неверно", "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);
}