var Calendar={};
// short month names
Calendar._SMN = new Array
("Jan",
 "Feb",
 "Mar",
 "Apr",
 "May",
 "Jun",
 "Jul",
 "Aug",
 "Sep",
 "Oct",
 "Nov",
 "Dec");

var RFPStrings={
    translate: function(msgKey) {
        if (RFPStrings.message[msgKey]) {
           return RFPStrings.message[msgKey];
        } else {
           return msgKey;
        }
    },
    message: {
        "js.calendar.dateFormat":"%d %b %Y",
        "js.calendar.dateTimeFormat":"%d %b %Y %H:%M"
    }

}

/*
showDateTime
Takes a unix time, and displays it in a format appropriate to the browser
*/

function showDateTime(dt) {
	formatDate(dt,RFPStrings.translate("js.calendar.dateTimeFormat"));
}
function showDate(dt) {
	formatDate(dt,RFPStrings.translate("js.calendar.dateFormat"));
}
function formatDate(dt,fmt) {
	d=new Date();
	d.setTime(new Number(dt));
	document.write("<span title='"+d.toUTCString()+"'>");
	document.write(d.print(fmt));
	document.write("</span>");
}

function getDateTimeHTML(dt) {
	d=new Date();
	d.setTime(new Number(dt));
	var html = "<span title='"+d.toUTCString()+"'>";
	html += d.print(RFPStrings.translate("js.calendar.dateTimeFormat"));
	html += "</span>";
	return html;
}

/** Prints the date in a string according to the given format. */
Date.prototype.print = function (str) {
	var m = this.getMonth();
	var d = this.getDate();
	var y = this.getFullYear();
	var w = this.getDay();
	var s = {};
	var hr = this.getHours();
	var pm = (hr >= 12);
	var ir = (pm) ? (hr - 12) : hr;
	if (ir == 0)
		ir = 12;
	var min = this.getMinutes();
	var sec = this.getSeconds();
    if (Calendar) {
	    s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
    }
	s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
	s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
	s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
	s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
	s["%Y"] = y;		// year with the century
	s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)

	var re = /%./g;
	if (Calendar && (!Calendar.is_ie5 && !Calendar.is_khtml))
		return str.replace(re, function (par) { return s[par] || par; });

	var a = str.match(re);
	for (var i = 0; i < a.length; i++) {
		var tmp = s[a[i]];
		if (tmp) {
			re = new RegExp(a[i], 'g');
			str = str.replace(re, tmp);
		}
	}

	return str;
};

if(!$){
  var $ = function(element_id){
    return document.getElementById(element_id);
  }
}
function doCancel(){
	var cancelForm = $('cancelForm');
	if(!cancelForm){
		alert('Cannot find a form with the id = \"cancelForm\" ');
		return;
	}
	cancelForm.submit()
}

function linkTo(url){
	window.location.href=url;
}

function changeSorting(sortFieldId, isDescendingId, newSort){
	var sortObj			= document.getElementById(sortFieldId);
	var isDescendingObj	= document.getElementById(isDescendingId);
	if(null == sortObj)	{return false;} //nothing to do.

	var isDescending = false;
	
	if(sortObj.value == newSort){
		if(null != isDescendingObj){
			if("true" == isDescendingObj.value){
				isDescendingObj.value = "false";
			} else {
				isDescendingObj.value = "true";
				isDescending = true;
			}
		}
	} else {
		sortObj.value = newSort;
	}
	return isDescending;
}

function changeSortSign(spanId, isDescending){
	var spanElem = document.getElementById(spanId);
	if(null == spanElem) {	return;	}
	var newtext = document.createTextNode(isDescending ? '(-)' : '(+)');
	spanElem.appendChild(newtext);
}
String.prototype.trim = function(){
	// this functions trims the string from left & right;
	return this.replace(/^\s*/,"").replace(/\s*$/,"");
}

function debug(m) {
    try{
        console.debug(m);
    }catch(e){
        //ignore
    }
}

