/*
 * @description:    noPobox is a JavaScript utility to test text fields against different variations of PO Boxes.
 * 
 *                  Because of the ajax refreshing that occurs on the checkoutstep2 page, 
 *                  it was necessary to hijack the original script name and replace it with the noPobox.onSubmitRequest method.
 *                  the old submit function is then inserted appropriately into the onSubmitRequest method.
 * 
 * @dependencies: jQuery, some manner of sensing
 * 
 */
var noPobox = {
    oldSubmitFn : "",   //native submit function is reassigned to this property
    Regex : new RegExp(/(\b((po)\s+(box)|(po|pobox)|(post)\s+(office))\b)/), //http://regexpal.com/?flags=i&regex=((po)%5Cs%2B(box)|(po|pobox)|(%5Cs*post%5Cs*office%5Cs*)|(%5Cs*p%5Cs*%5Co%5Cs%2B)|(%5Cs*p%5C.%5Cs*o.%5Cs*box%5Cs*))&input=p%20%20%20%20%20o%20box%0A%0Apo%20box%0A%20po%20box%20%0A%20p%20%20%20%20%20%20o%20box%20%0A%0Apob123%0APost%20office%20box%0Apostoffice%0A%0A%20%20p.%20o.box%20%232134
    fieldsToTest : "",  //string of jQuery selectors separated by comma
    preSubmitFn : "",   //function passed for page specific checking (checkoutpage2 vs registration or updateaccount)
    debug : false,      //if true, the oldSubmitFn never gets executed, an alert stating
    active : true,      //true/false = on/off, if during processing the script is not longer required.
    type : "error",     // type=[error/warning] Error = alerts user and stops submit process, Warning = alerts user to problem, but continues submit process
    messages :  {       //text for popup messages
        "warning" : "Please Note:\n\nThis store does not ship to PO Box numbers. You will need to enter a different shipping address later in the order process",
        "error" : "The following errors were detected:\n\nThis store does not ship to PO boxes, please enter an alternate shipping address."
    }
};

//@description: noPobox.init sets up the script to operate on the page.
//@parameter: submitFunctionName = name of native function.  attached to Window element.
//@parameter: type = warning or error
//@parameter: fieldsToTest = jQuery slector string to match fields requring validation
//@parameter: preSubmitFn[optional] = inserts function to fire at start of noPobox processing.
noPobox.init = function(submitFunctionName, type, fieldsToTest, preSubmitFn){
    noPobox.reassignSubmit(submitFunctionName);
    noPobox.type = type;
    noPobox.fieldsToTest = fieldsToTest;
    if(typeof preSubmitFn === "function"){
        noPobox.preSubmitFn = preSubmitFn;
    }
};
noPobox.onSubmitRequest = function(){
    var submissionValid;

    if(typeof noPobox.preSubmitFn === "function"){
        noPobox.preSubmitFn();
    }
    
    submissionValid = noPobox.checkFields();
    
    // console.log("submisssion valid:", submissionValid);
    
    //warning allows use of a Po Box but with a warning.
    if(!submissionValid && noPobox.active) {

        noPobox.displayMessage();
        if(noPobox.type === "error") {
            
        }
        if(noPobox.type === "warning"){
            if(noPobox.debug) {
                alert("DEBUG: oldSubmitFn executed");
            } else {
                noPobox.oldSubmitFn();
            } 
        }
        
    } else {
            if(noPobox.debug) {
                alert("DEBUG: oldSubmitFn executed");
            } else {
                noPobox.oldSubmitFn();
            }
    }
};

//Reassign nativeSubmit function to onSubmitRequest
//@property: native submit function name
noPobox.reassignSubmit = function(submitFunctionName){
    //Check if already assigned
    if (typeof window[submitFunctionName] === "function" && typeof noPobox.oldSubmitFn !== "function" ) {
        noPobox.oldSubmitFn = window[submitFunctionName];
        window[submitFunctionName] = noPobox.onSubmitRequest;
    }
};

//Message keyed to noPobox.type
noPobox.displayMessage = function(){
    var message = noPobox.messages[noPobox.type];
    alert(message);
};

//iterate through selected fields
noPobox.checkFields = function(){
    var valid = true,
        $fields = $(noPobox.fieldsToTest); //each checkFields must start with valid = true

    $fields.each(function(){
       var $this = $(this),
            value = $this.val(),
            id = $this.attr("id"),
            isValid = noPobox.validAddress(value);
            
       // console.log("CheckFields: %s is %s",id, isValid);
       //test field
       if(!isValid){
           valid = false;
           
           //clear text input
           if(noPobox.type === "error" && noPobox.active) {
                $this.removeAttr("value");//clear field
                $this.addClass("field-error");
           }
       } 
    });
    return valid;
};

//Does this field have a pobox or not
//http://regexpal.com/?flags=i&regex=((po)%5Cs%2B(box)|(po|pobox)|(%5Cs*post%5Cs*office%5Cs*)|(%5Cs*p%5Cs*%5Co%5Cs%2B)|(%5Cs*p%5C.%5Cs*o.%5Cs*box%5Cs*))&input=p%20%20%20%20%20o%20box%0A%0Apo%20box%0A%20po%20box%20%0A%20p%20%20%20%20%20%20o%20box%20%0A%0Apob123%0APost%20office%20box%0Apostoffice%0A%0A%20%20p.%20o.box%20%232134
noPobox.validAddress = function(strAddress){
    var value = strAddress.toLowerCase().replace(/[\.]/g,''),// remove period
        result = value.search(noPobox.Regex);
    if(result !== -1 ){
        return false;
    } else {
        return true;
    }
};

//rather than "re-init" change the jQuery selector string only
noPobox.changeFields = function(newFieldsToTest){
    noPobox.fieldsToTest = newFieldsToTest;
};

//noPobox usage
if(CNST.PAGEID === "updateaccount" || CNST.PAGEID === "register"){
    noPobox.init("submitRegistrationForm","warning","[type=text][id*=address]");
}


/*
 * for CheckoutStep2 the instore pickup option requires the script to be turned off.
 * replace "#shippingmethod_method_id_25" with the appropriate jQuery selector.
 */
if(CNST.PAGEID === "checkoutstep2"){
     
    var checkoutPreSubmit = function(){
        var useBillingAddress = $("input#shipping_ship_to_billing").is(":checked"),
            inStoreShip = $("#shippingmethod_method_id_25").is(":checked");
        
        // //inStoreShip negates need for Pobox filter    
        noPobox.active = inStoreShip ? false : true;

        if(useBillingAddress) {
            //Billing fields selector
            noPobox.changeFields("input[type=text][id*=billing_address]");
        } else {
            noPobox.changeFields("input[type=text][id*=shipping_address]");
        }
    };
    
    /*
     * submitFunction name, type, jquery Selector of fields to test, presubmit function
     */
    noPobox.init( "defaultSubmit", "error", "input[type=text][id*=billing_address]", checkoutPreSubmit );
}


