function setElementText(element, text, display) {
    var elem = document.getElementById(element);
    if (elem != null) {
        elem.innerHTML = text; 
        elem.style.display = display;
    }
}

function crossBrowserLinkClick(element) {
    var clicked = false;
	if (element.click) {
		element.click();
		clicked = true;
	} else if (element.onclick) {
	    element.onclick();
	    clicked = true;
	}
	
	if (!(clicked && window.ie) && element.href != null) {
	    var href = element.href;
	    //strip off the leading 'javascript:'
	    var func;
    	
	    if (href.indexOf('javascript:') > -1) {
		    func = href.substr(11);
	    } else
		    func = href;
    		
	    //strip the space off (encoded as %20)		
	    if (func.indexOf('%20') > -1)
		    func = func.replace(/%20/gi, ' ').replace(/^\s+|\s+$/g, '');

	    //run the function
	    log('crossBrowserLinkClick, execute: '+func);
	    eval(func);
	}	
}

function setLinkTarget(linkID, target) { 
	if (document.getElementById(linkID))
  	document.getElementById(linkID).target = target;
}

function ClearOptions(OptionList) {
	for (x = OptionList.length; x >= 0; x = x - 1) {
		OptionList[x] = null;
	}
}

function AddToOptionList(OptionList, OptionValue, OptionText) {
	OptionList[OptionList.length] = new Option(OptionText, OptionValue);
}

function populate_days(day, month, year) {			
    var value = day.selectedIndex;

    ClearOptions(day);	

	if (month[month.selectedIndex].value == 1) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 2) {
	    for (x=1; x < 29; x++)
		    AddToOptionList(day, x, x);
	    if ((year[year.selectedIndex].value % 4 == 0) && ((year[year.selectedIndex].value % 100 != 0) || (year[year.selectedIndex].value % 400 == 0)))
		    AddToOptionList(day, 29, 29);
    } else if (month[month.selectedIndex].value == 3) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 4) {
	    for (x=1; x < 31; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 5) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 6) {
	    for (x=1; x < 31; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 7) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 8) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 9) {
	    for (x=1; x < 31; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 10) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 11) {
	    for (x=1; x < 31; x++)
		    AddToOptionList(day, x, x);
    } else if (month[month.selectedIndex].value == 12) {
	    for (x=1; x < 32; x++)
		    AddToOptionList(day, x, x);
    }	

    if (day.length < value || day.length == value)
	    value = (day.length - 1);
	    
    day.selectedIndex = value;
}

function transfer(objFrom, objTo, selected, action) {
	for (var i=0, l=objFrom.options.length; i<l; i++) {
		if (objFrom.options[i].selected) {
			addOption(objTo, objFrom.options[i].text, objFrom.options[i].value);
			
			/*if (action == 'add') {
			    //sVal = ((selected.value == null) ? "" : selected.value) + ',' + objFrom.options[i].value;
			    selected.value += ',' + objFrom.options[i].value;
			}*/
		}
	}
	for (var i=objFrom.options.length-1; i>-1; i--) {
		if (objFrom.options[i].selected) {
			deleteOption(objFrom, i, selected, action);
		}
	}
	var objSelected = (action == 'add') ? objTo : objFrom;
	calculateSelected(objSelected, selected);
}

function calculateSelected(objSelected, selected) {
    selected.value = '';
	for (var i=0; i<objSelected.options.length; i++) {
	    selected.value += ',' + objSelected.options[i].value
	}
}

function deleteOption(object, index, selected, action) {
    /*if (action == 'remove') { 
        var sVal = selected.value.split(',');
        for (x=0; x<sVal.length; x++)
        {
            if (sVal[x] != object.options[index].value)
                sNewVal = ',' + sVal[x]; 
        }
        selected.value = (sNewVal == ',') ? '' : sNewVal;
    }*/
    object.options[index] = null;
}

function addOption(object, text, value) {
	var defaultSelected = true;
	var selected = true;
	var optionName = new Option(text, value, defaultSelected, selected)
	object.options[object.length] = optionName;
}		

function selectAll(objSelect, blnSelected) {
	for (var i=0, l=objSelect.options.length; i<l; i++) {
		objSelect.options[i].selected = blnSelected;
	}			
}

