var rashBox, rashTxt, rashTime;
var opac;
var debugClearStr = '<a href="javascript:debugClear();" class="right">clear</a><a href="javascript:debugMarker();" class="right">marker</a><br class="clear" /><br />';

//----------------------------------------------------------------------------------//
//		Globally used functions														//
//----------------------------------------------------------------------------------//

function id (x) {
	return document.getElementById(x);
}
function leadingZero (nr) {
	if (nr < 10) nr = "0" + nr;
	return nr;
}

var zindex = 12;
function zChange (x) { // Incriments the z-index of an object
	zindex++;
	document.getElementById(x).style.zIndex = zindex;
}

function trim (s) {
  while (s.substring(0,1) == ' ') {
    s = s.substring(1,s.length);
  }
  while (s.substring(s.length-1,s.length) == ' ') {
    s = s.substring(0,s.length-1);
  }
  return s;
}
function pipeBreak (s) {
	var x_str = String(s);
	var ispipe;
	for (var dot = 0; dot < x_str.length; dot++) {
		if(x_str.charAt(dot) == "|") {
			ispipe = true;
			break;
		} else {
			ispipe = false;
		}
	}
	if (ispipe == true) {
		var x_arr = x_str.split("|");
		var noteStr = "";
		for (var i = 0; i < x_arr.length; i++) {
			noteStr += x_arr[i] + "\r\n";
		}
		return noteStr;
	} else {
		return x_str;
	}
}

