﻿var month = 30 * 24 * 60 * 60 * 1000;
var year = 365 * 24 * 60 * 60 * 1000;

var textRemoveFromCart;
var textBuyUpper;
var textAddToCompare;
var textRemoveFromComparison;
var textHoldLower;
var textDetachLower;
var text4ItemMax;
var textItemAddedToCompare;
var textItemRemovedFromTheComparison;
var textSubscribed;
var textChooseTheTypeOfNotification;
var textSomeFieldsAreIncorrect;
var textPutYourScore;
var textTheNameOfNoMoreThan50Characters;
var textHeaderRecallNoMoreThan150Characters;
var textTextRecallNoMoreThan3000Characters;
var textCheckTheFillingFields;

function TextInitialize() {
    textRemoveFromCart = $('#textRemoveFromCart').val();
    textBuyUpper = $('#textBuyUpper').val();
    textAddToCompare = $('#textAddToCompare').val();
    textRemoveFromComparison = $('#textRemoveFromComparison').val();
    textHoldLower = $('#textHoldLower').val();
    textDetachLower = $('#textDetachLower').val();
    text4ItemMax = $('#text4ItemMax').val();
    textItemAddedToCompare = $('#textItemAddedToCompare').val();
    textItemRemovedFromTheComparison = $('#textItemRemovedFromTheComparison').val();
    textSubscribed = $('#textSubscribed').val();
    textChooseTheTypeOfNotification = $('#textChooseTheTypeOfNotification').val();
    textSomeFieldsAreIncorrect = $('#textSomeFieldsAreIncorrect').val();
    textPutYourScore = $('#textPutYourScore').val();
    textTheNameOfNoMoreThan50Characters = $('#textTheNameOfNoMoreThan50Characters').val();
    textHeaderRecallNoMoreThan150Characters = $('#textHeaderRecallNoMoreThan150Characters').val();
    textTextRecallNoMoreThan3000Characters = $('#textTextRecallNoMoreThan3000Characters').val();
    textCheckTheFillingFields = $('#textCheckTheFillingFields').val();
}

$(document).ready(function () {
    TextInitialize();
});

