﻿// service URLs
var authUserService = "/ajax/authenticateuser.ashx";
var logoutService = "/ajax/logout.ashx";
var userExistsService = "/ajax/userexists.ashx";
var registerUserService = "/ajax/registeruser.ashx";  
var priceService = "/ajax/getperitemprice.ashx";
var updatecartService = "/ajax/updatecart.ashx";
var updateppService = "/ajax/updatecartwithpersonalproof.ashx";
var shoppingcartmodelpopupservice = "/ajax/GetShoppingCartPopUp.ashx";
var pingService = "/ajax/ping.ashx";
var productdetailService = "/ajax/GetProductDetailByBrandColorFinish.ashx";
var facetsearchService = "/ajax/FacetSearch.ashx";
var ppcartcountservice = "/ajax/GetPPCountFromCart.ashx";
var shippingchargeservice = "/ajax/CalculateShippingRate.ashx";
var validatecouponservice = "/ajax/ValidateCoupon.ashx";
var comparisonservice = "/ajax/GetProductComparison.ashx";
var insideremailservice = "/ajax/InsiderEmailSubmission.ashx";
var getsesionidservice = "/ajax/GetSessionId.ashx";

var form1validator;  // need this for special handling of form events for primary form

function InitSetupChain() 
{
    setupTopNav();
    setupLoginLink();
    setupRegistration();
    setupLogoutLink();
    setupFooterToolbar();
    setupTables();
    setupToolbarButtons();
    setupSubmitButtons();
    setupSearchButton();
    setupCheckoutButton();
    setupCartButton();
    setupValidatorDefaults();
    SetupInsiderForm();
    setupCopyShippingAddressButton();

    jQuery("#searchinput").keyup(function(event) {
        if (event.keyCode == 13) {
            jQuery("#globalsearchlink").click();
        }
    });

    jQuery("#lefthand_contentsearch_input input").keyup(function(event) {
        if (event.keyCode == 13) {
            jQuery("#contentsearchlink").click();
        }
    });


    jQuery("#closeloginwindowbutton").keydown(function(e) {
        if (e.which == 9) {
            e.preventDefault();
            jQuery("#loginusername").focus();
        }
    });
    jQuery("#loginusername").keydown(function(e) {
        if (e.which == 9 && e.shiftKey) {
            e.preventDefault();
            jQuery("#closeloginwindowbutton").focus();
        }
    });

    jQuery(".NeenahInsiderBanner").click(function(e) {
        e.preventDefault();
        PopupEmailSubmission()
    });
}

function popupVideo(url, height, width) {
    var src = url; //"http://www.neenahpaper.com/swf/Video_16x9.mp4";
    $.modal('<iframe src="' + src + '" height="' + height + '" width="' + width + '" style="border:0">', {
        closeHTML: "",
        containerCss: {
            backgroundColor: "#fff",
            borderColor: "#fff",
            height: height,
            padding: 0,
            width: width
        },
        overlayClose: true
    });



}

function popupRately(url, height, width, padding) {
    var src = url;
    $.modal('<iframe src="' + src + '" height="' + height + '" width="' + width + '" style="border:0">', {
        closeHTML: "",
        containerCss: {
            backgroundColor: "#fff",
            borderColor: "#fff",
            height: height,
            padding: padding,
            width: width
        },
        overlayClose: true
    });

}

function megaHoverOver() 
{
    jQuery(this).find(".sub").stop().fadeTo('fast', 1).show(); 
    jQuery(this).find(".subRight").stop().fadeTo('fast', 1).show(); 

    (function(jQuery) {

        //Function to calculate total width of all ul's
        jQuery.fn.calcSubWidth = function() {
            rowWidth = 0;
            //Calculate row
            
            jQuery(this).find("ul").each(function() { //for each ul...
                rowWidth += jQuery(this).width(); //Add each ul's width together
                
            });
        };
    })(jQuery);
    
    if (jQuery(this).find(".row").length > 0) { //If row exists...
    
        var biggestRow = 0;
        
        jQuery(this).find(".row").each(function() {	//for each row...
            jQuery(this).calcSubWidth(); //Call function to calculate width of all ul's
            //Find biggest row
            if (rowWidth > biggestRow) {
                biggestRow = rowWidth;
            }
        });

        jQuery(this).find(".sub").css({ 'width': biggestRow }); //Set width
        jQuery(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin

        jQuery(this).find(".subRight").css({ 'width': biggestRow }); //Set width for subRight
        jQuery(this).find(".row:last").css({ 'margin': '0' });  //Kill last row's margin for subRight


    } else { //If row does not exist...

        jQuery(this).calcSubWidth();  //Call function to calculate width of all ul's
        jQuery(this).find(".sub").css({ 'width': rowWidth }); //Set Width
        jQuery(this).find(".subRight").css({ 'width': rowWidth }); //Set Width for subRight

    }
}

//On Hover Out
function megaHoverOut() {

    jQuery(this).find(".sub").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
        jQuery(this).hide();  //after fading, hide it
    });

    jQuery(this).find(".subRight").stop().fadeTo('fast', 0, function() { //Fade to 0 opactiy
        jQuery(this).hide();  //after fading, hide it
    });

}


