﻿var aProductSubscribe;
var aSubmitSubscription;
var divLock;
var divSubscribeForm;
var divSysMessage;
var h1ProductName;
var tbUserEmail;
var tbUserName;
var tbUserPhone;
var productId;

$(function() {
    aProductSubscribe = $("a[id*=aProductSubscribe_]");
    aSubmitSubscription = $("#aSubmitSubscription");
    divLock = $("#lock");
    divSubscribeForm = $("div[id*=divSubscribeForm]");
    divSysMessage = $("#divSysMessage");
    h1ProductName = $("#h1ProductName");
    tbUserEmail = $("#tbUserEmail");
    tbUserName = $("#tbUserName");
    tbUserPhone = $("#tbUserPhone");

    ShowFilter();
    FilterParameters();
    AddToBasket();

    aProductSubscribe.click(function() {
        divLock.show();
        divSubscribeForm.show();
        productId = this.id.split("_")[1];
        h1ProductName.text($($(this).parent().parent().children("h3").get(0)).text());
    });

    divLock.click(function() {
        divSubscribeForm.hide();
        divLock.hide();
    });

    aSubmitSubscription.click(function() {
        SubmitSubscription();
        return false; //Preventing page postback
    });

    $(".more").unbind("click").click(function () {
        $("#pMoreInfo").removeClass("more-info");
        $(this).remove();
    });
});

function ShowFilter(){
    $("span[class*=s-title]").click(function(){
        if($("span[class*=s-title]").hasClass("open")){
            $("span[class*=s-title]").removeClass("open");
            $("fieldset[id=fSearch]").slideUp(200);            
        }
        else{
            $("span[class*=s-title]").addClass("open");
            $("fieldset[id=fSearch]").slideDown(200);
        }
    });
}

function SubmitSubscription() {
    var name = $.trim(tbUserName.val());
    var email = $.trim(tbUserEmail.val());
    var phone = $.trim(tbUserPhone.val());

    if (name == "") {
        aSubmitSubscription.hide();
        divSysMessage.html('<div class="msg-error">Пожалуйста, укажите свое имя (или псевдоним), чтобы мы знали как к Вам обращаться.</div>');
        divSysMessage.fadeIn("fast").fadeTo(3000, 1);
        divSysMessage.fadeOut(2000, function() {
            aSubmitSubscription.show();
        });
        return false;
    }
    else if (phone == "" && email == "") {
        aSubmitSubscription.hide();
        divSysMessage.html('<div class="msg-error">Пожалуйста, укажите хотя бы один контакт для связи с вами (телефон или адрес электронной почты).</div>');
        divSysMessage.fadeIn("fast").fadeTo(3000, 1);
        divSysMessage.fadeOut(2000, function() {
            aSubmitSubscription.show();
        });
        return false;
    }

    $.ajax({
        type: "POST",
        url: "/Articles/ReviewItem.aspx/HandleSubscription",
        data: "{name:'" + name + "', email:'" + email + "', phone:'" + phone + "', productId:'" + productId + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(response) {
            if (response.d.toLowerCase() == "true") {
                aSubmitSubscription.hide();
                divSysMessage.html('<div class="msg-success">Ваша заявка принята, обработана и сохранена.</div>');
                divSysMessage.fadeIn("fast").fadeTo(3000, 1);
                divSysMessage.fadeOut(2000, function() {
                    tbUserEmail.val("");
                    tbUserName.val("");
                    tbUserPhone.val("");
                    divLock.hide();
                    divSubscribeForm.hide();
                    aSubmitSubscription.show();
                });
            }
            else {
                aSubmitSubscription.hide();
                divSysMessage.html('<div class="msg-error">Ошибка сервера. Пожалуйста, попробуйте еще раз.</div>');
                divSysMessage.fadeIn("fast").fadeTo(3000, 1);
                divSysMessage.fadeOut(2000, function() {
                    aSubmitSubscription.show();
                });
            }
        },
        error: function() {
            aSubmitSubscription.hide();
            divSysMessage.html('<div class="msg-error">Ошибка сервера. Пожалуйста, попробуйте еще раз.</div>');
            divSysMessage.fadeIn("fast").fadeTo(3000, 1);
            divSysMessage.fadeOut(2000, function() {
                aSubmitSubscription.show();
            });
        }
    });
}

function FilterParameters(){
    $("select[id^=sParam_]").bind("change", function(){
        UpdateParameters();
    });
    $("select[id=manufacturerParam]").bind("change", function(){
        UpdateParameters();
    });
    $("input[id^=chParam_]").bind("change", function(){
        UpdateParameters();
    });
    $("input[id$=btnFilterSubmit]").click(function(){
        UpdateParameters();
    });
    
    $("input[id$=tbMinPrice]").bind("keyup", function(){                
       var reg = /[^0-9]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        } 
    });
    $("input[id$=tbMinPrice]").bind("blur", function(){                
       var reg = /[^0-9]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        } 
    });
    $("input[id$=tbMaxPrice]").bind("keyup", function(){
       var reg = /[^0-9]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        } 
    });
    $("input[id$=tbMaxPrice]").bind("blur", function(){
       var reg = /[^0-9]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        } 
    });
}

function UpdateParameters(){
    var paramsUrl = "";
    $("select[id=manufacturerParam]").each(function(){
        if(this.value != "0"){
            paramsUrl += "m=" + this.value + "~";
        }
    });
    $("select[id^=sParam_]").each(function(){
        if(this.value != "0"){
            paramsUrl += this.id.split("_")[1] + "=" + this.value + "~";
        }
    });
    $("input[id^=chParam_]").each(function(){
        if(this.checked){
            paramsUrl += this.id.split("_")[1] + "=0~";
        }
    });
    paramsUrl = paramsUrl.substr(0, paramsUrl.length - 1);    
    $("input[id$=hParameters]").val(paramsUrl);
}

//Adds product to the basket.
function AddToBasket() {
    $("span[id*=spanAddToBasket_]").click(function() {
        var id = this.id.split("_")[1];
        if ($("span[id*=spanAddToBasket_" + id + "]").hasClass("ico_down")) {            
            $(this).hide();
            $("#loader").insertAfter($(this));
            $("#loader").show();
            $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&basketadd=" + id + "", function() {
                $("#loader").hide();
                $("span[id*=spanAddToBasket_" + id + "]").removeClass("ico_down");
                $("span[id*=spanAddToBasket_" + id + "]").addClass("ico_up");
                $("span[id*=spanAddToBasket_" + id + "]").show();
            });
            UpdateTopBasketCount();
        }
    });
}

//Updates basket count in header.
function UpdateTopBasketCount() {
    var topValue = $("span[id$=spanItemCount]").html();
    var count = parseInt(topValue);
    count++;
    topValue = count;
    $("span[id$=spanItemCount]").html(topValue);
}

String.prototype.replaceAll = function(search, replace) {
    return this.split(search).join(replace);
}
