var logDebug = 1;
/** Header

Javascript File: CORE.JS<br>
AUTHOR: Guy MOrazain<br>
Last Modified: August 7, 2007<br>
<p>
This file contains common javascript functionality.<p>

 
**/

function showDebug(msg, clear) {
/**
params:<ul>

msg: message to be displayed<br>
clear: flag controlling the reset of the display<br>
</ul>
 <p>  
if a div with the id 'msgDiv' exists on the page, then 
   msg with be displayed appended to the top of the div's body.<p>
   
if clear is true then div's body will be cleared of previous messages.<p>
<p>
Note: This function is used primarely for debugging javascript.<p>

**/ 


	if (logDebug == 0) {
		return;
	}
	var div = $("msgDiv");
	if (!div) {
		return;
	}
	if (clear) {
		var msgs = "<li><font color='orange'>" + msg + "</font></li>";
	} else {
		var msgs = "<li><font color='orange'>" + msg + div.innerHTML + "</font></li>";
	}
	div.innerHTML = msgs;
	toggleOn("msgDiv");
}
function showError(msg, divId) {
	if (!divId) {
		divId = "msgDiv";
	}
	var div = $(divId);
	if (!div) {
		alert(msg);
		return;
	}
	var msgs = "<li><font color='red'>" + msg + div.innerHTML + "</font></li>";
	div.innerHTML = msgs;
	toggleOn(divId);
}
function $() {
/**

usage: $('abc')  $('abc','def');
params:<ul>

id: Element id, or list of ids<br>
</ul>
 <p>  
returns the element or an array of elements whose id(s) is/are referenced by the specified parameter(s);
**/ 
	var elements = new Array();
	for (var i = 0; i < arguments.length; i++) {
		var element = arguments[i];
		if (typeof element == "string") {
			element = document.getElementById(element);
		}
		if (arguments.length == 1) {
			return element;
		}
		elements.push(element);
	}
	return elements;
}

function getField(fieldId)
{
	var field=document.getElementById(fieldId);
	if (field)
	{
		return field;
	}
}

function detach(divId, doc) {
	toggleOff(divId);
	window.open(doc, "_blank");
}

function toggleOn(element) {
	var e = $(element);
	if (e) {
		e.style.display = "";
	}
}
function toggleOff(element) {
	var e = $(element);
	if (e) {
		e.style.display = "none";
	}
}


function toggle(divId){
  var way=$(divId).style.display;
  if(way=="none"){
      toggleOn(divId);
  } else
      toggleOff(divId);


}

function toggleDiv(divId,url){
  var way=$(divId).style.display;
  if(way=="none"){
      toggleOn(divId);
      loadDivWith(divId,url);
  } else
      toggleOff(divId);


}

function loadDivWithSimple(divId, url) {
	var ax = new AJAXRequest("POST", url, null, function (AJAX) {
		if (AJAX.readyState == 4) {
			if (AJAX.status == 200) {
				$(divId).innerHTML = AJAX.responseText;
			} else {
				//showError("URL" + url + "<br>There was a problem retrieving the XML data:\n" + AJAX.statusText);
				$(divId).innerHTML = "There was a problem retrieving the data:<br>"+ AJAX.statusText;
			}
		}
	}, true);
}

function loadDivWith(divId, url)
{
	var host = window.location.host;
	var pathName = window.location.pathname;
	var contextPath = pathName.substring(0,pathName.indexOf("/", 1));
	var imgUrl = "http://" + host + contextPath + "/images/cc/icons/icon_progressCircles.gif";
	var msg = "<table><tr><td><img src=\"" + imgUrl + "\"/></td></tr></table>";
	$(divId).innerHTML = msg;

	var ax = new AJAXRequest("POST", url, null, function (AJAX) {
		if (AJAX.readyState == 4) {
			if (AJAX.status == 200) {
				$(divId).innerHTML = AJAX.responseText;
					var x = $(divId).getElementsByTagName("script");
					for( var i=0; i < x.length; i++)
					{
						eval(x[i].text);
					}

			} else {
				//showError("URL" + url + "<br>There was a problem retrieving the XML data:\n" + AJAX.statusText);
				$(divId).innerHTML = "There was a problem retrieving the data:<br>"+ AJAX.statusText;
			}
		}
	}, true);
}

 
 
