﻿var fieldError = "fieldError";
function trim(stringToTrim) {
    stringToTrim = stringToTrim || "";
    return stringToTrim.replace(/^\s+|\s+$/g, "");
}

function isNullOrEmpty(str) {
    str = trim(str || "");
    if (str.length < 1)
        return true;
    return false;
}

/*  validation */
function isValidEmail(strEmail) {
    var regEmail = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
    return regEmail.test(strEmail);
}

function hasValidated(source, argument) {
    if ($(source).prev().attr("tagName") == "SPAN" && $(source).prev().prev().attr("tagName") == "INPUT" && $(source).prev().prev().prev().attr("tagName") == "INPUT") {
        if ($(source).prev().css("display") != "none" && $(source).prev().prev().prev().attr("ID") != null && $(source).prev().prev().attr("ID") == $(source).prev().prev().prev().attr("ID") + "_Field") {
            argument.IsValid = true;
            return true;
        }
    }
    return false;
}

function validateEmail(source, argument) {
    if (hasValidated(source, argument)) return;
    var email = trim(argument.Value);
    if (isNullOrEmpty(email)) {
        argument.IsValid = true;
        return argument.IsValid;
    }
    var controlToValidate = $("#" + source.controltovalidate);
    if (!isValidEmail(email)) {
        argument.IsValid = false;
        controlToValidate.addClass(fieldError);
    }
    else {
        argument.IsValid = true;
        controlToValidate.removeClass(fieldError);
    }
    if (typeof validateEmailEx == "function") {
        argument.IsValid = validateEmailEx(source, argument);
    }
    return argument.IsValid;
}

function validatePostCode(source, argument) {
    argument.IsValid = /^\s*\d{4}\s*[a-zA-Z]{2}\s*$/.test(argument.Value);
    if (typeof validatePostCodeEx == "function") {
        argument.IsValid = validatePostCodeEx(source, argument);
    }
    setValidateResultStyle(source, argument);
}

function validatePostCodeNew(source, argument) {
    if (hasValidated(source, argument)) return;
    validateRequired(source, argument);
}


function validatePhoneNumber(source, argument) {
    if (hasValidated(source, argument)) return;
    var span = $(source);
    if ($(source).prev().length > 0 && $(source).prev().prev().length > 0) {
        if ($(source).prev().attr("ID") == $(source).prev().prev().attr("ID") + "_Field" && $(source).prev().attr("tagName") == "INPUT") {
            if (!$(source).prev().val()) {
                argument.IsValid = true;
                return;
            }      
        }
    }
    argument.IsValid = /^[0-9\-\+\s]+$/.test(argument.Value);
    if (typeof validatePhoneNumberEx == "function") {
        argument.IsValid = validatePhoneNumberEx(source, argument);
    }
    setValidateResultStyle(source, argument);
}
// call this function after the validation logic
function setValidateResultStyle(source, argument) {
    var controlToValidate = $("#" + source.controltovalidate);
    if (argument.IsValid) {
        controlToValidate.removeClass(fieldError);
    } else {
        controlToValidate.addClass(fieldError);
    }
}

function validateRequired(source, argument) {
    var span = $(source);
    if ($(source).prev().length > 0 && $(source).prev().prev().length > 0) {
        if ($(source).prev().attr("ID") == $(source).prev().prev().attr("ID") + "_Field" && $(source).prev().attr("tagName") == "INPUT") {
            if (!$(source).prev().val()) {
                argument.IsValid = false;
            }
        }
    }
    var controlToValidate = $("#" + source.controltovalidate);
    if (isNullOrEmpty(trim(argument.Value))) {
        argument.IsValid = false;
        controlToValidate.addClass(fieldError);
    }
    else {
        argument.IsValid = true;
        controlToValidate.removeClass(fieldError);
    }
    if (typeof validateRequiredEx == "function") {
        argument.IsValid = validateRequiredEx(source, argument);
    }
    return argument.IsValid;
}

