
var url_add = "proxy.php"; 		//url of the proxy which is used to relay the AJAX requests
var tog=1;						//Variable which is used in initializing the script of HP
var ck_security = 'a3d4feji45g8we5kio87';	
var ck_array = ['id', 'nick', 'c6346359c72f0d28e27a'];	
var ck_result = [];
var root_ck = "http://roohit.org/get_root_ck.php";

var home_domain = 'roohit.org';


var highliter_loaded = false;
var hp_form_loaded = false;
var loaded_hp_text = ""

var restore_url = URLEncode(window.location.href);

var hash_secure_start = 'hdf4t56dfg5gsr2w';
var hash_secure_end = 'ty6dgber23es1q2s';


var orig_hash = location.hash;
var url_to_replace = window.location.href;




if (orig_hash !="")
{	
url_with_hash = window.location.href;
url_without_hash = url_with_hash.substring(0, url_with_hash.indexOf(orig_hash));
restore_url = URLEncode(url_without_hash);	//current page URL. Used in loading of HP
}

if (orig_hash == "")
{
	url_to_replace = url_to_replace + "#";
}


var url_root = "";

if (orig_hash != "")
	{
		url_root = 'http://roohit.org/get_root_ck.php?url=' + restore_url + '&hash=' + URLEncode(orig_hash);
	}
else
	{
		url_root = 'http://roohit.org/get_root_ck.php?url=' + restore_url;
	}
	
var id_root='ck_frame';


var urlide= "http://roohit.org/index.php?url=" + restore_url + "&hponly=1";		//Request URL made to roohit.org






function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}






function generate_iframe(id, url) {				//Function to create an iframe dynamically of 1px X 1px, and display none.
  var IFrameObj;
  if (!document.createElement) {return true};
  var IFrameDoc;
  //var URL = 'http://www.mabaloo.com';
 if (!IFrameObj && document.createElement) {
    // create the IFrame and assign a reference to the
    // object to our global variable IFrameObj.
    // this will only happen the first time 
    // callToServer() is called
   try {
      var tempIFrame=document.createElement('iframe');
      tempIFrame.setAttribute('id',id);
	  tempIFrame.setAttribute('name',id);
      tempIFrame.style.border='0px';
      tempIFrame.style.width='1px';
      tempIFrame.style.height='1px';
	  tempIFrame.style.display='none';
      IFrameObj = document.body.appendChild(tempIFrame);
      
      if (document.frames) {
        // this is for IE5 Mac, because it will only
        // allow access to the document object
        // of the IFrame if we access it through
        // the document.frames array
        IFrameObj = document.frames[id];
      }
    } catch(exception) {
      // This is for IE5 PC, which does not allow dynamic creation
      // and manipulation of an iframe object. Instead, we'll fake
      // it up by creating our own objects.
      iframeHTML='\<iframe id="RSIFrame" style="';
      iframeHTML+='border:0px;';
      iframeHTML+='width:0px;';
      iframeHTML+='height:0px;';
      iframeHTML+='"><\/iframe>';
      document.body.innerHTML+=iframeHTML;
      IFrameObj = new Object();
      IFrameObj.document = new Object();
      IFrameObj.document.location = new Object();
      IFrameObj.document.location.iframe = document.getElementById(id);
      IFrameObj.document.location.replace = function(location) {
        this.iframe.src = location;
      }
    }
  }

  
  if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
    // we have to give NS6 a fraction of a second
    // to recognize the new IFrame
    setTimeout('callToServer()',10);
    return false;
  }
  
  if (IFrameObj.contentDocument) {
    // For NS6
    IFrameDoc = IFrameObj.contentDocument; 
  } else if (IFrameObj.contentWindow) {
    // For IE5.5 and IE6
    IFrameDoc = IFrameObj.contentWindow.document;
  } else if (IFrameObj.document) {
    // For IE5
    IFrameDoc = IFrameObj.document;
  } else {
    return true;
  }
  
  IFrameDoc.location.replace(url);
  return false;
}



function URLEncode(url)						//Function to encode URL.
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var plaintext = url;
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};


function URLDecode(url)				//function decode URL
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = url;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while

   return plaintext;
};


function createCookie(name,value,days)
{
	if (days) 
	{
	var date = new Date();
	date.setTime(date.getTime()+(days*24*60*60*1000));
	var expires = "; expires="+date.toGMTString();
	}

	else 
		{
		var expires = "";
		}

	document.cookie = name+"="+value+expires+"; path=/";
}



function readCookie(name) 
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) 
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}

	return null;
}



function eraseCookie(name) 
{
	createCookie(name,"",-1);
}



function exec_initialize_when_ready()    	//executes only after IE loads and create function initialize 
{

	try
	{
		if (tog == 1) 
		{
		initialize();
		tog =0;	
		}
	}
	catch(exc)
	{	
		setTimeout("exec_initialize_when_ready();", 200);
	}

}



function init_js_rewrite() //executes only when IE creates all objects
{
	try
	{
	if(initialize);
	}
	catch(exc)
	{
		setTimeout("init_js_rewrite();", 200);
		return 0;
	}

	var win_doc = window.document;
	$("popup").style.visibility = "visible";
	//init.js lines are follows 
		//ommit  if (top == self)
	$("minimized").style.top = 0;
	$("minimized").style.left = (win_doc.body.clientWidth - parseInt($("minimized").style.width )-6) + 'px' ; 
	$("popup").style.top = 0;
	$("popup").style.left = (win_doc.body.clientWidth - parseInt($("popup").style.width )-6) + 'px' ; 
	$("reduce").style.top = 0;
	$("reduce").style.left = (win_doc.body.clientWidth - parseInt($("reduce").style.width )-6) + 'px' ; 
	exec_initialize_when_ready();//waits till script file will be loaded and ready to use
	//actb($('mail_for_link'),usercontacts);
	//end of init.js code
}