function opacity (id, opacStart, opacEnd, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;
	
	//determine the direction for the blending, if start and end are the same nothing happens
	if(opacStart > opacEnd) {
		for(i = opacStart; i >= opacEnd; i--) {
			opac = setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	} else if(opacStart < opacEnd) {
		for(i = opacStart; i <= opacEnd; i++) {
			opac = setTimeout("changeOpac(" + i + ",'" + id + "')",(timer * speed));
			timer++;
		}
	}
}
//change the opacity for different browsers
function changeOpac (opacity, id) {
	var object = document.getElementById(id).style;
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function debug (x) {
	if (document.getElementById("debug_p").innerHTML == "") {
		document.getElementById("debug_p").innerHTML = debugClearStr;
	}
	document.getElementById("debug").style.display = "block";
	document.getElementById("debug_p").innerHTML += x;
	document.getElementById("debug_p").innerHTML += "<br />";
}
function debugClear () {
	document.getElementById("debug").style.display = "none";
	document.getElementById("debug_p").innerHTML = debugClearStr;
}
function debugMarker () {
	document.getElementById("debug_p").innerHTML += '<p style="border-bottom: 1px solid #ccc;"></p>';
}

function rash (msg) {
	rashBox = document.getElementById("rashbox");
	rashTxt = document.getElementById("rashtxt");
	if (msg) {
		clearTimeout(rashTime);
		clearTimeout(opac);
		changeOpac(100, "rashbox");
		rashTxt.innerHTML = msg;
		rashBox.style.top = 180+"px";
		//rashBox.style.left = "35%";
		rashBox.style.left = "300px";
		rashBox.style.display = "block";
		rashTime = window.setTimeout("rash()",5000);
	} else {
		//rashBox.style.display = "none";
		opacity("rashbox", 100, 0, 400);
	}
}


//----------------------------------------------------------------------------------//
//		Calendar specific															//
//----------------------------------------------------------------------------------//

function dialogY () {
	if (IE) { // grab the x-y pos.s if browser is IE
		var theTop;
		if (document.documentElement && document.documentElement.scrollTop) {
			theTop = document.documentElement.scrollTop;
		} else if (document.body) {
			theTop = document.body.scrollTop;
		}
		return theTop + 30;
	}
	else {  // grab the x-y pos.s if browser is NS
		var dy = ((tempY-200)>20) ? (tempY-200) : 20;
		return dy;
	}  
}
function dialogX () {
	if (IE) { // grab the x-y pos.s if browser is IE
		var theLeft;
		if (document.documentElement && document.documentElement.scrollLeft) {
			theLeft = document.documentElement.scrollLeft;
		} else if (document.body) {
			theLeft = document.body.scrollLeft;
		}
		return theLeft;
	}
	else {  // grab the x-y pos.s if browser is NS
		var dx = ((tempX-200)>20) ? (tempX-200) : 20;
		return dx
	}  
}

function generateID () {
	//debug("event_"+(parseFloat(dEvent[dEvent.length-1][0].split("_")[1])+1));
	return "event_"+(parseFloat(dEvent[dEvent.length-1][0].split("_")[1])+1);
}

function fracTime (x) {
	var x_str = String(x);
	var isdot = (x_str.indexOf(".") == -1) ? false : true;
	var ap;
	
	if (isdot == true) {
		var x_arr = x_str.split(".");
		ap = (x_str[0]<12) ? "am" : "pm";
		
		if (x_arr[1]) {
			if(x_arr[1] == "0")
				x_arr[1] = "00";
			if(x_arr[1] == "5")
				x_arr[1] = "30";
			if(x_arr[1] == "25")
				x_arr[1] = "15";
			if(x_arr[1] == "75")
				x_arr[1] = "45";
			return x_arr[0]+":"+x_arr[1]/*+ap*/;
		}
	} else {
		ap = (x_str<12) ? "am" : "pm";
		return x_str+":00"/*+ap*/;
	}
}

function updateTotal ()
{
	//	rash ('updated total...');
	alert ('hi');
	return false;
}


function toggle (x) 
{
	document.getElementById(x).style.display = document.getElementById(x).style.display == "none" ? "block" : "none";
	document.getElementById(x).blur();
}
function setValue (elementID, value)
{
	document.getElementById (elementID).value = value;
}
function confirmAction (message)
{
	var agree = confirm (message);
	if (agree) return true;
	else return false;
}
function catcalc (cal) 
{
	var date = cal.date;				//get date
	var time = date.getTime ();			//get time
	var endField = document.getElementById ("dateEnd");
	var startField = document.getElementById ("dateStart");
	
	if (endField == cal.params.inputField) 
	{
		endField = document.getElementById ("dateStart");
		time -= Date.HOUR;
	} 
	
	else //if (startField == '')
	{
		time += Date.HOUR;
	}
	
	var date2 = new Date (time);
	endField.value = date2.print ("%Y-%m-%d %H:%M");
}
function toggleChecked (button, field)
{	
	if (button.value == 'Select All') 
	{
		for (i = 0; i < field.length; i++)
		{
			field [i].checked = true;
		}
		
		button.value = 'Deselect All';
	}
	
	else
	{
		for (i = 0; i < field.length; i++)
		{
			field [i].checked = false;
		}
		
		button.value = 'Select All';		
	}
}
function uncheckAll (field)
{
	for (i = 0; i < field.length; i++)
	{
		field [i].checked = false;
	}
}
function checkLen (Target, tally)
{
	StrLen = Target.value.length;
	
	if (StrLen > tally) 
	{
		Target.value = Target.value.substring (0,tally);
		charsLeft = 0;
	}
	
	else charsLeft = tally - StrLen;
	
	document.getElementById ("characters").innerHTML = charsLeft;
}
function goTo (page) {
	/* This function is called from the navigation menu
	to jump to the designated URL. Empty values
	are ignored and "--" indicates a menu seperator    */
	
	if (page != "" ) {
		if (page == "--" ) {
			resetMenu();
		} else {
			document.location.href = page;
		}
	}
	return false;
}
function resetMenu () {
	/* Resets the menu to the specified menu item           */   
	document.gmenu.page.options[0].selected = true;
}
function elementFade (elementID)
{
	new Effect.Fade(document.getElementById(elementID));
}
function elementAppear (elementID)
{
	new Effect.Appear(document.getElementById(elementID));
}
function validateTerms ()
{
	
}
function searchInit (linkType, withinGroup, loadingElementID, targetDivID, searchFormID)
{
	showLoading (loadingElementID);
	xajax_performEntitySearch (linkType, withinGroup, loadingElementID, targetDivID, xajax.getFormValues (searchFormID));
	//	hideLoading (loadingElementID);	
}
function showLoading (loadingElementID)
{
	document.getElementById(loadingElementID).innerHTML = '<img src="images/loading/blueapple.gif" />';
}
function hideLoading (loadingElementID)
{	
	document.getElementById(loadingElementID).innerHTML = '';
}

function entityChange (spanID, inputSpanID)
{
	var span = document.getElementById (spanID);
	span.style.display = 'none';
	
	var inputSpan = document.getElementById (inputSpanID);
	inputSpan.style.display = 'block';
}
function toggleUser (e) {
	if (e.value == "Username") {
		e.value = "";
	} else if (e.value == "") {
		//e.value = "Username"; // disabled for consistency - can't onblur the password field
	}
}
function togglePass (e) {
	if (e.value == "Password") {
		e.value = "";
		id(e.id).type = "password";
	} else if (e.value == "") {
		e.type = "text";
		e.value = "Password";
	}
}
function passFocus (target_id, new_id) {
	/*
	id('innerPass').innerHTML = '<input type="password" name="password" id="password" value="" class="loginput password" />';
	id('password').focus();
	id('password').select();
	*/
	id(target_id).innerHTML = '<input type="password" name="password" id="'+new_id+'" value="" class="loginput password" />';
	id(new_id).focus();
	id(new_id).select();
}
function passBlur () {
	id('innerPass').innerHTML = '<input type="text" name="password" id="password" value="Password" class="password required" onfocus="passFocus();" onblur="passBlur();" />';
}
function showHide (id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = 'block';
	} else {
		document.getElementById(id).style.display = 'none';
	}
}
function loginDialog (state) {
	if (state == "hide") {
		id("loginPop").style.display = "none";
	} else {
		id("loginPop").style.width = "280px";
		//var xtop = parseFloat((xClientHeight()+xScrollTop())/2);
		var xtop = parseFloat(((xClientHeight()/2)-(70))+xScrollTop());
		xtop = (xtop > 0) ? xtop : 0;
		id("loginPop").style.top = xtop+"px";
		id("loginPop").style.left = parseFloat((xClientWidth()/2)-120)+"px";
		id("loginPop").style.display = "block";
	}
}

function saveStart() {
	if (debugTitles) debug("saveStart");
	id("savex").style.display = "block";
	id("savex").style.height = parseFloat(xClientHeight()+xScrollTop())+"px";
	
	//saving = true;
	//document.getElementById(x+"t").style.display = "block";
}
function saveStop() {
	if (debugTitles) debug("saveStop");
	id("savex").style.display = "none";
	/*
	for(var ss = 0; ss <= ia.length; ss++) {
		document.getElementById(ia[ss]+"t").style.display = "none";
	}
	saving = false;
	*/
}
function goToURL( url ){
	if( !url ){ return false; }
	location.href = url;
	return true;	
}
function includeFunc (target) { // Global function for adding code to the calendar javascript output - currently runs upon initial calendar event population
	if (debugTitles) debug("includeFunc("+target+")");
	var inc = '<img id="savex" src="http://lib.sesalos.com/images/unisite/x.gif" width="1" height="1" title="Please wait... saving changes" />';
	id(target).innerHTML += inc;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}
var blurPageFlowID;
function editBox (pageFlowID, toggle) {
	if (toggle == "show") {
		if (id("editBox-"+pageFlowID).style.display == "none") {
			id("editBox-"+pageFlowID).style.display = "block";
		} else {
			id("editBox-"+pageFlowID).style.display = "none";
		}
	} else if (toggle == "blur") {
		blurPageFlowID = pageFlowID;
		window.setTimeout('document.getElementById("editBox-"+blurPageFlowID).style.display = "none";', 200);
	} else if (toggle == "hide") {
		id("editBox-"+pageFlowID).style.display = "none";
	}
}

/* --------------------------------------------------------------------------------------------------------------------- */

function xScrollTop(e, bWin)
{
  var offset=0;
  if (!xDef(e) || bWin || e == document || e.tagName.toLowerCase() == 'html' || e.tagName.toLowerCase() == 'body') {
    var w = window;
    if (bWin && e) w = e;
    if(w.document.documentElement && w.document.documentElement.scrollTop) offset=w.document.documentElement.scrollTop;
    else if(w.document.body && xDef(w.document.body.scrollTop)) offset=w.document.body.scrollTop;
  }
  else {
    e = xGetElementById(e);
    if (e && xNum(e.scrollTop)) offset = e.scrollTop;
  }
  return offset;
}

function xClientHeight()
{
  var v=0,d=document,w=window;
  if((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientHeight)
    {v=d.documentElement.clientHeight;}
  else if(d.body && d.body.clientHeight)
    {v=d.body.clientHeight;}
  else if(xDef(w.innerWidth,w.innerHeight,d.width)) {
    v=w.innerHeight;
    if(d.width>w.innerWidth) v-=16;
  }
  return v;
}

function xClientWidth()
{
  var v=0,d=document,w=window;
  if((!d.compatMode || d.compatMode == 'CSS1Compat') && !w.opera && d.documentElement && d.documentElement.clientWidth)
    {v=d.documentElement.clientWidth;}
  else if(d.body && d.body.clientWidth)
    {v=d.body.clientWidth;}
  else if(xDef(w.innerWidth,w.innerHeight,d.height)) {
    v=w.innerWidth;
    if(d.height>w.innerHeight) v-=16;
  }
  return v;
}

function xGetElementById(e)
{
  if(typeof(e)=='string') {
    if(document.getElementById) e=document.getElementById(e);
    else if(document.all) e=document.all[e];
    else e=null;
  }
  return e;
}

function xDef()
{
  for(var i=0; i<arguments.length; ++i){if(typeof(arguments[i])=='undefined') return false;}
  return true;
}

function xNum()
{
  for(var i=0; i<arguments.length; ++i){if(isNaN(arguments[i]) || typeof(arguments[i])!='number') return false;}
  return true;
}

function showOnValue (showValue, value, target)
{	
	var targetElement = document.getElementById (target);	
	
	if (value == showValue)
	{
		targetElement.style.display = 'block';
	}
	
	else
	{
		targetElement.style.display = 'none';
	}
}

function setLoadingMessage (targetID)
{
	id (targetID).innerHTML = '<span style="padding: 2px; margin-right: 2px; background-color: red; color: white;">Loading...</span>';
}

function applyClass (id, classname)
{
	document.getElementById (id).className = classname;
}
function displayLoadingIcon(targetID, msg, swicth){
	if(swicth == true){
		id (targetID).innerHTML =  '<div class="loadingBar">'+msg+'</div>';
		id(targetID).style.display = "block";
	}
}
function getCookie(name) { 
	var start = document.cookie.indexOf(name+"="); 
	var len = start+name.length+1; 
	if ((!start) && (name != document.cookie.substring(0,name.length))) return null; 
	if (start == -1) return null; 
	var end = document.cookie.indexOf(";",len); 
	if (end == -1) end = document.cookie.length; 
	return unescape(document.cookie.substring(len,end)); 
} 
function addCookie(name,value,expires,path,domain,secure) { 
	expires = expires * 60*60*24*1000;
	var today = new Date();
	var expires_date = new Date( today.getTime() + (expires) );
	var cookieString = name + "=" +escape(value) + 
	( (expires) ? ";expires=" + expires_date.toGMTString() : "") + 
	( (path) ? ";path=" + path : "") + 
	( (domain) ? ";domain=" + domain : "") + 
	( (secure) ? ";secure" : ""); 
	document.cookie = cookieString; 
} 

function toggleTr(x) {
	document.getElementById(x).style.display = document.getElementById(x).style.display == "none" ? "table-row" : "none";
	document.getElementById(x).blur();
}

//used in member to member quote
function hideMemberQuoteForm() {
	document.getElementById('memberquoteform').style.display = "none";
	document.getElementById('loading').innerHTML = "Please wait...Sending Mails.";
}

// -------------- Javascript for the Accounting Module ------------------- //
//This function validates the data entered in the add new ledger form.  TODO :implement this validation - for now just returning true 
function validateAddLedgerEntryForm() {
	//alert('hello');
	//if validates then save to db else return false with message
	
	saveNewGeneralLedgerEntry();
	
	return true;
	
	
}

//default value and id, e is the target element
function showHidDefaultFormInputValue (e, defaultValue) {
	if (e.value == defaultValue) {
		e.value = "";
	} else if (e.value == "") {
		e.value = defaultValue;
	}
	//alert(defaultValue);
}

//TODO: move this out into it's own js file ie. accounting.js
function outputNewGeneralLedgerEntryHTML(form) {
	if(checkForm()) {
		alert('form validated');
		alert('outputting general ledger entry on page');
		document.getElementById('newLedgerEntry').innerHTML = 'Fred Flinstone';
		return true;
	} else {
		alert('form not validated');
		return false;
	}
	
	
}

//validates new general ledger form entry
function checkForm() {
	
	return true;
}

function checkJumpMenus(value){
	if(value == -1){
		return false;
	}else{
		window.location = value;
	}
		
}

function checkUncheckAllSafeArray(name, value, formID) {
	var formblock= document.getElementById(formID);
  var forminputs = formblock.getElementsByTagName('input');
	for (i = 0; i < forminputs.length; i++) {
		// regex here to check name attribute
		var regex = new RegExp(name, "i");
		if (regex.test(forminputs[i].getAttribute('name'))) {
			if (!forminputs[i].checked) {
				forminputs[i].checked = true;
			} else {
				forminputs[i].checked = false;
			}
		}
	}
}

function IsNumeric(strString) {
	var strValidChars = "0123456789.-";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
	for (i = 0; i < strString.length && blnResult == true; i++) {
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1) { blnResult = false; }
	}
	return blnResult;
}



