/*############################################################################
# Document: Phone Tracking Script                                            #
# Created: 8/27/10                                                           #
# By: Sean Gallagher                                                         #
#                                                                            #
# Company: Gallagher Website Design                                          #
# Web: http://www.GallagherWebsiteDesign.com                                 #
# Email: webmaster@gallagherwebsitedesign.com                                #
#                                                                            #
# Proprietary Software - Legal Note                                          #
#                                                                            #
# This entire document was created by Sean Gallagher and Gallagher Website   #
# Design. The creator maintains all rights of ownership of this document and #
# it's contents in part of whole.                                            #
#                                                                            #
# Only those who have been granted rights of use through an authorizated     #
# license, which is granted by the script creator, my use this document in   #
# part or whole. All licenses are good for only one website domain unless    #
# otherwise granted by the script creator. Unauthorized use of this script   #
# is subject to legal repercussions.                                         #
#                                                                            #
# Copyright 2010. Gallagher Website Design. All Rights Reserved.             #
############################################################################*/

///////////////////////
// DEFINE VARIABLES //
//////////////////////
var phoneReplace = '1-925-241-4271 '; // phone number to replace
var phonePPC = '925-241-4271'; // PPC phone number
var phoneSEO = '(925) 241-4271'; // SEO phone number

/////////////////////////////////
// START CALL TRACKING SCRIPT //
////////////////////////////////
var ct_run = 1;
addErrorEvent(phoneDyn);
var startCallTracking = new ct_domFunc(phoneDyn);

/////////////////////////
// ADD ON ERROR EVENT //
////////////////////////
function addErrorEvent(func)
{
 var oldOnError = window.onerror;
 if(typeof window.onerror != 'function')
 {
  window.onerror = func;
 }
 else
 {
  window.onerror = function()
  {
   oldOnError();
   func();
  }
 }
}

/////////////////////////////////
// REPLACE ALL FOR STRING OBJ //
////////////////////////////////
String.prototype.ReplaceAll = function(stringToFind,stringToReplace)
{
 var temp = this;
 var index = temp.indexOf(stringToFind);
 while(index!=-1)
 {
  temp = temp.replace(stringToFind,stringToReplace);
  index = temp.indexOf(stringToFind);
 }
 return temp;
}

/////////////////////////////////
// GET IMG WITH REL ATTRIBUTE //
////////////////////////////////
function getImgByRel(rel)
{
 var imgs = document.getElementsByTagName("img");
 var e = [];
 for(i=0;i<imgs.length;i++)
 {
  if(imgs[i].getAttribute("rel") && imgs.rel==rel) { e[i] = imgs[i]; }
 }
 return e;
}

/////////////////////////////////
// GET DIV WITH REL ATTRIBUTE //
////////////////////////////////
function getDivByRel(rel)
{
 var imgs = document.getElementsByTagName("div");
 var e = [];
 for(i=0;i<imgs.length;i++)
 {
  if(imgs[i].getAttribute("rel") && imgs.rel==rel) { e[i] = imgs[i]; }
 }
 return e;
}

////////////////////////////////////
// COUNTRY CODE REPLACE FUNCTION //
///////////////////////////////////
function contCodeReplace(h,t,p)
{
 h = h.replace(new RegExp("1"+t,"\g"),p);
 h = h.replace(new RegExp("1-"+t,"\g"),p);
 h = h.replace(new RegExp("1."+t,"\g"),p);
 h = h.replace(new RegExp("1 "+t,"\g"),p);
 h = h.replace(new RegExp("1  "+t,"\g"),p);
 return h;
}
function contCodeReplaceP(h,t,p)
{
 h = h.ReplaceAll("1"+t,p);
 h = h.ReplaceAll("1-"+t,p);
 h = h.ReplaceAll("1."+t,p);
 h = h.ReplaceAll("1 "+t,p);
 h = h.ReplaceAll("1  "+t,p);
 return h;
}

