/*
This method populates input variables with given values and submits the form
@frmId the form element ID
@varMap is a map of input ( element)parameter IDs and values. 
*/
function formSubmit(frmID, varMap) {
  if (varMap) {
    for(var name in varMap){   
      if (varMap[name] != null)
        document.getElementById(name).value = varMap[name];
    }
  }
  frm = document.getElementById(frmID);
  frm.submit();
}

/*
This function provides the service to create an in-place edit form based 
on a template. Use this in conjunction with the InPlaceEdit_Cancel method
to restore the content 
It takes in a templateMap to replace template tags
with values form the map.It also creates the following tags implicitly:
#the inlinetext# : the original text of the element that is being editable
@inplaceID is the in-place editable element container ID
@templateID is the template element container ID
@templateMap is the template map of tags and the values to replace them with
@uniqueID is the ID to uniquely identify this instance on in-place edit
*/
function InPlaceEdit_Show(inplaceID, templateID, templateMap, uniqueID, contentID){
  if (uniqueID == null)
    return;
  var hid_txt_uniqueID = 'hid_txt_' + uniqueID;
  if (document.getElementById(hid_txt_uniqueID))
    return;
  var inplaceElem = document.getElementById(inplaceID);
  if (inplaceElem == null)
    return;
  var innerHTMLSrc = inplaceElem.innerHTML;
  
  var theContent = innerHTMLSrc;
  var contentElem = document.getElementById(contentID);
  if (contentElem != null)
    theContent = contentElem.innerHTML;
    
  var innerHTMLTarget = "";
  var templateElem = document.getElementById(templateID);
  if (templateElem != null)
    innerHTMLTarget = templateElem.innerHTML;
  if (templateMap != null){
    templateMap['#the content#'] = theContent;
    for(var name in templateMap){   
      var value = templateMap[name];
      if (value != null)
        innerHTMLTarget = innerHTMLTarget.replace(new RegExp(name, 'g'), value);
    }
  }
  innerHTMLTarget = innerHTMLTarget.concat('<input type="hidden" id="' + hid_txt_uniqueID + '" value="' 
    + escape(innerHTMLSrc) + '" />');
  innerHTMLTarget = innerHTMLTarget.concat('<input type="hidden" id="' + 'hid_inplaceid_' + uniqueID + '" value="' 
    + inplaceID + '" />');
  inplaceElem.innerHTML = innerHTMLTarget;
  return;
}

/*
This function will restore the contents of a in-place edit. Use this in
conjuntion with InPlaceEdit_Show
@uniqueID is the ID to uniquely identify this instance on in-place edit
*/
function InPlaceEdit_Cancel(uniqueID){
  if (uniqueID == null)
    return;
  var hid_txt_uniqueIDElem = document.getElementById('hid_txt_' + uniqueID);
  if (hid_txt_uniqueIDElem == null)
    return;
  var hid_inplaceid_elem = document.getElementById('hid_inplaceid_' + uniqueID);
  if (hid_inplaceid_elem == null)
    return;
  var inplaceElem = document.getElementById(hid_inplaceid_elem.value);
  if (inplaceElem == null)
    return;
  inplaceElem.innerHTML = unescape(hid_txt_uniqueIDElem.value);
}

/*
  this function will show an element
*/
function showElement(elemID, displayType) {
  var elem = document.getElementById(elemID);
  if (displayType == null)
    displayType = 'block'
  elem.style.display = displayType;
}

/*
  this function will show an element
*/
function showElementInline(elemID, displayType) {
  var elem = document.getElementById(elemID);
  if (displayType == null)
    displayType = 'inline'
  elem.style.display = displayType;
}

/*
  this function will hide an element
*/
function hideElement(elemID) {
  var elem = document.getElementById(elemID);
  elem.style.display = 'none';
}

/*
  this function will clear an input element
*/
function clearInput(elemID) {
  var elem = document.getElementById(elemID);
  elem.value = '';
}

/*
  this function will clear an input element
*/
function setInput(elemID, value) {
  var elem = document.getElementById(elemID);
  elem.value = value;
}

/*
  this function will set the focus an input element
*/
function setInputFocus(elemID) {
  var elem = document.getElementById(elemID);
  elem.focus();
  //elem.select();/*IE does not set the focus on a newly visible form*/
  // In IE7 this was causing the file dialog to open upon 2 clicks.
}

