//Various text replacements
  $('p#login-tip-text').html("Customers with accounts may login below. Logging in allows you to access extra features.");
  $('p#contact_tip_text').html("Please use the form below to contact us. Alternatively, our telephone, fax and mailing address are also given.<br>Fields marked * are mandatory.");

if(!window.console){
    window.console = {};
    console.log = function(){};
}

//category links reformat
(function ($) {
	var $catTableBody = $("table.cattablebody").remove(),
		cellblocks, cellblocksTMPL = "<ul class='cellblocks cellblocks-categories'>[[HTML]]</ul>",
		cells = "", cellHTML, cellTMPL = "<li class='cell'><div class='cell-inner'>[[HTML]]</div></li>",
		htmlTMPL = "<h4 class='heading'><a class='thumb-wrap' href='[[HREF]]' title='[[TITLE]]'>[[TITLE]]</a></h4>" +
					"<a class='thumb-wrap' href='[[HREF]]' title='[[TITLE]]'><img alt='[[TITLE]]' src='[[SRC]]' /></a>",
		$catImageCells = $catTableBody.find("tr.cattablerowimage td"),
		$catTextCells = $catTableBody.find("tr.cattablerowtext td");
		
	$catTextCells.each(function (index) {
		var $this = $(this),
			href = $this.find("a").attr("href"),
			title = $this.text(),
			src = $catImageCells.eq(index).find("img").attr("src") || "/images/spacer.gif",
			cellHtml = htmlTMPL
					.replace(/\[\[TITLE\]\]/g, title)
					.replace(/\[\[HREF\]\]/g, href)
					.replace(/\[\[SRC\]\]/g, src);
	
		cells += cellTMPL.replace(/\[\[HTML\]\]/, cellHtml );
	});
	cellblocks = cellblocksTMPL.replace(/\[\[HTML\]\]/g, cells );
	$(cellblocks).insertAfter("#select-category-heading");
}(jQuery));


(function($){
if(CNST.PAGEID === "checkoutstep2"){

	window.insertNoPoboxAlert = function(){
	    var $location = $("#table-navigation td[align=right]").empty(),
	        $alert = $("<div class='alert' />"),
	        $heading = $("<h3 class='heading' />").text("IMPORTANT!"),
	        $text = $("<p></p>").text("This store DOES NOT ship to PO boxes.");
	    $alert.append($heading).append($text);
	    $alert.appendTo($location);
	};
	insertNoPoboxAlert();
	
	
	//look for "in-store pickup" in shipping-method-list labels
	var InStorePickupId = (function() {
		var $labels = $("#shipping-method-list label"),
			inStorePickup = false;
			
		$labels.each(function(){
			var $this = $(this),
				thisText = $this.text().toLowerCase();

			if(thisText.search("in-store pickup") !== -1){
				var forAttr = $this.attr("for");
				inStorePickup = forAttr;
			} 
		});
		console.log("In-Store pickup selector: ", inStorePickup);
		return inStorePickup;
	}());



	
	var inStorePickupAlert = function(){
		
		// if(InStorePickupId){
	        var heading = "Important",
	            $text = "<p><strong>IMPORTANT:</strong> If using <i>In-Store Pickup</i> leave the above checked.</p>",
	            $heading = $("<h5 class='heading'></h5>").text(heading),
	            $alert = $("<div class='alert alert-small'></div>").append($text).css("clear","both");
	        $alert.insertAfter("#label_shipping_ship_to_billing");
		// }
	};
	
	inStorePickupAlert();

}//end if checkoutstep2
}(jQuery));



var noPobox = {
    oldSubmitFn : "",
    fieldsToTest : "",
    preSubmitFn : "",
    debug : false,
    active : true,  //  true/false = on/off
    valid : true,   // evaluation
    type : "error",
    logArray : [],
    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."
    }
};

noPobox.log = function(label,value){
    var message = label + " : " + value;
    noPobox.logArray.push(message);
};

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
//Native submit will fire only pobox validation
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 testRegExp =  /(\b((po)\s+(box)|(po|pobox)|(post)\s+(office))\b)/,
        value = strAddress.toLowerCase().replace(/[\.]/g,''),// remove period
        result = value.search(testRegExp);
    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;
};

//setups script to operate on the page.
//submitFunctionName = name of native function.  attached to Window element.
//type = warning or error
//fieldsToTest = jQuery slector string to match fields requring validation
//preSubmitFn[optional] = inserts function to fire at start of noPobox processing.  Allows for re-evaluating parameters before executing validation 
noPobox.init = function(submitFunctionName, type, fieldsToTest, preSubmitFn){
    noPobox.reassignSubmit(submitFunctionName);
    noPobox.type = type;
    noPobox.fieldsToTest = fieldsToTest;
    if(typeof preSubmitFn === "function"){
        noPobox.preSubmitFn = preSubmitFn;
    }
};


if(CNST.PAGEID === "updateaccount" || CNST.PAGEID === "register"){
    noPobox.init("submitRegistrationForm","warning","[type=text][id*=address]");
}

 if(CNST.PAGEID === "checkoutstep2"){
     
    var checkoutPreSubmit = function(){
        var useBillingAddress = $("input#shipping_ship_to_billing").is(":checked"),
            inStoreShip = $("#" + window.insertNoPoboxAlert ).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]");
        }
    };

    noPobox.init( "continueCheckout", "error", "input[type=text][id*=billing_address]", checkoutPreSubmit );
}