/////////////////////////////////
// PHONE REPLACEMENT FUNCTION //
////////////////////////////////
function replacePhones(p,r,h)
{
 //////////////////////
 // FORMAT PHONE #s //
 /////////////////////
 r = r.replace(/[-.\s()[\]]/g,"");
 r = (r.length==11) ? r.substr(1) : r;

 ////////////////////////////////
 // RETURN IF PHONE = REPLACE //
 ///////////////////////////////
 var j = p.replace(/[-.\s()[\]]/g,"");
 j = (j.length==11) ? j.substr(1) : j;
 if(r==j) { return h; }

 //////////////////////
 // REPLACE NUMBERS //
 /////////////////////
 var t;
 var r2 = (r.length==10) ? '1'+r : r;

 $("body *").replaceText(r2,p);
 $("body *").replaceText(r,p);

 // dashes between
 t = r.substr(0,3)+'-'+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h = contCodeReplace(h,t,p); }
 $("body *").replaceText(t,p);

 // dots between
 t = r.substr(0,3)+'.'+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplace(h,t,p); }
 $("body *").replaceText(t,p);

 // spacing between
 t = r.substr(0,3)+' '+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplace(h,t,p); }
 $("body *").replaceText(t,p);

 // areacode parentheses
 t = '('+r.substr(0,3)+')'+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+') '+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+')  '+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+')'+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h =  contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+') '+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+')-'+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+')'+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+') '+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 t = '('+r.substr(0,3)+').'+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 $("body *").replaceText(t,p);

 // DONE
 return;

/*
 h = h.replace(new RegExp(r2,"\g"),p);
 h = h.replace(new RegExp(r,"\g"),p);


 // dashes between
 t = r.substr(0,3)+'-'+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h = contCodeReplace(h,t,p); }
 h = h.replace(new RegExp(t,"\g"),p);

 // dots between
 t = r.substr(0,3)+'.'+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplace(h,t,p); }
 h = h.replace(new RegExp(t,"\g"),p);

 // spacing between
 t = r.substr(0,3)+' '+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplace(h,t,p); }
 h = h.replace(new RegExp(t,"\g"),p);

 // areacode parentheses
 t = '('+r.substr(0,3)+')'+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+') '+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+')  '+r.substr(3,3)+' '+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+')'+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h =  contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+') '+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+')-'+r.substr(3,3)+'-'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+')'+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+') '+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 t = '('+r.substr(0,3)+').'+r.substr(3,3)+'.'+r.substr(6);
 if(r!=r2) { h = contCodeReplaceP(h,t,p); }
 h = h.ReplaceAll(t,p);

 // with html tags
  // detect and replace phone #s which have parts wrapped with html tags

 /////////////////////
 // Return Results //
 ////////////////////
 return h;
*/

}

//////////////////////////////////////////////
// ENTIRE PHONE DYNAMIC PLACEMENT FUNCTION //
////////////////////////////////////////////
function phoneDyn()
{

 ///////////////////////////
 // ONLY RUN SCRIPT ONCE //
 //////////////////////////
 if(window.ct_run>1) { return; }
 window.ct_run++;

 //////////////////////////
 // CHECK VISITOR REFER //
 /////////////////////////
 // Checks where visitor came from: PPC or SEO
 var refer = getRefer();

 //////////////////////////
 // GET PHONE #s TO USE //
 ////////////////////////
 // Parse phone numbers from files phonePPC and phoneSEO
 var phoneNum = (refer=='seo') ? window.phoneSEO : window.phonePPC;
 if(!phoneNum) { return false; } // fail safe if no phone number

 ////////////////////////////////
 // REPLACE ALL TEXT PHONE #s //
 //////////////////////////////
 // Replace all text phone numbers with PPC or SEO number
// document.body.innerHTML = replacePhones(phoneNum,phoneReplace,document.body.innerHTML);
replacePhones(phoneNum,phoneReplace,document.body.innerHTML);


 /////////////////////////////////
 // REPLACE ALL IMAGE PHONE #s //
 ////////////////////////////////
 // Replace all image phone numbers with PPC or SEO number image by using: rel="seo[image_url.jpg],ppc[image_url.jpg]"
 var x,r,s,p;
 var imgs = getImgByRel();
 for(x in imgs)
 {
  r = imgs[x].getAttribute('rel');
  if(refer=='seo' && r.split('seo[').length==2)
  {
   s = r.split('seo[');
   s = s[1].split('],');
   s = s[0];
   imgs[x].src = s;
  }
  else if(r.split('ppc[').length==2)
  {
   p = r.split('ppc[');
   p = p[1].split(']');
   p = p[0];
   imgs[x].src = p;
  }
 }

 /////////////////////////////////
 // SHOW/HIDE ALL DIV PHONE #s //
 ////////////////////////////////
 // Hide divs not for the phone number and show divs for the phone number
 if(refer=='seo')
 {
  $('.calltrackingSEO').css("display","block");
  $('.calltrackingPPC').css("display","none");
 }
 else
 {
  $('.calltrackingSEO').css("display","none");
  $('.calltrackingPPC').css("display","block");
 }

}

