///////////////////////////////////////////////////////////////////
//
//	Title: 		eRSP Javascript Functions Library
//	Created:	6/2/2005
//	Modified:	-
//	
////////////////////////////////////////////////////////////////////

// Place all functions that need to be run after page load in here
jQuery(document).ready(function(){
	onloadFunctions();
});
function onloadFunctions() {
	try{
		startList();
	}catch(e){}
}
// This will load the function upon page load

function toggleElements(element,classVar,activate)
// Usage:
// onclick="toggleElements('TD','myClass','true');"
// Placement:
// in the action element, such as a radio or checkbox 
{
	// element is the type of element to search for to toggle (e.g. TD, DIV, P)
	// classVar is the name of the class to activate the toggle on, the "element" above must have that class
	// activate is a boolean to show or hide the element
	// can be used with (condition) ? "true" : "false"; inside the activate statement for more control
	
	var elemArray = document.getElementsByTagName(element);
	for(var x = 0; x < elemArray.length; x++ )
	{
		if(elemArray[x].className == classVar)
		{
			if (activate == "true")
			{
				elemArray[x].style.display = 'none';
			}
			else
			{
				elemArray[x].style.display = '';
			}
			
		}
	}
}


function switchFormOnOff(switchElement,form,formElements)
// Usage:
// onClick="switchFormOnOff(this,'form1','start1,end1');"
// Placement:
// in the action element, such as a radio or checkbox 
{ 
	// switchElement is the Radio Button or Form that contains the function with the onClick event
	// form is the name of the form that contains the elements in "string" format
	// formElements is a comma delimited string of elements to turn on/off in "string" format

	var srcEle = window.event.srcElement;
	var srcElemValue = document.getElementById(srcEle.id);		
	var elementArray = formElements.split(",");
	
	if (srcElemValue.value == "off")
	{
		for (var i=0; i < elementArray.length; i++)
		{
			var obj = eval("document." + form + "." + elementArray[i]);
			obj.style.display = 'none';
		}
	}
	else
	{
		for (var i=0; i < elementArray.length; i++)
		{
			var obj = eval("document." + form + "." + elementArray[i]);
			obj.style.display = '';
		}
	}
}


// ----------------------------------------------------------

function clickDeactivate(id,msg)
// Usage:
// onSubmit="clickDeactivate('AddBlkSubmit','Adding Block(s)');"
// Placement:
// in the form declaration <form onsubmit="">
{
	try{
		var node = document.getElementById(id); // Get the Node we want to work on
	
		node.style.display = 'none'; // Hide the node
		newNode = document.createElement('BUTTON'); // Create a new Button to replace it
		newNode.disabled = true; // Disable the new Button
		newNode.style.fontSize = '12px'; //Change the font size
		newNode.innerHTML = msg; // Add the message passed into the function to the button
		//node.parentNode.appendChild(newNode); // Display the new button
		node.parentNode.insertBefore(newNode,node); // Display the new button (using new insertBefore method)
	}catch(e){}
}



// ----------------------------------------------------------
function eRSPFormValidation(formObj) {
// Usage: 
// onsubmit="return eRSPFormValidation(this)"
// Placement:
// in the form declaration <form onsubmit="">
// For each field that needs validation, give it a class of the function name below (vText, vSelect, etc.)

   var fName, cleanName, x, obj;

   for(var x = 0; x < formObj.length; x++ ){
		if(formObj.elements[x].className == 'vText' || formObj.elements[x].className == 'vSelect') {
			fName = formObj.elements[x].className; // Use the class name as the function to call	
			obj = document.getElementById(formObj.elements[x].id);
			obj.style.backgroundColor = "";
			//alert('Processing:'+ fName+"(obj.id)") // Debugging
			if (!eval(fName+"(obj.id)")) return false; // If field fails validation, stop						
		}		
	}
	return result;
}

