/*
	NetMinistry/VOSpace Javascript Core Kit v1.0	(Replaces inline <head> functions)

	Created by CPruitt Monday, January 30, 2006 4:16:25 PM
	This file defines constants, classes, functions & subs used for managing the template system

*/

vLoader = '<table border=0 cellpadding=0 cellspacing=0 width=100% height=100%><tr valign=middle><td align=center><img src=/images/gui/loading1.gif border=0 width=32 height=32><br><b>Loading...</b></td></tr></table>';

/*  Function to output system messages & alerts  */

function nmAddSystemMessage(messageToAdd){
	nmOpenSystemFeedbackView()
	return nmAddToSystemFeedback('nm_system_message_view', messageToAdd);
}

function nmAddSystemAlert(messageToAdd){
	nmOpenSystemFeedbackView()
	return nmAddToSystemFeedback('nm_system_alert_view', messageToAdd);
}

function nmAddSystemError(messageToAdd){
	nmOpenSystemFeedbackView()
	return nmAddToSystemFeedback('nm_system_error_view', messageToAdd);
}

function nmOpenSystemFeedbackView() {
	document.getElementById('nm_system_feedback_view').style.display='block'
}

function nmAddToSystemFeedback(IDOfMessageContainer, messageToAdd){
	if (document.getElementById(IDOfMessageContainer)) {
		var targetFeedbackView = document.getElementById(IDOfMessageContainer);
		testString = new String(messageToAdd)
		if(testString.length > 0) {
			targetFeedbackView.innerHTML = targetFeedbackView.innerHTML + '<div>' + messageToAdd + '</div>';
			}
		targetFeedbackView.style.display='block';
		return true;
	} else {
		return false;
	}
}

function nmDisplaySystemFeedback(IdOfMessageContainer, messageToAdd){
	var targetFeedbackView = document.getElementById(IdOfMessageContainer);
	targetFeedbackView.innerHTML = targetFeedbackView.innerHTML + '<div>' + messageToAdd + '</div>';
	targetFeedbackView.style.display='block';
	return true;
}


/*  WIndow & Display Controls  */


// Simple Open a new window
function nmPopWin(v_url, v_windowName, v_width, v_height){
	window.open(v_url, v_windowName, "width=" + v_width + ",height=" + v_height);
}

// Open a new window with scroll bars
function nmPopWinWithScroll(v_url, v_windowName, v_width, v_height){
	window.open(v_url, v_windowName, "scrollbars=1,width=" + v_width + ",height=" + v_height);
}

/*  Generic Use Functions  */
function nmHandleError(){
	alert('An error has occurred.  You may experience trouble viewing this page.');
	return true;
}

function nmSupressError(){
	return true;
}





//	Toggle Visability by element ID

function nmToggleDisplay(element_id)
{
	if (document.getElementById(element_id)) {
		toggleElement = document.getElementById(element_id);
		elementStatus = toggleElement.style.display
		if (elementStatus == 'none')
		{
			toggleElement.style.display = 'block';
		} else {
			toggleElement.style.display = 'none';
		}
		return true;
	} else {
		return false;
	}
}

function nmToggleOverflow(element_id, opt1, opt2)
{
	if (document.getElementById(element_id)) {
		toggleElement = document.getElementById(element_id);
		elementStatus = toggleElement.style.overflow
		if (elementStatus == opt1)
		{
			toggleElement.style.overflow = opt2;
		} else {
			toggleElement.style.overflow = opt1;
		}
		return true;
	} else {
		return false;
	}
}

function nmSetInnerHTMLOfElementOfClass_toValue(fv_className, fv_newVal)
{
	arr = nmGetElementsByClassName(fv_className)
	for (i=0; i<arr.length; i++)
	{
		arr[i].innerHTML = fv_newVal;
	}
}
			
function nmGetElementsByClassName(fv_className){
	var idx = 0;
	returnArray = Array;
	if (document.getElementsByTagName())
	{
		var tagColletion = document.getElementsByTagName("*");
	
	} else if (document.all) {
		var tagColletion = document.all;
	}
	for (i=0; i < tagColletion.length; i++)
	{
		if (tagColletion[i].className==fv_className)
		{
			returnArray[idx]=tagColletion[i];
			idx++;
		}
	}
	//alert(returnArray.length)
	return returnArray;
}




