function getA8id() {
/*-------------------------------------
Description:
Gets the A8id from a cookie or returns the default

Author: JL Aug '09
Dependencies: jquery.js, jq.cookie.js
Updates:
-------------------------------------*/
	//if we cant find a cookie
	if (cookieRead('A8ID') == null){
		return 'a08_uswitch_PostcodeForm';
	}
	else{
		return cookieRead('A8ID');
	}
}

function cookieRead(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}


function getTrackingWithDcStorm(){
/*-------------------------------------
Description:
Concatenates a8id, delimiter and dc storm id. 

Author: JL Aug '09
Dependencies: jquery.js, jq.cookie.js

-------------------------------------*/
	var delimiter ='~~';//change this if the delimiter changes on DC storm
	var DcStormCookie = ''; // the dc storm cookie which is set

	if(!$.cookie('_#clkid')){//if no dc storm id defined for what ever reason
		DcStormCookie = 'NoDcStormCookieSet';
	}
	else{
		DcStormCookie = $.cookie('_#clkid');
	}
	return getA8id() + delimiter + DcStormCookie;
}

function redir(frmDetails) {
    //This is the main calling function from the p
    //http://www.tkqlhce.com/click-1682713-10292942?URL=http://www.uSwitch.com/gas-electricity/current-supplier/?ref=cj&QASpostcode=br2%208jd&sid=a00_123a8id~~dcStormCode


    if($('#terms').attr('checked') == false){
        alert('Please check the Terms and conditions');
        return false;
    }
  
   
    if ( !validPostcode($('#postcode').val()) ) {
        return false;
    } else {
     //register ga goal
      var pageTracker = _gat._getTracker('UA-12107129-1');
      pageTracker._trackPageview('/goal.php');
      
      _gaq.push(['gwo._setAccount', 'UA-12107129-4']);
      _gaq.push(['gwo._trackPageview', '/0540110030/goal']);
      
      myURL = "http://being.successfultogether.co.uk/click.asp?ref=301781&site=7777&type=text&tnb=2&subid=A8ID&diurl=http://www.uSwitch.com/gas-electricity/current-supplier/?ref=cj&QASpostcode=" + encodeURI($('#postcode').val());
      $.ajax({
          url : "/headto-ajax.php",
          data : {'affLink' : myURL},
          success: function(data){
              if(a8util.GetParameterFromURL('showlink') ){
                alert(data);
                return false;
              }
              else{ 
                document.location.href = data;
                return false
              }
          }
      })
      return false
    }

    document.location.href = myURL;
    return false
}

// PostCode Validation Code - Used to be in pCodeCheck.js ( See CIT 3425 for more details )
function validPostcode(postCode) {
    /*
    sjm 24/05/2001
    There are 6 possible valid UK postcodes:
    where L = letter and N = Number
    LN NLL
    LLN NLL
    LNN NLL
    LNL NLL
    LLNN NLL
    LLNL NLL
    
    changelog:
    JL - nov - changed original code so that we pass in a value to evaluate as oppose to the dom form object to reference
    */

    //var pcode = frmElement.value;   
    var pcode = postCode;
    var pcType1 = /^[A-Z]{1}\d{1}\s{1}\d{1}[A-Z]{2}/;
    var pcType2 = /^[A-Z]{2}\d{1}\s{1}\d{1}[A-Z]{2}/;
    var pcType3 = /^[A-Z]{1}\d{2}\s{1}\d{1}[A-Z]{2}/;
    var pcType4 = /^[A-Z]{2}\d{2}\s{1}\d{1}[A-Z]{2}/;
    var pcType5 = /^[A-Z]{2}\d{1}[A-Z]{1}\s{1}\d{1}[A-Z]{2}/;
    var pcType6 = /^[A-Z]{1}\d{1}[A-Z]{1}\s{1}\d{1}[A-Z]{2}/;

    var sAlertEmpty = "Please enter a valid UK postcode.";
    var sAlertLength = "Sorry, but the postcode you entered was too long or too short. Please enter a valid UK postcode.";
    var sAlertInvalid = "Sorry, but the postcode you entered was not valid. Please enter a valid UK postcode.";

    if (pcode == null || pcode == "") {
        alert(sAlertEmpty);
        return false;
    }

    pcode = formatPostcode(pcode);

    if (pcode.length < 6 || pcode.length > 8) {
        alert(sAlertLength);
        return false;
    }

    if (pcode.match(pcType1) || pcode.match(pcType2) || pcode.match(pcType3) || pcode.match(pcType4) || pcode.match(pcType5) || pcode.match(pcType6)) {
        //frmElement.value = pcode;
        return true;
    } else {
        alert(sAlertInvalid);
        return false;
    }
}