function ErrorMsg(FormObj,Text){
// Display an error message, and highlight the field that needs attention
   FormObj = document.getElementById(FormObj);
   FormObj.focus(); // Send the cursor back to the field
   FormObj.style.backgroundColor = "#FFFFCA"; // Highlight the field yellow
   alert(Text); // Display the error message
}


function vText(FormObj) {
// Return false if "string" is empty or all blank
	FormObj = document.getElementById(FormObj);
	var String = FormObj.value;
	if (String.length == 0) {
		ErrorMsg(FormObj.id,'Cannot leave field blank.');
		return(false);
	}
	for (var i=0; i < String.length; i++) {
		if (String.substring(i) != " ") {return (true);}
	}
}

function vSelect(FormObj) {
// Return false if a blank option is selected
	FormObj = document.getElementById(FormObj);
	var String = FormObj.options[FormObj.selectedIndex].value
	if (String.length == 0) {
		ErrorMsg(FormObj.id,'Please select an option.');
		return(false);
	}
	for (var i=0; i < String.length; i++) {
		if (String.substring(i) != " ") {return (true);}
	}
}

function vDecimal(FormObj) {
// Return false if a non decimal value is entered
	FormObj = document.getElementById(FormObj);
	re = /^[\d\.]+$/
	if (re.test(FormObj.value)) {
		return (true);
	} else {
		ErrorMsg(FormObj.id,'Field must be a number.');
		return(false);		
	}
}




// ----------------------------------------------------------


function dateAdd(intval, numb, base){
	/*intval is YYYY, M, D, H, N, S as in VBscript; numb is amount +/-; base is javascript date object*/
	switch(intval){
		case "M":
			base.setMonth(base.getMonth() + numb);
			break;
		case "YYYY":
			base.setFullYear(base.getFullYear() + numb);
			break;
		case "D":
			base.setDate(base.getDate() + numb);
			break;
		case "H":
			base.setHours(base.getHours() + numb);
			break;
		case "N":
			base.setMinutes(base.getMinutes() + numb);
			break;
		case "S":
			base.setSeconds(base.getSeconds() + numb);
			break;
		default:
	}
	return base
}

function dateFormat(aDate, displayPat){
	/********************************************************
	Example Usage: 
	alert(dateFormat(new Date() , "!yyyy !dd !mmm"))

	*   Valid Masks:
	*   !mmmm = Long month (eg. January)
	*   !mmm = Short month (eg. Jan)
	*   !mm = Numeric date (eg. 07)
	*   !m = Numeric date (eg. 7)
	*   !dddd = Long day (eg. Monday)
	*   !ddd = Short day (eg. Mon)
	*   !dd = Numeric day (eg. 07)
	*   !d = Numeric day (eg. 7)
	*   !yyyy = Year (eg. 1999)
	*   !yy = Year (eg. 99)
   ********************************************************/

	intMonth = aDate.getMonth();
	intDate = aDate.getDate();
	intDay = aDate.getDay();
	intYear = aDate.getFullYear();

	var months_long =  new Array ('January','February','March','April',
	   'May','June','July','August','September','October','November','December')
	var months_short = new Array('Jan','Feb','Mar','Apr','May','Jun',
	   'Jul','Aug','Sep','Oct','Nov','Dec')
	var days_long = new Array('Sunday','Monday','Tuesday','Wednesday',
	   'Thursday','Friday','Saturday')
	var days_short = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat')

	var mmmm = months_long[intMonth]
	var mmm = months_short[intMonth]
	var mm = intMonth < 9?'0'+ (1 + intMonth) + '':(1+intMonth)+'';
	var m = 1+intMonth+'';
	var dddd = days_long[intDay];
	var ddd = days_short[intDay];
	var dd = intDate<10?'0'+intDate+'':intDate+'';
	var d = intDate+'';
	var yyyy = intYear;

	century = 0;
	while((intYear-century)>=100)
	century = century + 100;

	var yy = intYear - century
	if(yy<10)
	yy = '0' + yy + '';

	displayDate = new String(displayPat);

	displayDate = displayDate.replace(/!mmmm/i,mmmm);
	displayDate = displayDate.replace(/!mmm/i,mmm);
	displayDate = displayDate.replace(/!mm/i,mm);
	displayDate = displayDate.replace(/!m/i,m);
	displayDate = displayDate.replace(/!dddd/i,dddd);
	displayDate = displayDate.replace(/!ddd/i,ddd);
	displayDate = displayDate.replace(/!dd/i,dd);
	displayDate = displayDate.replace(/!d/i,d);
	displayDate = displayDate.replace(/!yyyy/i,yyyy);
	displayDate = displayDate.replace(/!yy/i,yy);

	return displayDate;
}