/*  DEBUGGING FUNCTIONS  */

function nmLog(logVal)
{
	console_id_string = 'javascript_debug_console';
	if (document.getElementById(console_id_string))
	{
		strCurrentLogVal = document.getElementById(console_id_string).value;
		document.getElementById(console_id_string).value = strCurrentLogVal  + '\n\n' + logVal;
	} else {
		if (false) {
			alert('nmLog(): ' + logVal);
		}
	}
}




/*  Function to gracefully append a function to the body.onload event  */
function nmAppendOnload(func) {
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		var oldonload = window.onload;
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

//		Let the system know that this kit was successfully loaded
var nmcore_kit_loaded = true;
















var gAjaxSupressAllAlerts = false;
window.onbeforeunload = function(){
    gAjaxSupressAllAlerts = true;
}


/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
/*                      BORROWED LIBRARY                      */
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/



/**
SAL - Simple Ajax Lib. 23-Sep-2005
by Nigel Liefrink
Email: leafrink@hotmail.com
*/

var debug = false;
/**
Browser Compatability function.
Returns the correct XMLHttpRequest depending on the current browser.
*/
function GetXmlHttp()
{	
	var xmlhttp = false;
	if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
	}
		else if (window.ActiveXObject)	// code for IE
	{
		try
		{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp=false;
			}
		}
	}
	//alert('XMLReq OK');
	return xmlhttp;
}


/**
<summary>
Gets the response stream from the passed url, and then calls the callbackFuntion passing the response and the div_ids.
</summary>
<param name="url">The url to make the request to get the response data.</param>
<param name="callbackFunction">The function to call after the response has been recieved. the response <b>must</b> always be the first argument to the function.</param>
<param name="params"> (optional) Any other parameters you want to pass to the functions. (Note: only constants/strings/globals can be passed as params, most variables will be out of scope.) </param>
</summary>
<example>
	<code>
PassAjaxResponseToFunction('?getsomehtml=1', 'FunctionToHandleTheResponse', "\'div1\',\'div2\',\'div3\'');

function FunctionToHandleTheResponse(response, d1, d2, d3){
	var data = response.split(';');
	document.getElementById(d1).innerHTML = data[0];
	document.getElementById(d2).innerHTML = data[1];
	document.getElementById(d3).innerHTML = data[2];
}
	</code>
</example>
*/
function PassAjaxResponseToFunction(url, callbackFunction, params)
{
	debug = true;
	if (debug) { nmLog('Preparing to send XMLHTTP...'); }
	 var xmlhttp = new GetXmlHttp();
	 if (debug) { nmLog('New XMLHTTP OK...'); }
	 //now we got the XmlHttpRequest object, send the request.
	 if (xmlhttp)
	 {
	 	try
	 	{
			xmlhttp.onreadystatechange = 	function ()
											{
												debug = true;
												if (debug) { nmLog('State Change: ' + xmlhttp.readyState); }
												if (xmlhttp && (xmlhttp.readyState==4))
												{	//we got something back..
													if (xmlhttp.status==200)
													{
														var response = xmlhttp.responseText;
														var functionToCall = callbackFunction+'(response,'+params+')';
														if(debug)
														{
															nmLog(response);
															nmLog (functionToCall);
														}
													    eval(functionToCall);
													} else if(debug) {
														if(!gAjaxSupressAllAlerts){
														    alert('PassAjaxResponseToFunction Debug Flag - ' + xmlhttp.responseText);
														} else {
														    //alert('Error when leaving page.');
														}
														
													}
												}
											}
			
			
			// prob
			nmLog('AJAX Lib Sending to: ' + url);
			xmlhttp.open("GET",url,true);
			xmlhttp.send(null);
		} 
		
		catch(e_err)
		
		{
			if (debug) { 'PassAjaxResponseToFunction: ' + nmLog(e_err); }
		}
		
		
		
			
		
	 } else {
	 	nmLog('Error: No XML Object');
	 	alert('Error: No XML Object');
	 }
}