///////////////////
// GET REFERRER //
//////////////////
function getRefer()
{
 var source = 'seo';
 if(_readCookie('__ct')) { source = _readCookie('__ct'); }
 else
 {
  if($_GET('gclid')!='' && $_GET('gclid')!=null) { source = 'ppc'; }
 }
 var date = new Date();
 date.setTime(date.getTime()+(1800000));
 var expires = "; expires="+date.toGMTString();
 document.cookie = "__ct="+source+expires+"; path=/";
 return source;
}

//////////////////
// READ COOKIE //
/////////////////
function _readCookie(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 null;
}

///////////////////////
// GET URL GET VARS //
//////////////////////
function $_GET(q,s)
{
 s = (s) ? s : window.location.search;
 var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
 return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
}

// DF1.1 :: domFunction 
// *****************************************************
// DOM scripting by brothercake -- http://www.brothercake.com/
// GNU Lesser General Public License -- http://www.gnu.org/licenses/lgpl.html
//******************************************************

/////////////////////////////
// LOAD ON DOM READY FUNC //
////////////////////////////
//DOM-ready watcher
function ct_domFunc(f,a)
{
	//initialise the counter
	var n = 0;
	
	//start the timer
	var t = setInterval(function()
	{
		//continue flag indicates whether to continue to the next iteration
		//assume that we are going unless specified otherwise
		var c = true;

		//increase the counter
		n++;
	
		//if DOM methods are supported, and the body element exists
		//(using a double-check including document.body, for the benefit of older moz builds [eg ns7.1] 
		//in which getElementsByTagName('body')[0] is undefined, unless this script is in the body section)
		if(typeof document.getElementsByTagName != 'undefined' && (document.getElementsByTagName('body')[0] != null || document.body != null))
		{
			//set the continue flag to false
			//because other things being equal, we're not going to continue
			c = false;

			//but ... if the arguments object is there
			if(typeof a == 'object')
			{
				//iterate through the object
				for(var i in a)
				{
					//if its value is "id" and the element with the given ID doesn't exist 
					//or its value is "tag" and the specified collection has no members
					if
					(
						(a[i] == 'id' && document.getElementById(i) == null)
						||
						(a[i] == 'tag' && document.getElementsByTagName(i).length < 1)
					) 
					{ 
						//set the continue flag back to true
						//because a specific element or collection doesn't exist
						c = true; 

						//no need to finish this loop
						break; 
					}
				}
			}

			//if we're not continuing
			//we can call the argument function and clear the timer
			if(!c) { f(); clearInterval(t); }
		}
		
		//if the timer has reached 60 (so timeout after 15 seconds)
		//in practise, I've never seen this take longer than 7 iterations [in kde 3 
		//in second place was IE6, which takes 2 or 3 iterations roughly 5% of the time]
		if(n >= 60)
		{
			//clear the timer
			clearInterval(t);
		}
		
	}, 250);
};

/*
 * jQuery replaceText - v1.1 - 11/21/2009
 * http://benalman.com/projects/jquery-replacetext-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){$.fn.replaceText=function(b,a,c){return this.each(function(){var f=this.firstChild,g,e,d=[];if(f){do{if(f.nodeType===3){g=f.nodeValue;e=g.replace(b,a);if(e!==g){if(!c&&/</.test(e)){$(f).before(e);d.push(f)}else{f.nodeValue=e}}}}while(f=f.nextSibling)}d.length&&$(d).remove()})}})(jQuery);