/*
Cross browser code to add listeners to DOM objects
*/
function addEvtListener(obj, evt, fn, cap){ 
    if(obj.addEventListener)
        obj.addEventListener(evt, fn, cap);
    else 
        if (obj.attachEvent)
            obj.attachEvent('on' + evt, fn);
        else 
            eval('obj.on' + evt + '=' + fn);
}

/*
Return a string with leading and ending whitespace removed 
*/
function trim(str){
   
   return str.replace(/^\s*|\s*$/g,"");
}

/* This function loads the given page*/
function loadPage(pageToLoad){
	window.location.href = pageToLoad;
}

/* This function shows the public private help page in a new window */
  var pubPriHelpWin;
  function showPubPriHelp(url){
	try{
	  pubPriHelpWin.focus();
	}catch(error){
	  pubPriHelpWin = window.open( url , "", "top=100,left=200,height=300,width=500,fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
	}
  }
    
  function pubPriHelpWinClosed(){
    pubPriHelpWin = null;
  }  
  
  /* This function shows the Item Voting help page in a new window */
  var itemVotingHelpWin;
  function showItemVotingHelp(){
  try{
    itemVotingHelpWin.focus();
  }catch(error){
    
    itemVotingHelpWin = window.open( "/ht/html/itemVotingHelp.html" , "", "top=100,left=200,height=300,width=500,fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
  }
  }
    
  function itemVotingHelpWinClosed(){
    itemVotingHelpWin = null;
  }  
   
   
   /* This function shows the page purpose help page in a new window */
  var pagePurposeHelpWin;
    
  function pagePurposeHelpWinClosed(){
    pagePurposeHelpWin = null;
  }  
    
    /* This function shows the allowed HTML tags for HTML supported textbox. */
  var htmlTagsHelpWin;
  function showHtmlTagsHelp(){
    try{
      htmlTagsHelpWin.focus();
    }catch(error){
      htmlTagsHelpWin = window.open( "/ht/html/htmlTagSupportGuide.html" , "", "top=100,left=200,height=500,width=500,fullscreen=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizable=0");
    }    
  }

  function htmlTagsHelpWinClosed(){
    htmlTagsHelpWin = null;
  }

  /*
    this function set the item imagesize
  */
  function scale_to_fit(img, nPixels){
      var nPixelsMax = nPixels * 1;
      if (img.classname == "processed")
        return;
      if (img.height > img.width && img.height > nPixelsMax){
          img.width = parseInt (img.width*nPixelsMax/img.height);
          img.classname="processed";
      }
      else if (img.width >= img.height && img.width > nPixelsMax){
          img.width = nPixelsMax;
	      img.classname="processed";
      }
      else {
      }
      img.style.visibility = 'visible';
  }
  
  function onLoadForScaling(imgId, nPixels){
    
    var img = document.getElementById(imgId);
    if (img == null)
      return;
    if (img.height == 0 && img.width == 0){
      setTimeout('scale_to_fit(document.getElementById(\''+imgId+'\'), ' + nPixels + ')', 500);
    }
    else {
      scale_to_fit(document.getElementById(imgId), nPixels);
    }
  }  
  
  
function findPosX(obj){

  var curleft = 0;
  
  if (obj.offsetParent){
    
    while (obj.offsetParent){
      
      curleft += obj.offsetLeft;
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj){

  var curtop = 0;

  if (obj.offsetParent){
    
    while (obj.offsetParent){
      
      curtop += obj.offsetTop;
      obj = obj.offsetParent;
    }
  }
  else if (obj.y)
    curtop += obj.y;
  return curtop;
}

/**
*This methos should be included in all pages where png image is displayed. 
*This is to fix the transparency issue in ie. Call this function onload event of all jsps
**/
function correctPNG() {// correctly handle PNG transparency in Win IE 5.5 & 6.
   if ( navigator.appVersion.indexOf("MSIE") >= 0) {
     var arVersion = navigator.appVersion.split("MSIE")
     var version = parseFloat(arVersion[1])
     if ((version >= 5.5 && version < 7.0) && (document.body.filters)) 
     {

        for(var i=0; i<document.images.length; i++)
        {
           var img = document.images[i]
           var imgName = img.src.toUpperCase()
           if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
           {
              var imgID = (img.id) ? "id='" + img.id + "' " : ""
              var imgClass = (img.className) ? "class='" + img.className + "' " : ""
              var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
              var imgStyle = "display:inline-block;" + img.style.cssText 
              if (img.align == "left") imgStyle = "float:left;" + imgStyle
              if (img.align == "right") imgStyle = "float:right;" + imgStyle
              if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
              var strNewHTML = "<span " + imgID + imgClass + imgTitle
              + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
              + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
              + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
              img.outerHTML = strNewHTML
              i = i-1
           }
        }
     }
   }    
}

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

 
	return encoded;
};

function URLDecode( )
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef"; 
   var encoded = document.URLForm.F2.value;
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2) 
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1 
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while
   document.URLForm.F1.value = plaintext;
   return false;
};

function stripTags(str) {
    return str.replace(/<\/?[^>]+>/gi, '');
}

function escapeHTML(palinText) {
    var div = document.createElement('div');
    var text = document.createTextNode(palinText);
    div.appendChild(text);
    return div.innerHTML;
}

function unescapeHTML(htmlText) {
    var div = document.createElement('div');
    div.innerHTML = stripTags(htmlText);
    return div.childNodes[0].nodeValue;
  } 

addEvtListener(window, 'load', correctPNG, false);

function limitCharacters(textBoxElement, maxCount){
  var currentCount = textBoxElement.value.length;
  if(currentCount > maxCount){
   textBoxElement.value = textBoxElement.value.substring(0,maxCount);
  }
}

/**
 * Returns true if the string has Internation characters, i.e., characters
 * beyond the 255 ascii range. Else false
 * 
 * @param str
 * @return Returns true if the string has Internation characters
 */
function isI18N(str) {
	
	if (str == null) {
  	return false;
  }

  for (var i = 0; i < str.length; i++) {
	  if (str.charCodeAt(i) > 255) {
	    return true;
    }
  }

  return false;
}

function addBookmark(url, title) {
        if (window.sidebar) { // Firefox
              window.sidebar.addPanel(title, url,"");
        } else if( document.all ) { //IE
                window.external.AddFavorite( url, title);
        } else {
               alert("Sorry, your browser doesn't support bookmarks");
        }
}

function validateImageFile(imageElementId, imageRequired, fileNameId, imageErrorEleId,errorMessage){
	if(typeof imageRequired == "undefined"){
		imageRequired = true;
	}
	if(typeof errorMessage == "undefined"){
		errorMessage = 'Invalid image. Please upload a file ending with JPG, JPEG, GIF, or PNG.';
	}
    var imageUrl = document.getElementById(imageElementId).value;

	  if(imageUrl == ""){
	    if(imageRequired){
	    	document.getElementById(imageErrorEleId).innerHTML = errorMessage;
	     setInputFocus(imageElementId);
	    }
	    return (!imageRequired);
	  }
	 
		var isValidFileCheckForIE = true;
	  if ( navigator.appVersion.indexOf("MSIE") >= 0) {
	    var arVersion = navigator.appVersion.split("MSIE")
	    var version = parseFloat(arVersion[1])
	    if (version < 7.0) {
	       
	      isValidFileCheckForIE = (imageUrl.indexOf(":") == 1); 
	    }
	   }  
	          
    if(!isValidFileCheckForIE){
      document.getElementById(imageErrorEleId).innerHTML = 'Please specify a valid path';
	    setInputFocus(imageElementId);
      return false;
    } 
     
    if(!(imageUrl == "") && isValidFileCheckForIE) {
        
      var ext = imageUrl;
      var result = ext.lastIndexOf('.'); 
        
      if (result != -1) {
        ext = ext.substr(result+1).toLowerCase();
      }
      else{
        ext="";
      }
      
      if((ext == "jpeg") || (ext == "jpg") || (ext == "gif") || (ext == "png")){
        
        if(typeof fileNameId != "undefined" && fileNameId !=null){

         var fileNameEle = document.getElementById(fileNameId);
           fileNameEle.value = imageUrl;
        }
        if(typeof imageErrorEleId != "undefined" && imageErrorEleId !=null){
      	 document.getElementById(imageErrorEleId).innerHTML = '';
      	}
      	return true;
      }
      if(typeof imageErrorEleId != "undefined" && imageErrorEleId !=null){
	      document.getElementById(imageErrorEleId).innerHTML = errorMessage;  
      }
      
      setInputFocus(imageElementId);
      
      return false;
    }  
}

function showUserPagesCall(results, callbackParams){
	var myPagesLinkElem = document.getElementById('myPagesLink');
	var innerHtml = document.getElementById("myPagesDefContainer").innerHTML;
	showPopupAboveRight(myPagesLinkElem, 300, 160, innerHtml, true, -35, 158, 'popUpMyPagesDiv', 'popUpMyPagesContent');
	formSubmitAJAX('/za/userPages', null, 'showUserPagesCallback');
}
		
function showUserPagesCallback(results, callbackParams){
	if(results.firstChild){
 		var innerHtml = "";
 		for(var i=0; i<results.childNodes.length; i++){
 			innerHtml += results.childNodes[i].nodeValue;
 		}
 		
 		var myPagesLinkElem = document.getElementById('myPagesLink');
 		var kPopup = showAndReturnPopupAboveRight(myPagesLinkElem, 300, 275, innerHtml, true, -38, 274, 'popUpMyPagesDiv', 'popUpMyPagesContent');
 		onMouseMovedPopup(kPopup.popupIndex);
 	}
}

/*------------------ Ajax library -----------------------*/	
function getHTTPRequestObject() {

  var xmlHttpRequest;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (exception1) {
      try {
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (exception2) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttpRequest = false;
  @end @*/
 
  if (!xmlHttpRequest && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlHttpRequest = new XMLHttpRequest();
    } catch (exception) {
      xmlHttpRequest = false;
    }
  }
  return xmlHttpRequest;
}

var requestsArray = new Array();
var MAX_REQUEST_SIZE = 5;

function processResponse(index){
  var request = requestsArray[index];
  if ( request.httpRequester.readyState == 4 ){
    if ( request.httpRequester.status == 200) {
      try{
        request.complete = true;
        var xmlResponse = request.httpRequester.responseXML;
        var resultStatus = xmlResponse.getElementsByTagName("result")[0].firstChild.nodeValue;
        if(resultStatus == 0){
          var results = xmlResponse.getElementsByTagName("results")[0];
          eval(request.callbackMethod)(results, request.callbackParams);
          try {
            var operation = xmlResponse.getElementsByTagName("operation")[0].firstChild.nodeValue;
            if(typeof tcLink != "undefined" && operation != null && operation != "") {
              setTimeout("tcLink(true,'"+operation+"')",5);
            }
          } catch(trackError) {}
        }else if(resultStatus == 2){
          if(!request.ignoreError){
            alert("Oops!  You need to be logged in to do this. The page will refresh after you click ok");
            document.location.reload();
          }else{
            eval(request.callbackMethod)(null, request.callbackParams);
          }
        }else{
	      if(!request.ignoreError){
            alert("Oops! Something went wrong. Error code: CL-1. The page will refresh after you click ok");
	        document.location.reload();
	      }else{
	        eval(request.callbackMethod)(null, request.callbackParams);
	      }
        }
      }catch(error){
        if(!request.ignoreError){
          alert("Oops! Something went wrong. Error code: CL-2. The page will refresh after you click ok");
          document.location.reload();
        }else{
          eval(request.callbackMethod)(null, request.callbackParams);
        }
      }
    }else {
      if(!request.ignoreError){
	      alert("Oops! Something went wrong. Error code: CL-3. The page will refresh after you click ok");
	      document.location.reload();
      }else{
        eval(request.callbackMethod)(null, request.callbackParams);
      }
    }
  }
}

function initialize(index){
  var request = requestsArray[index];
  if (request.varMap) {
    for(var name in request.varMap){   
      if (request.varMap[name] != null){
        if(request.postValueStr == "")
          request.postValueStr = name + '=' + encodeURIComponent(request.varMap[name]);
        else
          request.postValueStr += '&' + name + '=' + encodeURIComponent(request.varMap[name]);  
      }
    }
  }   
}

function makeServerCall(index) {
  var request = requestsArray[index];
  request.httpRequester.open("POST", request.url, request.asyncCall);
  request.httpRequester.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  if(request.asyncCall){
    request.httpRequester.onreadystatechange = new Function('', 'processResponse('+request.index+');');
  }
  request.httpRequester.send(request.postValueStr);
  if(!request.asyncCall){
    processResponse(request.index);
  }
}

function formSubmitAJAX(url, varMap, sucesscallbackMethod, callbackParams, ignoreError, asyncCall, suppressRequestPoolError) {
  
  var request = null;
  var fromPool = false;
  
  for(var i=0; i<requestsArray.length; i++){
    if(requestsArray[i].complete == true){ //can be reused
      request = requestsArray[i];
      fromPool = true;
      break;
    }
  }
  
  if(!fromPool){ //No free request found in pool
    if(requestsArray.length == MAX_REQUEST_SIZE && suppressRequestPoolError == false){
      alert("Oops! Something went wrong. Error code: CL04.");
      return;
    }
    request = new Object();
    request.httpRequester = getHTTPRequestObject();
    request.index = requestsArray.length;

    requestsArray[request.index] = request;
  }
  
  request.complete = false;
  request.url = url;
  request.varMap = varMap;
  request.callbackMethod = sucesscallbackMethod;
  request.callbackParams = callbackParams;
  request.postValueStr = "";
  request.ignoreError = (typeof ignoreError == "undefined" || ignoreError == null)? false : ignoreError;
  request.asyncCall = (typeof asyncCall == "undefined" || ignoreError == null)? true : asyncCall;
  
  initialize(request.index)
  makeServerCall(request.index);
}
/*------------------ Ajax library END -----------------------*/

/*------------------ popup library -----------------------*/	
var popupArray = new Array();

function KaboodlePopup(srcEle, width, height, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId, leftAlign){
	this.srcEle = srcEle;
	this.xPosition = calcXCoordinates(srcEle, width, xAdjust, leftAlign);
	this.yPosition = calcYCoordinates(srcEle, height, yAdjust);
	this.width = width;
	this.height = height;
	this.nonsticky = nonsticky;
	this.popUpDivId = popUpDivId;
	this.popUpContentId = popUpContentId;
	this.blanktimeout = 0;
	this.popupIndex = -1;
	
	//Find the popup with same id
	for(var i=0; i<popupArray.length; i++){
		if(popupArray[i].popUpDivId == popUpDivId){
			this.popupIndex = i;
			break;
		}
	}
	
	if(this.popupIndex == -1){
		this.popupIndex = 	popupArray.length;
		popupArray[popupArray.length] = this;
	}
	
	this.populateHtml = function(popupHtml){
	  document.getElementById(this.popUpContentId).innerHTML = popupHtml;
	}
	
	this.showPopup = function(){
	  hideElement(this.popUpDivId);
	  
	  var popupDiv = document.getElementById(this.popUpDivId);
	  if(this.nonsticky){
	    popupDiv.onmouseout = new Function('', 'onMouseOutPopup('+this.popupIndex+');');
	    popupDiv.onmousemove = new Function('', 'onMouseMovedPopup('+this.popupIndex+');');
	    
	    this.srcEle.onmouseout = new Function('', 'onMouseOutPopup('+this.popupIndex+');');
	    this.srcEle.onmousemove = new Function('', 'onMouseMovedPopup('+this.popupIndex+');');
	  }else{
	    popupDiv.onmouseout = "";
	    popupDiv.onmousemove = "";
	  }
	
	  var popUpContent = document.getElementById(this.popUpContentId);
	
	  if(this.height > 0){
		  popUpContent.style.height = this.height + "px";
	  }
	  
	  if(this.width > 0){
	  	popUpContent.style.width = this.width + "px";
	  	popupDiv.style.width = (this.width + 9) + "px";
	  }
	  
	  popupDiv.style.top = (this.yPosition) + "px";
	  popupDiv.style.left = (this.xPosition) + "px";
	  popupDiv.style.display = "block";
	}
}

function onMouseMovedPopup(popupIndex){
	var kPopup = popupArray[popupIndex];
  clearTimeout(kPopup.blanktimeout);
}

function onMouseOutPopup(popupIndex){
	var kPopup = popupArray[popupIndex];
  kPopup.blanktimeout = setTimeout("hideElement('"+kPopup.popUpDivId+"')", 500);
  kPopup.srcEle.onmouseout = "";
  kPopup.srcEle.onmousemove = "";
}

function calcXCoordinates(srcEle, width, xAdjust, leftAlign){
  var x = findPosX(srcEle);
  
  if(!leftAlign){  
  	 x += srcEle.offsetWidth;
  }
  
  if(typeof xAdjust != 'undefined'){
  	x += xAdjust;
  }

	if(x < 0)x=0;
	return x;
}

function calcYCoordinates(srcEle, height, yAdjust){

  var y;
  
  if(height > 0){
	y = findPosY(srcEle) + srcEle.offsetHeight - height;
  }else{
  	y = findPosY(srcEle) + srcEle.offsetHeight;
  }
  if(typeof yAdjust != 'undefined'){
  	y += yAdjust;
  }

	if(y < 0)y=0;
	return y;
}

function showPopupAboveRight(srcEle, width, height, popupHtml, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId){
	showAndReturnPopupAboveRight(srcEle, width, height, popupHtml, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId);
}

function showAndReturnPopupAboveRight(srcEle, width, height, popupHtml, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId){
	if(typeof popUpDivId == "undefined" || popUpDivId == null){
		popUpDivId = "popUpDiv";
	}
	if(typeof popUpContentId == "undefined" || popUpContentId == null){
		popUpContentId = "popUpContent";
	}

	hideSelectBoxes();
		
	var kPopup = new KaboodlePopup(srcEle, width, height, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId, false);
  kPopup.populateHtml(popupHtml);
  kPopup.showPopup();
  return kPopup;
}
function showAndReturnPopupAboveLeft(srcEle, width, height, popupHtml, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId){
	//TODO: consolidate showAbove left and right to 1 function. 
	
	if(typeof popUpDivId == "undefined" || popUpDivId == null){
		popUpDivId = "popUpDiv";
	}
	if(typeof popUpContentId == "undefined" || popUpContentId == null){
		popUpContentId = "popUpContent";
	}

	hideSelectBoxes();
		
	var kPopup = new KaboodlePopup(srcEle, width, height, nonsticky, xAdjust, yAdjust, popUpDivId, popUpContentId, true);
	kPopup.populateHtml(popupHtml);
	kPopup.showPopup();
	return kPopup;
}
//hide select boxes from IE 6
function hideSelectBoxes(){

   if ( navigator.appVersion.indexOf("MSIE") >= 0) {

     var arVersion = navigator.appVersion.split("MSIE")

     var version = parseFloat(arVersion[1])

     if (version < 7.0 && document.body.filters) 
     {

			for(i=0; i<document.forms.length; i++){
		
				for(j=0; j<document.forms[i].elements.length; j++)
				{
					if(document.forms[i].elements[j].options != null && document.forms[i].elements[j].className.indexOf('hidePopup') <0){
		
						document.forms[i].elements[j].className = document.forms[i].elements[j].className  + ' hidePopup';
					}
		
				}//ednd for(j=0; j<document.forms[i].elements.length; j++)
				
			}//end for(i=0; i<document.forms.length; i++)
		}//end if (version < 7.0 && document.body.filters)
	}//end if ( navigator.appVersion.indexOf("MSIE") >= 0) {
}
function hidePopupAndShow(elementId){

   if ( navigator.appVersion.indexOf("MSIE") >= 0) {

     var arVersion = navigator.appVersion.split("MSIE")

     var version = parseFloat(arVersion[1])

     if (version < 7.0 && document.body.filters) 
     {

		for(i=0; i<document.forms.length; i++){
	
			for(j=0; j<document.forms[i].elements.length; j++)
			{
				if(document.forms[i].elements[j].options != null){
	
					var className = document.forms[i].elements[j].className;
					
					document.forms[i].elements[j].className = className.replace('hidePopup', '');
				}
	
				}//ednd for(j=0; j<document.forms[i].elements.length; j++)
				
			}//end for(i=0; i<document.forms.length; i++)
		}//end if (version < 7.0 && document.body.filters)
	}//end if ( navigator.appVersion.indexOf("MSIE") >= 0) {
	
	hideElement(elementId);
}

/*------------------ popup library END -----------------------*/	

function searchTopNav(allowBlankSearch){
	
	if(!allowBlankSearch && trim(document.getElementById('searchBox').value) == ""){
		alert("Please enter your search query in the search box");
		return;		
	}
	
	if(document.getElementById('st').value == 'group'){
		document.getElementById('search').action = '/groups';
		document.getElementById('search').submit();	
	}else{
		document.getElementById('search').submit();
	}
}

function callOnEnterKey(event, callBack){

	if (event.keyCode == 13) {
		eval(callBack);
  }
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie_c(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));
}

/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie_c(name, value, expires, path, domain, secure) {
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie_c(name, path, domain) {
    if (getCookie_c(name)) {
        document.cookie = name + "=" +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}
 
function checkIfBrowserSupportCookies(){
 	if(document.cookie != null && document.cookie != ''){
 		return true;
 	}
 	else{
		setCookie_c("hp", "0");
		if(getCookie_c("hp")) {
	  	deleteCookie_c("hp");
	  	return true;
		} 
		else{
	  	return false;
		} 
 	}	
}

function clearActionText(){
	if(document.getElementById('actionDivId')){
		document.getElementById('actionDivId').style.display = 'none';
	}
}

function generateAJAXResponseHTML(domNodes){
		var nodeHtml = '';
		for(var i=0; i<domNodes.length; i++){
			nodeHtml += domNodes[i].nodeValue;
		}
		return nodeHtml;
}

/* Inline editing */
var inlineEditTimers = new Array();
function editTextMouseOver(uniqueID){
	clearTimeout(inlineEditTimers[uniqueID]);
	document.getElementById("editMOSection_" + uniqueID).className = "inline-edit-mo";
}
function editTextMouseOut(uniqueID){
	inlineEditTimers[uniqueID] = setTimeout("editTextMouseOutTimerFunc('"+uniqueID+"')", 500);
}
function editTextMouseOutTimerFunc(uniqueID){
	document.getElementById("editMOSection_" + uniqueID).className = "";
}
function inlineEditStart(uniqueID){
	document.getElementById("editTextbox_" + uniqueID).value = document.getElementById("orignalText_" + uniqueID).value;
	showElement("editSection_" + uniqueID, 'inline');
	hideElement("editText_" + uniqueID);
}
function inlineEditAbort(uniqueID){
	hideElement("editSection_" + uniqueID);
	showElement("editText_" + uniqueID, 'inline');
	document.getElementById("editMOSection_" + uniqueID).className = "";
	document.getElementById("editError_" + uniqueID).innerHTML = "";
	hideElement("editError_" + uniqueID);
}
function inlineEditSubmit(uniqueID, url, varMap, sucesscallbackMethod){

	varMap["inlineEditedText"] = document.getElementById("editTextbox_" + uniqueID).value;

	var callbackParams = new Object();
	callbackParams.uniqueID = uniqueID;
	callbackParams.inlineEditedText = varMap["inlineEditedText"];
	callbackParams.callbackMethod = sucesscallbackMethod;
	
	formSubmitAJAX(url, varMap, "inlineEditSubmitCallback", callbackParams)
}
function inlineEditSubmitCallback(results, callbackParams){

	var validationError = results.getElementsByTagName("validationError");
	
	if(validationError.length == 0){
		
		var inlineEditedNode = results.getElementsByTagName("inlineEditedText")[0];
		var inlineEditedText = "";
		if(inlineEditedNode.firstChild){
			inlineEditedText = inlineEditedNode.firstChild.nodeValue;
		}
		
		document.getElementById("editText_" + callbackParams.uniqueID).innerHTML = inlineEditedText;
		document.getElementById("orignalText_" + callbackParams.uniqueID).value = callbackParams.inlineEditedText;
		inlineEditAbort(callbackParams.uniqueID);
		
		if(callbackParams.callbackMethod != ""){
		   eval(callbackParams.callbackMethod)(inlineEditedText);
		}    
	}else{
		document.getElementById("editError_" + callbackParams.uniqueID).innerHTML = validationError[0].firstChild.nodeValue;
		showElement("editError_" + callbackParams.uniqueID);
	}
}
var snTimeout;

function snOver(index){
	snTimeout = setTimeout("showSn('"+index+"')", 300);
}
function snOut(){
	clearTimeout(snTimeout);
}
/**
	Shows the sub nav
*/
function showSn(index){
	var navTab = document.getElementById('n' + index);
	
	if(document.getElementById('sn' +index)){
	
		var innerHtml = document.getElementById('sn' +index).innerHTML;
		
		showAndReturnPopupAboveLeft(navTab, -1, -1, innerHtml, true, 0, -5, 'popNavDiv', 'popNavContent');
		
	}else{
		//Need to have the html here because otherwise we will get js errors when the html for this div has not been loaded yet
		var innerHtml = '<div class="cb-loading loadingSn"></div>';

		showAndReturnPopupAboveLeft(navTab, -1, -1, innerHtml, true, 0, -5, 'popNavDiv', 'popNavContent');
		
	}
}