$(function () {
    $().piroBox({
        my_speed: 1, //animation speed
        bg_alpha: 0.5, //background opacity
        radius: 4, //caption1 rounded corner
        scrollImage: false, // true == image follows the page, false == image remains in the same open position
        pirobox_next: 'piro_next', // Nav buttons -> piro_next == inside piroBox , piro_next_out == outside piroBox
        pirobox_prev: 'piro_prev', // Nav buttons -> piro_prev == inside piroBox , piro_prev_out == outside piroBox
        close_all: '.piro_close', // add class .piro_overlay(with comma)if you want overlay click close piroBox
        slideShow: 'slideshow', // just delete slideshow between '' if you don't want it.
        slideSpeed: 4 //slideshow duration in seconds(3 to 6 Recommended)
    });
    $('input.star').rating();

    $("#aBeznal").unbind("click").click(function () {
        SetCookie("ordertype", "cashless", null);
        BuyBeznalProduct();
    });

    $("#aCredit").unbind("click").click(function () {
        SetCookie("ordertype", "credit", null);
        BuyCreditProduct();
    });

    $("#spanShowAllComments").unbind("click").click(function () {
        $("#spanShowAllComments").hide();
        $("#divHiddenComments").slideDown();
    });

    $("li[id*=liImgSmall_]").click(function () {
        $("img[id*=imgBig_]").hide();
        var id = this.id.split("_")[1];
        $("img[id$=imgBig_" + id + "]").show();
        $("li[id*=liImgSmall_]").removeClass("active");
        $("li[id*=liImgSmall_" + id + "]").addClass("active");
        pageTracker._trackPageview("/quickgallery_analytics");
    });
    $("#aWriteReview").unbind("click").click(function () {
        $("div[id$=divWriteComment]").slideToggle();
    });
    $("span[class*=add-compare]").unbind("click").click(function () {
        var a = $(this);
        var div = a.parent();
        div.hide();
        div.after("<span class='to-cart-loading'></span>");
        div.queue(function () {
            setTimeout(function () {
                div.next().remove();
                div.show();
                div.dequeue();
            }, 500);
        });
        if (a.hasClass("not")) {
            a.removeClass("not");
            a.html("<span>" + textAddToCompare + "</span>");
            var arr = GetCookie(CompareCookieName).split(',');
            arr.splice(arr.indexOf($("input[id$=hProductId]").val()), 1);
            var val = "";
            for (var i = 0; i < arr.length; i++) {
                if (val == "")
                    val += arr[i];
                else
                    val += ',' + arr[i];
            }
            $("div[id$=Comp]").addClass("hide");
            if (arr.length == 0) {
                $("#spanCompareCount").html("");
                SetCookie(CompareCookieName, val, new Date(new Date().getTime() - month).toUTCString());
            }
            else {
                $("#spanCompareCount").html(arr.length);
                SetCookie(CompareCookieName, val, new Date(new Date().getTime() + month).toUTCString());
                if (arr.length == 1)
                    $("div[id$=divAddOneProductComp]").removeClass("hide");
                else
                    $("div[id$=divGotoComp]").removeClass("hide");
            }
            NotifySuccessRemove();
        }
        else {
            var val = GetCookie(CompareCookieName);
            if (val == null)
                val = $("input[id$=hProductId]").val();
            else {
                count = val.split(",").length;
                if (count >= 4) {
                    $.notifier(text4ItemMax, "error");
                    return false;
                }
                else {
                    if (val.indexOf($("input[id$=hProductId]").val()) == -1) {
                        val += "," + $("input[id$=hProductId]").val();
                    }
                }
            }
            a.addClass("not");
            a.html("<span>" + textRemoveFromComparison + "</span>");
            var count = val.split(",").length;
            $("#spanCompareCount").html(count);
            $("div[id$=Comp]").addClass("hide");
            if (count == 1)
                $("div[id$=divAddOneProductComp]").removeClass("hide");
            else
                $("div[id$=divGotoComp]").removeClass("hide");
            SetCookie(CompareCookieName, val, new Date(new Date().getTime() + month).toUTCString());
            NotifySuccessAdd();
        }
    });
    $("#aPhoto360").unbind("click").click(function () {
        //container360
        var container = $("*[id^=container360]");
        var productId = parseInt(container[0].id.split('_')[1]);
        $.get('/360.ashx?id=' + productId, function (data) {
            container.html(data);
        });
        $(this).next().fadeIn();
        pageTracker._trackPageview("/photo360_analytics");
    });

    $("img[id^=imgBig_]").unbind("click").click(function () {
        pageTracker._trackPageview("/gallery_analytics");
    });

    $("img[id^=imgBig_]").unbind("click").click(function () {
        pageTracker._trackPageview("/gallery_analytics");
    });

    //exists
    $("#aAddSubscription").unbind("click").click(function () {
        var name = HtmlEncode($("#tbName1").val());
        var email = $("#tbEmail").val();
        var phone = $("#tbPhone").val().replaceAll(" ", "");
        var trackerPage = "/instock_subscription";
        if (productStatus == 20) {
            trackerPage = "/discount_subscription";
        }
        if (name != null && email != null && phone != null && phone != "" && ValidateEmail(email)) {
            $.ajax({
                type: "POST",
                url: "/Catalog/Product.aspx/AddSubscription",
                data: "{productId: '" + $("input[id$=hProductId]").val() + "', name: '" + name + "', email: '" + email + "', phone: '" + phone + "', productStatus: '" + productStatus + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { $('#divPopup').fadeOut(); pageTracker._trackPageview(trackerPage); $.notifier(textSubscribed, "success"); },
                error: function (response, textStatus) { $.notifier(textErrorTryAgain, "error"); }
            });
        }
        else {
            $.notifier(textErrorFieldsAreFilledInIncorrectly, "error");
        }
    });

    //priceChange, reviewAdd
    $("#aAddSubscription2").unbind("click").click(function () {
        var name = HtmlEncode($("#tbName1").val());
        var email = $("#tbEmail").val();
        var trackerPage1 = "";
        var trackerPage2 = "";

        var subscriptionTypes = "";
        if ($("#cbReview")[0].checked == true) {
            subscriptionTypes = "3";
            var trackerPage1 = "/reviewadd_subscription";
        }
        if ($("#cbDiscount")[0].checked == true) {
            subscriptionTypes == "" ? subscriptionTypes = "2" : subscriptionTypes += "_2";
            var trackerPage2 = "/discount_subscription";
        }

        if (name != null && email != null && ValidateEmail(email) && subscriptionTypes != "") {
            $.ajax({
                type: "POST",
                url: "/Catalog/Product.aspx/AddSubscription2",
                data: "{productId: '" + $("input[id$=hProductId]").val() + "', name: '" + name + "', email: '" + email + "', subscriptionTypes: '" + subscriptionTypes + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) { $('#divPopup').fadeOut(); if (trackerPage1 != "") { pageTracker._trackPageview(trackerPage1); } if (trackerPage2 != "") { pageTracker._trackPageview(trackerPage2); } $.notifier(textSubscribed, "success"); },
                error: function (response, textStatus) { $.notifier(textErrorTryAgain, "error"); }
            });
        }
        else {
            $.notifier(textErrorFieldsAreFilledInIncorrectly, "error");
            if (subscriptionTypes == "") {
                $.notifier(textChooseTheTypeOfNotification, "error");
            }
        }
    });

    $("div[id*=divCommentResponse] a").unbind("click").click(function () {
        var commentId = this.parentNode.id.split('_')[1];
        var isGood = $(this).hasClass("yes") ? true : false;
        $.ajax({
            type: "POST",
            url: "/Catalog/Product.aspx/AddCommentResponse",
            data: "{commentId: '" + commentId + "', isGood: '" + isGood + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var resp = eval(response.d);
                var val = GetCookie(ResponsesCookieName);
                if (val == null)
                    val = resp.commentId;
                else
                    val += "," + resp.commentId;
                SetCookie(ResponsesCookieName, val, new Date(new Date().getTime() + year).toUTCString());
                var div = $("div[id*=divCommentResponse_" + resp.commentId + "]");
                div.hide();
                var strongs = div.next().find("strong");
                if (resp.isGood == "True") strongs[0].innerHTML++;
                strongs[1].innerHTML++;
            }
        });
    });

    $("*[id*=btConfirmOverview]").unbind("click").click(function () {
        if (isExistError()) {
            $.notifier(textSomeFieldsAreIncorrect, "error");
            MoveToFirstUnvalid();
            return false;
        }

        var rating2 = $("div[class*=star-rating-on]").length * 20;
        if (rating2 == 0) {
            $(document).scrollTo($(".star-rating-control"), 800, { offset: -25 });
            $.notifier(textPutYourScore, "error");
            return false;
        }
        $("*[id$=tbComment]").val(removeDoubleLine($("*[id$=tbComment]").val()));

        if ($("*[id$=tbTitle]").val().length > 150 || $("*[id$=tbName]").val().length > 50 || $("*[id$=tbComment]").val().length > 3000) {
            if ($("*[id$=tbName]").val().length > 50) {
                $.notifier(textTheNameOfNoMoreThan50Characters, "error");
            }
            if ($("*[id$=tbTitle]").val().length > 150) {
                $.notifier(textHeaderRecallNoMoreThan150Characters, "error");
            }
            if ($("*[id$=tbComment]").val().length > 3000) {
                $.notifier(textTextRecallNoMoreThan3000Characters, "error");
            }
            return false;
        }

        var rating = $("div[class*=star-rating-on]").length * 20;
        $("*[id*=hRating]").val(rating);

        $("div[id$=divWrite]").slideUp(500, function () {
        });
    });
    $("#aEditComment").unbind("click").click(function () {
        $("div[id$=divPreview]").slideUp(500, function () {
            $("*[id$=tbTitle]").val(Decode($("*[id$=tbTitle]").val()));
            $("*[id$=tbName]").val(Decode($("*[id$=tbName]").val()));
            $("*[id$=tbComment]").val(Decode($("*[id$=tbComment]").val()));
            $("div[id$=divWrite]").slideDown();
        });
    });
    $("input[id$=btConfirmOverview]").unbind("click").click(function () {
        $("*[id$=tbComment]").val($("*[id$=tbComment]").val().replace(/</g, "&lt;").replace(/>/g, "&gt;"));
    });
    $("#aClose").unbind("click").click(function () {
        $("div[id$=divWriteComment]").slideUp(500, function () { $("div[id$=divAdded]").hide(); $("div[id$=divWrite]").show(); });
        $(document).scrollTo(0, 1000);
    });

    QuickOrderPinStatus();

    $("input[id$=tbOrderPhone]").bind("keyup", function () {
        if (this.value.length > 20) {
            this.value = this.value.substring(0, this.value.length - (this.value.length - 20));
        }
        var reg = /[^0-9-() +]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        }
    });
    $("input[id$=tbOrderPhone]").bind("blur", function () {
        if (this.value.length > 20) {
            this.value = this.value.substring(0, this.value.length - (this.value.length - 20));
        }
        var reg = /[^0-9-() +]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        }
    });

});

