/*!
 * @author Gproxy Design Inc.
 * @copyright (c) 2010, Gproxy Design Inc. All rights reserved.
 * @version 1.0
 *
 * Gproxy dosen't allow to copy or change this code without Gproxy authorization.
 * Go to http://www.gproxy.com/licenses/license01.pdf for the full license governing this code.
 */

var strBookingURL = 'http://77.68.106.149/index.aspx';
//var strSetCustomerSessionURL = "/app/site/hosting/scriptlet.nl?script=customscript_av_ss_setcustomersession&deploy=customdeploy_av_ss_setcustomersession";
var strSetCustomerSessionURL = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=39&deploy=1&compid=1126477&h=38d1c34fa8e8db2ac417"; 
//var strCheckPostCodeURL = "/app/site/hosting/scriptlet.nl?script=customscript_av_ss_checkdeliverypostcode&deploy=customdeploy_av_ss_checkdeliverypostcode";
var strCheckPostCodeURL = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=38&deploy=1&compid=1126477&h=fa1d5831255e5c38bfdc";

function setBookDeliveryIframe(strCustomerId,strIframeId,strLoadingCntId,strErrorsCntId){
	var strSessionId = readCookie('JSESSIONID');
	$j("#" + strIframeId).hide();	
	var intRand = Math.round(Math.random() * 1000);
	if (strSessionId != null && strSessionId != ''){
		if (strCustomerId != null && strCustomerId != '') {			
	        $j("#" + strLoadingCntId).show();
	        $j.ajax({
	            url: strSetCustomerSessionURL + '&customerid=' + escape(strCustomerId) + '&sessionid=' + escape(strSessionId) + "&callback=?",
	            type: "GET",
	            dataType: "jsonp",
	            success: function(data){
	                if (data.Errors.length > 0) {
	                    $j.each(data.Errors, function(i, val){
	                        errorManager('Check Post Code', val.code, val.details, strErrorsCntId);
	                    });
	                }
	                else {
	                    $j.each(data.CustomerZip, function(i, val){							                    
							$j("#" + strIframeId).attr('src', strBookingURL + '?postcode=' + val.zipcode + '&sessionid=' + escape(strSessionId) + '&rand=' + intRand);							
							$j("#" + strIframeId).load(function(){
								$j(this).show(50,function(){
									$j("#" + strLoadingCntId).hide();
								});
							});
							
	                    });
	                }
	            },	            
	            error: function(XMLHttpRequest, textStatus, errorThrown){
	                errorManager('Check Post Code', textStatus, errorThrown, strErrorsCntId);
	            }
	        });
			
		}else{
			$j("#" + strErrorsCntId).append("<li>You must login to select a booking slot...</li>");
		}
	}else{
		$j("#" + strErrorsCntId).append("<li>Booking a Delivery it's not working, please try again in a few minutes...</li>");
	}
}

function checkValidPostCode(strPostCodeCnt, strLoadingCntId, strErrorsCntId, strRegisterURL, strLeadFormURL){
	$j("#" + strErrorsCntId).hide();
	$j("#" + strErrorsCntId).html("");
    var strPostCode = $j("#" + strPostCodeCnt).val();
    if (checkPostCode(strPostCode)) {
        strPostCode = checkPostCode(strPostCode);
        $j("#" + strLoadingCntId).show();
        $j.ajax({
            url: strCheckPostCodeURL + '&postcode=' + escape(strPostCode.substr(0, strPostCode.length - 4)) + "&callback=?",
            type: "GET",
            dataType: "jsonp",
            success: function(data){
                if (data.Errors.length > 0) {
                    $j.each(data.Errors, function(i, val){
                        errorManager('Check Post Code', val.code, val.details, strErrorsCntId);
                    });
                }
                else {
                    $j.each(data.CheckPostCode, function(i, val){
                        if (val.value == 'true') {
                            document.location.href = strRegisterURL + '?zipcode=' + strPostCode;
                        }
                        else {
                            document.location.href = strLeadFormURL + '?zipcode=' + strPostCode;
                        }
                    });
                }
            },
            complete: function(XMLHttpRequest, textStatus){
                $j("#" + strLoadingCntId).hide();
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                errorManager('Check Post Code', textStatus, errorThrown, strErrorsCntId);
            }
        });
    }
    else {
		document.location.href = strLeadFormURL + '?zipcode=' + strPostCode;
        //$j("#" + strErrorsCntId).append("<li>Invalid Post Code...</li>");
		//$j("#" + strErrorsCntId).show();
    }
}

