////////////////////////////////////////////////////////////////////////////////////////
//
//  Ajax Functions for WebForms
//  Written by: April Luan & Mike Gonyea
//  Additional code snippets provided by:
//  (documented separately)
//

// xmlHttp Object (used for Ajax calls)
var xmlHttp;
var shouldShowProgress = false;

// Gets the XMLHttpRequest Object - REQUIRED for use of Ajax throughout system
function GetXmlHttpObject()
{ 
	if (xmlHttp && xmlHttp.readyState < 4) { xmlHttp.abort(); }
	
	var objXMLHttp = null;
	var msg = "";
	try {
	  objXMLHttp = new XMLHttpRequest();
	} catch (tryMS_2) {
  		try {
			objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP");
  		} catch (tryMS_original) {
    		try {
      			objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
    		} catch (failed) {
      			objXMLHttp = null;
			}
		}
	}
	return objXMLHttp;
}

//Function for loading in specified element using a specified image source
function showProgressImage(element, imageSrc) {
	element.innerHTML="<img src='" + imageSrc + "' alt='Loading'>";
}

//Function for uloading in specified element using a specified image source
function hideProgressImage(element) {
	element.innerHTML="";
}

// Shows a progress DIV with a specified message
function showProgress(progText) {
//	return; 
//	progText = "Loading...";
	
	var viewTop = 0;
	var viewLeft = 0;
	var sTop = 0;
	var sLeft = 0;
	
	if (typeof(window.innerWidth) == 'number') {
		//Non-IE
		viewLeft += window.innerWidth;
		viewTop += window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		viewLeft += document.documentElement.clientWidth;
		viewTop += document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		viewLeft += document.body.clientWidth;
		viewTop += document.body.clientHeight;
	}

  	if (typeof(window.pageYOffset) == 'number') {
		//Netscape compliant
		sLeft += window.pageXOffset;
		sTop += window.pageYOffset;
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		//DOM compliant
		sLeft += document.body.scrollLeft;
		sTop += document.body.scrollTop;
	} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		//IE6 standards compliant mode
		sLeft += document.documentElement.scrollLeft;
		sTop += document.documentElement.scrollTop;
	}
	
	document.getElementById('progressIndicator').style.top = (((viewTop - 100) / 2) + sTop)+"px";
	document.getElementById('progressIndicator').style.left = (((viewLeft - 350) / 2) + sLeft)+"px";

	document.getElementById('progressText').innerHTML = progText;
	document.getElementById('progressIndicator').style.display = "block";
	document.getElementById('progressIndicator').style.zIndex = 10000;
}

// Hides the progress window
function hideProgress() {
//	return; 
	document.getElementById('progressText').innerHTML = "";
	document.getElementById('progressIndicator').style.display = "none";
	// if (xmlHttp) { xmlHttp.responseText = ""; }
}

// Hilites the specified table row in kit/clause/form list
function hiliteRow(obj,flag) {
	if (obj == selectedRow) { return; }
	if (flag == true) {
		obj.style.backgroundColor = "#DFEAEC"; 
	} else {
		obj.style.backgroundColor = obj.bgColor;
	}
}