/*
   name - name of the desired cookie
   return string containing value of specified cookie or null
   if cookie does not exist
 */
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1) {
		begin = dc.indexOf(prefix);
		if (begin != 0) return null;
	} else
		begin += 2;
	var end = document.cookie.indexOf(";", begin);
	if (end == -1)
		end = dc.length;
	return unescape(dc.substring(begin + prefix.length, end));
}
/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
   (defaults to end of current session)
   [path] - path for which the cookie is valid
   (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
   (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
   a secure transmission
 * an argument defaults when it is assigned null as a placeholder
 * a null placeholder is not required for trailing omitted arguments
 */

function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
			((path) ? "; path=" + path : "") +
				((domain) ? "; domain=" + domain : "") +
				((secure) ? "; secure" : "");
	document.cookie = curCookie;
}


/**
 * Reloads current page with a parameter set to the value specified.
 * If the parameter has not been used in the current page url it is 
 * appended.
 parameterName - parameter name
 newParameterValue - new parameter value 
*/
function reloadPage(parameterName, newParameterValue){
	
	var url = window.location.href;
	
	var newUrl = "";

	var queryStart = url.indexOf("?");
	if(queryStart == -1){
		newUrl = url +"?"+parameterName+"="+newParameterValue;
	}else{
		var paramStart = url.indexOf(parameterName+"=", queryStart);
		if(paramStart== -1){
			newUrl = url +"&"+parameterName+"="+newParameterValue;	
		}else{
			var valueStart = paramStart+parameterName.length+1;
			var valueEnd = url.indexOf("&", valueStart);
			if(valueEnd == -1){
				newUrl = url.substr(0, valueStart) + newParameterValue;
			}else{
				newUrl = url.substr(0, valueStart) + newParameterValue;
				if(valueEnd < url.length){
					newUrl += url.substr(valueEnd, url.length - valueEnd);
				}
			}
		}
	}
	window.location = newUrl;
}
/*
 * Looks up all checkbox elements with the name "elName" and sets the 
 * Dom attribute "checked" to the value of checkedOrNot
 * arguments
 *  checkedOrNot - true or false
 *  elName - name of the input checkbox elements to update
 */
function setAllCheckboxes(elName, checkedOrNot){
	var elements = document.getElementsByTagName("input");
	for(i=0; i<elements.length; i++){
		var el = elements.item(i);
		if(el.getAttribute("type") == "checkbox" && el.getAttribute("name") == elName){
			el.checked = checkedOrNot;
		}
	}
}
/*
 * Function which wraps Prototype's Ajax.Updater object.
 * @param url - the url to make the Ajax call to
 * @param targetNode - the HTMLElement into which text is to be inserted.
 * @indicatorNode - the HTMLElement which shows a progress indicator
 * @bHideTarget - a boolean value indicating whether to begin the process by hiding the targetNode (defaults to true).
 */

function ajaxUpdate(url, targetNode, indicatorNode, bHideTarget){
	if(indicatorNode) Element.show(indicatorNode); 
	if(bHideTarget  || typeof(bHideTarget) == "undefined") Element.hide(targetNode);
	new Ajax.Updater(targetNode, url, 
		{
				onComplete: function(response, json){ 
					window.setTimeout(
						function(){
		 					if(indicatorNode) Element.hide(indicatorNode);
		 					Element.show(targetNode); //show the target node (for the case when it is hidden)							
						},1500
					);
		 		}
		 }
	); 
}

if (typeof(console)!="undefined") {
	if (typeof(console.debug)=="undefined") {
		if (typeof (console.log)!="undefined") {
			// Chrome
			console.debug=console.log;
		}
	}
}
/*
* Concatenates a String to a given number of characters (default 20)
*/
function concatString(value,characters){
    characters = characters ? characters : 20;
    var suffix = "...";
    if(value.trim().length < characters){
        suffix = "";
    }
    var concatenated = value.substring(0,characters);
    return concatenated + suffix;
}

/*
* Generic toggle function.
* simple:  toggle('divId')
* with indicator: toggle('divId', 'imgId', 'minus.gif', 'plus.gif')
*/
function toggle(nodeId, indicatorId, expandedImg, collapsedImg){
	var node = document.getElementById(nodeId);
	if(node){
		if(node.style.display=='none'){
			node.style.display='';
			if(indicatorId) {
				document.getElementById(indicatorId).src = expandedImg;
			}
		}else{
			node.style.display = 'none';
			if(indicatorId) {
				document.getElementById(indicatorId).src = collapsedImg;
			}
		}
	}
}
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

