/*******************************************************************************

	Exceptional SLEEP Framework.
	Copyright Peter Kaplan & Exceptional IT Services Inc 2007-2010
		
	$Date$
	$Rev$
	$Author$

*******************************************************************************/
// **********************************************************************
// This file is for javascript that will be used throughout the system
// **********************************************************************
function addslashes(str) {
str=str.replace(/\'/g,"\'");
str=str.replace(/\"/g,'\"');
str=str.replace(/\\/g,'\\');
str=str.replace(/\0/g,'\0');
return str;
}
// **********************************************************************
function stripslashes(str) {
str=str.replace(/\\'/g,'\'');
str=str.replace(/\\"/g,'"');
str=str.replace(/\\\\/g,'\\');
str=str.replace(/\\0/g,'\0');
return str;
}
// **********************************************************************
var g_code = null;
function SLEEPCredentials( keycode)
{
	g_code = keycode;
}
// **********************************************************************
SLEEP_SendForm = function (  url, form_name, successFunc)
{

	var formObject = document.getElementById( form_name);
	var uri = SLEEP_BuildURI( form_name);
	YAHOO.util.Connect.setForm(formObject, true, true);
//	alert( url + "?" + uri);
	
	// This example facilitates a POST transaction.  The POST data(HTML form)
	// are initialized when calling setForm(), and it is automatically
	// included when calling asyncRequest.
	var cObj = YAHOO.util.Connect.asyncRequest('POST', url, {
		                success: function(obj) {
							if (obj.argument.finish)
								obj.argument.finish( obj.argument.type, obj.responseText);
			                },
		                failure: function(obj) {
							if (obj.argument.failureFunc)
								obj.argument.failureFunc( obj.argument.type, obj.responseText);
			                },
						upload: function(obj) {
							if (obj.argument.finish)
								obj.argument.finish( obj.argument.type, obj.responseText);
			                },
						argument: { 
							address: url, 
							finish:successFunc}
		            	}, uri);
}
// **********************************************************************
SLEEP_LoadURL = function ( type, url, successFunc, failureFunc, postData)
{
	YAHOO.util.Connect.asyncRequest( type, url, 
						{
		                success: function(obj) {
							if (obj.argument.finish)
								obj.argument.finish( obj.argument.type, obj.responseText);
			                },
		                failure: function(obj) {
							if (obj.argument.failureFunc)
								obj.argument.failureFunc( obj.argument.type, obj.responseText);
			                },
						argument: { 
							type:type, 
							address: url, 
							finish:successFunc, 
							failure: failureFunc}
		            	}, 
		            	postData);
}
// **********************************************************************
SLEEP_UpdateContent = function (ele, url, successFunc, failureFunc)
{

	SLEEP_LoadURL( 'GET', url, function(type, response) {  
	
							var result_obj = eval('(' + response + ')');
								if (result_obj.resultcode >=0) {
									SLEEP_Replace_innerHTML( ele, result_obj.data);
								}
								else {
									SLEEP_Replace_innerHTML( ele, result_obj.message);
								}
							if (successFunc)
								successFunc( ele, result_obj.data);
	}, failureFunc, null);
		            	
}
// **********************************************************************
function SLEEP_Replace_innerHTML( element, html_string)
{
	// If we doing have an element
	// Get out of here
	if (!element) return;
	
	// This is the reg exp for finding the items between <script> tags
	var reg_scripts = "<script[^>]*>(.|\s|\n|\r)*?</script>";
	

	// replace the html with the new html once we have removed the scripts
	var theElement = document.getElementById( element);
	if (theElement)
		theElement.innerHTML = html_string.replace(new RegExp(reg_scripts, "gim"), "");;

	// See if we have any scripts to run
	var our_scripts = html_string.match(new RegExp(reg_scripts, "gim"));
	if (our_scripts) {
		var count = our_scripts.length;
		for (var i = 0; i < count; i++) {
			var s = our_scripts[i].replace(/<script[^>]*>[\s\r\n]*(<\!--)?|(-->)?[\s\r\n]*<\/script>/img, "");
			eval(s);
		}
	}

};
// **********************************************************************
function SLEEP_RunScriptsFromHTML( html_string)
{
	// This is the reg exp for finding the items between <script> tags
	var reg_scripts = "<script[^>]*>(.|\s|\n|\r)*?</script>";
	
	// See if we have any scripts to run
	var our_scripts = html_string.match(new RegExp(reg_scripts, "gim"));
	if (our_scripts) {
		var count = our_scripts.length;
		for (var i = 0; i < count; i++) {
			var s = our_scripts[i].replace(/<script[^>]*>[\s\r\n]*(<\!--)?|(-->)?[\s\r\n]*<\/script>/img, "");
			eval(s);
		}
	}

};


// **********************************************************************
function SLEEP_BuildURI( form_name)
{	
	var theForm = document.getElementById( form_name);
	var uri = '';
	var already_selected = false;

	if (theForm != null) {
	   for (i = 0; i < theForm.length; i++) {
	   		if (theForm.elements[i].type == undefined || 
	   			theForm.elements[i].name == undefined ||
	   			theForm.elements[i].name == "") {
	   		
	   		}
	   		else if (theForm.elements[i].type == "radio") {
				if (theForm.elements[i].checked) {
					// We Handle the radio button
				   if (i == 0)
						uri+= theForm.elements[i].name + "=";
				   else
						uri+= "&" + theForm.elements[i].name + "=";
				
					uri+= encodeURIComponent(addslashes(theForm.elements[i].value));
				}
			}
	   		else {
	   
			   if (i == 0)
					uri+= theForm.elements[i].name + "=";
			   else
					uri+= "&" + theForm.elements[i].name + "=";
		   
				if (theForm.elements[i].type == "checkbox") {
					if (theForm.elements[i].checked)
						uri+= "Y";
					else
						uri+= "N";
				}
				else if (theForm.elements[i].type == "select-multiple") {
					already_selected = false;
					for ( j = 0; j < theForm.elements[i].length; j++) {
						if (theForm.elements[i].options[j].selected) {
							if (already_selected)  uri+='--';
							uri+= theForm.elements[i].options[j].value;
							already_selected = true;
						}
					}
				}
				else {
						uri+= encodeURIComponent(addslashes(theForm.elements[i].value));
				}
			}
	   }
   }
return uri;
}
//****************************************************************
function SLEEP_PostURLAsync( url, uri, completion) 
{
	SLEEP_LoadURL( "POST", url, completion, null, uri);
}
// **********************************************************************
function SLEEP_PostURL_Completion( type, text) 
{
	if (isNaN( text)) {
        SLEEP_Replace_innerHTML( 'save_progress', "Error: Could not save");
    }
    else {
        SLEEP_Replace_innerHTML( 'save_progress', "");
    }
}
//*******************************************************************
function AdjustUIFields( )
{
	SLEEP_Replace_innerHTML( 'save_progress', "Unsaved Changes");
}
// **********************************************************************
function SLEEP_FadeElement( element, url){

	SLEEP_LoadURL ( 'GET', 'framework/tmpl/loading.tmpl',  function( type, text) {
		SLEEP_Replace_innerHTML( element, text);

		SLEEP_LoadURL( "GET", url, function( type, response) {
		
		
			var result_obj = eval('(' + response + ')');
				if (result_obj.resultcode >=0) {
					FadeOpacity( element, 100, 0, 1, 15);			
					SLEEP_Replace_innerHTML( element, result_obj.data);
					FadeOpacity( element, 0, 100, 250, 10);			
				}
				else {
					SLEEP_Replace_innerHTML( element, result_obj.message);
				}
		
		}, null, null
		);

	}, null, null);
}

// **********************************************************************
function ReturnToModule( mod, func, inactive)
{	
	var	uri = "?module=" + mod + "&function=" + func;
	if (inactive == 'Y')
		uri += "&inactive=Y";
		
	document.location.search = uri;
}
// **********************************************************************
function PadDigits(n, totalDigits) 
{ 
	n = n.toString(); 
	var pd = ''; 
	if (totalDigits > n.length) 
	{ 
		for (i=0; i < (totalDigits-n.length); i++) 
		{ 
			pd += '0'; 
		} 
	} 
	return pd + n.toString(); 
} 
//*******************************************************************
function resize_iframe( )
{
	mainRgn = document.getElementById('main_rgn');
	frameRgn = document.getElementById('iframe_id');	
	if (mainRgn && frameRgn) {
		frameRgn.height = mainRgn.offsetHeight - 1;
		frameRgn.width = mainRgn.offsetWidth - 1;
	}
}
//*******************************************************************
function Menu_Go( uri)
{		
	document.location.href = uri;
}
//*******************************************************************

var g_Our_Program_Name = 'EXECPTIONAL_SANDBOX';

function SLEEP_SetProgram( name)
{
	g_Our_Program_Name = name;
}
//*******************************************************************
function SLEEP_SetCookie(cookieName, cookieValue, nDays) {
 var today = new Date();
 var expire = new Date();
 
 
 
 if (nDays==null || nDays==0) nDays=1;
 expire.setTime(today.getTime() + 3600000*24*nDays);
 document.cookie = g_Our_Program_Name + "_" + cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}
//*******************************************************************
function SLEEP_GetCookie(c_name)
{

c_name = g_Our_Program_Name + "_" + c_name;
if (document.cookie.length>0)
  {
  c_start=document.cookie.indexOf(c_name + "=");
  if (c_start!=-1)
    { 
    c_start=c_start + c_name.length+1; 
    c_end=document.cookie.indexOf(";",c_start);
    if (c_end==-1) c_end=document.cookie.length;
    return unescape(document.cookie.substring(c_start,c_end));
    } 
  }
return "";
}
//*******************************************************************
function SLEEP_Menu_Install()
{
            /*
                 Initialize and render the MenuBar when its elements are ready 
                 to be scripted.
            */

            YAHOO.util.Event.onContentReady("our_eits_menu", function () {

                /*
                     Instantiate a MenuBar:  The first argument passed to the 
                     constructor is the id of the element in the page 
                     representing the MenuBar; the second is an object literal 
                     of configuration properties.
                */

                var oMenuBar = new YAHOO.widget.MenuBar("our_eits_menu", { 
 //                                                          autosubmenudisplay: true, 
                                                            hidedelay: 750, 
                                                            lazyload: true });

                /*
                     Call the "render" method with no arguments since the 
                     markup for this MenuBar instance is already exists in 
                     the page.
                */

                oMenuBar.render();

            });


}

// -------------------------------------------------------------------------
//  Name: SelectOptionInList
//  Abstract: Given a select list and an ID search the list for the option with
//                  the matching ID and select it.
// -------------------------------------------------------------------------
function SelectOptionInList( lstSelectList, intID )
{
    try
    {
          var intIndex = 0;
          // Loop through all the options
          for( intIndex = 0; intIndex < lstSelectList.options.length; intIndex++ )
          {
                // Is this the ID we are looking for?
                if( lstSelectList.options[intIndex].value == intID ) 
                {
                      // Select it
                      lstSelectList.selectedIndex = intIndex;
                      // Yes, so stop searching
                      break;
                }
          }
    }
    catch( expError )
    {
          alert( "ClientUtilities1.js::SelectOptionInList( ).\n" +
                      "Error:" + expError.number + ", " + expError.description );
    }
} // SelectOptionInList



function SetOpacity(elem, opacityAsInt)
{
	var opacityAsDecimal = opacityAsInt;
	
	if (opacityAsInt > 100)
		opacityAsInt = opacityAsDecimal = 100; 
	else if (opacityAsInt < 0)
		opacityAsInt = opacityAsDecimal = 0; 
	
	opacityAsDecimal /= 100;
	if (opacityAsInt < 1)
		opacityAsInt = 1; // IE7 bug, text smoothing cuts out if 0
	
	elem.style.opacity = opacityAsDecimal;
	elem.style.filter  = "alpha(opacity=" + opacityAsInt + ")";
}

function FadeOpacity(elemId, fromOpacity, toOpacity, time, fps)
{
	var steps = Math.ceil(fps * (time / 1000));
	var delta = (toOpacity - fromOpacity) / steps;
	
	FadeOpacityStep(elemId, 0, steps, fromOpacity, delta, (time / steps));
}

function FadeOpacityStep(elemId, stepNum, steps, fromOpacity, delta, timePerStep)
{
    SetOpacity(document.getElementById(elemId), Math.round(parseInt(fromOpacity) + (delta * stepNum)));

    if (stepNum < steps)
        setTimeout("FadeOpacityStep('" + elemId + "', " + (stepNum+1) + ", " + steps + ", " + fromOpacity + ", " + delta + ", " + timePerStep + ");", timePerStep);
}