function setupTopNav() {

    var config = {
        sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)
        interval: 100, // number = milliseconds for onMouseOver polling interval
        over: megaHoverOver, // function = onMouseOver callback (REQUIRED)
        timeout: 200, // number = milliseconds delay before onMouseOut
        out: megaHoverOut // function = onMouseOut callback (REQUIRED)
    };
    jQuery("ul#topmenu_topnav li .sub").css({ 'opacity': '0' }); //Fade sub nav to 0 opacity on default
    jQuery("ul#topmenu_topnav li .subRight").css({ 'opacity': '0' }); //Fade subRight nav to 0 opacity on default
    jQuery("ul#topmenu_topnav li").hoverIntent(config); //Trigger Hover intent with custom configurations
}



function setupTables() {
    jQuery("table.stripe").each(
        function() {
            jQuery(this).find('tbody tr:odd').addClass('alt');
        });

        jQuery("table.brandspectable").each(
        function() {
            jQuery(this).find('tbody tr:odd').addClass('alt');
        });
}

function setupToolbarButtons() {
    jQuery(".scrollable .items div a").hover(function() {
        jQuery("img", this).stop().animate({ top: "-70px" }, { queue: false, duration: 0 });
    }, function() {
        jQuery("img", this).stop().animate({ top: "0px" }, { queue: false, duration: 0 });
    });

    jQuery(".scrollable .items div a").mousedown(function() {
        jQuery("img", this).stop().animate({ top: "-140px" }, { queue: false, duration: 0 });
    });
}

function setupSearchButton() {

    jQuery('#searchinput').clearField();
    setupButtonHover(jQuery("#globalsearchlink"), 22);
    setupButtonHover(jQuery("#contentsearchlink"), 22);
    
    jQuery("#globalsearchlink").click(function(ev) {
        ev.preventDefault();
        var search = jQuery.trim(jQuery("#searchinput").val());
        var newurl = jQuery(this).attr('href') + "?search=" + jQuery.URLEncode(search);
        window.location = jQuery.trim(newurl);
    });

    jQuery("#contentsearchlink").click(function(ev) {
        ev.preventDefault();
        var search = jQuery("#lefthand_contentsearch_input input").val();
        var newurl = jQuery(this).attr('href') + "?requesttype=content&search=" + jQuery.URLEncode(search);
        window.location = jQuery.trim(newurl);
    });
}

function setupCheckoutButton() {
    setupButtonHover(jQuery("#checkoutbutton"), 21);
}

function setupCopyShippingAddressButton() {
    setupButtonHover(jQuery("#copyshipaddress"), 16);
}
function setupCartButton() {

    setupButtonHover(jQuery("#shoppingcart"), 12);
    
    jQuery("#shoppingcart").click(function(ev) {
        jQuery("#shoppingcart").blur();
    });

    jQuery("#shoppingcart").mousedown(function(ev) {
        jQuery("#shoppingcart").blur();
    });

}