function GoToTop() {
    if (window.top.location.href != window.location.href) {
        window.top.location.href = window.location.href;
    }
}
function ProductSearchKeyPress(sender, eventArgs) {
    if (eventArgs.get_domEvent().keyCode == 13) {
        ProductSearch();
    }
}
function ProductSearchIndex(sender, eventArgs) {
    ProductSearch();
}

function ProductSearch() {
    var href = $("a[ID*=btnProductSearch]").attr("href");
    RunHref(href);
}

function RunHref(href) {
    href = href.replace("javascript:", "");
    eval(href);
}

function OrderKeyPress(event) {
    var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (Key == 13) {
        var href = $("a[ID*=btnOrderSearch]").attr("href");
        RunHref(href);
    }
}

function CancelSSL(domain) {
    $(document).ready(function() {
        $("a").each(function() {
            var o = $(this);
            var href = o.attr("href");
            if (href && !(href.indexOf("javascript") == 0 || href.indexOf("http:") == 0 || href.indexOf("https:") == 0)) {
                o.attr("href", "http://" + domain + href);
            }
        });
    });

}

function PaymentCheck(msg) {
    var option = "";
    var list = $(".cart-all .payment-method").find("input[type=radio]");
    for (i = 0; i < list.length; i++) {
        if (list[i].checked) {
            option = list[i].value;
        }
    }
    if (typeof PaymentCheckEx != "undefined") {
       var result =PaymentCheckEx(list);
       if (result == 1) {
           return true;
       } else if (result == 0) {
          return false;
       }
    }
    if (option != "") {
    }
    else {
        alert(msg)
        return false;
    }
}

function CbAgree(soruce, args) {
    var obj = document.getElementById("cbAgree");
    args.IsValid = obj.checked;
    if (!args.IsValid) {
        var lb = document.getElementById("spanAgree");
        lb.style.display = "none";
    }
}
function ClearTermsCheckErrorMessage(cvId) {
    var obj = document.getElementById("cbAgree");
    if (obj.checked) {
        var err = document.getElementById(cvId);
        var lb = document.getElementById("spanAgree");
        err.style.display = "none";
        lb.style.display = "inline";
    }
}

function OpenNewsLetterPage() {
    var url = "/SubscribeMail.aspx?keepThis=false";
    tb_show("", url + "&TB_iframe=true&height=395&width=636&modal=false", false);
}

/* Modified By wenbin */
function HideAllCategorySearchMenu() {
    $('.product-search-filter .by-brand > a').removeClass('active');
    $('.product-search-filter .by-sort > a').removeClass('active');
    $('.product-search-filter .by-brand > div').hide();
    $('.product-search-filter .by-sort ul').hide();
}

///Category search menu function
function InitCategorySearchMenu() {
    $('.product-search-filter .by-brand > a').click(function() {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            $(this).siblings('div').hide();
        }
        else {
            HideAllCategorySearchMenu();
            $(this).addClass('active');
            $(this).siblings('div').show();
        }
    });

    $('.product-search-filter .by-sort > a').click(function() {
        if ($(this).hasClass('active')) {
            $(this).removeClass('active');
            $(this).siblings('ul').hide();
        }
        else {
            HideAllCategorySearchMenu();
            $(this).addClass('active');
            $(this).siblings('ul').show();
        }
        return false;
    });

    $('.product-search-filter .by-brand .buttons .close').click(function() {
        $('.product-search-filter .by-brand > a').removeClass('active');
        $('.product-search-filter .by-brand > div').hide();
    });
    
    $('body').click(function() {
	    $('.product-search-filter .by-sort ul:visible').hide();
	    $('.product-search-filter .by-sort > a').removeClass('active');
    });
}

