/*!
 * http://www.kryogenix.org/code/browser/searchhi/ 
 * Modified 20021006 to fix query string parsing and add case insensitivity 
 * Modified 20070316 to stop highlighting inside nosearchhi nodes 
 * Modified 20090104 by Bruce Lawson to use html5 mark element rather than span 
     http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-mark-element 
 * Modified 20090105 by Pete Boere to clean-up namespace, add hostname referrerurl check for unconventional 
     query parameters and change behaviour to highlight the full search phrase and whole word matches ( not word sub-strings )
 * This script is by Stuart Langridge licensed under MIT license http://www.kryogenix.org/code/browser/licence.html
*/

var  referrerurl = document.referrer;// || window.location.protocol === 'file:' ? window.location.href : '';

(function () {
// Shortcuts
var win = window,
	doc = document,
	loc = win.location,
	
	// Allow local files for testing
	//referrerurlurl = doc.referrer || loc.protocol === 'file:' ? loc.href : '',
	
	// Parse referrerurl hostname from referrerurl string
    referrerurlHost = function () {
        var a = doc.createElement( 'a' );
        a.href = referrerurl;
        return a.hostname;
    }(),
	
	// By default check for the parameter 'q' as it's a convention
	searchParameter = 'q',

	// List any search engines that do not use the conventional 'q' query parameter;
	// less chance of creating unexpected effects this way ( i.e. 'p' could easily be used as an alias for 'page' or 'product' )
	searchEngines = {
		yahoo: 'p' 
	},
	
	// Helper for iterating arrays, nodelists and objects
	each = function ( obj, callback ) {
		if ( obj+'' === '[object Object]' ) {
			for ( var key in obj ) { 
				callback.call( obj, key, obj[ key ] ); 
			}
		}
		else {
			for ( var i = 0; i < obj.length; i++ ) { 
				callback.call( obj, obj[ i ], i ); 
			}
		}
	},
	
	// Cache word match regexs for performance gain
	reCache = {},
	
	highlightWord = function ( node, word ) {
		// Iterate into this nodes childNodes
		if ( node.hasChildNodes ) {
			each( node.childNodes, function ( cn ) {
				highlightWord( cn, word );
			});
		}
		// And do this node itself if it's text and it hasn't already been highlighted
		if ( node.nodeType == 3 && node.parentNode.className != 'searchword' ) { 
			
			var tempNodeVal = node.nodeValue.toLowerCase(),
				tempWordVal = word.toLowerCase(),
				// Setup regex outline
				wordPatt = '\\b' + tempWordVal + '\\b',
				// Get regex from cache or create it ( and cache for re-use )
				wordPatt = reCache[ wordPatt ] = ( reCache[ wordPatt ] || new RegExp( wordPatt ) ),
				
				match = wordPatt.exec( tempNodeVal );
				
			if ( match ) {
				var pn = node.parentNode,
					checkn = pn;
					
				// check if we're inside a "nosearchhi" zone
				while ( checkn && checkn != doc.body ) { 
					if ( /\bnosearchhi\b/.test( checkn.className ) ) { 
						return; 
					}
					checkn = checkn.parentNode;
				}
				
				var nv = node.nodeValue,
					ni = match.index,
					// Create a load of replacement nodes
					before = doc.createTextNode( nv.substr( 0, ni ) ),
					docWordVal = nv.substr( ni, word.length ),
					after = doc.createTextNode( nv.substr( ni + word.length ) ),
					hiwordtext = doc.createTextNode( docWordVal ),
					hiword = doc.createElement( 'mark' );
				hiword.className = 'searchword';
				hiword.appendChild( hiwordtext );
				pn.insertBefore( before, node );
				pn.insertBefore( hiword, node );
				pn.insertBefore( after, node );
				pn.removeChild( node );
			}
		}
	},
	
	searchTermHighlight = function () {
		var tokens = referrerurl.substr( referrerurl.indexOf( '?' ) + 1 ).split( '&' );
		each( tokens, function ( token ) {
			var parts = token.split( '=' ),
				param = parts[ 0 ],
				value = parts[ 1 ];
			if ( value && param === searchParameter ) { 
				var phrase = unescape( value.replace( /\+/g, ' ' ) ),
					words = phrase.split( /\s+/ );
				// Add the complete phrase to the front of the stack 
				words.unshift( phrase );
				var StrToRecord = referrerurlHost + ': ' + phrase;
				if (window.location.href.indexOf("gclid")!==-1)
				{
					StrToRecord += ' -CPC-';
				}
				else
				{
					StrToRecord += '';
				}
				
				StrToRecord += '	' + GetCurDate() + ' ' + GetCurTime() + '\n';
				
				var orig = '';
				if (orig = Get_Cookie('kwt'))
				{
					Delete_Cookie('kwt', '/', '');
					// name, value, expires, path, domain, secure
					Set_Cookie( 'kwt', orig + StrToRecord , 60, '/', '', '' );

				}
				else
				{
					// name, value, expires, path, domain, secure
					Set_Cookie( 'kwt', StrToRecord , 60, '/', '', '' );
				}
				//alert(Get_Cookie('kwt'));
				/*
				// remember, these are the possible parameters for Set_Cookie:
				if ( Get_Cookie( 'kwt' ) ) alert( Get_Cookie('test'));
				// and these are the parameters for Delete_Cookie:
				// name, path, domain
				// make sure you use the same parameters in Set and Delete Cookie.
				Delete_Cookie('kwt', '/', '');
				( Get_Cookie( 'kwt' ) ) ? alert( Get_Cookie('test')) :
				alert( 'it is gone');
				*/
				each( words, function ( word ) {
					//highlightWord( doc.body, word );
				}); 
			}
		});
	};

// Apply any non-standard search parameter
each( searchEngines, function ( engine, param ) {
	if ( referrerurlHost.indexOf( '.' + engine + '.' ) !== -1 ) {
		searchParameter = param;
	}
});

// Proceed only if the referrerurl string has a query
if ( referrerurl.indexOf( '?' ) === -1 ) {
	return;
}
else if ( 'jQuery' in win ) {
	jQuery( doc ).ready( searchTermHighlight ); 
}
else if ( 'addEventListener' in win ) {
	win.addEventListener( 'load', searchTermHighlight, false );
}
else if ( 'attachEvent' in win ) {
	win.attachEvent( 'onload', searchTermHighlight );
}
else {
	win.onload = searchTermHighlight();
}




})();
// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Get_Cookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}
// this deletes the cookie when called
function Delete_Cookie( name, path, domain ) {
if ( Get_Cookie( name ) ) document.cookie = name + "=" +
( ( path ) ? ";path=" + path : "") +
( ( domain ) ? ";domain=" + domain : "" ) +
";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}
function GetCurDate()
{
	var d = new Date();
	var curr_date = d.getDate();
	var curr_month = d.getMonth();
	curr_month++;
	var curr_year = d.getFullYear();
	return curr_month + "/" + curr_date + "/" + curr_year;
}
function GetCurTime()
{
	var a_p = "";
	var d = new Date();
	
	var curr_hour = d.getHours();
	
	if (curr_hour < 12)
	   {
	   a_p = "AM";
	   }
	else
	   {
	   a_p = "PM";
	   }
	if (curr_hour == 0)
	   {
	   curr_hour = 12;
	   }
	if (curr_hour > 12)
	   {
	   curr_hour = curr_hour - 12;
	   }
	
	var curr_min = d.getMinutes();

	if (curr_min < 10) {
	    curr_min = "0" + curr_min;
	}

	return curr_hour + ":" + curr_min + " " + a_p;
}