function errorCallback(XMLHttpRequest, textStatus, errorThrown){
	exceptionMsg = XMLHttpRequest.getResponseHeader('ErrorMessage')
   	exceptionTrace = XMLHttpRequest.responseText
   	if(exceptionMsg){
   		jAlert('Error '+exceptionMsg,'Error',null,exceptionTrace);
   	}else if(XMLHttpRequest && XMLHttpRequest.status==401){
		alert("User session timed out. Please login again to continue...");
   	}else{
   		exceptionMsg = "Server returned an error"
		jAlert('Error '+exceptionMsg,'Error',null,exceptionTrace);
   	}
}

function getQueryStringValue(queryString, name)
{
	// parse out name/value pairs separated via &
	var args = queryString.split('&');

	// split out each name=value pair
	for (var i = 0; i < args.length; i++) {
		var pair = args[i].split('=');
		var actual_name = decodeURIComponent(pair[0]);
		if (actual_name == name)
			return decodeURIComponent(pair[1])
	}
	return null
}

function addEvent() {
	$('a#slick-toggle').click(function() {
		$('#slickboxtest').slideToggle(400);
		return false;
	  });
}
function stopPropagation(e) {
	if (!e) var e = window.event
	// handle event
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function getSelectionStart(o) {
	if (o.createTextRange) {
		var r = document.selection.createRange().duplicate()
		r.moveEnd('character', o.value.length)
		if (r.text == '') return o.value.length
		return o.value.lastIndexOf(r.text)
	} else return o.selectionStart
}

function numbersonly(myfield, e, dec,decLen)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);
caretPos=getSelectionStart(myfield)//$(myfield).caret().begin;
dotLength=myfield.value.indexOf(".");
charsAfterDot=0;
if(dotLength>0)
    charsAfterDot=myfield.value.substring(dotLength,myfield.value.length).length
if(decLen<=charsAfterDot-1)
{
    if ((key==null) || (key==0) || (key==8) ||(key==9) || (key==13) || (key==27) )
        return true;
    if(caretPos>dotLength+decLen)
        return false;
    if(caretPos<=dotLength)
        return true;
    else
    {
       return false;
    }
   return true;
}

// control keys
if ((key==null) || (key==0) || (key==8) ||
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;
else if (myfield.value.length==0 && (("+-").indexOf(keychar)>-1))
   return true;
// decimal point jump
else if (dec && (keychar == "."))
   {
   dotLength=myfield.value.indexOf(".");
   if(dotLength==-1)
    return true;
   else
    return false
   }
else
   return false;
}

function sortModifiedBy(a,b)
{
	return a.CreatedAt<b.CreatedAt;
}

function trimString(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function indexOf(listOfElements,elt /*, from*/)
{
    var len = listOfElements.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in listOfElements &&
          listOfElements[from] === elt)
        return from;
    }
    return -1;
};

function contains(arr,obj){
    var len = arr.length;
    for (var i = 0; i < len; i++){
      if(arr[i]===obj){ return true;}
    }
    return false;
};

function remove(arr,obj){
	var i = -1;
	 for(var j=0; j<arr.length; j++){
	    if(arr[j]==obj){
			i=j;
	    }
	}
	if(i != -1) arr.splice(i, 1);
}
function arrayLength(tempArray) {
   var result = 0;
   for (var tempValue in tempArray ) {
      result++;
   }
   return result;
}

function hasElement(tempArray) {
   for (var tempValue in tempArray )
      return true;
   return false;
}

function arrayContains(arrayElement, value){
	for(var i in arrayElement){
		if (arrayElement[i] == value)
			return true
	}
	return false
}

function arrayContainsKey(arrayElement, keyValue){
	for(var key in arrayElement){
		if (key == keyValue)
			return true
	}
	return false
}

function removeArrayElement(arrayElement, value){
	for(var i in arrayElement){
		if (arrayElement[i] == value)
			arrayElement.splice(i,1)
	}
}

function todayStr() {
	MonthArray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
	DayArray = new Array("Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday", "Sunday");
	var today=new Date()
	return  today.getDate()+ "-" + MonthArray[today.getMonth()]+"-"+(today.getFullYear())
}