// assign class .keephref if you want a link styled like a button but you want it to remain a link.
// function grabs all button elements or links and submits with button as a classname. 
// use the class name formvalidator to allow a asp:button to continue behaving as an asp:button.
function setupSubmitButtons(el) {

    var arr = (el == null) ? jQuery("button, .button") : el;
    arr.each(function() {
        var b = jQuery(this);
        var tt = b.text() || b.val();
        var display = jQuery(this).css("display");

        b = jQuery("<a>").insertAfter(this).addClass(this.className).attr("name", this.name).attr("id", this.id);

        if (!jQuery(this).is('.keephref'))
            b.attr("href", "#");
        else
            b.attr("href", this.href);

        jQuery(this).remove();
        b.text(tt);

        b.css({ textIndent: "-9000px" });
        if (display && display == "none")
            b.css({ display: "none" });

        b.hover(function() {
            if (!b.hasClass("disabled"))
                b.css({ backgroundPosition: "0 -" + b.height() + "px" });
        }, function() {
            if (!b.hasClass("disabled"))
                b.css({ backgroundPosition: "0 0" });
        });

        b.mousedown(function() { if (!b.hasClass("disabled")) b.css({ backgroundPosition: "0 -" + (b.height() * 2) + "px" }) });
        b.mouseup(function() { if (!b.hasClass("disabled")) b.css({ backgroundPosition: "0 -" + b.height() + "px" }); });

        if (!jQuery(this).is('.keephref')) {
            b.click(function(e) {
                e.preventDefault();
                if (b.hasClass("disabled"))
                    return;
                // if the form validator class is not on the button or if it is, if the form is valid.
                if ( (!jQuery(this).is('.formvalidator') || jQuery("#form1").valid())) {
                    jQuery("<input />").attr("type", "hidden").attr("name", this.name).val(this.id).insertBefore(this);  // add this for situations where we want to get a command name
                    jQuery("form").submit();
                }
            });
        };
    });
}


function setupLoginLink() {

    var loginvalidationtriggered = 0;
    jQuery("#loginusernamevalidation").hide();
    jQuery("#loginvalidation").hide();
    
    setupButtonHover(jQuery("#loginbutton"), 21);
    setupButtonHover(jQuery("#createnewaccount_login_submit_btn"), 21);
    setupButtonHover(jQuery("#closeloginwindowbutton"), 19);

    jQuery(window).resize(function() {
        var offset = jQuery("#loginlink").offset();
        jQuery("#signincontainerwrapper").css({ top: offset.top + 22, left: offset.left - 340 })
    });
    


    jQuery("#loginlink").click(function(e) {

    e.preventDefault();
	jQuery("#loginlink").blur();       // Added blur() to make the text gray
    var offset = jQuery(this).offset();

	//Changed from left: offset.left-248 to left: offset.left-340
        jQuery("#signincontainerwrapper").css({ top: offset.top+22 , left: offset.left-340 })         
        jQuery("#signincontainerwrapper").toggle();
    });
    
    jQuery("#closeloginwindowbutton").click(function(e) {
        e.preventDefault();
        jQuery("#signincontainerwrapper").toggle();
    });

    jQuery("#page_content").click(function(e) {
        jQuery("#signincontainerwrapper").hide();
    });

    jQuery("#loginbutton").click(function(e) {
        e.preventDefault();

        if (jQuery("#loginusername").val() == "") {
            jQuery("#loginusernamevalidation").html("The user name is required.").show();
            loginvalidationtriggered = 1;
        }
        else if (jQuery("#loginpassword").val() == "") {
            jQuery("#loginvalidation").html("The user name and password combination could not be found.").show();
            loginvalidationtriggered = 2;
        }
        else {

            jQuery("#loginusernamevalidation").html("").hide();

            jQuery.ajax({
                url: authUserService,
                type: "POST",
                data: ({ "loginusername": jQuery("#loginusername").val(), "loginpassword": jQuery("#loginpassword").val() }),
                success: function(data) {
                    if (!data["Exceptions"]) {
                        location.reload(true);
                    }
                    else {
                        jQuery.each(data["Exceptions"], function(i, val) {
                            if (val["TargetName"] == "") {
                                jQuery("#loginvalidation").html(val["Message"]).show();
                            }
                            else {
                                var targetname = "#" + val["TargetName"] + "validation";
                                jQuery(targetname).html(val["Message"]).show();
                            }
                        });
                    }
                },
                error: function(msg) {
                    jQuery("#loginvalidation").html("An error occured while trying to log in.  Try again shortly.").show();
                }
            });
        }
    });

    jQuery("#loginusername").blur(function() {
    if (loginvalidationtriggered == 1) {
        var username = jQuery("#loginusername").val();
        if (jQuery("#loginusername").val() == "") 
            jQuery("#loginusernamevalidation").html("The user name is required.").show();
        else 
            jQuery("#loginusernamevalidation").html("").hide();
        }
    }); 

}

function setupFooterToolbar() {
    jQuery(".scrollable").scrollable({  next: ".next", prev: ".prev", easing: 'custom', speed: 500 });



}