var divTech;
var divQuick;
var divBottom;
var animationTime = 1000;
var allowAnimate = true;
function QuickOrderPanelPosition() {
    divTech = $("#divTech");
    divQuick = $("div[id$=divQuick]");
    divBottom = $("*[class=pre-footer bottom]");

    $(window).scroll(function() {
        setTimeout(function() {
        
        if (allowAnimate) {
            allowAnimate = false;
            var topOffset = "0px";
            var beginScrollTop = divTech.position().top;
            var documentScrollTop = $(document).scrollTop();
            if (documentScrollTop > 0) {
                var top = divQuick.position().top;
                var footerTop = divBottom.position().top;
                var height = divQuick.height();
                var dTop = documentScrollTop;
                if (dTop > beginScrollTop) {
                    topOffset = (dTop - beginScrollTop) + "px";
                }

                if (height + top < footerTop) {
                    divQuick.animate({
                        top: topOffset
                    }, animationTime, function() {
                        allowAnimate = true;
                    });

                }
            }
            else {
                divQuick.animate({
                    top: 0
                }, animationTime, function() {
                    allowAnimate = true;
                });
            }
        }

        }, 1000)
    });

    $("input[id$=tbOrderPhone]").bind("keyup", function() {
        if (this.value.length > 20) {
            this.value = this.value.substring(0, this.value.length - (this.value.length - 20));
        }
        var reg = /[^0-9-() +]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        }
    });
    $("input[id$=tbOrderPhone]").bind("blur", function() {
        if (this.value.length > 20) {
            this.value = this.value.substring(0, this.value.length - (this.value.length - 20));
        }
        var reg = /[^0-9-() +]/;
        if (this.value.match(reg)) {
            this.value = this.value.toLowerCase().replaceAll(reg, "");
        }
    });
}

