/*
Script: salestracking.js
	Fasttrack IT - Sales tracking script to manage visitor cookies and the setting of sales 
	tracking information within capturing web forms.

License:
	24-7 Fasttrack Ltd Standard Terms Of Business. Check IP Section Clauses. 

24-7 Fasttrack IT Ltd Copyright:
	copyright (c) 2010 Graham Bell, 24-7 Fasttrack IT Ltd;

Script Built To Service
-----------------------
This script has been created to service the following website forms.

Website Form                Local Html Version
------------                ------------------
/signup/SignupIntl.aspx     SignupIntl.htm
/feedback.aspx              feedback.htm


Version Details
---------------
0.1         Graham Bell (24-7 Fasttrack IT Ltd)

*/

/* Constants & Settings */
/* -------------------- */

/* Set DEBUG_ON to true to track the progress of this script on page. 
On a live site ensure this is set to false. */
var DEBUG_ON = false;

/* Defines which cookie wins if both are defined. If LONG_WINS is set to true
then the long term cookie will be used in the hidden form fields if its found. 
otherwise the first cookies to be used will be the current session and if not found,
the long term cookie will be used. 

Using the LONG term cookie by default should ensure we track sales by the first visit
rather than subsequent searches.
*/
var LONG_WINS = true;

/* Setting SEO_WINS to true will override both LONG and SHORT keywords and adverts.
This is suggested to ensure we track SEO keywords which produce sales. */
var SEO_WINS = true;

/* Change this to a string which will be passed through in the event of a keyword or advert not being 
found in any cookie */
var NONE_SET = "NONE";

/*
Domain to use for cookies (can use www.timetrackingsoftware.com but incase signup 
switches to another subdomain, using timetrackingsoftware.com is safer */
var DOMAIN = "pjb.com"; 

/* 
Path for cookies. Normally just / to imply all areas */
var PATH = "/";

/*
Default Expire of longer term cookies. This value is specified in days.*/
var EXPIRE_DAYS = 31;

/* Keyword parameter value */
var KEYWORD = "kw";

/* Advert parameter value */
var ADVERT = "ad";

/* 
SEO Tracking. Most search engines use q to sepcify the keyword */
var SEO = "q";

/*
These are the cookie names for tracking
*/
var LONG_KEYWORD = "stl_keyword" //Long term cookie holding the keyword
var SHORT_KEYWORD = "st_keyword" //Short term cookie holding the keyword
var LONG_AD = "stl_ad" //Long term cookie holding the advert
var SHORT_AD = "st_ad" //Short term cookie holding the advert
var LONG_SEO = "stl_seo" //Long term cookie holding the seo keyword
var SHORT_SEO = "st_seo" //Short term cookie holding the seo keyword

/*
The are the hidden form fields added to the submission forms
*/
var FRM_KEYWORD = "ST_KEYWORD";
var FRM_ADVERT = "ST_ADVERT"; //If an SEO lead, this will be SEO

/* Event Handlers */
/* -------------- */
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

/* Tracking Methods */
/* ---------------- */
function track() {
    debug("track() started");

    if (getKeyword() != NONE_SET) {
        if (LONG_WINS) {
            debug("Long term keyword found and LONG_WINS is true. Exiting track().");
            return;
        }
    }
    
    //Regular Expressions to search
    var reKW = KEYWORD+"=([^&]*);?";
    var reAD = ADVERT + "=([^&]*);?";
    var reSEO = SEO + "=([^&]*);?";
    var queryString = location.search;
	var referrer = document.referrer + "";
	
    //Set local vars
    var keyword, advert, seo
    
    var re = new RegExp(reKW);

    if (re.test(queryString)) {
        keyword = decodeURIComponent(RegExp["$1"]);
        debug("Keyword is " + keyword);
    }
    else {
        keyword = "";
        debug("Keyword not found");
    }
    
    re = new RegExp(reAD);

    if (re.test(queryString)) {
        advert = decodeURIComponent(RegExp["$1"]);
        debug("Advert is " + advert);
    }
    else {
        advert = "";
        debug("Advert not found");
    }
    
    re = new RegExp(reSEO);

    if (re.test(referrer)) {
        seo = decodeURIComponent(RegExp["$1"]);
        debug("SEO is " + seo);
    }
    else {
        seo = "";
        debug("SEO not found");
    }

    if (keyword != "") {
        debug("Creating keyword cookies");
        createCookie(LONG_KEYWORD, keyword, EXPIRE_DAYS, PATH, DOMAIN, false);
        createCookie(SHORT_KEYWORD, keyword);
    }

    if (advert != "") {
        debug("Creating advert cookies");
        createCookie(LONG_AD, advert, EXPIRE_DAYS, PATH, DOMAIN, false);
        createCookie(SHORT_AD, advert);
    }

    if (seo != "") {
        debug("Creating seo cookies");
        createCookie(LONG_SEO, seo, EXPIRE_DAYS, PATH, DOMAIN, false);
        createCookie(SHORT_SEO, seo);
    }
    
    debug("track() Ended");
}

