﻿var obj;
var Content = {

    enterSubmit: function(btn, e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            btn.click();
            return false;
        }
        else
            return true;
    },

    formError: function(result, context, methodName) {
        obj.removeAttr('disabled');
        alert(result.get_message());
    },

    loadError: function(result, context, methodName) {
        alert(result.get_message());
    },

    loadSuccess: function(result, context, methodName) {

        if ((methodName == "submitRoleForm" || methodName == "updateRoleForm") && result.substring(0, 6).toLowerCase() == "error:")
            $(obj).removeAttr('disabled');

        if (methodName == "submitRoleForm" && result.substring(0, 6).toLowerCase() == "error:") 
            $('.formErrorRegister').show().html(result);
        
        else if (methodName == "updateRoleForm" && result.substring(0, 6).toLowerCase() == "error:")
            $('.formErrorEdit').show().html(result);
        else if (result.substring(0, 6).toLowerCase() == "error:") {
            $('.forgotOpen').hide();
            $('#lbforgot').show();
            alert(result);
        }
        else if (result.substring(0, 6).toLowerCase() == "error:")
            alert(result);

        else {
            switch (methodName) {
                case "addToCart":
                    if (result.length)
                        location.href = result;
                    break;
                case "addToCartSKU":
                    if (result.length)
                        location.href = result;
                    break;
                case "checkCoupon":
                    if (result.indexOf("Coupon accepted!") > -1) {
                        var button = document.getElementById($('.update').attr('id'));
                        $('.couponMessage').html(result);
                        button.click();
                    }
                    else
                        $('.couponMessage').html(result);
                    break;
                case "loginRoleUser":
                    if (result == "true")
                        window.location = context;
                    else {
                        obj.removeAttr('disabled');
                        $('.loginError', obj.parent().parent()).show();
                    }
                    break;
                case "logoutUser":
                    if (result == "true")
                        window.location = context;
                    break;
                case "SendPassword":
                    $('.forgotOpen').hide();
                    $('#lbforgot').show();
                    break;
                case "submitRoleForm":
                    if (result == "true")
                        window.location = context;
                    break;
                case "updateRoleForm":
                    if (result == "true")
                        window.location = context;
                    break;
                case "updateSKUPrice":
                    var arr = result.split("|||");
                    var price = parseFloat(arr[1].replace('$', ''));
                    var salePrice = parseFloat(arr[0].replace('$', ''));

                    if (arr[2] == 0) {
                        $(".soldOut[rel='" + context + "']").show();
                        $("a[rel='" + context + "']").hide();
                    }
                    else {
                        $(".soldOut[rel='" + context + "']").hide();
                        $("a[rel='" + context + "']").show();
                    }

                    $(".skuPrice[rel='" + context + "']").text(arr[1]);
                    $(".skuQuantity[rel='" + context + "']").text(arr[2]);
                    $(".skuSalePrice[rel='" + context + "']").text(arr[0]);

                    $(".skuPrice[rel='" + context + "']").removeClass('onSale');
                    $(".skuSalePrice[rel='" + context + "']").removeClass('onSale');

                    if (salePrice > 0 && salePrice < price) {
                        $(".skuPrice[rel='" + context + "']").addClass('onSale');
                        $(".skuSalePrice[rel='" + context + "']").addClass('onSale');
                    }
                    break;
                case "addCheckoutOptToCart": case "removeCheckoutOptToCart":
                    $(".totalPrice").text(result);
                    break;
            }
        }
    },

    Masks: {

        loadMasks: function() {
            $('.dateMask').mask("99/99/9999");
            $('.phoneMask').mask("(999) 999-9999");
            //$('.internationalPhoneMask').mask("+(99) (999) 999-9999"); // omar code
            $('.creditExpMask').mask("99/99");
            $('.percentMask').mask("99%");
        }

    }

}

var CheckoutOptions = {

    update: function(coID, cartID, thisObj) {
        $('.optionPriceToggle', $(thisObj).parent().parent()).toggle();
        if ($(thisObj).attr('checked'))
            WebMethods.addCheckoutOptToCart(coID, cartID, Content.loadSuccess, Content.loadError);
        else
            WebMethods.removeCheckoutOptToCart(coID, cartID, Content.loadSuccess, Content.loadError);
    }

}