function checkPostCode(strPostCode){

    // Permitted letters depend upon their position in the postcode.
    var alpha1 = "[abcdefghijklmnoprstuwyz]"; // Character 1
    var alpha2 = "[abcdefghklmnopqrstuvwxy]"; // Character 2
    var alpha3 = "[abcdefghjkpmnrstuvwxy]"; // Character 3
    var alpha4 = "[abehmnprvwxy]"; // Character 4
    var alpha5 = "[abdefghjlnpqrstuwxyz]"; // Character 5
    // Array holds the regular expressions for the valid postcodes
    var pcexp = new Array();
    
    // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
    pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
    
    // Expression for postcodes: ANA NAA
    pcexp.push(new RegExp("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
    
    // Expression for postcodes: AANA  NAA
    pcexp.push(new RegExp("^(" + alpha1 + "{1}" + alpha2 + "{1}" + "?[0-9]{1}" + alpha4 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$", "i"));
    
    // Exception for the special postcode GIR 0AA
    pcexp.push(/^(GIR)(\s*)(0AA)$/i);
    
    // Standard BFPO numbers
    pcexp.push(/^(bfpo)(\s*)([0-9]{1,4})$/i);
    
    // c/o BFPO numbers
    pcexp.push(/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
    
    // Overseas Territories
    pcexp.push(/^([A-Z]{4})(\s*)(1ZZ)$/i);
    
    // Load up the string to check
    var postCode = strPostCode;
    
    // Assume we're not going to find a valid postcode
    var valid = false;
    
    // Check the string against the types of post codes
    for (var i = 0; i < pcexp.length; i++) {
        if (pcexp[i].test(postCode)) {
        
            // The post code is valid - split the post code into component parts
            pcexp[i].exec(postCode);
            
            // Copy it back into the original string, converting it to uppercase and
            // inserting a space between the inward and outward codes
            postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
            
            // If it is a BFPO c/o type postcode, tidy up the "c/o" part
            postCode = postCode.replace(/C\/O\s*/, "c/o ");
            
            // Load new postcode back into the form element
            valid = true;
            
            // Remember that we have found that the code is valid and break from loop
            break;
        }
    }
    
    // Return with either the reformatted valid postcode or the original invalid 
    // postcode
    if (valid) {
        return postCode;
    }
    else 
        return false;
}

function sendInvite(strCustomerNameCnt,strCustomerEmailCnt,strFriendEmailCnt,strSendLink,strMessageDisplayCnt,strErrorsDisplayCnt,strLoadingCntId,strInviteFormCnt){
		    
	var strCustomerName = $j("#" + strCustomerNameCnt).val();
	var strCustomerEmail = $j("#" + strCustomerEmailCnt).val();
	var strFriendEmail = $j("#" + strFriendEmailCnt).val();
	var bolErrors = false;   
    $j("#" + strMessageDisplayCnt).hide();
	$j("#" + strErrorsDisplayCnt).html("");
	if (!strCustomerName){
		bolErrors = true;
		$j("#" + strErrorsDisplayCnt).append("<li>Please, enter your Name...</li>");	
	}
	if (!strCustomerEmail){
		bolErrors = true;
		$j("#" + strErrorsDisplayCnt).append("<li>Please, enter your email...</li>");	
	}
	if (!strFriendEmail){
		bolErrors = true;
		$j("#" + strErrorsDisplayCnt).append("<li>Please, enter your friend's email...</li>");			
	}
	if (!bolErrors) {
		$j("#" + strLoadingCntId).show();
		//var src = '/app/site/hosting/scriptlet.nl?script=customscript_av_ss_inviteafriend&deploy=customdeploy_av_ss_inviteafriend&customername=' + escape(strCustomerName) + '&customeremail=' + escape(strCustomerEmail) + '&friendemail=' + escape(strFriendEmail) + '&sendlink=' + escape(strSendLink) + '&callback=?';
		var src = "https://forms.netsuite.com/app/site/hosting/scriptlet.nl?script=31&deploy=1&compid=1126477&h=bd6fd009d14afd255b8c&customername=" + escape(strCustomerName) + '&customeremail=' + escape(strCustomerEmail) + '&friendemail=' + escape(strFriendEmail) + '&sendlink=' + escape(strSendLink) + '&callback=?';
		$j.ajax({
			url: src,
			type: "GET",
			dataType: "jsonp",
			success: function(data){
				if (data.Errors.length > 0) {
					$j.each(data.Errors, function(i, val){
						errorManager('Invite a Friend', val.code, val.details, strErrorsDisplayCnt);
					});
				}
				else {
					$j("#" + strCustomerNameCnt).val("");
					$j("#" + strCustomerEmailCnt).val("");
					$j("#" + strFriendEmailCnt).val("");
					$j("#" + strCustomerNameCnt).focus();
					$j("#" + strMessageDisplayCnt).show();					
					setTimeout(function(){
						showInviteAFriendForm(strInviteFormCnt);
					},3000);
				}
			},
			complete: function(XMLHttpRequest, textStatus){
				$j("#" + strLoadingCntId).hide();
			},
			error: function(XMLHttpRequest, textStatus, errorThrown){
				errorManager('Invite a Friend', textStatus, errorThrown, strErrorsDisplayCnt);
			}
		});
	}else{
		$j("#" + strErrorsDisplayCnt).show();
	}
}

function showInviteAFriendForm(strInviteFormCnt) {
	if ($j("#" + strInviteFormCnt).css('display') == 'none'){
		$j("#" + strInviteFormCnt).show(500);	
	}else{
		$j("#" + strInviteFormCnt).hide(500);
	}			
}

function errorManager(strSource, strCode, strDetails, strErrorsCntId){
    $j("#" + strErrorsCntId).append("<li>" + strSource + ", code: " + unescape(strCode) + ", details: " + unescape(strDetails) + "</li>");
	$j("#" + strErrorsCntId).show();	
}

function readCookie(name){
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(name + "=");
        if (c_start != -1) {
            c_start = c_start + name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) 
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return null;
}

function trim(strText){
    if (strText === null) {
        return null;
    }
    return strText.replace(/^\s*/, '').replace(/\s+$/, '');
}

