//////////////////////////////////////////////////////////////////
// !!! WARNING !!!                                              //
// While using this Script inside an existing HTML, make sure   //
// that it is included / paste at the very end of the document  //
// or else the document.write function of JavaScript which      //
// makes the iFrame URLs, stops the existing page from showing  //
// up as usual.                                                 //
// Explanation of this bug? is given in Post 8 at:              //
// http://www.dynamicdrive.com/forums/showthread.php?t=30450    //
//////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////
// Step 1                                                       //
// Check if a Cookie Pre-Exists, if it does, do nothing,        //
// if it doesn't, make a new one!                               //
// This is to avoid two things:                                 //
// a) Avoiding the script from killing an existing Cookie when  //
//    the URL is accessed without making any queries.           //
//    i.e. http://www.domain.tld/ ... instead of                //
//         http://www.domain.tld/file.ext?something=something   //
// b) Avoid overwriting an existing Cookie which was made by    //
//    the referring partner, http://www.domain-A.tld with a     //
//    new Cookie which another referring partner,               //
//    http://www.domain-B.tld would like to make.               //
// Script Received from                                         //
// http://techpatterns.com/downloads/javascript_cookies.php     //
//////////////////////////////////////////////////////////////////

// this fixes an issue with the old method, ambiguous values
// with this test document.cookie.indexOf( name + "=" );
function Do_Cookie_Check( 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 = ""; // used to be null instead of "" 
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return ""; // used to be null instead of "" 
	}
}

//////////////////////////////////////////////////////////////////
// Do a Cookie Check to see if the Cookie Name returned "null"  //
// if it did return "null", then run Step 2 onwards or else     //
// do nothing as shown in the end, on line 240                  //
//////////////////////////////////////////////////////////////////
if ( Do_Cookie_Check( 'kcreferrer' ) == "") // used to be null instead of "" 
{ 


//////////////////////////////////////////////////////////////////
// Step 2                                                       //
// Getting URL and Setting the VAR ...                          //
// Script Received from                                         //
// http://www.netlobo.com/url_query_string_javascript.html      //
// To Test:                                                     //
// http://www.domain.tld/file.ext?referrer1=some_referrer_word  //
//////////////////////////////////////////////////////////////////

function gup( name )
{
    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];}

var referrer1_param = gup( 'referrer1' );
//document.write("-------------------------"); // Commented out as in realtime, these statements are not needed.
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.
//document.write(referrer1_param); // Commented out as in realtime, these statements are not needed.
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.
//document.write("-------------------------"); // Commented out as in realtime, these statements are not needed.
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.
// Step 2 - Ended ...


//////////////////////////////////////////////////////////////////
// Step 3                                                       //
// Entire Cookie Function ...                                   //
// Script Received from                                         //
// http://techpatterns.com/downloads/javascript_cookies.php     //
// By default, this step creates AND deletes the Cookie, so     //
// make sure to delete OR comment-out the "Delete_Cookie"       //
// function from Line 203 to Line 205.                          //
// Because mostly, we won't want the Cookie to be deleted, but  //
// rather expire in the number of days mentioned in the         //
// "Set_Cookie" function on Line 198                            //
//////////////////////////////////////////////////////////////////

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" : "" );
}


// 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";
}


// remember, these are the possible parameters for Set_Cookie:
// name, value, expires, path, domain, secure
Set_Cookie( 'kcreferrer', referrer1_param, '365', '/', '', '' );
//if ( Get_Cookie( 'kcreferrer' ) ) alert( Get_Cookie('kcreferrer')); // Commented out as in realtime, these statements are not needed.
// 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('kcreferrer', '/', '');
( Get_Cookie( 'kcreferrer' ) ) ? alert( Get_Cookie('kcreferrer')) :
alert( 'it is gone');*/
// Step 3 - Ended ...


//////////////////////////////////////////////////////////////////
// Step 4                                                       //
// Function to create iFrame's URL which sends the variable     //
// to the iFrame's PHP file to update the visitor counter       //
// in the MySQL Database.                                       //
// The URL is made partially with the help of the               //
// "referrer1_param" created above in Step 2                    //
//////////////////////////////////////////////////////////////////
function WriteiFrameURL () { 
var iFrameLocation = "referrer_counter.php?referrer1_param="+referrer1_param; 
document.write('<iframe src="' + iFrameLocation + '" name="test_referrer_counter" id="test_referrer_counter" width="20" height="20"  frameborder="0" allowTransparency="true">'); 
} 
//////////////////////////////////////////////////////////////////
// Learnt the hard way, that unlike PHP, JavaScripts can't have //
// same function names in If-Then-Else Statements. So have to   //
// convert the Function to a VAR                                //
//////////////////////////////////////////////////////////////////
var WriteiFrameURL = WriteiFrameURL (); 
// Step 4 - Ended ...

//////////////////////////////////////////////////////////////////
// Closing the "If" Statement for Step 1, started at Line 71    //
// which helps Step 1 to execute further and go to the rest     //
// of the Steps.                                                //
//////////////////////////////////////////////////////////////////
}

//////////////////////////////////////////////////////////////////
// But if a Cookie already exist with some value in it, then    //
// do nothing as shown below.                                   //
//////////////////////////////////////////////////////////////////
else {
var Pre_Existing_Cookie_Value = Do_Cookie_Check( 'kcreferrer' );
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.
//document.write("Cookie already exists with the value"); // Commented out as in realtime, these statements are not needed.
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.
//document.write(Pre_Existing_Cookie_Value); // Commented out as in realtime, these statements are not needed.
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.
//document.write("So I'm gonna do nothing!"); // Commented out as in realtime, these statements are not needed.
//document.write("<br>"); // Commented out as in realtime, these statements are not needed.


//////////////////////////////////////////////////////////////////
// Step 5                                                       //
// Function to create iFrame's URL which sends the variable     //
// to the iFrame's PHP file to update the visitor counter       //
// in the MySQL Database.                                       //
// The URL is made partially with the help of the               //
// "Pre_Existing_Cookie_Value" created just above.              //
//////////////////////////////////////////////////////////////////
function WriteiFrameURL2 () { 
var iFrameLocation = "referrer_counter.php?referrer1_param="+Pre_Existing_Cookie_Value; 
document.write('<iframe src="' + iFrameLocation + '" name="test_referrer_counter" id="test_referrer_counter" width="20" height="20"  frameborder="0" allowTransparency="true">'); 
} 
var WriteiFrameURL = WriteiFrameURL2 (); 
// Step 5 - Ended ...

//////////////////////////////////////////////////////////////////
// Closing the "Else" Statement, started at Line 240            //
// which helps Step 5 to execute further.                       //
//////////////////////////////////////////////////////////////////
}

