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 setIndicator (content)
{
	document.getElementById('indicator').style.display = 'none';
	document.getElementById('indicator').innerHTML = content;
	elementAppear ('indicator');
}
function elementFade (elementID)
{
	new Effect.Fade(document.getElementById(elementID));	
}
function elementAppear (elementID)
{
	new Effect.Appear(document.getElementById(elementID));
}
function indicatorCycle ()
{
	xajax_getNewIndicator();
	setTimeout('indicatorCycle ();', 10000);
}
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 loadSkinnyTypes (broadCatID)
{
	//div skinnyTypes
	showLoading ('skinnyTypes');
	xajax_loadSkinnies (broadCatID);
}
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 () {
	//id('passTest').innerHTML = '<input type="password" name="password" id="password" value="" class="password" onfocus="passFocus();" onblur="passBlur();" />';
	id('innerPass').innerHTML = '<input type="password" name="password" id="password" value="" class="loginput password" />';
	id('password').focus();
	id('password').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 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 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];
}

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

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;
}