var Cart = {

    SKU: {

        addCoupon: function(e, thisObj) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
                return false;
            else {
                var code = $(thisObj).val();
                //code += (e.which) ? String.fromCharCode(e.which) : String.fromCharCode(e.keyCode);
                WebMethods.checkCoupon(code, Content.loadSuccess, Content.loadError, $(thisObj));
                return true;
            }
        },

        addToCart: function(o, instID, redirect) {
            var skus = new Array();
            var skuValues = new Array();
            var skuQty = $('.skuQty[rel=' + instID + ']').val();
            var orderMetaField = new Array();
            var href = $(o).attr("href");

            $('.orderMetaField[rel=' + instID + ']').each(function(i) {
                orderMetaField.push($(this).attr('rev'));
                orderMetaField.push($(this).val());
            });

            if (skuQty != undefined && skuQty.length > 0 && isNaN(skuQty)) {
                alert('Error: Quantity must be a valid number');
                return;
            }
            else if (skuQty == undefined || skuQty.length == 0)
                skuQty = null;

            if ($('.sku').size() > 0) {
                $(':checked', '.sku[rel=' + instID + ']').each(function(i) {
                    skus[i] = $(this).val();
                });

                if (redirect)
                    WebMethods.addToCartSKU(instID, skus, skuQty, orderMetaField, redirect, function() { window.location = href; }, Content.loadError);
                else
                    WebMethods.addToCartSKU(instID, skus, skuQty, orderMetaField, false, Content.loadSuccess, Content.loadError);

            }
            else {
                $('.skufield[rel="' + instID + '"]').each(function(i) {
                    skuValues[i] = $(this).val();
                });

                $('.skuRadio[rel="' + instID + '"]:checked').each(function(i) {
                    skuValues[i] = $(this).val();
                });

                if (redirect)
                    WebMethods.addToCart(instID, skuValues, skuQty, orderMetaField, (!redirect ? false : redirect), function() { window.location = href; }, Content.loadError);
                else
                    WebMethods.addToCart(instID, skuValues, skuQty, orderMetaField, (!redirect ? false : redirect), Content.loadSuccess, Content.loadError);
            }
        },

        addQtyToCart: function(e, thisObj) {
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
                Cart.SKU.addToCart(null, (thisObj).attr('rel'));
                return false;
            }
            else
                return true;
        },

        updatePrice: function(instID) {
            var skuValues = new Array();

            $('.skufield[rel="' + instID + '"]').each(function(i) {
                skuValues[i] = $(this).val();
            });

            $('.skuRadio[rel="' + instID + '"]:checked').each(function(i) {
                skuValues[i] = $(this).val();
            });

            WebMethods.updateSKUPrice(instID, skuValues, Content.loadSuccess, Content.loadError, instID);
        }

    }

}

var EmailSignUp = {

    addNewSignUpEmailComplete : function(result, context, methodName){
        if(result.indexOf("Error:") > -1)
            $('.emailSignUpError').html(result.substring(7));
        else 
            context.parent().parent().slideUp(400, function(){
                $(this).html(result);
                $(this).slideDown(400);
            });        
    },

    submit: function(thisObj, successMessage){
        obj = thisObj;
        var email = $(':text', obj.parent().parent()).val();
        
        WebMethods.addNewSignUpEmail(email, successMessage, EmailSignUp.addNewSignUpEmailComplete, Content.loadError, obj);
    },  

    enterSubmit: function(e, btn, successMessage){
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
            EmailSignUp.submit($('#'+btn), successMessage);
            return false;  
        } 
        else
            return true;   
    }   

}