function Encode(originalString) {
    return originalString.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/\n/g, "<br/>");
}

function Decode(originalString) {
    return originalString.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/<br\/>/g, "\n");
}

function NotifySuccessAdd() {
    $.notifier(textItemAddedToCompare, "success");
}
function NotifySuccessRemove() {
    $.notifier(textItemRemovedFromTheComparison, "success");
}

String.prototype.replaceAll = function(search, replace) {
    return this.split(search).join(replace);
}

function removeDoubleLine(obj) {
    var str = obj;
    while (str.indexOf("\n\n\n") >= 0) {        
        str = str.replace(/\n\n\n/g, "\n\n");
    }
    return str;
}


function QuickOrderPinStatus() {
    var hPinQuickOrder = $("input[id*=hPinQuickOrder]");
    var spanPin = $("span.pin");

    if (hPinQuickOrder.val() == "0") {
        $(window).scroll(function() {
            QuickOrderPanelPosition();
        });
    }

    spanPin.click(function() {
        var isPinned = hPinQuickOrder.val() == "1" ? true : false;
        if (isPinned) {
            hPinQuickOrder.val("0");
            spanPin.removeClass("pinned");
            spanPin.html(textHoldLower);
            $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&PinQuickOrderForm=0");
            $(window).scroll(function() {
                QuickOrderPanelPosition();
            });
        }
        else {
            hPinQuickOrder.val("1");
            spanPin.addClass("pinned");
            spanPin.html(textDetachLower);
            $("#jQueryAjaxRequest").load("/jQueryAjaxRequest.aspx?random=" + (new Date()).getTime() + "&PinQuickOrderForm=1");
            $(window).unbind("scroll");
            divQuick.animate({ top: 0 }, { duration: 500, queue: false });
        }
    });
}