function inspect(obj, maxLevels, level)
{
  var str = '', type, msg;

    // Start Input Validations
    // Don't touch, we start iterating at level zero
    if(level == null)  level = 0;

    // At least you want to show the first level
    if(maxLevels == null) maxLevels = 1;
    if(maxLevels < 1)
        return '<font color="red">Error: Levels number must be > 0</font>';

    // We start with a non null object
    if(obj == null)
    return '<font color="red">Error: Object <b>NULL</b></font>';
    // End Input Validations

    // Each Iteration must be indented
    str += '<ul>';

    // Start iterations for all objects in obj
    for(property in obj)
    {
      try
      {
          // Show "property" and "type property"
          type =  typeof(obj[property]);
          str += '<li>(' + type + ') ' + property +
                 ( (obj[property]==null)?(': <b>null</b>'):('')) + '</li>'+'/n';

          // We keep iterating if this property is an Object, non null
          // and we are inside the required number of levels
          if((type == 'object') && (obj[property] != null) && (level+1 < maxLevels))
          str += inspect(obj[property], maxLevels, level+1);
      }
      catch(err)
      {
        // Is there some properties in obj we can't access? Print it red.
        if(typeof(err) == 'string') msg = err;
        else if(err.message)        msg = err.message;
        else if(err.description)    msg = err.description;
        else                        msg = 'Unknown';

        str += '<li><font color="red">(Error) ' + property + ': ' + msg +'</font></li>';
      }
    }

      // Close indent
      str += '</ul>';

    return str;
}

function msgAlert(event)
{
	alert(event);
}

function replaceHtml(el, html) {
	var oldEl = typeof el === "string" ? document.getElementById(el) : el;
	/*@cc_on // Pure innerHTML is slightly faster in IE
		oldEl.innerHTML = html;
		return oldEl;
	@*/
	var newEl = oldEl.cloneNode(false);
	newEl.innerHTML = html;
	oldEl.parentNode.replaceChild(newEl, oldEl);
	/* Since we just removed the old element from the DOM, return a reference
	to the new element, which can be used to restore variable references. */
	return newEl;
}
function encodeToAscii(value) {
	value=value.replace(/\'/g, "&#39;");
    value=value.replace(/\"/g, "&#34;");
  return value;
}

function jsonToString(json){
	strBuf = '{'
	for(id in json){
		sheet = json[id]
		if(id == "root"){
			strBuf = strBuf+'"'+id+'":"'+sheet+'",'
		}else{
			strBuf = strBuf+'"'+id+'":{'
			for(key in sheet){
				val = sheet[key]
				if(typeof val =='number'){
					strBuf = strBuf+'"'+key+'":'+val+','
				}else if(typeof val == 'string'){
					strBuf = strBuf+'"'+key+'":"'+val+'",'
				}else if(typeof val == 'object' && key!='controller'){
					strBuf = strBuf+'"'+key+'":{'
					for(sheetId in val){
						strBuf = strBuf+'"'+sheetId+'":"'+val[sheetId]+'",'
					}
					strBuf = strBuf+'},'
				}

			}
			strBuf = strBuf+'},'
		}
	}
	strBuf = strBuf+'}'
	return strBuf
}
function printWebPart(tagid){
    if (tagid) {
        //build html for print page
        var html = "<HTML>\n<HEAD>\n"+
            $("head").html()+
            "\n</HEAD>\n<BODY>\n"+
            $("#"+tagid).html()+
            "\n</BODY>\n</HTML>";
        //open new window
        var printWP = window.open("","printWebPart");
        printWP.document.open();
        //insert content
        printWP.document.write(html);
        printWP.document.close();
        //open print dialog
        printWP.print();
    }
}

function getSelectedText(){
/* Copy paste reference web site: http://help.dottoro.com/ljcvonpc.php
*/
	 var selText = "";
	if (window.getSelection) {  // all browsers, except IE before version 9
	    if (document.activeElement &&
	            (document.activeElement.tagName.toLowerCase () == "textarea" ||
	             document.activeElement.tagName.toLowerCase () == "input"))
	    {
	        var text = document.activeElement.value;
	        selText = text.substring (document.activeElement.selectionStart,
	                                  document.activeElement.selectionEnd);
	    }
	    else {
	        var selRange = window.getSelection ();
	        selText = selRange.toString ();
	    }
	}
	else {
	    if (document.selection.createRange) { // Internet Explorer
	        var range = document.selection.createRange ();
	        selText = range.text;
	    }
	}

	return selText
}

function getStartSelection(){
	 var startSelection = null;
	if (window.getSelection) {  // all browsers, except IE before version 9
	    if (document.activeElement &&
	            (document.activeElement.tagName.toLowerCase () == "textarea" ||
	             document.activeElement.tagName.toLowerCase () == "input"))
	    {
	        startSelection =  document.activeElement.selectionStart
	    }
	}
	return startSelection
}

function getEndSelection(){
	 var endSelection = null;
	if (window.getSelection) {  // all browsers, except IE before version 9
	    if (document.activeElement &&
	            (document.activeElement.tagName.toLowerCase () == "textarea" ||
	             document.activeElement.tagName.toLowerCase () == "input"))
	    {
	        endSelection =  document.activeElement.selectionEnd
	    }
	}
	return endSelection
}

function clearSelection(){
	if (window.getSelection) {
	   if (window.getSelection().empty) {  // Chrome
	     window.getSelection().empty();
	   } else if (window.getSelection().removeAllRanges) {  // Firefox
	     window.getSelection().removeAllRanges();
	   }
	} else if (document.selection) {  // IE?
	  document.selection.empty();
	}
}