function changeDate(id, currDate, days, format)
// Usage:
// onChange="changeDate('element1','6/12/2005',7);"
// Placement:
// in the action element, such as a radio or checkbox 
{
	// id is the id name of element to insert the new date into
	// currDate is the value of the date you want to add days to
	// days is the number of days you want to add to the currDate

	//get the Element we want to change
	var elem = document.getElementById(id);

	//Add the correct # of days to the current Date
	var newDate = new Date(currDate);
	newDate = dateAdd("D", days, newDate);
	
	//Insert the new date, formatted using the dateFormat function
	elem.innerHTML = dateFormat(newDate , format);
}

function getTime () {
	
	var now = new Date();
	var hours = now.getHours();
	var minutes = now.getMinutes();
	var seconds = now.getSeconds()
	var timeValue = "" + ((hours >12) ? hours -12 :hours)
	if (timeValue == "0") timeValue = 12;
	timeValue += ((minutes < 10) ? ":0" : ":") + minutes
	//timeValue += ((seconds < 10) ? ":0" : ":") + seconds
	timeValue += (hours >= 12) ? " PM" : " AM"
	
	return timeValue;
	
}


function unCheckAll(field, checked)
// Usage:
// onClick="unCheckAll(document.form.checkbx, this.checked)"
// Placement:
// in the action element, such as a radio or checkbox 
{	
	if(field.length) {
		for (i = 0; i < field.length; i++) {		
				field[i].checked = checked ;
		}	
	} else {
		field.checked = checked;
	}	
}

// ----------------------------------------------------------------------------------------------------------------------------
// Opens a new Browser Window as a popup
  function openWindow(windowURL,windowName,windowWidth,windowHeight)
	{
		if (windowWidth == null)
		{
			windowWidth = 700;
		}
		if (windowHeight == null)
		{
			windowHeight = 500;
		}

		var winl = (screen.width-windowWidth)/2;
		var wint = (screen.height-windowHeight)/2;
		if (winl < 0) winl = 0;
		if (wint < 0) wint = 0;

		var g = document.getElementById('popup_container');  // gets the ID of the DIV to show/hide
		if(isdefined('g')) {
			g.style.display = 'none'; // Hide the Popup Container
		}

		//Create the Window
		window.name = 'parentWnd';
		newWindow = window.open(windowURL,windowName,'width='+windowWidth+',height='+windowHeight+',top='+wint+',left='+winl+',toolbar=0,location=0,directories=0,status=0,menuBar=0,scrollBars=yes,resizable=0');
		newWindow.focus();
	}
/* DEPRECATED
// ----------------------------------------------------------------------------------------------------------------------------
// Optional Code to auto hide the Floater Div
	function hidePopup()
	{
		if (overdiv != 1)
		{
			var g = document.getElementById('popup_container');  // gets the ID of the DIV to show/hide
			g.style.display = 'none';
		}
	}
*/
// ----------------------------------------------------------
// Navigation Menu