function setupRegistration() {
    jQuery("#registrationlink").click(function(e) {
         activateRegistrationForm(e);
    });

    jQuery("#createnewaccount_login_submit_btn").click(function(e) {
        activateRegistrationForm(e);
    });

    setupButtonHover(jQuery("#registration_submit"), 21);

    jQuery("#registration_submit").click(function() {
        jQuery("#registrationfrm").submit();
    });	
}

function SetupInsiderForm() {

    setupButtonHover(jQuery("#insider_submit"), 30);

    jQuery("#insider_submit").click(function(e) {        
        e.preventDefault();
        SubmitInsiderEmail();
    });

    jQuery("#insider_emailaddress").keydown(function(e) {
        if (e.keyCode == '13') {
            e.preventDefault();
            SubmitInsiderEmail();
        }
    });
}


function SubmitInsiderEmail() {
    jQuery.ajax({
        url: insideremailservice,
        type: "POST",
        dataType: "json",
        data: ({ "emailaddress": jQuery("#insider_emailaddress").val() }),
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert("An error occured while submitting your request.  Please try again in a little while.");
        },
        success: function(data) {
            if (!data["Exceptions"]) {
                jQuery("#insider_emailaddress").val("");
                jQuery.modal.close();
            }
            else {
                jQuery.each(data["Exceptions"], function(i, val) {
                    alert(val["Message"]);
                });
            }
        }
    });
}


function PopupEmailSubmission() {
    jQuery("#insiderrequestwrapper").modal({
        persist: true,
        overlayClose: true,
        autoResize: true,        
        onClose: function(d) {
            d.container.slideUp('fast', function() {
                d.overlay.fadeOut('slow', function() {
                    jQuery.modal.close();
                });
            });
        },
        onShow: function(d) {
            var sm = this;
            jQuery("#signincontainerwrapper").hide();
            jQuery('#insiderreuestfrm', d.container[0]).click(function(e) {
                d.container.css({ height: 0, width: 0 }); // reset dimensions
                sm.setContainerDimensions();
            });
        },
        onOpen: function(d) {
            d.overlay.fadeIn('fast', function() {
                d.data.hide();
                d.container.fadeIn('fast', function() {
                    d.data.slideDown('fast');
                });
            });
        }
    });
}



/*
function setupShoppingCartpopUp() {

    
    jQuery('#cartwrapper').dialog({
        autoOpen: false,
        position: ['right','top']
    });

    jQuery('#shoppingCartlink').click(function(e) {
        e.preventDefault();        
        jQuery('#cartwrapper').dialog('open');       
        jQuery('#cartwrapper').delay(2000).fadeOut('slow', function() {
            // Animation complete.
            jQuery('#cartwrapper').dialog('close');
        });

    });  
    
}
*/

function activateRegistrationForm(e) {
    e.preventDefault();

    jQuery("#registrationwrapper").modal({
        minHeight: 480,
        maxHeight: 480,
        persist: true,
        overlay:30,
        overlayClose: true,
        autoResize: true,
        onClose: function(d) {
            d.container.slideUp('fast', function() {
                d.overlay.fadeOut('slow', function() {
                    jQuery.modal.close(); 
                });
            });
        },
        onShow: function(d) {
            jQuery("body").css({ zoom: '1' });
            var sm = this;
            jQuery("#signincontainerwrapper").hide();
            //jQuery('#registrationfrm', d.container[0]).click(function(e) {
             //   d.container.css({ height: 0, width: 0 }); // reset dimensions
            //    sm.setContainerDimensions();
            //});
        },      
        onOpen: function(d) {
            d.overlay.fadeIn('fast', function() {
                d.data.hide();
                d.container.fadeIn('fast', function() {
                    d.data.slideDown('fast');
                });
            });
        }
    });
}





function setupLogoutLink() {

    jQuery("#logoutlink").click(function(e) {
        e.preventDefault();

        jQuery.ajax({
            url: logoutService,
            type: "POST",
            success: function(data) {
                if (!data["Exceptions"]) {
                    location.reload(true);
                }
                else {
                    jQuery.each(data.Exceptions, function(i, item) {
                        alert(item.Message);
                    });
                   
                }
            }
        });
    });
}


