﻿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();
    });

    $("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();
    });
});

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();
    }
}

$(document).ready(function() {
    searchBox.focus(function() {
        $("#divCallNote").hide();
        $(".search").toggleClass('active');
        if ($(this).val() == "Поиск") {
            $(this).val("");
        }
        GetSearchSlide();
    });
    searchBox.blur(function() {
        $(".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');
    });
    $("a.bg-out").click(function(event) {
        $("div.plus-popup").toggleClass('opened');
        event.stopPropagation();
    })

    $(".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 #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 #tbName5").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);
}

//TEaser========================================
function TeaserSetCase(obj) {
    var toCase = obj.id.split('_')[1];
    setTeaserSwitch(toCase, false);

}
function setTeaserSwitch(newCase, slow) {
    var delay1 = 100;
    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 + "]").fadeIn(delay2);
        $("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========================================

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);
        }
    });
	