startList = function() {
	
	$(".eRSPMenu_topNav li").each(function(){
		$(this).hover(function(){
			$(this).addClass("over");
		},function(){
			$(this).removeClass("over");	
		});		
	});
	$("ul.eRSPMenu_sub_nav1 li,ul.eRSPMenu_sub_nav2 li").each(function(){
		$(this).hover(function(){
			$(this).addClass("subover");
		},function(){
			$(this).removeClass("subover");	
		});		
	});
				}

// Private Functions 
function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

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 to call upon Resource Dropdown Change
// Pass in the ID of the confirmation checkbox and the resource dropdown
// must have the autoConfirm option as a class in the option tags
function updateConfirm(confirmNodeID,resourceNodeID) {
	if ($("option[value="+$("#"+resourceNodeID).val()+"]").attr("class") == 1) {
		$("#"+confirmNodeID).attr("checked",true);
	} else {
		$("#"+confirmNodeID).attr("checked",false);
	}
}

String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};


function showModalNew( argObj ){		
	
	this.url = argObj.url || "";
	this.titleText = argObj.titleText || "";
	this.loadCallBack = argObj.loadCallBack || {};
	this.height = argObj.height || 250;
	this.width = argObj.width || Math.max($(window).width()/2,400);
	this.showOverlay = argObj.showOverlay || true;
	this.buttons = argObj.buttons || {};	
	
	var newDiv = document.createElement("div");			
	
	$(newDiv).attr("id","eRSPDialog");
	
	$(newDiv).load(this.url,this.loadCallBack);
	
	// Append it to the page
	$("body").append(newDiv);
	
	// Create the Dialog box
	// ,overlay: {opacity: 0.50, background: "black"}
	if(!!this.showOverlay == true){
		$(newDiv).dialog({
			modal: true,
			title: this.titleText,
			width: this.width,
			height: this.height,
			overlay: {
				opacity: 0.50,
				background: "black"
			},
			buttons: this.buttons
		}); 				
	}else{
		$(newDiv).dialog({modal:true,title:this.titleText,width:this.width,height:this.height}); // ,overlay: {opacity: 0.50, background: "black"}
	}		
	$('.ui-dialog-titlebar-close').click(closeModal); // destroys modal instead of closing

}	


function showModal(url,titleText,loadCallBack,height,width,showOverlay){	
	
	showModalNew({url: url, titleText : titleText, loadCallBack : loadCallBack, height : height, width : width, showOverlay : showOverlay });
	
	

}	

function showAlert(html,classVar,titleText,buttonsObj){		
	var newDiv = document.createElement("div");
	var divWidth = Math.max($(window).width()/2,400);
	html = unescape(html);

	if(arguments.length < 2){
		classVar = "alert";
		titleText = "&nbsp;";
	} else if(arguments.length < 3){
		titleText = "&nbsp;";
	} else if(arguments.length < 4){
		buttonsObj = {};  // Example: { "Ok": function() { $(this).dialog("close"); }}
	}
	
	// Populate the Dialog box w/ the HTML
	$(newDiv).html(html);
	$(newDiv).attr("class",classVar);
	$(newDiv).attr("id","eRSPDialogAlert");
	
	// Append it to the page
	$("body").append(newDiv);
		
	// Create the Dialog box
	$(newDiv).dialog({autoOpen: false,modal:true,title:titleText,width:divWidth, buttons: buttonsObj});
	$(newDiv).dialog('open');	
	
	if(classVar == "alert"){
		$(newDiv).parent().attr("id","eRSPDialogAlertContainer");
	}
		

	$('.ui-dialog-overlay').click(closeModal); // clicking outside modal closes modal.
	$('.ui-dialog-titlebar-close').click(closeModal); // destroys modal instead of closing
	
	
}	

function closeModal(){
	//$("div[id*=eRSPDialog]").remove();	
	$("div[id*=eRSPDialog]").dialog("close");	// Changed when updated to 1.6RC2
	$(".ui-dialog").remove();
	$("#eRSPDialog").remove();
}	