function setupButtonHover(obj, height) {

    obj.focusin(function(e) {
        jQuery(this).css({ backgroundPosition: "0 -" + height * 2 + "px" });
    });
    obj.focusout(function(e) {
        jQuery(this).css({ backgroundPosition: "0 0" });
    });
    obj.hover(function() {
        jQuery(this).css({ backgroundPosition: "0 -" + height + "px" });
    }, function() {
        jQuery(this).css({ backgroundPosition: "0 0" });
    });


}

// activates the ping service
function activatePing() 
{
    setInterval(ping, 60000);
}



// requests the ping service
function ping() {
    jQuery.get(pingService);
}


function setupValidatorDefaults() {

    // this one requires the value to be the same as the first parameter
    jQuery.validator.methods.minlen = function(value, element, param) {
        return value.length >= param;
    };

    var registrationformpopup = jQuery("#registrationfrm").validate({ meta: "validate",
        submitHandler: function(form) {
            jQuery.blockUI.defaults.css = {};
            jQuery('#registrationwrapper').block({ message: '<img src="/images/global/ajax-loader.gif" />' });
            jQuery.ajax({
                url: registerUserService,
                type: "POST",
                dataType: "json",
                data: JSON.stringify(jQuery(form).serializeObject()),
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    jQuery('#registrationwrapper').unblock();
                    alert("An error occured while submitting your request.  Please try again in a little while.");
                },
                success: function(data) {
                    jQuery('#registrationwrapper').unblock();
                    if (!data["Exceptions"])
                        location.reload(true);
                    else {
                        jQuery.each(data["Exceptions"], function(i, val) {
                            var target = jQuery("#" + val["TargetName"]);
                            jQuery("<label />").attr("generated", "true").attr("style", "display:block;").attr("for", "#" + val["TargetName"]).attr("class", "error").html(val["Message"]).insertAfter(target);
                        });
                    }
                }
            });
        },
        errorPlacement: function(error, element) {
            if (element.is(":radio"))
                error.appendTo(element.parent().next().next());
            else if (element.is(":checkbox"))
                error.appendTo(element.parent().next());
            else {
                error.appendTo(element.parent());
            }
        }

    });
    // next 3 lines reset the form - noticed some caching in Firefox that was creating strange issues.  So let's be safe and completely reset the form.
    jQuery('#registrationfrm')[0].reset();    // this resets form variables to their initial values (must be set in form fields)...
    registrationformpopup.resetForm();        // next two lines reset the Validation plugin error messages...
    registrationformpopup.submit = {};

}

// sorts and fills the pack dropdown
function sortPackDropDown(ele, parray) {
	ele.addOption("", "");
    sortPackSize(parray);
    jQuery.each(parray, function(ini, item) {
        var psize = convertPack(item[0], item[1]);
        var psized = convertPackDisplay(item[0], item[1], item[2]);
        if (!ele.containsOption(psize)) ele.addOption(psize, psized);
    });
}

// sorts and fills the weight dropdown
function sortWeightDropDown(ele, parray) {
	ele.addOption("", "");
    sortWeight(parray);

    jQuery.each(parray, function(ini, item) {
        var wt = item[0] + item[1];
        if (!ele.containsOption(wt)) ele.addOption(wt, wt);
    });
}


// sorts and fills the size dropdown
function sortSizeDropDown(ele, parray) {

    ele.addOption("", "");
    
    sortSize(parray);
    jQuery.each(parray, function(ini, item) {
        var psize = item[1];        
        if (!ele.containsOption(psize)) ele.addOption(psize, psize);
    });
}

function sortCottonDropDown(ele, parray) {

    if (parray.length == 1 && parray[0] == 0) {
        ele.addOption("0", "No Cotton Content");
        return;
    }
    else if (parray.length == 1 && parray[0] != 0) {
        ele.addOption(parray[0], parray[0] + "%");
        return;
    }
    else
        ele.addOption("", "");
    
    parray.sort(function(a, b) {
        return parseInt(a) - parseInt(b);
    });

    jQuery.each(parray, function(ini, item) {
        if (!ele.containsOption(item)) {
            if (item == 0)
                ele.addOption(item, "No Cotton Content");
            else
                ele.addOption(item, item + "%");
        }
    });
}
// sorts pack sizes
function sortSize(parray) {
    parray.sort(function(a, b) {
    return parseFloat(a[0]) - parseFloat(b[0]);
    });
}

// sorts pack sizes
function sortPackSize(parray) 
{
    parray.sort(function(a, b) {
        return parseInt(a[0]) - parseInt(b[0]);
    });
}