function createXMLHttp()  
{  
	if (typeof XMLHttpRequest != "undefined")    
		{   return new XMLHttpRequest();   }   
   else if (window.ActiveXObject)    
   		{   var aVersions = [ "MSXML2.XMLHttp.5.0",         "MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",         "MSXML2.XMLHttp","Microsoft.XMLHttp"       ];    
			for (var i = 0; i < aVersions.length; i++)    
				{    
				try      
					{     
					var oXmlHttp = new ActiveXObject(aVersions[i]);     
					return oXmlHttp;
					}     
				catch (oError)      
					{    
					//Do nothing
					}
				}  
		}   
	throw new Error("XMLHttp object could be created."); 
} 



function do_post(url, data, suc) 
{ 
	var url_post=url;
	var oXmlHttp = createXMLHttp(); 
	oXmlHttp.open("post", url_add , true); 
	oXmlHttp.onreadystatechange = function ()	{  
												if (oXmlHttp.readyState == 4) 
													{   
														if (oXmlHttp.status == 200) 
															{    
															var response ;    
															response = oXmlHttp.responseText;
															if(response == "a3d4fe")
																{
																alert('An error occured while loading the highlighter.');
																}
															else
																{											
																var t_st = response.indexOf("<script>");
																var t_en = response.indexOf("</script>");
																eval(response.substring(t_st+8,t_en));    
																save_ck_back(response.substring(t_en+9,response.length-1)); 
																if(suc==onMailResponse)
																	{
																		suc(URLDecode(y)); 
																	}
																else
																	{
																		var transport = new Object;
																		transport.responseText = URLDecode(y); 
																		suc(transport);
																	}
																	
																}  
															}
													} 
												};
	oXmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	var data_post="";
	if (data != "" && data != null) data_post = "&"  + data;
	var self_url = URLEncode(window.location.href);
	oXmlHttp.send('a3d4fe=' + URLEncode(url_post) +   data_post);
} 


function analyze(transport) 
{ 
	
	var response = transport.responseText;
	loaded_hp_text = transport.responseText;
	
	hp_form_loaded = true;
	
	//if (clicked == true || readCookie('open') == 'auto')
	//{
		add_hp_form();
		init_js_rewrite();
		eraseCookie('open');
		highliter_loaded = true;
	//}
} 


function add_hp_form()
{
	document.body.innerHTML += loaded_hp_text;
	document.getElementById("sesid").value = trim(document.getElementById("sesid").value);
	
	if (document.getElementById("frm_login"))
	{
		var v = document.getElementById("frm_login");
		v.onsubmit = function () { createCookie("open","auto",'1'); }
	}
			
		
	if (document.getElementById("logout_link"))
	{
		var v = document.getElementById("logout_link");
		v.onclick = function () { createCookie("open","auto",'1');  }
	}
}


function start()
{

	if (highliter_loaded == false && hp_form_loaded == true && clicked == false)
		{
			add_hp_form();
			init_js_rewrite();
			clicked = true;
			highliter_loaded = true;
		}
		
	else if (highliter_loaded == false && clicked == false && hp_form_loaded == false)
		{
			clicked = true;
		}
	else if (highliter_loaded == false && clicked == true)
	{
		if (chk_home()) {alert("Please wait Highliter is loading");}
	}
	else if (highliter_loaded == true)
	{
		if (chk_home()) {alert("Highliter is already loaded");}
	}

}

function save_ck_back(res)
{ 
	if (res.indexOf("[name]")==-1) 
		{  
			return;  
		}   

	var st =""; 
	var en=""; 
	var ck=""; 
	var val=""; 
	var t=1; 

	while (t==1) 
		{  
		st = res.indexOf("[name]");  
		en = res.indexOf("[value]");  
		ck = res.substring(st+10,en-13);  
		res = res.substring(en+11);  
		en = res.indexOf(")");  
		val = res.substring(0,en-9);  
		if (ck =='id')
		{
		createCookie(ck,val,1);
		generate_iframe("temp1", root_ck+"?url=" + ck + "&value=" + val);
		}
		res = res.substring(en);  
		if (res.indexOf("[name]") == -1)  t=0; 
		} 
} 




function start_load(ck)
{
	ck_result = ck;
	for (i=0;i<ck_array.length;i++)
	{
		if (ck_result[i] !=	ck_security)
			{
				createCookie(ck_array[i],ck_result[i],'1');
			}
		else
			{
				eraseCookie(ck_array[i]);
			}
	}
	do_post(urlide,"",analyze); 
}



function chk_home()
{
	
var chkStr = window.location.href;

if (chkStr.indexOf(home_domain) == 0 || chkStr.indexOf('http://' + home_domain) == 0 || chkStr.indexOf('www.' + home_domain) == 0 || chkStr.indexOf('http://www.' + home_domain) == 0)
	{
		return false;
	}
else
	{
		return true;
	}
	
}



function checkForMessages()
{
	if(location.hash != orig_hash)
		{
			lastId = URLDecode(location.hash);
			window.location.href = url_to_replace;
			if (lastId.indexOf(hash_secure_start) != -1)
				{	
					var start_ck = lastId.indexOf(hash_secure_start) + hash_secure_start.length;
					if (lastId.indexOf(hash_secure_end) != -1)
					{
						var end_ck = lastId.indexOf(hash_secure_end);
						ck_result = URLDecode(lastId.substring(start_ck, end_ck)).split(',');
						window.clearInterval(intval);
						//alert(ck_result);
						start_load(ck_result);
					}
				}
		}
}


function starte()
{
if (chk_home())
{	
	intval = setInterval(checkForMessages, 200);
	generate_iframe(id_root, url_root);
}
}