function showNotice(html){

	var newDiv = document.createElement("div");
	$(newDiv).attr("id","msgDiv");
	$(newDiv).attr("class","notice ui-corner-all");
	var wHeight = $(window).height();
	var wWidth = $(window).width();
	$(newDiv).html(html);
	
	$("body").append(newDiv);
	$(newDiv).animate({opacity: 1.0}, 2500).fadeOut('slow', function() {
	  $(newDiv).remove();
	});
	var nWidth = (wWidth / 2) - ($(newDiv).width() / 2);
	if($.browser.msie) { /* IE Hack */
		var nHeight = document.body.scrollTop + 100;
	}else{
		var nHeight = window.pageYOffset + 100;	
	}

	$(newDiv).css({
	   left			: 		nWidth + 'px',
	   top			: 		nHeight + 'px'
	});

}



var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		//alert("The date format should be : mm/dd/yyyy")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		//alert("Please enter a valid month")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		//alert("Please enter a valid day")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		//alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		//alert("Please enter a valid date")
		return false
	}
return true
}


// Custom JQuery Functions -----------------

jQuery.fn.showHighlight = function() {		
	$(this).show("highlight", {"color": "#D9E7FF"}, 1000);	
};
jQuery.fn.hideHighlight = function() {
	$(this).hide("highlight", {"color": "#FFCC80"}, 500);
};
// override validate date function
jQuery.validator.methods.date = function(value, element) {
	return (value.length)?isDate(value):true;
};

jQuery.validator.addMethod("invalidChars", function(value, element, param) { 	
	var re = eval('/[' + param + ']/gi');
    return this.optional(element) || value.match(re) == null; 
}, "Invalid characters.");
jQuery.validator.addMethod("phoneUS", function(phone_number, element) {
    phone_number = phone_number.replace(/\s+/g, ""); 
	return this.optional(element) || phone_number.length > 9 &&
		//phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/);
		phone_number.match(/^(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})$/);
}, "Please specify a valid phone number");


jQuery.fn.ajaxSortTable = function(url, settings) {
	// Call on a table, pass in a form and an ID to load the returned ajax data
	// $("#customerListTable").ajaxSortTable("includes/ajax/controller.cfm?action=custListing",{form : "customerList", dataElement:"customerListingTBody"});
	settings = jQuery.extend({	   
	   form			:	"",
	   callback		:   function(){}
	}, settings);

	var tableObj = this;
	var tableTBody = $(tableObj).find("tbody");

	// do the rest of the plugin, using url and settings
	$(this).find("thead th[id]").addClass("sortable");
	$(this).find("thead th[id]").toggle(function(){
		loadAsc(this);
	},function(){
		loadDesc(this);
	});
	
	var colCount = $(this).find("thead th").length;	
	var loadingHTML = "<tr><td colspan='" + colCount + "' style='height:200px;'><div class='loading'></div></td></tr>";
	
	function loadAsc(e){
		var qString = "ajax=y&";
		if(settings.form.length){qString = qString + $("#" + settings.form).formSerialize();}
		$(tableObj).find("thead th").removeClass("headerSortDown");
		$(tableObj).find("thead th").removeClass("headerSortUp");
		if($("input#sort").length == 0){qString = qString + "&sort=" + $(e).attr("id");}
		if($("input#direction").length == 0){qString = qString + "&direction=" + "asc";}		 		
		$(e).addClass("headerSortDown");
		$("input#sort").val($(e).attr("id"));
		$("input#direction").val("asc");
		
		$(tableTBody).html(loadingHTML);
		$.get(url, qString, function(data){
			$(tableTBody).html(data);
			settings.callback();
		});		
	}
	function loadDesc(e){
		var qString = "ajax=y&";
		if(settings.form.length){qString = qString + $("#" + settings.form).formSerialize();}
		$(tableObj).find("thead th").removeClass("headerSortDown");
		$(tableObj).find("thead th").removeClass("headerSortUp");
		if($("input#sort").length == 0){qString = qString + "&sort=" + $(e).attr("id");}
		if($("input#direction").length == 0){qString = qString + "&direction=" + "desc";}
		$(e).addClass("headerSortUp");
		$("input#sort").val($(e).attr("id"));
		$("input#direction").val("desc");
		
		$(tableTBody).html(loadingHTML);
		$.get(url, qString, function(data){
			$(tableTBody).html(data);
			settings.callback();
		});
	}
	
	$("#" + settings.form).find("#iRowCNT").change(function(){		
		var ele = $(tableObj).find("thead th[class*='headerSort']").get(0);
		loadAsc(ele);
	});
	
	// This is the action to take when page loads to highlight column being sorted
	var sortingDirection = "headerSortDown";
	if($("input#sort").length > 0 && $("input#sort").val().length > 0){
		if($("input#direction").val() == "desc"){
			sortingDirection = "headerSortUp";
		}
		$(this).find("thead th[id=" + $("input#sort").val() + "]").addClass(sortingDirection);		
	}else{		
		$(this).find("thead th:first").addClass("headerSortDown");
	}
}