// sorts weights
function sortWeight(pweight) {
    pweight.sort(function(a, b) {
        if (a[1] == b[1] && a[0] == b[0])
            return 0;
        else if (a[1] == b[1])
            return a[0] - b[0];
        else if (a[1] == "DTC" && b[1] != "DTC")
            return 1;
        else if (a[1] == "C" && (b[1] == "T" || b[1] == "W"))
            return 1;
        else if (a[1] == "T" && b[1] == "W")
            return 1;
        else
            return -1;
    });
}

// converts a basis weight to a display abbreviation.
function convertWTC(b, wtc) {
    if (jQuery.isNullOrUndefined(wtc) || jQuery.emptyString(wtc)) return b + "";
    return b + shortWTC(wtc);
}

function shortWTC(wtc) {
    
    if (wtc == "W" || wtc == "T" || wtc == "C") return wtc; 
    if (wtc == "Text") return "T";
    if (wtc == "Writing" ) return "W";
    if (wtc == "Cover") return "C";
    return "DTC";
}

// converts a pack value to include a carton or ream
function convertPack(s, t) {
    return s + ((t == 1) ? " Carton" : " Pack");
}

// converts a pack value to include a carton or ream
function convertPackValue(s, t) {
    return s + ((t == 1) ? "CARTON" : "REAM");
}

// converts a pack value to include a carton or ream
function convertPackDisplay(s, t, type) {
    if (type) {
        switch (type.toLowerCase()) {
            case "business envelopes":
            case "social envelopes":
                return s + ((t == 1) ? " Envelope Carton" : " Envelope Pack");
            case "note cards":
                return s + ((t == 1) ? " Card Carton" : " Card Pack");
        }
    }
    return s + ((t == 1) ? " Sheet Carton" : " Sheet Pack");
    
}


// provides a nicer serialization option than jQuery's serializeArray
(function(jQuery, undefined) {
    'jQuery:nomunge'; // Used by YUI compressor.

    jQuery.fn.serializeObject = function() {
        var obj = {};

        jQuery.each(this.serializeArray(), function(i, o) {
            var n = o.name,
            v = o.value;
            obj[n] = obj[n] === undefined ? v
          : jQuery.isArray(obj[n]) ? obj[n].concat(v)
          : [obj[n], v];
        });

        return obj;
    };

    // customize the easing action on scrollers
    jQuery.easing.custom = function(x, t, b, c, d) {   
        var s = 1.70158;
        if ((t /= d / 2) < 1) return c / 2 * (t * t * (((s *= (1.525)) + 1) * t - s)) + b;
        return c / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2) + b;
    }

    // custom validators follow
    jQuery.validator.methods.minlenallowblank = function(value, element, param) {
        return value.length == 0 || value.length >= param;
    };

    jQuery.validator.methods.minlen = function(value, element, param) {
        return value.length >= param;
    };

    jQuery.validator.methods.oneselection = function(value, element, param) {
        return jQuery.trim(value) != '';
    };

    jQuery.validator.methods.mindecimal = function(value, element, param) {
        return parseFloat(jQuery.trim(value)) > parseFloat(param);
    };

    jQuery.validator.methods.uscanadianzip = function(value, element, param) {
        return IsPostalCodeCorrectForCountry(jQuery(param).val(), value)
    };

})(jQuery);



function IsPostalCodeCorrectForCountry(countrycode, postalcode) {
    if (countrycode.toLowerCase() == "us" || countrycode.toLowerCase() == "usa")
        return /^\d{5}(-\d{4})?$/i.test(postalcode);
    else
        return /^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$/i.test(postalcode);
}

jQuery.extend({ URLEncode: function(c) {
    var o = ''; var x = 0; c = c.toString(); var r = /(^[a-zA-Z0-9_.]*)/;
    while (x < c.length) {
        var m = r.exec(c.substr(x));
        if (m != null && m.length > 1 && m[1] != '') {
            o += m[1]; x += m[1].length;
        } else {
            if (c[x] == ' ') o += '+'; else {
                var d = c.charCodeAt(x); var h = d.toString(16);
                o += '%' + (h.length < 2 ? '0' : '') + h.toUpperCase();
            } x++;
        } 
    } return o;
},
    URLDecode: function(s) {
        var o = s; var binVal, t; var r = /(%[^%]{2})/;
        o = o.replace(/\+/g, '%20');
        while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
            b = parseInt(m[1].substr(1), 16);
            t = String.fromCharCode(b); o = o.replace(m[1], t);
        } return o;
    }
});