/* Form Update Methods */
/* -------------- */
function updateForms() {
    debug("updateForms() started");
    
    var formCount = document.forms.length;
    var form;
    
    for (i = 0; i < formCount; i++) {
        form = document.forms[i];
        
        /* Add conditions here to block form additions based on name or id's if required */
        debug("Inserting hidden fields into form " + form.name);
        insertHiddenFields(form);
    }

    debug("updateForms() Ended");
}

function insertHiddenFields(form) {

    debug("insertHiddenFields() started");
    
    var keyword, advert;
    keyword = getKeyword();
    advert = getAdvert();
    
    var fldKeyword = document.getElementById(FRM_KEYWORD);
    if(fldKeyword!=null)
		fldKeyword.value = keyword;
    
    var fldAd = document.getElementById(FRM_ADVERT);
    if(fldAd!=null)
		fldAd.value = advert;
    
    debug("insertHiddenFields() Ended");
}

//Set to true if keyword is an SEO keyword
var useSEO = false;

function getKeyword() {

    debug("getKeyword() started [No Ended Will Fire]");
    
    var skeyword,lkeyword,sseokeyword,lseokeyword;
    
    skeyword = readCookie(SHORT_KEYWORD);
    lkeyword = readCookie(LONG_KEYWORD);
    sseokeyword = readCookie(SHORT_SEO);
    lseokeyword = readCookie(LONG_SEO);

    if (LONG_WINS && lkeyword != null) {
        if (SEO_WINS && lseokeyword != null) {
            useSEO = true;
            return lseokeyword;
        }
        return lkeyword;
    }

    if (skeyword != null) {
        if (SEO_WINS && sseokeyword != null) {
            useSEO = true;
            return sseokeyword;
        }

        return skeyword;
    }

    if (LONG_WINS) {
        if (lseokeyword != null) {
            useSEO = true;
            return lseokeyword;
        }
        else if (sseokeyword != null) {
            useSEO = true;
            return sseokeyword;
        }
    }
    else {
        if (sseokeyword != null) {
            useSEO = true;
            return sseokeyword;
        }

        if (lseokeyword != null) {
            useSEO = true;
            return lseokeyword;
        }
    }
    
    return NONE_SET;
}

function getAdvert() {
    var sad, lad;

    debug("getAdvert() started [No Ended Will Fire]");
    
    if (useSEO)
        return "SEO";
    
    sad = readCookie(SHORT_AD);
    lad = readCookie(LONG_AD);

    if (LONG_WINS && lad != null) {
        return lad;
    }

    if (sad != null) {
        return sad;
    }

    if (lad != null) {
        return lad;
    }

    return NONE_SET;
}

/* Cookie Methods */
/* -------------- */
/* Creates a Cookie */
function createCookie(name, value, days, path, domain, secureOnly) {

    debug("createCookie() started");
    
    var cookieString = name + "=" + encodeURIComponent(value);
    
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        cookieString += "; expires=" + date.toGMTString();
    }

    if (path)
        cookieString += "; path=" + path;

    if (domain)
        cookieString += "; domain=" + domain;

    if (secureOnly)
        cookieString += "; secure";

    document.cookie = cookieString;

    if (readCookie(name))
        return cookieString;
    else
        return null;

    debug("createCookie() Ended");
}

/* Reads a cookie value */
function readCookie(name) {

    debug("readCookie(" + name + ") started [No Ended will fire]");
    
    var reString = "(?:; )?" + name + "=([^;]*);?";
    var re = new RegExp(reString);

    if (re.test(document.cookie)) {
        return decodeURIComponent(RegExp["$1"]);
    }
    else {
        return null;
    }
}
/* Deletes a cookie */
function eraseCookie(name) {
    debug("eraseCookie(" + name + ") started");
    createCookie(name, "", 0, "/", DOMAIN, false);
    debug("eraseCookie(" + name + ") Ended");
}

//If cookie create not working alert null will display.
function TestCookieCreate() {
    alert(createCookie("test1", "value1", EXPIRE , "/", DOMAIN, true));
    alert(createCookie("test2", "value2", EXPIRE , "/", DOMAIN, false));
    alert(createCookie("test3", "value3"));
}

/* Helper Methods */
/* -------------- */
function debug(debugData) {
    if (DEBUG_ON)
        alert(debugData);
}

/* PageLoad Event */
/* -------------- */
addLoadEvent(track);
/* addLoadEvent(updateForms); Should be added to lead capture pages only */