if ($) {
    var applicationSubmitTemp = "submit::&&ApplicationExtend_##201109021039**Name";
    var ApplicationFlag = 0;
    var applicationSubmitControl = new Array();
    $(document).ready(function () {
        ApplicationFlag = 1;
        registerControlEvent();
    })
    function initSubmitButton() {
        setTimeout(function () {
            registerControlEvent();
            if (ApplicationFlag != 1) {
                setTimeout(function () {
                    initSubmitButton();
                }, 100);
            }
        }, 100);
    }
    function registerControlEvent() {
        var btns = $(".buttons>.button,a.button");
        for (var index = 0; index < btns.length; index++) {
            var control = $(btns[index]);
            var key = control.attr("id");
            if (applicationSubmitControl[key] == null) {
                control.click(function () {
                    $("*[name='submit']").attr("name", applicationSubmitTemp);
                    if (typeof ApplicationSubmitFunction != "undefined") {
                        ApplicationSubmitFunction(applicationSubmitTemp, control);
                    }
                });
                applicationSubmitControl[key] = control;
            }
        }
    }
    initSubmitButton();
    if ($("*[name='" + applicationSubmitTemp + "']").attr("name") != "submit") {
        $("*[name='" + applicationSubmitTemp + "']").attr("name", "submit");
    }
    if (typeof ApplicationExtendFunction != "undefined") {
        ApplicationExtendFunction(applicationSubmitTemp);
    }
}

var ControlComponent = function (param) {
    var Self = this;
    var config = {
        EmptyMessage: "",
        ID: ""
    }
    var specialChar = ""; // "^&%$#";
    Self.control = null;
    Self.controlState = null;
    Self.fieldControl = null;

    var init = function () {
        $.extend(config, param);
        Self.control = $("#" + config.ID);
        var fieldID = Self.control.attr("ID") + "_Field";
        Self.fieldControl = $("#" + fieldID);
        var maxlength = Self.control.attr("maxlength");

        if (Self.control.parent().parent().attr("tagName") == "TR") {
            Self.trControl = Self.control.parent().parent();
        } else {
            Self.trControl = Self.control.parent().parent().parent();
        }
        Self.control.mousedown(function () {
            if (!Self.controlState) {
                Self.control.val("");
                Self.control.css("color", "#000000");
            }
        });
        Self.control.change(function () {
            Self.controlState = Self.control.val();
            if (Self.fieldControl != null) {
                if (Self.controlState == config.EmptyMessage) {
                    Self.fieldControl.val(Self.controlState + specialChar);
                } else {
                    Self.fieldControl.val(Self.controlState);
                }
            }
            if (maxlength) {
                var value = Self.control.val().substr(0, maxlength);
                if (value == config.EmptyMessage) {
                    Self.fieldControl.val(value + specialChar);
                } else {
                    Self.fieldControl.val(value);
                }
                Self.control.val(value);
            }
        })
        Self.control.blur(function () {
            if (!Self.controlState) {
                Self.control.val(config.EmptyMessage);
                Self.control.css("color", "#8A8A8A");
            }
        })
        Self.control.focus(function () {
            if (!Self.controlState) {
                Self.control.val("");
                Self.control.css("color", "#000000");
            }
        });
        Self.control.keyup(function (e) {
            if (maxlength) {
                if (Self.control.val().length > maxlength && (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)) {
                    var value = Self.control.val().substr(0, maxlength);
                    if (value == config.EmptyMessage) {
                        Self.fieldControl.val(value + specialChar);
                    } else {
                        Self.fieldControl.val(value);
                    }
                    Self.control.val(value);
                    return false;
                }
                Self.controlState = Self.control.val();
            }
        });
        Self.control.keydown(function (e) {
            if (maxlength) {
                if (Self.control.val().length > maxlength - 1 && (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 38 && e.keyCode != 39 && e.keyCode != 40)) {
                    return false;
                }
                Self.controlState = Self.control.val();
            }
        });
        if (!Self.fieldControl.val()) {
            Self.control.val(config.EmptyMessage);
            Self.control.css("color", "#8A8A8A");
        } else {
            Self.controlState = Self.fieldControl.val();
            Self.control.css("color", "#000000");
        }
    }
    Self.Validator = function (type) {
        Self.control.removeClass("fieldError");
        var fieldID = Self.control.attr("ID") + "_Field";
        var fieldControl = $("#" + fieldID);
        if (!Self.control.val() || Self.control.val() == config.EmptyMessage) {
            var Ignore = Self.control.attr("Ignore");
            if (Ignore == "1") {
                return true;
            }
            Self.control.addClass("fieldError");
            return false;
        }
        if (Self.control.val() && Self.control.val().length > 0) {
            var validateFunc = Self.control.attr("validateFunc");
            if (validateFunc) {
                var args = { Value: Self.control.val(), IsValid: true };
                var spanElement = Self.control.parent().find("span[controltovalidate='" + Self.control.attr("ID") + "']");
                eval(validateFunc + "(spanElement,args)");
                return args.IsValid;

            }
        }
        return true;
    }
    init();
}
var ComponentContainer = function () {
    var Self = this;
    Self.Container = [];
    Self.configContainer = [];
    Self.addComponent = function (config) {
        if (Self.Container[config.ID] == null) {
            Self.configContainer[config.ID] = config;
        }
    }
    Self.Binding = function () {
        $(document).ready(function () {
            for (var item in Self.configContainer) {
                Self.Container[item] = new ControlComponent(Self.configContainer[item]);
            }
        });
    },
    Self.Validator = function (elem) {
        if (elem == null) return true;
        var id = $(elem).parent().find("input[type='text']").attr("ID");
        if (!Self.Container[id]) {
            var radios = $(elem).parent().find("input[type='radio']");
            if (radios.length > 0) {
                for (var index = 0; index < radios.length; index++) {
                    if ($(radios[index]).attr("checked") == true) return true;
                }
                return false;
            } else {
                var combox = $(elem).parent().find("select");
                if (combox.length > 0) {
                    var options = combox.find("option");
                    for (var index = 0; index < options.length; index++) {
                        if ($(options[index]).attr("selected") == true && $(options[index]).html().trim() != "") {
                            return true;
                        }
                    }
                    return false;
                }
            }
            return true;
        }
        return Self.Container[id].Validator("Required");
    }
}