// Selects (activates as current) specified table row in kit/clause/form list
function selectRow(obj,kitID) {
	// alert(obj);
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	obj.style.backgroundColor = "#D6E6E5";
	
	if (document.kitList.kitAction.value == kitID) { document.kitList.kitAction.checked = true; }
	else {
		for (i=0; i < document.kitList.kitAction.length; i++){
			if (document.kitList.kitAction[i].value == kitID){
				document.kitList.kitAction[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#D6E6E5";
	selectedRow = obj;
//	toggleKitForms(kitID);
}

// selects a clause row
function selectClause(obj,clauseID) {
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	
	if (document.kitList.clauseAction.value == clauseID) { document.kitList.clauseAction.checked = true; }
	else {
		for (i=0; i < document.kitList.clauseAction.length; i++){
			if (document.kitList.clauseAction[i].value == clauseID){
				document.kitList.clauseAction[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#C5E2E9";
	selectedRow = obj;
}

// selects a reminder row
function selectReminder(obj,reminderID) {
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	
	if (document.kitList.selReminder.value == reminderID) { document.kitList.selReminder.checked = true; }
	else {
		for (i=0; i < document.kitList.selReminder.length; i++){
			if (document.kitList.selReminder[i].value == reminderID){
				document.kitList.selReminder[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#C5E2E9";
	selectedRow = obj;
}

// selects a email row
function selectEmail(obj,emailID) {
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	
	if (document.kitList.selEmail.value == emailID) { document.kitList.selEmail.checked = true; }
	else {
		for (i=0; i < document.kitList.selEmail.length; i++){
			if (document.kitList.selEmail[i].value == emailID){
				document.kitList.selEmail[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#C5E2E9";
	selectedRow = obj;
}

// Selects (activates as current) specified table row in custom clause categories list
function selectCategory(obj,catID) {
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	obj.style.backgroundColor = "#D6E6E5";
	
	if (document.catList.catAction.value == catID) { document.catList.catAction.checked = true; }
	else {
		for (i=0; i < document.catList.catAction.length; i++){
			if (document.catList.catAction[i].value == catID){
				document.catList.catAction[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#D6E6E5";
	selectedRow = obj;
//	toggleKitForms(kitID);
}

// selects a lawyer row
function selectLawyer(obj,lawyerID) {
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	
	if (document.kitList.selLawyer.value == lawyerID) { document.kitList.selLawyer.checked = true; }
	else {
		for (i=0; i < document.kitList.selLawyer.length; i++){
			if (document.kitList.selLawyer[i].value == lawyerID){
				document.kitList.selLawyer[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#C5E2E9";
	selectedRow = obj;
}

// selects an office template row
function selectOfficeTemplate(obj,templateID) {
	if (selectedRow != null && selectedRow != obj) { selectedRow.style.backgroundColor = selectedRow.bgColor; }
	
	if (document.kitList.selTemplate.value == templateID) { document.kitList.selTemplate.checked = true; }
	else {
		for (i=0; i < document.kitList.selTemplate.length; i++){
			if (document.kitList.selTemplate[i].value == templateID){
				document.kitList.selTemplate[i].checked = true;
			}
		}
	}
	
	obj.style.backgroundColor = "#C5E2E9";
	selectedRow = obj;
}

// tabs1 is used by the tabbing system throughout the site
function tabs1(tab){
var ar = document.getElementById("tabs").getElementsByTagName("td");
	
	for (var i=0; i<ar.length; i++){ 
		if (ar[i].id != "none"){
				if (ar[i].id == "side_left"){
					ar[i].className = "tab_available_left";
				}
				else if (ar[i].id == "side_right"){
					ar[i].className = "tab_available_right";
				}
				else {
					ar[i].className="tab_available";
				}
		}
	}
	ar[tab-1].className="tab_current_left";
	ar[tab].className="tab_current";
	ar[tab+1].className="tab_current_right";
	sortDirection = "DESC";
}

var storedAction = "";

// This function stores (via Ajax) a set of session variables that can be retrieved/modified/etc.
// in subsequent scripts
function sessionStore(urlString,custAction,changePath) {
	xmlHttp = GetXmlHttpObject();
	if (!xmlHttp) { alert("Your browser doesn't support AJAX"); return; }
	
//	var params = URLEncode(urlString);
	var params = urlString;
	
	var url = "";
	if (custAction != "") { storedAction = custAction; }
	if (changePath != undefined && changePath != "") { url += changePath; }
	url += "includes/misc.inc.php";

	var postData = "action=sessionStore&inAjax=Y&params="+URLEncode(params);
	// alert(url);

//	xmlHttp.onreadystatechange=doSessionStore;
	xmlHttp.open("POST",url,true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", postData.length);
	xmlHttp.setRequestHeader("Expires",new Date(0));
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.onreadystatechange = function () { doSessionStore(); };
	xmlHttp.send(postData);
//	xmlHttp.close();
}

// Performs the custom action (if any) that was provided to the sessionStore function
function doSessionStore() {
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
		if (storedAction != "") {
			var tAction = storedAction;
			storedAction = "";
			eval(tAction);
		}
	}
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function URLEncode(plaintext)
{
	// 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 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;
}

// Parses out the <script> tags within the returned (usu Ajax) code and runs the javascript
// - also, sets the innerHTML of the "targetElement" to the non-JS code within the passed string
function parseAJAX(htmlCode,targetElement) {
	// Check the response text and parse out any JS script tags so we
	// can 'eval' them (run them)
	var respText = htmlCode;
	var jsEvalCode = "";
	var beginScript = respText.indexOf('<script');
	
	while (true) {
		// Looks like we have JS code, so parse it out and evaluate it
		beginScript = respText.indexOf('<script');
		if (beginScript < 0) { break; }
		
		var endScript = respText.indexOf('/script');
		var jsScript = respText.substr(beginScript,(endScript-beginScript-1));
		var endStartTag = jsScript.indexOf('>');
		jsEvalCode += jsScript.substr(endStartTag+1);
//		var beforeJS = respText.substr(0,beginScript-1);
		var beforeJS = respText.substr(0,beginScript);
		var afterJS = respText.substr(endScript+8);
		respText = beforeJS+afterJS;
	}

	targetElement.innerHTML=respText;

	if (jsEvalCode != "") {
		jsEvalCode += ";";
		jsEvalCode = stripComments(jsEvalCode);
		eval(jsEvalCode);
	}
}

// Strip out comments within HTML/JS code
function stripComments(htmlCode) {
	var startComment = htmlCode.indexOf('<!--');
	var endComment = htmlCode.indexOf('//-->');
	var preCode = "";
	var postCode = "";
	
	while (true) {
		startComment = htmlCode.indexOf('<!--');
		endComment = htmlCode.indexOf('//-->');

		if (startComment < 0 && endComment < 0) { break; }
		
		if (startComment >= 0) {
			preCode = htmlCode.substr(0,startComment);
			postCode = htmlCode.substr(startComment+4);
			htmlCode = preCode+postCode;
		}
		
		endComment = htmlCode.indexOf('//-->');
		if (endComment >= 0) {
			preCode = htmlCode.substr(0,endComment);
			postCode = htmlCode.substr(endComment+5);
			htmlCode = preCode+postCode;
		}
	}
	return htmlCode;
}

var activeEditor;

function FCKeditor_OnComplete(editorInstance) {
	activeEditor = editorInstance;
}

function trim(strText) { 
    
    while (strText.substring(0,1) == ' ') 
        strText = strText.substring(1, strText.length);

    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
}

function getBrowserCookie(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 "";
}

function getJSScriptPath() {
	var docLoc = new String(window.location);
	var fsPos = 0;
	for (var i=0; i < 4; i++) {
		fsPos = docLoc.indexOf("/",fsPos+1);
	}

	var retstr = docLoc.substr(0,fsPos);
	return retstr;
}

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=/";
}

// Shows a DIV in the middle of the screen
function centreDIVOnScreen(theDIV,wid,hgt) {
	var viewHeight = 0;
	var viewWidth = 0;
	var sTop = 0;
	var sLeft = 0;
	
	if (typeof(window.innerWidth) == 'number') {
		//Non-IE
		viewWidth += window.innerWidth;
		viewHeight += window.innerHeight;
	} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
		//IE 6+ in 'standards compliant mode'
		viewWidth += document.documentElement.clientWidth;
		viewHeight += document.documentElement.clientHeight;
	} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
		//IE 4 compatible
		viewWidth += document.body.clientWidth;
		viewHeight += document.body.clientHeight;
	}

  	if (typeof(window.pageYOffset) == 'number') {
		//Netscape compliant
		sLeft += window.pageXOffset;
		sTop += window.pageYOffset;
	} else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		//DOM compliant
		sLeft += document.body.scrollLeft;
		sTop += document.body.scrollTop;
	} else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
		//IE6 standards compliant mode
		sLeft += document.documentElement.scrollLeft;
		sTop += document.documentElement.scrollTop;
	}
	
	document.getElementById(theDIV).style.width = wid+"px";
	document.getElementById(theDIV).style.height = hgt+"px";
	
	document.getElementById(theDIV).style.top = (((viewHeight - hgt) / 2) + sTop)+"px";
	document.getElementById(theDIV).style.left = (((viewWidth - wid) / 2) + sLeft)+"px";
}