function formatPostcode(xPC) {

    xPC = xPC.toUpperCase();

    // replace all spaces
    xRegExp = / /g;
    xPC = xPC.replace(xRegExp, "");

    // replace all !
    xRegExp = /!/g;
    xPC = xPC.replace(xRegExp, "");

    // now put the space back in the right place
    xLen = xPC.length;
    xLastStart = xLen - 3;
    xPart1 = xPC.substr(0, xLastStart);
    xPart2 = xPC.substr(xLastStart, 3);
    xPC = xPart1 + " " + xPart2;
    return xPC;
}


function validateform(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if(reg.test(address) == false) {
      alert('Invalid Email Address');
      return false;
   }
   if($('#tc').attr('checked') == false){
      alert('Please agree to T&C');
      return false;
   }
   //do ajax call to send email to person
   resp = sendEmail($('#emailBox').val());

   if(resp['err']){
       alert(resp['status']);
   }
   else{
       var emailPrompt ='Thank you for entering our win a Wattson competition! \n' +
                        'Draws take place on the 28th of every calendar month. \n' +
                        'We give away one Wattson per month and the winners are notified by email within 10 days of the draw taking place.Good Luck!';
       alert(emailPrompt);
   }

   //stops the form from procession further
   return false;
}

function sendEmail(email){
/**
* @desc sends email to php script
* @author Joe Lee Nov '09
* @dependencies  jquery
* @Rev
* @return none;
*/
    var urlRequest = 'http://'+document.domain+'/' +"scripts/email.php?email=" + email;
    var response = '';

    $.getJSON(urlRequest,
            function(json){
                response = json;
            });
    return response;
}

function GetParameterFromURL(name){
/*-------------------------------------
Description:
Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
GetParameterFromURL('msg') will get 'hello'

Author: http://www.netlobo.com/url_query_string_javascript.html
Dependencies:
Updates:
@Parameters: name = name of the parameter to extract
-------------------------------------*/
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

a8util = {
    GetParameterFromURL : function(name){
    /*-------------------------------------
    Description:
    Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
    GetParameterFromURL('msg') will get 'hello'

    Author: http://www.netlobo.com/url_query_string_javascript.html
    Dependencies:
    Updates:
    @Parameters: name = name of the parameter to extract
    -------------------------------------*/
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return results[1];    
    },
    jmpLinkWellFormed : function(headPage, pageRef){
        //chks if link parts are present
        if(headPage.length <1 || pageRef.length < 1 ){
            return false
        }
        else{
            return true;
        }
    },
    headJmp : function(headPage, pageRef){
        //the javascript masking solution

        if(a8util.GetParameterFromURL('showlinks') || a8util.GetParameterFromURL('showlink') ){
            if(a8util.jmpLinkWellFormed(headPage, pageRef)){
                alert('This link will go to ' + headPage + pageRef);
                return false;
            }
            else{
                alert('Re-chk this link');
                return false;
            }
        }
        else{
            window.location = headPage + pageRef;
        }
    }
}

a8util = {
    GetParameterFromURL : function(name){
    /*-------------------------------------
    Description:
    Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
    GetParameterFromURL('msg') will get 'hello'

    Author: http://www.netlobo.com/url_query_string_javascript.html
    Dependencies:
    Updates:
    @Parameters: name = name of the parameter to extract
    -------------------------------------*/
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( window.location.href );
        if( results == null )
            return "";
        else
            return results[1];    
    },
    jmpLinkWellFormed : function(headPage, pageRef){
        //chks if link parts are present
        if(headPage.length <1 || pageRef.length < 1 ){
            return false
        }
        else{
            return true;
        }
    },
    headJmp : function(headPage, pageRef){
        //the javascript masking solution

        if(a8util.GetParameterFromURL('showlinks') || a8util.GetParameterFromURL('showlink') ){
            if(a8util.jmpLinkWellFormed(headPage, pageRef)){
                alert('This link will go to ' + headPage + pageRef);
            }
            else{
                alert('Re-chk this link');
            }
        }
        else{
            window.location = headPage + pageRef;
        }
        return false;
    }

}



$(document).ready(function() {
   //attach clear event
   $('#postcode').click(function(event) {
       $(this).val("");
   });

   //attach validation on "gas & electricity" page postCode form
   $('#homeForm').submit(function(event) {
       return redir($(this));
   });

   //attach validation on "gas a& electricity" page comp form
   $('#wattsonCompetitionForm').submit(function(event) {
       return validateform("wattsonCompetitionForm","emailBox");
   }).removeAttr('target');
   $.cookie('A8ID',GetParameterFromURL('A8ID'),{path: '/'});
      
});