function trim(val)
{
	return Trim(val);
}
 

function Trim(STRING) {
	STRING = LTrim(STRING);
	return RTrim(STRING);
}
function RTrim(STRING) {
	while (STRING.charAt((STRING.length - 1)) == " ") {
		STRING = STRING.substring(0, STRING.length - 1);
	}
	return STRING;
}
function LTrim(STRING) {
	while (STRING.charAt(0) == " ") {
		STRING = STRING.replace(STRING.charAt(0), "");
	}
	return STRING;
}
function Replace(STRING, REPLACE_THIS, REPLACE_WITH) {
	while (STRING.indexOf(REPLACE_THIS) > -1) {
		STRING = STRING.replace(REPLACE_THIS, REPLACE_WITH);
	}
	return STRING;
}
function dbCheck(STRING) {
	if (STRING.indexOf("'") > -1) {
		return false;
	}
}
var _ms_XMLHttpRequest_ActiveX = ""; // Holds type of ActiveX to instantiate
var _ajax;                           // Reference to a global XMLHTTPRequest object for some of the samples
var _logger = true;                  // write output to the Activity Log
var _status_area;                    // will point to the area to write status messages to
BASE_URL = ".";
if (document.location.href.indexOf("www.clearnova.com") > 0) {
	BASE_URL = "/ThinkCAP";
}
if (!window.Node || !window.Node.ELEMENT_NODE) {
	var Node = {ELEMENT_NODE:1, ATTRIBUTE_NODE:2, TEXT_NODE:3, CDATA_SECTION_NODE:4, ENTITY_REFERENCE_NODE:5, ENTITY_NODE:6, PROCESSING_INSTRUCTION_NODE:7, COMMENT_NODE:8, DOCUMENT_NODE:9, DOCUMENT_TYPE_NODE:10, DOCUMENT_FRAGMENT_NODE:11, NOTATION_NODE:12};
}

// Method to get text from an XML DOM object
function getTextFromXML(oNode, deep) {
	var s = "";
	var nodes = oNode.childNodes;
	for (var i = 0; i < nodes.length; i++) {
		var node = nodes[i];
		if (node.nodeType == Node.TEXT_NODE) {
			s += node.data;
		} else {
			if (deep == true && (node.nodeType == Node.ELEMENT_NODE || node.nodeType == Node.DOCUMENT_NODE || node.nodeType == Node.DOCUMENT_FRAGMENT_NODE)) {
				s += getTextFromXML(node, true);
			}
		}
	}
	return s;
}

// If you plan on doing anything outside of North America, then you'd better encode the things you pass back and forth
// the escape() method in Javascript is deprecated -- should use encodeURIComponent if available
function encode(uri) {
	if (encodeURIComponent) {
		return encodeURIComponent(uri);
	}
	if (escape) {
		return escape(uri);
	}
}
function decode(uri) {
	uri = uri.replace(/\+/g, " ");
	if (decodeURIComponent) {
		return decodeURIComponent(uri);
	}
	if (unescape) {
		return unescape(uri);
	}
	return uri;
}
/*
 * AJAXRequest: An encapsulated AJAX request. To run, call
 * new AJAXRequest( method, url, async, process, data )
 *
 */