function disableDelete(){
	if($("input.rowHighlight:checked,input.cellHighlight:checked").length > 0){
		$("input.masterDelete").attr("disabled",false);
	}else{
		$("input.masterDelete").attr("disabled",true);
	}	
}


jQuery(document).ready(function(){
	try{
		// Highlight rows when checked 		
		$("input.rowHighlight").live("click",function() {			
			if (this.checked){$(this).parent().parent().addClass('alert');}else {$(this).parent().parent().removeClass('alert');}disableDelete();
		});	
		$("input.cellHighlight").live("click",function() {
			if (this.checked){$(this).parent().next().addClass('alert');}else {$(this).parent().next().removeClass('alert');}disableDelete();
		});			
		disableDelete();
		
		$("input.submit:submit").live("click",function(){
			
			var action = $(this).val();
			action = action.replace(/Add/, "Adding");
			action = action.replace(/Remove/, "Removing");
			action = action.replace(/Update/, "Updating");		
			action = action.replace(/Save/, "Saving");		
			action = action.replace(/Run/, "Running");		
			
			clickDeactivate($(this).attr("id"),action);		
		});
	}catch(e){}
	
});

function reloadPage(params){
	var url = window.location.href;
	if(params){
		url = url + params;	
	}
	window.location.assign(url);
}

function focusEditor(sEditorID) {
    try {
    	tinyMCE.execCommand('mceFocus',false,sEditorID);
    } catch(e) {
        //error handling -
    }
}

function turnOffEditor(sEditorID){
	tinyMCE.removeMCEControl(tinyMCE.getEditorId(sEditorID));
    tinyMCEmode = false;
    $("#" + sEditorID + "_toggler").html('Show Rich Text');
	$("#" + sEditorID).focus();
}

function turnOnEditor(sEditorID){
 	tinyMCE.addMCEControl($('#'+sEditorID).get(0), sEditorID);
    tinyMCEmode = true;
    $("#" + sEditorID + "_toggler").html('Show Plain Text');
    //focusEditor(sEditorID);
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

jQuery.fn.replaceSelect = function (masterSelect,newVal,newID){
	// Takes a select box and makes a copy of it, then replaces another select with the copy, this saves download by only building one select on the server	
	var masterNodeCopy = $("select#" + masterSelect).clone();
	
	if(newVal){// Set the default selection
		$(masterNodeCopy).val(newVal);	
	}else{			
		$(masterNodeCopy).val($(this).val());
	}
	
	if(newID){ // If not passing in new ID, then take old one
		$(masterNodeCopy).attr("id",newID);
		$(masterNodeCopy).attr("name",newID);
	}else{
		$(masterNodeCopy).attr("id",$(this).attr('id'));
		$(masterNodeCopy).attr("name",$(this).attr('name'));
	}	
		
	$(this).replaceWith(masterNodeCopy);	
}



