﻿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:")         
            alert(result);                
        else 
        {
            switch (methodName)
            {
                case "addToCart":
                    location.href = result;
                    break;
                case "checkCoupon":
                    if (result.indexOf("Coupon accepted!") > -1)
                    {
                        var button = document.getElementById($('.update').attr('id'));
                        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 "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;
            }
        }
    },
    
    Masks: {
    
        loadMasks: function(){
            $('.dateMask').mask("99/99/9999");
            $('.phoneMask').mask("(999) 999-9999");
            $('.creditExpMask').mask("99/99");
            $('.percentMask').mask("99%");            
        }
    
    }

}


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(instID){
            var skus = new Array();
            var skuValues = new Array();
            var skuQty = $('.skuQty[rel='+instID+']').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='+instanceID+']').each(function(i){
                    skus[i] = $(this).val();
                });                
            }
            else
            {
                $('.skufield[rel="' + instID + '"]').each(function(i){
                    skuValues[i] = $(this).val();
                });

                $('.skuRadio[rel="' + instID + '"]:checked').each(function(i){
                    skuValues[i] = $(this).val();
                });  
                
                WebMethods.addToCart(instID, skuValues, skuQty, Content.loadSuccess, Content.loadError);         
            }                      
        },  
        
        addQtyToCart: function(e, thisObj){
            if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
            {
                Cart.SKU.addToCart($(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, setPassword, formType, thisObj){
        $(thisObj).attr('disabled', 'disabled');
        
        var fields = new Array();
        var isValid = true;
        var fVal = 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');
                
                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};    
                    });
                }
                else
                    fields[fields.length] = {roleFieldID: fID, roleFieldValue: val, isRequired: isReq};
            });
            
            if (formType == "Edit")
                WebMethods.updateRoleForm(roleID, fields, autoLogin, setPassword, Content.loadSuccess, Content.formError, successURL);
            else
                WebMethods.submitRoleForm(roleID, fields, autoLogin, setPassword, sendEmail, successEmail, successEmailSubject, successEmailCC, 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);  
        }
    
    }

}


var Search = {

    enterSubmit: function(resultsPage, searchType, searchFields, thisObj, e){
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))
        {
            this.submit(resultsPage, searchType, searchFields, thisObj);
            return false;
        }
        else
            return true;
    },
    
    submit: function(resultsPage, searchType, searchFields, thisObj){
        if ($(':text:first', $(thisObj).parent().parent()).val().length > 0)
            window.location = "/" + resultsPage + "?type=" + searchType + "&searchFields=" + searchFields + "&searchTerm=" + $(':text:first', $(thisObj).parent().parent()).val();
    }

}