// JavaScript Document
//	Javascript  for tracking Phone numbers
//	Created by Patrick Hegarty on 07/06/10
//	Modified by Patrick Hegarty on 8/12/10
//	Modified by Subhajit Sabui on 04/06/2011
/*
 * Modified to work with Jquery
 */

//Testing this works
//console.debug('Starting Script!');


//Setup for picking the number

// Arrays for storing the HTML or filename for the different phone numbers
var numberHTML = new Array();
numberHTML['direct'] = new Array();
numberHTML['organic']= new Array();
numberHTML['paid'] = new Array();
var phoneNo = new Array();

var bannerTag = ''; //  points to the html element you want to change
var teaserTag = '';

var currentURL = document.URL;
var currentDomain ='';
 

var	 imgpath = getBaseURL()+'/';
	 
// Cookie variables
var cookieName ='phoneTracking';
// These are used to set the value of the cookie for tracking a visitor around your site
var googlePaid ='Paid'; 
var googleSearch = 'Search';

//	This sets up the various information for altering the site.
//	This needs altering to fit the site it's working on
function setup()
{
	 bannerTag = $j('#phoneNumber');
	 //console.debug('banner img: ' + bannerTag.attr('src'));
	 teaserTag = $j('#phoneNumber');
	 //console.debug('teaser img: ' + teaserTag.attr('src'));
	 officetag = $j('#phoneNumber');
	 // These are the images that have different phone numbers on them
    

	 if( currentURL.match(new RegExp('http://easyoff.virtualsite.co.uk/franchising(.*)$')))
	 {
	     //console.debug('On a Franchise Page '+currentURL);
	     numberHTML['direct']['banner'] = numberHTML['direct']['teaser'] = numberHTML['organic']['banner'] = numberHTML['organic']['teaser'] = numberHTML['paid']['banner'] = numberHTML['paid']['teaser'] = '<img src="'+imgpath+'images/020-7871-1200.gif">';
	 }
	 else
	 {
	 numberHTML['direct']['banner']	= '<img src="'+imgpath+'images/020-7871-1200.gif">';
	 numberHTML['direct']['teaser']	= '<img src="'+imgpath+'images/020-7871-1200.gif">';
	 numberHTML['organic']['banner']= '<img src="'+imgpath+'images/020-7871-1200.gif">';
	 numberHTML['organic']['teaser']= '<img src="'+imgpath+'images/020-7871-1200.gif">';
	 numberHTML['paid']['banner']	= '<img src="'+imgpath+'images/020-7870-8200.gif">';
	 numberHTML['paid']['teaser']	= '<img src="'+imgpath+'images/020-7870-8200.gif">';
	 }
	 
}

// get the Domain the URL is on
function getDomain()
{
	
	// replace Blog Entries
	currentURL = currentURL.replace('blog.','www.'); // this can be used to remove other subdomains
	
	if(currentURL != '')
	{
		return currentURL.replace(/^http\:\/\/(www\.|)([^\/]+)(.*)$/,'$2');
	}
	else
	{
		return '';
	}
}