function PassAjaxResponseToFunctionUsingPost(url, formData, callbackFunction, params)
{
	debug = true;
	if (debug) { nmLog('Preparing to send XMLHTTP with POST...'); }
	 var xmlhttp = new GetXmlHttp();
	 if (debug) { nmLog('New XMLHTTP OK...'); }
	 //now we got the XmlHttpRequest object, send the request.
	 if (xmlhttp)
	 {
	 	try
	 	{
			xmlhttp.onreadystatechange = 	function ()
											{
												debug = true;
												if (debug) { nmLog('State Change: ' + xmlhttp.readyState); }
												if (xmlhttp && (xmlhttp.readyState==4))
												{	//we got something back..
													if (xmlhttp.status==200)
													{
														var response = xmlhttp.responseText;
														var functionToCall = callbackFunction+'(response,'+params+')';
														if(debug)
														{
															nmLog('PassAjaxResponseToFunctionUsingPost::SeadyStateChange.Function::Response - ' + response);
															//nmLog (functionToCall);
														}
													eval(functionToCall);
													
													} else if(debug) {
														alert('PassAjaxResponseToFunction Debug Flag - ' + xmlhttp.responseText);
													}
												}
											}
			
			
			// prob
			nmLog('AJAX Lib Sending to: ' + url);
			nmLog('AJAX Lib FORM DATA: ' + formData);
			xmlhttp.open("POST",url,true);
			xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xmlhttp.send(formData);
		} 
		
		catch(e_err)
		
		{
			if (debug) { 'PassAjaxResponseToFunction: ' + nmLog(e_err); }
		}
		
		
		
			
		
	 } else {
	 	nmLog('Error: No XML Object');
	 	alert('Error: No XML Object');
	 }
}


/**
///<summary>
///Sets the innerHTML property of obj_id with the response from the passed url./
///</summary>
///<param name="url">The url to make the request to get the response data.</param>
///<param name="obj_id">The object or the id of the object to set the innerHTML for.</param>
*/
function SetInnerHTMLFromAjaxResponse(url, obj_id)
{		
	var xmlhttp = new GetXmlHttp();
	//now we got the XmlHttpRequest object, send the request.
	if (xmlhttp)
	{
		xmlhttp.onreadystatechange = 	function () 
										{
											debug = false;
											if (xmlhttp && xmlhttp.readyState==4)
											{//we got something back..
												if (xmlhttp.status==200)
												{
													if(debug)
													{
														alert(xmlhttp.responseText);
													}
													
													if(typeof obj_id == 'object'){
														obj_id.innerHTML = xmlhttp.responseText;
													} else {
														document.getElementById(obj_id).innerHTML = xmlhttp.responseText;
													}
												} else if(debug){
													alert(xmlhttp.responseText);
												}
											}
										}
	xmlhttp.open("GET",url,true);
	xmlhttp.send(null);
	}
}


function formatCurrency(num)
{
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	{
		num = "0";
	}
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	{
		cents = "0" + cents;
	}
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	{
		num = num.substring(0,num.length-(4*i+3))+','+ num.substring(num.length-(4*i+3));
	}
	
	return (((sign)?'':'-') + '' + num + '.' + cents);
}


// Will find any <textarea> with a maxlength="" attribute and limit it's
// length accordingly on key up.  Also limits on paste but only with ctrl+v.
// otherwise catches paste only on blur.
// Should be called on page load
function initTextareaMaxLength() {
    $('textarea[maxlength]').bind('keydown paste', function () {
        $(this).data('maxLengthValueCache', $(this).val());
    });
    $('textarea[maxlength]').bind('keyup click blur', function () {
        var s = $(this).val();
        var s2;
        var max = parseInt($(this).attr('maxlength'));
        var notice = $(this).attr('maxlengthlabel');
        var previous = $(this).data('maxLengthValueCache');
        if (s.length > max) {
            s2 = s.substr(0, max);
            if (s.length - previous.length > 1) {
                // If we've changed length by more than one character per event then we'll assume a paste.
                $(this).val(s2);
                alert('You have pasted too much text.  This field is limited to ' + max + ' characters.');
            } else {
                $(this).val(previous);
                if ($(this).val().length > max) {
                    $(this).val(s2);
                }
                alert('You have entered too much text.  This field is limited to ' + max + ' characters.');
            }

        }
        if (notice != '') {
            $('#' + notice).html('You have ' + (max - ($(this).val().length)) + ' characters remaining.');
        }
    });
}