var Form = {

    submit: function(roleID, successURL, sendEmail, successEmail, successEmailSubject, successEmailCC, autoLogin, setEmail, setPassword, formType,isMailinglist,showcategories, thisObj) {

        $(thisObj).attr('disabled', 'disabled');

        var fields = new Array();
        var isValid = true;
        var fVal = new Array();
        var formMailcat = new Array();

        $('.roleField', $(thisObj).parent().parent()).each(function(i) {
            var isReq = $(':password, :text, select, textarea', $(this)).attr('rev') == "true";
            var val = $(':password, :text, select, textarea', $(this)).val();


            if ($(':radio', $(this)).html() != null) {
                isReq = $(':radio', $(this)).parents('table').attr('rev') == "true";
                val = $(':radio:checked', $(this)).val();
            }
            else if ($(':checkbox', $(this)).html() != null) {
                isReq = $(':checkbox', $(this)).parents('table').attr('rev') == "true";
                val = $(':checkbox:checked', $(this)).parent().children('label').html();
            }

            if (isReq && (!val || val.length == 0)) {
                $(this).addClass('roleFieldError');
                isValid = false;
            }
            else
                $(this).removeClass('roleFieldError');
        });

        if (isValid) {

            obj = thisObj;

            $('.roleField', $(thisObj).parent().parent()).each(function(i) {
                var fID = $(':password, :text, select, textarea', $(this)).attr('rel');
                var val = $(':password, :text, select, textarea', $(this)).val();
                var isReq = $(':password, :text, select, textarea', $(this)).attr('rev');
                var name = $('> label', this).text();

                if ($(':radio', $(this)).html() != null) {
                    fID = $(':radio', $(this)).parents('table').attr('rel');
                    isReq = $(':radio', $(this)).parents('table').attr('rev');
                    val = $(':radio:checked', $(this)).val();
                }

                if ($(':checkbox', $(this)).html() != null) {
                    fID = $(':checkbox', $(this)).parents('table').attr('rel');
                    isReq = $(':checkbox', $(this)).parents('table').attr('rev') == "true";

                    $(':checkbox:checked', $(this)).each(function(j) {
                        val = $(this).parent().children('label').html();
                        fields[fields.length] = { roleFieldID: fID, roleFieldValue: val, isRequired: isReq, Name: name };
                    });
                }
                else
                    fields[fields.length] = { roleFieldID: fID, roleFieldValue: val, isRequired: isReq, Name: name };
            });

            /*
            Adding Categories to the Form - MS
            */
            $('.categories', $(thisObj).parent().parent()).each(function() {

                if ($(':checkbox:checked', $(this)).is(':checked')) {
                    var catid = $(':checkbox:checked', $(this)).parent().attr('rel');
                    var catname = $($(this).children('.lbcategories')).text();
                    formMailcat[formMailcat.length] = { MailCatId: catid, MailCatName: catname };
                }

            });
            /* End of the Categories  - MS*/

            if (formType == "Edit")
                WebMethods.updateRoleForm(roleID, fields, autoLogin, setEmail, setPassword, formMailcat, isMailinglist, showcategories, Content.loadSuccess, Content.formError, successURL);
            else                 
                WebMethods.submitRoleForm(roleID, fields, autoLogin, sendEmail, successEmail, successEmailSubject, successEmailCC,formMailcat,isMailinglist,showcategories, Content.loadSuccess, Content.formError, successURL);
          
        }
        else {
            $('.formErrorRegister, .formErrorEdit').hide().empty();
            $(thisObj).removeAttr('disabled');
        }
    }

}


var Login = {

    Form: {

        login: function(loginURL, thisObj) {
            $(thisObj).attr('disabled', 'disabled');
            obj = $(thisObj);
            var user = $(':text:eq(0)', $(thisObj).parent().parent()).val();
            var pass = $(':password:eq(0)', $(thisObj).parent().parent()).val();
            WebMethods.loginRoleUser(user, pass, Content.loadSuccess, Content.loadError, loginURL);
        },

        logout: function(logoutURL) {
            WebMethods.logoutUser(Content.loadSuccess, Content.loadError, logoutURL);
        },

        forgotPassword: function(thisObj) {
            $(thisObj).hide();
            $('.forgotOpen').show();
        },
        SendPassword: function(thisObj) {
            obj = $(thisObj);
            var emailRegEx = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            var user = $('.lbEmail', $(thisObj).parent().parent()).val();
            if (user.match(emailRegEx)) {
                WebMethods.SendPassword(user, Content.loadSuccess, Content.loadError);
            }
            else {
                $('.forgotError').show();
            }
        }

    }

}


var Search = {

    enterSubmit: function(resultsPage, searchType, searchFields, searchInstName, thisObj, e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            this.submit(resultsPage, searchType, searchFields, searchInstName, thisObj);
            return false;
        }
        else
            return true;
    },

    submit: function(resultsPage, searchType, searchFields, searchInstName, thisObj) {
        if ($(':text:first', $(thisObj).parent().parent()).val().length > 0)
            window.location = "/" + resultsPage +
                              "?type=" + searchType +
                              "&searchFields=" + searchFields +
                              "&searchTerm=" + $(':text:first', $(thisObj).parent().parent()).val() +
                              (!searchInstName ? "&searchInstName=false" : "");
    }

}