//	Pick the Number to display depended upon Referrer
function setNumber()
{
	if(!checkCookie(cookieName))
	{
		//console.debug('Referrer:' + document.referrer + '\n');
		var Referrer = document.referrer;
		if(Referrer != null && Referrer != '')
		{
			//console.debug('Referrer is Set:' + Referrer + '\nDomain is :' + getDomain());
			currentDomain = getDomain();

			if(Referrer.match(new RegExp('$http://(www\.)?'+currentDomain+'(.*)')))
			{
				//	This is someone going around your site, if they can directly and you didn't track that with a cookie
				//console.debug('Same Domain, internal Referrer\n' + currentURL + ' - ' + Referrer);
				if(bannerTag.length > 0 )bannerTag.html(numberHTML['direct']['banner']);
			}
			else if(Referrer.match(/^(.*)google(.*)$/))
			{
				//	referrer is Google
				//console.debug('From Google\n' + currentURL + ' - ' + Referrer);
				if( currentURL.match(/^(.*)?gclid\=(.*)$/) || currentURL.match(/^(.*)(\?|\&)utm\_term\=ppc(.*)$/) || document.cookie.match(/^(.*)utmcmd\=\(not\%20set\)(.*)$/) || document.cookie.match(/^(.*)utmcmd\=ppc(.*)$/))
				{
					// Referrer is a Paid/Sponsored link from Google
					//console.debug('From Paid Google Link\n' + currentURL + ' - ' + Referrer);
					if(bannerTag.length > 0 )bannerTag.html(numberHTML['paid']['banner']);
					if(teaserTag.length > 0 )teaserTag.html(numberHTML['paid']['teaser']);
					if(officetag.length > 0)
					{

					    officetag.each(function(index){
						$j(this).html('<img src="'+imgpath+'images/020-7870-8200.gif">');
						//console.debug('Index is '+index)
					    });
				}
					setCookie(cookieName,googlePaid,null);
				}
				else
				{
					//	Referrer is a Organic Search link from Google
					//console.debug('From Non-Paid Google link\n' + currentURL + ' - ' + Referrer);
					if(bannerTag.length > 0 ) bannerTag.html(numberHTML['organic']['banner']);
					if(teaserTag.length > 0 ) teaserTag.html(numberHTML['organic']['teaser']);
					setCookie(cookieName,googleSearch,null);
				}
			}
			else
			{
			    // Other search engines and referrers or sponsor links including internal links
			    // Break this donw depending on what traffic you want to track
			    //console.debug('Another Referrer\n' + currentURL + ' - ' + Referrer);
			    if(bannerTag.length > 0 )bannerTag.html(numberHTML['direct']['banner']);
			}
		}
		else
		{
			// Visitor came straight to the site
			//console.debug('No Referrer, so Direct link\n' + currentURL + ' - ' + Referrer);
			if(bannerTag.length > 0 )bannerTag.html(numberHTML['direct']['banner']);
		}
	}
	else
	{
		// Cookie is set, so check what the setting is
		//console.debug('Cookie Found :' + getCookie(cookieName));
		var currentCookie = getCookie(cookieName);
		switch(currentCookie)
		{
			case googleSearch : 
				if(bannerTag.length > 0 ) bannerTag.html(numberHTML['organic']['banner']);
				if(teaserTag.length > 0 ) teaserTag.html(numberHTML['organic']['teaser']);
				break;
			
			case googlePaid : 
				if(bannerTag.length > 0 )bannerTag.html(numberHTML['paid']['banner']);
				if(teaserTag.length > 0 ) teaserTag.html(numberHTML['paid']['teaser']);
				if(officetag.length > 0)
				{
				    officetag.each(function(index){
					$j(this).html('<img src="'+imgpath+'images/020-7870-8200.gif">');
					//console.debug('Index is '+index)
				    });
				}
				break;
			default	:
				if(bannerTag.length > 0 )bannerTag.html(numberHTML['organic']['banner']);
		}
	}
}

// Cookie Functions

function setCookie(c_name,value,expiredays)
{
//	alert('Setting Cookie');
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+ ";host=" + getDomain() + ";path=/" +
	((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}

function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
		{
		c_start=c_start + c_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 "";
}

function checkCookie(cookieName)
{
	var currentCookie=getCookie(cookieName);
	if (currentCookie!=null && currentCookie!="")
	  {
		return true;
	  }
	else
	  {
	  	return false;
	  }
}
function getBaseURL() {
    var url = location.href;  // entire url including querystring - also: window.location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));


    if (baseURL.indexOf('http://easyoff.virtualsite.co.uk/') != -1) {
        // Base Url for localhost
        var url = location.href;  // window.location.href;
        var pathname = location.pathname;  // window.location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/";
    }
    else {
        // Root Url for domain name
        return baseURL + "/";
    }

}
//Run the functions on document load

$j(document).ready(function(){
    //console.debug('Starting Setup - ' + currentURL);
    setup();
    //console.debug('Done Setup');
    //console.debug('Starting SetNumber');
    setNumber();
    //console.debug('Done SetNumber');
})