function executeReturn(AJAX) {
	if (AJAX.readyState == 4) {
		if (AJAX.status == 200) {
			showDebug("AJAXRequest is complete: " + AJAX.readyState + "/" + AJAX.status + "/" + AJAX.statusText);
			if (AJAX.responseText) {
				showDebug(AJAX.responseText);
				showDebug("-----------------------------------------------------------");
				eval(AJAX.responseText);
			}
		}
	}
}
function AJAXRequest(method, url, data, process, async, dosend) {
    // self = this; creates a pointer to the current function
    // the pointer will be used to create a "closure". A closure
    // allows a subordinate function to contain an object reference to the
    // calling function. We can't just use "this" because in our anonymous
    // function later, "this" will refer to the object that calls the function
    // during runtime, not the AJAXRequest function that is declaring the function
    // clear as mud, right?
    // Java this ain't
	var self = this;
	var urlStart = url.toUpperCase().substring(0, 4);
	showDebug("url=" + url + " start:" + urlStart);
	if (urlStart != "HTTP") {
		url = basePath + url;
	}
    // check the dom to see if this is IE or not
	if (window.XMLHttpRequest) {
	// Not IE
		self.AJAX = new XMLHttpRequest();
	} else {
		if (window.ActiveXObject) {
	// Hello IE!
        // Instantiate the latest MS ActiveX Objects
			if (_ms_XMLHttpRequest_ActiveX) {
				self.AJAX = new ActiveXObject(_ms_XMLHttpRequest_ActiveX);
			} else {
	    // loops through the various versions of XMLHTTP to ensure we're using the latest
				var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
				for (var i = 0; i < versions.length; i++) {
					try {
		    // try to create the object
		    // if it doesn't work, we'll try again
		    // if it does work, we'll save a reference to the proper one to speed up future instantiations
						self.AJAX = new ActiveXObject(versions[i]);
						if (self.AJAX) {
							_ms_XMLHttpRequest_ActiveX = versions[i];
							break;
						}
					}
					catch (objException) {
                // trap; try next one
					}
				}
			}
		}
	}
    
    // if no callback process is specified, then assing a default which executes the code returned by the server
	if (typeof process == "undefined" || process == null) {
		process = executeReturn;
	}
	self.process = process;

    // create an anonymous function to log state changes
	self.AJAX.onreadystatechange = function () {
        //showDebug("AJAXRequest Handler: State =  " + self.AJAX.readyState);
		self.process(self.AJAX);
	};

    // if no method specified, then default to POST
	if (!method) {
		method = "POST";
	}
	method = method.toUpperCase();
	if (typeof async == "undefined" || async == null) {
		async = true;
	}
	showDebug("AJAX Request: " + ((async) ? "Async" : "Sync") + "<br>" + method + "<br>URL: " + url + "<br>Data: " + data);
	self.AJAX.open(method, url, async);
	if (method == "POST") {
		self.AJAX.setRequestHeader("Connection", "close");
		self.AJAX.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		self.AJAX.setRequestHeader("Method", "POST " + url + "HTTP/1.1");
	}

    // if dosend is true or undefined, send the request
    // only fails is dosend is false
    // you'd do this to set special request headers
	if (dosend || typeof dosend == "undefined") {
		if (!data) {
			data = "";
		}
		self.AJAX.send(data);
	}
	return self.AJAX;
}
function isEmpty(a){  var b=Trim(a);  return b=="";}

function getValue(elmId){
	 var elmVal="";
     if($(elmId).type =='select-one'){
       var options= $(elmId).options;
       var ind= $(elmId).selectedIndex;
       elmVal=options[ind].text;
 
    } else {
       elmVal=$(elmId).value;
    	
    }
    return elmVal;
}


function getValueId(elmId){
	 var elmVal="";
     if($(elmId).type =='select-one'){
       var options= $(elmId).options;
       var ind= $(elmId).selectedIndex;
       elmVal=options[ind].value;
 
    } else {
       elmVal=$(elmId).value;
    	
    }
    return elmVal;
}
function checkInvalidEmailFormat(pEmail)
{
	var hasInvalidEmailFormat = false;
	var email = getField(pEmail);
	if (!isEmpty(email.value))
	{
		if (!isValidEmail(email.value))
		{
			email.className="invalidEmailField";
			hasInvalidEmailFormat=true;
		}
	}
	return hasInvalidEmailFormat;
}
function isValidEmail(email)
{
	atPos = email.indexOf("@");
	stopPos = email.lastIndexOf(".");
	endPos = email.length;

	if (atPos == -1 || stopPos == -1)
	{
		return false;
	}

	if (stopPos < atPos)
	{
		return false;
	}

	if (stopPos - atPos == 1)
	{
		return false;
	}
	if (stopPos == (endPos -1)){
	  return false;
	}
	return true;
}

function makePrintable(divID) {
	var printable=window.open();
	printable.document.write($(divID).innerHTML);
	printable.document.close();
}