String.prototype.startsWith = function(str) { return (this.match("^" + str) == str) }

jQuery.formatCurrency = function(num) {
    num = isNaN(num) || num === '' || num === null ? 0.00 : num;
    return parseFloat(num).toFixed(2);
}

jQuery.isProperNumber = function(o) {

    if (isNaN(o))
        return false;

    return jQuery.isNumber(o);
}

jQuery.isNumber = function(o) {
    return /^-?\d+$/.test(o);
}

jQuery.isBoolean = function(o) {
    if (typeof o == "object" && o !== null)
        return (typeof o.valueOf() === "boolean")
    else
        return (typeof o === "boolean");
}

jQuery.isNull = function(o) {
    return (o === null);
}

jQuery.isUndefined = function(o) {
    return (typeof o === "undefined");
}

jQuery.isNullOrUndefined = function(o) {
    return jQuery.isNull(o) || jQuery.isUndefined(o);
}

jQuery.isString = function(o) {
    return (typeof o === "string");
}

jQuery.isArray = function(o) {
    return (o != null && typeof o == "object" && "splice" in o && "join" in o);
}

jQuery.emptyString = function(str) {
    if (jQuery.isNullOrUndefined(str))
        return true;
    else if (!jQuery.isString(str))
        throw "isEmpty: the object is not a string";
    else if (str.length === 0)
        return true;

    return false;
}

jQuery.startsWith = function(str, search) {
    if (jQuery.isString(str))
        return (str.indexOf(search) === 0);

    return false;
}

jQuery.endsWith = function(str, search) {
    if (!jQuery.isString(str) || !jQuery.isString(search) || jQuery.emptyString(str) || jQuery.emptyString(search))
        return false;
    else if (search.length > str.length)
        return false;
    else if (str.length - search.length === str.lastIndexOf(search))
        return true;

    return false;
}

jQuery.formatString = function() {
    if (arguments.length < 2)
        return "";

    var str = arguments[0];
    for (var i = 1; i < arguments.length; i++) {
        var val = "";
        if (!jQuery.isNullOrUndefined(val))
            val = arguments[i] + ""; // avoid toString

        var regex = new RegExp("\\{" + (i - 1) + "\\}", "g");
        str = str.replace(regex, val);
    }

    return str;
}



jQuery.log = function() {
    if (typeof console !== "undefined") {
        console.log(jQuery.formatString.apply(this, arguments));
    }
}

var numb = '0123456789';
var lwr = 'abcdefghijklmnopqrstuvwxyz';
var upr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

function isValid(parm, val) {
    if (parm == "") return false;
    for (i = 0; i < parm.length; i++) {
        if (val.indexOf(parm.charAt(i), 0) == -1) return false;
    }
    return true;
}

function isNum(parm) { return isValid(parm, numb); }
function isLower(parm) { return isValid(parm, lwr); }
function isUpper(parm) { return isValid(parm, upr); }
function isAlpha(parm) { return isValid(parm, lwr + upr); }
function isAlphanum(parm) { return isValid(parm, lwr + upr + numb); }


jQuery.extend(jQuery.expr[":"],{reallyvisible: function(a) { return (jQuery(a).is(":visible") && jQuery(a).parents(":hidden").length == 0) }});