function limitText(limitField, limitCount, limitNum, usedChars) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	} else if (limitCount != null) {
		limitCount.value = limitNum - limitField.value.length;
	}
	
	if (usedChars != null && $(usedChars) != null)
	    $(usedChars).innerHTML = (limitNum - limitField.value.length) + ' characters left';
}

function textboxDetectEnter(event, buttonID) {
    if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
        crossBrowserLinkClick(document.getElementById(buttonID)); 
        return false;
    } 
    else 
        return true;
}

function swapText(dir, textbox, text) {
    if (dir == 'in' && textbox.value == text)
        textbox.value = '';
    else if (dir == 'out' && textbox.value == '')
        textbox.value = text;         
}

var bDirty = false;
var dirtyConfirmationMessage = 'You will lose the changes you have made to the data.';
var localConfirmationMesssage = '';
//var onSetDirty = new YAHOO.util.CustomEvent('setDirty');

function setDirty(value) {
    onSetDirty.fire();
    bDirty = value;
}

function userCheckDirty(message) {
    if (bDirty) {
        var messageToDisplay = message == '' ? dirtyConfirmationMessage : message; 
        if (confirm(messageToDisplay))
            return true;
        else
            return false;
    }     
}

function resetForm() {
    document.forms[0].reset();
    bDirty = false; 
}

/* A pretty little hack to make uploads not hang in Safari. Just call this
 * immediately before the upload is submitted. This does an Ajax call to
 * the server, which returns an empty document with the "Connection: close"
 * header, telling Safari to close the active connection. A hack, but
 * effective. From projectpath.com */
function closeKeepAlive() {
 if (/AppleWebKit|MSIE/.test(navigator.userAgent)) {
 new Ajax.Request("/ping/close", { asynchronous:false });
 }
}

//use this to embed flash or other objects without the ie 'click to activate' prob
function write_object(embedded_object)
{
	document.write(embedded_object);
	document.write('\n');
}

// ------------------------------------------------------------------
// from http://www.mattkruse.com/javascript/date/source.html
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// These functions use the same 'format' strings as the 
// java.text.SimpleDateFormat class, with minor exceptions.
// The format string consists of the following abbreviations:
// 
// Field        | Full Form          | Short Form
// -------------+--------------------+-----------------------
// Year         | yyyy (4 digits)    | yy (2 digits), y (2 or 4 digits)
// Month        | MMM (name or abbr.)| MM (2 digits), M (1 or 2 digits)
//              | NNN (abbr.)        |
// Day of Month | dd (2 digits)      | d (1 or 2 digits)
// Day of Week  | EE (name)          | E (abbr)
// Hour (1-12)  | hh (2 digits)      | h (1 or 2 digits)
// Hour (0-23)  | HH (2 digits)      | H (1 or 2 digits)
// Hour (0-11)  | KK (2 digits)      | K (1 or 2 digits)
// Hour (1-24)  | kk (2 digits)      | k (1 or 2 digits)
// Minute       | mm (2 digits)      | m (1 or 2 digits)
// Second       | ss (2 digits)      | s (1 or 2 digits)
// AM/PM        | a                  |
//
// NOTE THE DIFFERENCE BETWEEN MM and mm! Month=MM, not mm!
// Examples:
//  "MMM d, y" matches: January 01, 2000
//                      Dec 1, 1900
//                      Nov 20, 00
//  "M/d/yy"   matches: 01/20/00
//                      9/2/00
//  "MMM dd, yyyy hh:mm:ssa" matches: "January 01, 2000 12:30:45AM"
// ------------------------------------------------------------------

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

function formatDate(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
}

function getArgs(win, querystring)
{
    var args = new Object();
    var query = null;
    if (win != null) 
        query = win.location.search.substring(1);       //Get query string.
    else
        query = querystring;
     
    var pairs = query.split("&");                   //Break at ampersand.

    for(var i = 0; i < pairs.length; i++)
    {
        var pos = pairs[i].indexOf('=');            //Look for  "name=value".
        if (pos == -1) continue;                    //If not found, skip.
        var argname = pairs[i].substring(0,pos);    //Extract the name.
        var value = pairs[i].substring(pos+1);       //Extract the value.
        args[argname] = unescape(value);           //Store as a property
    }
    return args;                                     //Return the object
}

function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
    	output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/pad [rev. #1]

String.prototype.pad = function(l, s, t){
    return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
        + 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
        + this + s.substr(0, l - t) : this;
};