var HelpTipComponent = function (config) {
    var Self = this;
    var helptipContainer = null;
    Self.IsOnline = false;

    var init = function () {
        Self.control = $("#" + config.ID);
        Self.control.find("input,textarea,label,select").mouseenter(function (e) {
            if (Self.IsOnline) return;
            Self.IsOnline = true;
            helptipContainer = Self.control.find(".customTip");
            if (helptipContainer.length == 0) {
                helptipContainer = $("<span class='customTip' style='white-space:nowrap;'/>");
                var helpTip = Self.control.find(".helptip");
                var customTip = $(helpTip.html());
                customTip.addClass("active");
                customTip.show();
                customTip.appendTo(helptipContainer);
                helptipContainer.appendTo(Self.control);
            }
            var currentControl = $(e.target);
            var location = currentControl.position();
            helptipContainer.find("div.tooltip").css("left", location.left).css("top", location.top + currentControl.height() + 6);
            helptipContainer.show();
        });
        Self.control.find("input,textarea,label,select").mouseleave(function (e) {
            if (helptipContainer != null && helptipContainer.length > 0) {
                helptipContainer.hide();
                Self.IsOnline = false;
            }
        });
    }
    init();
}

var ComponentManage = {
    componentContainerObject: null,
    componentHelpTipExtandObject: null,
    Init: function (config) {
        if (config == null || config.ID == null) return;
        if (ComponentManage.componentContainerObject == null) {
            ComponentManage.componentContainerObject = new ComponentContainer();
        }
        ComponentManage.componentContainerObject.addComponent(config);
    },
    BindComponent: function () {
        if (ComponentManage.componentContainerObject != null) {
            ComponentManage.componentContainerObject.Binding();
        }
    },
    ValidateComponent: function (elem) {
        return ComponentManage.componentContainerObject.Validator(elem);
    },
    InitHelpTip: function (config) {
        if (ComponentManage.componentHelpTipExtandObject == null) {
            ComponentManage.componentHelpTipExtandObject = new Object();
        }
        if (ComponentManage.componentHelpTipExtandObject[config.ID] != null) return;
        var itemObject = new HelpTipComponent(config);
        ComponentManage.componentHelpTipExtandObject[config.ID] = itemObject;
    }
}
