﻿var dictionary;
var mapping;
$(document).ready(function () {
    //$(":text,:password").keypress(function (event) {
    $(":text").keypress(function (event) {
        var key = event.keyCode ? event.keyCode : event.which;
        if (key == '13') {
            if ($(this).hasClass("textEntry")) {
                var closestButton = $(this).closest(":has(:submit)").find(":submit:first");
                if (closestButton) {
                    $(closestButton).trigger("click");
                    return false;
                }
            }
            else {
                return false;
            }
        }
        else if ($(this).hasClass("InputValidation")) {
            if ($.browser.msie) {
                if (!String.fromCharCode(event.keyCode).match(/[a-zA-Z0-9\-\\\/+\s.@;#_\(\)]+/)) {
                    alert($.eStoreLocalizaion("not_a_valid_char"));
                    return false;
                }
            }
            else {
                if (event.which > 29 && !String.fromCharCode(event.which).match(/[a-zA-Z0-9\-\\\/+\s.@;#_\(\)]+/)) {
                    alert($.eStoreLocalizaion("not_a_valid_char"));
                    return false;
                }
            }

        }
    });

    $(":password").keypress(function (event) {
        if (event.keyCode == '13') {
            var closestButton = $(this).closest(":has(:submit)").find(":submit:first");
            if (closestButton) {
                $(closestButton).trigger("click");
                return false;
            }
        }
    });

    $(".qtytextbox").keyup(function (event) {
        if ($(this).val().match(/[^0-9]/g)) {
            $(this).val(1);
        }
        else {
            if ($(this).val().match(/\d{5,}/)) {
                $(this).val($(this).val().substr(0, 5));
                alert($.eStoreLocalizaion("too_large_number"));
                return false;
            }
        }
    });

    $(".qtyboxOnlyNO").keyup(function (event) {
        if (!checkQTYInfo($(this))) {
            $(this).val(1);
        }
        else {
            if ($(this).val().match(/\d{5,}/)) {
                $(this).val($(this).val().substr(0, 5));
                alert($.eStoreLocalizaion("too_large_number"));
                return false;
            }
        }
    });
    
    $("img[src='']").attr("src", "/images/photounavailable.gif");

    $(".editorpanel :text,textarea").PreFillToolTips();

    if (dictionary == null || dictionary == undefined) {
        $.getJSON("/proc/do.aspx",
        { func: 11 },
        function (data) {
            dictionary = data;
            mapping = $.map(dictionary, function (n) {
                return n.key;
            });
        });
    }

    $.each($(".ajaxproductprice"), function () {

        var pricepanel = $(this);
        var _isminprice = pricepanel.hasClass("miniprice");
        $.ajaxSetup({ cache: false });
        $.getJSON("/proc/do.aspx",
        { func: "12"
        , id: $(pricepanel).attr("id")
        , isminprice: _isminprice
        },
        function (data) {
            $(pricepanel).html(data.price);
        });
    });
});
$.fn.equalHeight = function () {
    var tallest = 0;
    this.each(function () {
        thisHeight = $(this).height();
        if (thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    return $(this).height(tallest);
};
jQuery.fn.center = function () {
    this.css("position", "absolute");
    this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px");
    this.css("left", ($(window).width() - this.width()) / 2 + $(window).scrollLeft() + "px");
    return this;
};

jQuery.fn.PreFillToolTips = function () {
    return this.each(function () {
        if ((this.type === "text" || this.type === "password" || this.type === "textarea") && this.title) {
            if ($.trim($(this).val()) == "") {
                $(this).val(this.title).css("color", "#CCC");
            }
            $(this).bind("focus", function () {
                if ($.trim($(this).val()) == this.title) {
                    $(this).val('').css("color", "#000");
                }
            });
            $(this).bind("blur", function () {
                if ($.trim($(this).val()) == '') {
                    $(this).val(this.title).css("color", "#CCC");
                }
            });
        }

    })
};

jQuery.fn.validateTextBoxWithToolTip = function () {
    var message = "";
    var isValidated = true;
    this.each(function () {
        if ((this.type === "text" || this.type === "password") && this.title) {
            if ($.trim($(this).val()) == this.title) {
                message += this.title + $.eStoreLocalizaion("can_not_be_empty") +"\r";
                isValidated = false;
            }
        }
    })
    if (!isValidated) {
        alert(message);
        return false;
    }
    else
        return true;
};
 
jQuery.cookie = function (name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = 1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

//store ads
var centerpopuptimeout;
function centerpopup(ad) {
    if ($(".centerpopupadvertisement").length == 0) {
        if (ad.HtmlContent != "") {
            $("<div/>").attr("class", "centerpopupadvertisement").html(ad.HtmlContent)
        .appendTo("body");
        }
        else {
            $("<div/>").attr("class", "centerpopupadvertisement").html(
            $("<a/>")
            .attr("href", ad.Hyperlink)
            .attr("target", ad.Target)
            .html($("<img/>").attr("src", ad.image).attr("alt", ad.Title)))
            .append($("<div/>").attr("class", "adclose").html(" &nbsp;&nbsp;&nbsp &nbsp;&nbsp;&nbsp"))
        .appendTo("body");
        } 
        //$(".centerpopupadvertisement").center();
        $(".centerpopupadvertisement").css("position", "absolute");
        $(".centerpopupadvertisement").css("top", $(".master-wrapper-page").offset().top + 325 + "px");
        $(".centerpopupadvertisement").css("left", $(".master-wrapper-page").offset().left + 312 + "px");

        $("#centerpopupreopen").html(ad.Title).bind("click", function () {
            $.cookie("centerpopup" + ad.id, false, { expires: -1 });
            $(".centerpopupadvertisement").show();
        });

        $(".centerpopupadvertisement .adclose").bind("click", function () {
            $.cookie("centerpopup" + ad.id, true);
            $(".centerpopupadvertisement").hide();
            clearTimeout(centerpopuptimeout);
        });
    }

    if (!$.cookie("centerpopup" + ad.id)) {
        $(".centerpopupadvertisement").show();
        centerpopuptimeout = setTimeout(function () {
            $(".centerpopupadvertisement").hide();
        }, 180000);
    }
    else {
        $(".centerpopupadvertisement").hide();
    }
};

function topsliderdown(ad) {
    $(".master-wrapper-content").before($("<div/>").attr("class", "advertisementtop").addClass("hide").html(
                        $("<a/>")
            .attr("href", ad.Hyperlink)
            .attr("target", ad.Target)
            .html($("<img/>").attr("src", ad.image).attr("alt", ad.Title)))
            .append($("<div/>").attr("class", "adclose").html(" &nbsp;&nbsp;&nbsp &nbsp;&nbsp;&nbsp")));
    setTimeout(function () {
        $(".advertisementtop").slideDown(2000, function () {
            $(this).removeClass("hide");
            setTimeout(function () {
                $(".advertisementtop").slideUp(2000)
            }, 10000)
        });
    }, 3000);
    $(".advertisementtop .adclose").bind("click", function () {
        $.cookie("topsliderdown" + ad.id, true);
        $(this).parent().remove();
    });
};
jQuery.eStoreAD = function (data) {
    
    if (data && data.length != 0) {
        $.each(data, function (i, item) {
            switch (data[i].type) {
                case "TopSliderDown":
                    if (!$.cookie("topsliderdown" + data[i].id)) {
                        topsliderdown(data[i]);
                    }
                    delete data[i];
                    break;
                case "CenterPopup":
                    centerpopup(data[i]);
                    delete data[i];
                    break;
                default:
                    break;
            }
        });
        
        var imgitems = 0;
        if ($("#storeSideAds").length != 0) {
            if ($(".master-wrapper-side").length != 0 && $(".master-wrapper-center").length != 0) {
                var deltaLength = $(".master-wrapper-center").height() - $(".master-wrapper-side").height();
                var imgheight = 110;
                imgitems = parseInt(deltaLength / imgheight);
            }
            else
                imgitems = 2;
            var i = 0;
            for (; i < imgitems && i < data.length; i++) {
                if (data[i] && data[i].image != null)
                    generateEstoreAds(data[i], "#storeSideAds", data[i].HtmlContent);
            }
            for (; i < data.length; i++) {               
                if (data[i] && data[i].image != null)
                    generateEstoreAds(data[i], "#storeBottomAds", data[i].HtmlContent);
                if (i - imgitems == 4) return false;
            }
        }
        else if ($("#storeBottomAds").length != 0) {
            var cnt = 0;
            for (var i = 0; i < data.length; i++) {
                if (data[i]) {
                    generateEstoreAds(data[i], "#storeBottomAds", data[i].HtmlContent);
                    cnt++;
                    if (cnt == 5) return false;
                }
            }
        }

    }
};
jQuery.eStoreLocalizaion = function (key) {

    var rlt = $.inArray(key, mapping);
    if (rlt == -1) {
        return key.replace(/_/g, " ");
    }
    else {
        return dictionary[rlt].value;
    }
};

function generateEstoreAds(data, container, content) {
    if (content == "") {
        $("<a/>")
            .attr("href", data.Hyperlink)
            .attr("target", data.Target)
            .html($("<img/>").attr("src", data.image).attr("alt", data.Title))
            .appendTo(container);
    }
    else {
        $(container).html(data.HtmlContent)
    }
}

function checkSubQTYInfo() {
    var isResult = true;
    var isReturnEach = false;
    $(".qtyboxOnlyNO").each(function (i) {
        if (!checkQTYInfo($(this))) {
            if (confirm("QTY must input NO. Don't notice it?")) {
                isResult = true;
                isReturnEach = true;
            }
            else {
                $(this).focus();
                isResult = false;
                isReturnEach = true;
            }
        };
        if (isReturnEach) {
            return false;
        };
    });
    return isResult;
}
function checkQTYInfo(obj) {
    var str = obj.val();
    if (str.match(/^0/g) || str.match(/[^0-9]/g)) {
        return false;
    }
    else {
        return true;
    }
}