/*
*
* Copyright (c) 2006-2008 Sam Collett (http://www.texotela.co.uk)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version 2.2.4
* Demo: http://www.texotela.co.uk/code/jquery/select/
*
* $LastChangedDate: 2008-06-17 17:27:25 +0100 (Tue, 17 Jun 2008) $
* $Rev: 5727 $
*
*/
; (function(h) { h.fn.addOption = function() { var j = function(a, f, c, g) { var d = document.createElement("option"); d.value = f, d.text = c; var b = a.options; var e = b.length; if (!a.cache) { a.cache = {}; for (var i = 0; i < e; i++) { a.cache[b[i].value] = i } } if (typeof a.cache[f] == "undefined") a.cache[f] = e; a.options[a.cache[f]] = d; if (g) { d.selected = true } }; var k = arguments; if (k.length == 0) return this; var l = true; var m = false; var n, o, p; if (typeof (k[0]) == "object") { m = true; n = k[0] } if (k.length >= 2) { if (typeof (k[1]) == "boolean") l = k[1]; else if (typeof (k[2]) == "boolean") l = k[2]; if (!m) { o = k[0]; p = k[1] } } this.each(function() { if (this.nodeName.toLowerCase() != "select") return; if (m) { for (var a in n) { j(this, a, n[a], l) } } else { j(this, o, p, l) } }); return this }; h.fn.ajaxAddOption = function(c, g, d, b, e) { if (typeof (c) != "string") return this; if (typeof (g) != "object") g = {}; if (typeof (d) != "boolean") d = true; this.each(function() { var f = this; h.getJSON(c, g, function(a) { h(f).addOption(a, d); if (typeof b == "function") { if (typeof e == "object") { b.apply(f, e) } else { b.call(f) } } }) }); return this }; h.fn.removeOption = function() { var d = arguments; if (d.length == 0) return this; var b = typeof (d[0]); var e, i; if (b == "string" || b == "object" || b == "function") { e = d[0]; if (e.constructor == Array) { var j = e.length; for (var k = 0; k < j; k++) { this.removeOption(e[k], d[1]) } return this } } else if (b == "number") i = d[0]; else return this; this.each(function() { if (this.nodeName.toLowerCase() != "select") return; if (this.cache) this.cache = null; var a = false; var f = this.options; if (!!e) { var c = f.length; for (var g = c - 1; g >= 0; g--) { if (e.constructor == RegExp) { if (f[g].value.match(e)) { a = true } } else if (f[g].value == e) { a = true } if (a && d[1] === true) a = f[g].selected; if (a) { f[g] = null } a = false } } else { if (d[1] === true) { a = f[i].selected } else { a = true } if (a) { this.remove(i) } } }); return this }; h.fn.sortOptions = function(e) { var i = h(this).selectedValues(); var j = typeof (e) == "undefined" ? true : !!e; this.each(function() { if (this.nodeName.toLowerCase() != "select") return; var c = this.options; var g = c.length; var d = []; for (var b = 0; b < g; b++) { d[b] = { v: c[b].value, t: c[b].text} } d.sort(function(a, f) { o1t = a.t.toLowerCase(), o2t = f.t.toLowerCase(); if (o1t == o2t) return 0; if (j) { return o1t < o2t ? -1 : 1 } else { return o1t > o2t ? -1 : 1 } }); for (var b = 0; b < g; b++) { c[b].text = d[b].t; c[b].value = d[b].v } }).selectOptions(i, true); return this }; h.fn.selectOptions = function(g, d) { var b = g; var e = typeof (g); if (e == "object" && b.constructor == Array) { var i = this; h.each(b, function() { i.selectOptions(this, d) }) }; var j = d || false; if (e != "string" && e != "function" && e != "object") return this; this.each(function() { if (this.nodeName.toLowerCase() != "select") return this; var a = this.options; var f = a.length; for (var c = 0; c < f; c++) { if (b.constructor == RegExp) { if (a[c].value.match(b)) { a[c].selected = true } else if (j) { a[c].selected = false } } else { if (a[c].value == b) { a[c].selected = true } else if (j) { a[c].selected = false } } } }); return this }; h.fn.copyOptions = function(g, d) { var b = d || "selected"; if (h(g).size() == 0) return this; this.each(function() { if (this.nodeName.toLowerCase() != "select") return this; var a = this.options; var f = a.length; for (var c = 0; c < f; c++) { if (b == "all" || (b == "selected" && a[c].selected)) { h(g).addOption(a[c].value, a[c].text) } } }); return this }; h.fn.containsOption = function(g, d) { var b = false; var e = g; var i = typeof (e); var j = typeof (d); if (i != "string" && i != "function" && i != "object") return j == "function" ? this : b; this.each(function() { if (this.nodeName.toLowerCase() != "select") return this; if (b && j != "function") return false; var a = this.options; var f = a.length; for (var c = 0; c < f; c++) { if (e.constructor == RegExp) { if (a[c].value.match(e)) { b = true; if (j == "function") d.call(a[c], c) } } else { if (a[c].value == e) { b = true; if (j == "function") d.call(a[c], c) } } } }); return j == "function" ? this : b }; h.fn.selectedValues = function() { var a = []; this.selectedOptions().each(function() { a[a.length] = this.value }); return a }; h.fn.selectedTexts = function() { var a = []; this.selectedOptions().each(function() { a[a.length] = this.text }); return a }; h.fn.selectedOptions = function() { return this.find("option:selected") } })(jQuery);
