var ua=navigator.userAgent;
var isIE=/MSIE/i.test(ua);
var isMoz=/Gecko/i.test(ua);

var css_browser_selector = function() {
	var 
		ua=navigator.userAgent.toLowerCase(),
		is=function(t){ return ua.indexOf(t) != -1; },
		h=document.getElementsByTagName('html')[0],
		b=(!(/opera|webtv/i.test(ua))&&/msie (\d)/.test(ua))?('ie ie'+RegExp.$1):is('gecko/')? 'gecko':is('opera/9')?'opera opera9':/opera (\d)/.test(ua)?'opera opera'+RegExp.$1:is('konqueror')?'konqueror':is('applewebkit/')?'webkit safari':is('mozilla/')?'gecko':'',
		os=(is('x11')||is('linux'))?' linux':is('mac')?' mac':is('win')?' win':'';
	var c=b+os+' js';
	h.className += h.className?' '+c:c;
}();

if (typeof $ != 'undefined') {
	$(document).ready(function() {
		installHovers();
	});
};

function installHovers() {
	var hoverClassName = "hover";
	var hoverClasses = new Array();
	
	hoverClasses.push("link");

	for (hc = 0; hc < hoverClasses.length; hc++) {
		$("." + hoverClasses[hc]).hover(
			function() {
			  $(this).addClass(hoverClassName);
			},
			function(){
			  $(this).removeClass(hoverClassName);
		  }
		);
	};
};

// This is used to set the outerHtml in Mozilla browser
if(isMoz){
	HTMLElement.prototype.__defineSetter__("outerHTML", function (sHTML) {
	   var r = this.ownerDocument.createRange();
	   r.setStartBefore(this);
	   var df = r.createContextualFragment(sHTML);
	   this.parentNode.replaceChild(df, this);
	   return sHTML;
	});
}

/*
 * This function it used to map more than one JavaScript function 
 * to the window.onload event.
 */
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            oldonload();
            func();
        }
    }
}

function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

// START scripts for onmouseover effect in headerbar
var imgPath="";

function preLoadImage(){
	a = preLoadImage.arguments;
	for(i=0; i<a.length; i+=2) 
	{
			this[a[i]] = new Image();
			this[a[i]].src = imgPath + a[i+1];
	}
}

function MM_findObj(n, d) { //v4.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && document.getElementById) x=document.getElementById(n); return x;
}

function swapImgRestore() {
  var i,x,a=document.sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function swapImage(name) {
  document.sr=new Array; 
  	 if ((x=MM_findObj(name))!=null){
	 	document.sr[0]=x; 
	 	if(!x.oSrc) x.oSrc=x.src; 
		x.src = eval(name + ".src");
	}
}
// END scripts for onmouseover effect in headerbar

// script for (de)selecting multiple checkboxes
function CheckAll(formName, checkboxName, check)
{
	var checkboxList = eval('document.forms[formName].' + checkboxName);
	if (checkboxList != null) {
		if (typeof checkboxList.length != 'undefined')		// there is more than one checkbox with the specified name
		{
			for (var i = 0; i < checkboxList.length; i++) 
					checkboxList[i].checked=eval(check);           
		} else {											// there is only one checkbox on the form
				checkboxList.checked=eval(check);
		}
	}
}

// script for submitting a form whereby the mode is changed
function doSubmit(formName, subMode)
{
	document.forms[formName].mode.value = subMode;
	document.forms[formName].submit();
}

//script for executing an action upon the press of the ENTER key. 
// the action to perform must be specified in the page by defining "var ACTION_ON_ENTER = '<action_to_perform>'"
if (navigator.appName == 'Netscape'){document.captureEvents(Event.KEYPRESS);} 
document.onkeypress = doEnterAction;
var preKeyWasNotEnter = true;

function doEnterAction(pressedKey){
	if (navigator.appName == 'Netscape'){pressedKeyCode=pressedKey.which;} 
	if (navigator.appName == 'Microsoft Internet Explorer'){pressedKeyCode=window.event.keyCode;}
	if (pressedKeyCode == 13) {
		if (typeof ACTION_ON_ENTER != 'undefined' && preKeyWasNotEnter==true) {
			eval(ACTION_ON_ENTER);	
			preKeyWasNotEnter = false;
			return !(window.event && window.event.keyCode == 13);
		}
	}
	else {
		preKeyWasNotEnter = true;
	}
}

// script to disable multiple submits
var formSubmitted = false;
function doSingleSubmit(formName, subMode)
{
	if (!formSubmitted)
	{
		formSubmitted = true;
		if (subMode != null) document.forms[formName].mode.value = subMode;
		document.forms[formName].submit();
	}
}

// script to disable multiple clicks on link
var linkClicked = false;
function doSingleClick(timeout) {
	
	if (!linkClicked) {
		linkClicked = true;
	    setTimeout("linkClicked = false;", arguments.length > 0 ? timeout : 3000);
		return true;
	} else {
		return false;
	}	
}

// perform trim function on the string sent as argument and returns the trimed string
// This function removes all the spaces "  money  art " => "moneyart".
// If you need only to remove the leading and trailing apce, use the trim(str) function.
function trimString(str){
	var s = "";

	if(str == null)
		return "";
		
	for (i=0; i< str.length; i++){
		c = str.charAt(i);
		if(c != ' ')
			s+=c;
	}

	return s;
}

/**
 * DON'T USE IT! It's unstable. Please use document.getElementById(elementId) instead.
 * returns a reference to object with given id as String, for three different DOM 
 */

function getObject(elemID) {
	if (document.all) {
		obj = document.all(elemID); 			/* Internet Explorer object reference */
	} else if (document.getElementById) {
		obj = document.getElementById(elemID);	/* Mozilla object reference */
	} else if (document.layers) {
		obj = document.layers[elemID];			/* Netscape object reference */
	}	
	return obj;
}

/* This function trims a string "   money  art " => "money  art".
 * It removes the space before and after the String str.
 */
function trim(str){
	str = str.replace(/^\s+/g, ""); //strip leading
	return str.replace(/\s+$/g, ""); //strip trailing
}

/**
 * Checks if key pressed is integer (0-9).
 * Numbers from 0 to 9 have key codes from 48 to 57
 */
function checkIntegerOnly(evt) {
	// Catch  the event: window.event for IE; evt for Mozilla
	evt = (evt) ? evt : window.event;
	// Take from event key pressed: evt.keyCode for IE; evt.which for Mozilla
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	// Check if character is valid (0-9)
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		return false;
	}
	return true;
}

/**
 * Checks if key pressed is decimal (0-9 or .).
 * Numbers from 0 to 9 have key codes from 48 to 57. Key "." has the
 * code 46
 */
function checkDecimalOnly(evt) {
	// Catch  the event: window.event for IE; evt for Mozilla
	evt = (evt) ? evt : window.event;
	// Take from event key pressed: evt.keyCode for IE; evt.which for Mozilla
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	// Check if character is valid (0-9 or .)
	if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46) {
		return false;
	}
	return true;
}

/**
 * When submitting a form with an action type that depends on user input 
 * having checked/selected at least one element from a list (each element 
 * prefixed by a checkbox), check must be performed if at least one element
 * was selected. 
 */
function checkAnySelected(formName, checkboxName) {
	var checkboxList = eval('document.forms[formName].' + checkboxName);
	var	isChecked = false;
			
	if (checkboxList != null) {
		if (typeof checkboxList.length != 'undefined') { 
			// there is more than one checkbox with the specified name
			for (var i = 0; i < checkboxList.length; i++) {
				if (checkboxList[i].checked == true) {
				  isChecked= true;
				  break;
				}
			}
		} else { // only one checkbox with the specified name
			isChecked = checkboxList.checked;
		}
	}
	
	return isChecked;
} 

/**
*  Sets the last selected search criteria.
*/
function setLastExample(selectElem) {
  selectElem.last = selectElem.value;
}
  
/**
* Sets an given element's visibility to false.
*/  
function setToNonVisible(searchType)
{ 
    var selType = document.getElementById(searchType.value);
    if (selType != null) {
    	 selType.className = "invisible";
	}	    	 
}

/**
* Shows the example for the selected search criteria.
*/
function changeExample(selectElem) {
  var searchType1 = document.getElementById ("searchType1");
  var searchType2 = document.getElementById ("searchType2");
  var searchType3 = document.getElementById ("searchType3");
  if (searchType1 != null ) {
	setToNonVisible(searchType1);
  }
  if (searchType2!= null ) {
	setToNonVisible(searchType2);
  }
  if (searchType3!= null ) {
	setToNonVisible(searchType3);
  }  
  var selectedExample = document.getElementById("ex" + selectElem.value);
  var elementId;
  var example;
  var length = selectElem.options.length;
  
  for (var i = 0; i < length; i++) {
  	elementId = selectElem.options[i].value;
  	example = document.getElementById("ex" + elementId);
  	if(example != null) {
		example.className = "invisible";
	}
  }  
  if (selectedExample != null) {
    selectedExample.className = "visibleEx";
  }
}

/**
* Changes the search type example in a search page
* @param select - the dropdown box with the search types
* @param elementID - the ID of the search text box
*/
function changeSearchValue(select, elementID) {
   changeExample(select);
   var searchForObj = document.getElementById (elementID);      
   searchForObj.value = '';      
}		

String.prototype.trim=function() {
	return this.replace(/^\s+|\s+$/,"");
}

/**
 * Opens a new window for given URL.
 */
function goToURL(url) {
	var height = screen.availHeight - 16;
	var width = screen.availWidth - 10;
	url = url.trim();
	if (url != '') {
		var index = url.indexOf("www");
		if (index == 0) url = "http://".concat(url);
		window.open(url, null, 'status=yes,menubar=yes,toolbar=yes,location=yes,scrollbars=yes,resizable=yes,top=0,left=0,width='+width+',height='+height);
	}
}

/**
 * Alternate table row colors. The table rows are not the result of a
 * iterate process but are relatively fixed with some rows that show or
 * do not show - depending on form's flag indicator values.
 * 
 */
function alternateRowColors(tableElemId, includeHeader) {
	var tableElem = document.getElementById(tableElemId);
	if (tableElem != null) {
		var tableRows = tableElem.tBodies[0].rows;
		var rowStart = 1;
		if (includeHeader) rowStart = 0;
		for(var i = rowStart; i < tableRows.length; i++) {
			tableRows[i].className=(i%2==1 ? "even" : "odd")
		}	
	}
}

/**
 * Alternate table row colors for groups of rows. 
 * A group of rows will have the same color. 
 * @param prmCfg.id: id of the table containg the groups of rows to be colored
 * @param prmCfg.rowsInGroup: the no of rows in the group can be specified
 * @param prmCfg.even: CSS class name coresponding to the even rows groups
 * @param prmCfg.odd: CSS class name coresponding to the odd rows groups
 */
function alternateColorsForGroupOfRows(prmCfg){
 	return(
    	function(){
			var rows=document.getElementById(prmCfg.id).tBodies[0].rows;
			var rowsInGroup=prmCfg.rowsInGroup || 1;
			var j=0;
			for(var i=0;i<rows.length;i+=rowsInGroup){
				if(j%2==0){
             		rows[i].className=prmCfg.even;
             		for(var k=i+1;k<i+rowsInGroup && k<rows.length;k++){
              			rows[k].className=prmCfg.even;
					}
				} else {
	            	rows[i].className=prmCfg.odd;
    	          	for(var k=i+1;k<i+rowsInGroup && k<rows.length;k++){
        	      		rows[k].className=prmCfg.odd;
					}
				}
				j++;
			}
      	}
	)
}

function getElementsByClassName(classname) {
    if (document.getElementsByTagName) {
         var els = document.getElementsByTagName("*");
         var c = new RegExp('\\b' + classname + '\\b');
         temp1 = new Array();
         var n=0;
         for (var i=0; i < els.length; i++) {
              if (els[i].className) {
                   if(c.test(els[i].className)) {
                   temp1[n] = els[i];
                   n++;
                   }
              }
         }
         return temp1;
    } else {
    	return false;
    }
}

/**
 * Function to disable scrolling within combo boxes (IE problem) 
 */
function stopWheelOnCombos() {
	var allCombos = document.getElementsByTagName("select");
	for(var i = 0; i< allCombos.length; i++) {
		allCombos[i].onmousewheel = (function(){return false});
	}
}

/**
 * Add load event for IE: disable scrolling within combo boxes
 */
addLoadEvent(function() {
	if(isIE) {
		stopWheelOnCombos();
		}
});
/**** START: methods used to limit the number of characters in a textarea ****/
//mask keyboard key press: allow only noncharacter keys if length reached the max allowed
//usage: return maskKeyPress(event, maxLength) on 'onkeypress' event
function maskKeyPress(objEvent, maxLength) {
	if (isIE) {
			var iKeyCode, strKey, objInput;
			//regular expression corresponding to noncharacter keys
		 	var reKeyboardChars = /[\x00\x03\x08\x0D\x16\x18\x1A]/;
	
			iKeyCode = objEvent.keyCode;
			objInput = objEvent.srcElement;
	
			strKey = String.fromCharCode(iKeyCode);
	
			//always allow keys to be used when with Ctrl is pushed.
	        if(objEvent.ctrlKey) {
				return true;
			}
			//allow keys to write if there is some text selected 
			// in the textarea (allow the user to overwrite it)
			var selectedText = document.selection;
			if (selectedText.type == 'Text') {
				return true;
			}		
	        if (objInput.value.length >= maxLength && !reKeyboardChars.test(strKey)) {
				return false;
			}				
			return true;
		} else if(isMoz) {
			return true;
		}
}
			
//paste only the allowed number of characters from the clipboard
//usage: return maskPaste(event, maxLength) on 'onpaste' event 
//(this event does not fire in Firefox)
function maskPaste(objEvent, maxLength) {
	if (isIE) {
		objInput = objEvent.srcElement;
		} else {
			objInput = objEvent.target;
		}
    if (isIE) {
    var oTR = objInput.document.selection.createRange();
    var insertLength = maxLength - objInput.value.length + oTR.text.length;
	try {
		var sData = window.clipboardData.getData("Text");
		oTR.text = sData.substr(0, insertLength);
		} catch (err) {
		}
    	window.event.returnValue = null;
    } else {//not IE
    	obj.value = obj.value.substr(0, maxLength);
        return false;
	}
}

//delete trailing newlines (if any)
//usage: simply call this method on 'onchange' event
function maskChange(objEvent, maxLength) {
  	var objInput;
  	if (isIE) {
    	objInput = objEvent.srcElement; 
  	} else {
    	objInput = objEvent.target;
  	}
	objInput.value = objInput.value.substring(0, maxLength);
}

//for Firefox, we limit the number of chars from the textarea
//by writing back just a substring of the text from the textarea
//usage: simply call this method on 'oninput' event
//this event shoots only in Firefox
function maskInput(objEvent, maxLength) {
  	var objInput;
    objInput = objEvent.target;
	objInput.value = objInput.value.substring(0, maxLength);
	
	var space = (objInput.value.charAt(objInput.value.length-1) == ' ');
	
	var minUnitsPerLine = 1;
	var maxUnitsPerLine = 25;
	var regEx=eval("/((.|\\n){" + minUnitsPerLine + "," + maxUnitsPerLine + "})/g");
	var words = objInput.value.split(/ /g);
	var rez = "";
	for(var i = 0; i < words.length; i++) {
		var word = words[i];
		word = word.replace(regEx,"$1 ");
		rez = rez + word;
	}
	if(!space) {
		rez = rez.replace(/ $/g, "");
	}
	
	objInput.value = rez;
}
/**** END: methods used to limit the number of characters in a textarea ****/

/* javascript method to allow only numbers in a textbox 
 usage: return what this method returns on keypress event.
 suggestion: use  validation from struts form also, 
 because the clipboard is not disabled */

function onlyNumbers(objEvent) {

	var iKeyCode, strKey;
	
	//regular expression correcponding to number characters
	var reValidChars = /\d/;
	
	//regular expression corresponding to noncharacter keys
 	var reKeyboardChars = /[\x00\x03\x08\x0D\x16\x18\x1A]/;
	
	if (isIE) {
	    iKeyCode = objEvent.keyCode;
	} else {
	    iKeyCode = objEvent.which;
	}
	strKey = String.fromCharCode(iKeyCode);
	
	//allow keys to be used when Ctrl is pushed. (to permit Ctrl+V and Ctrl+V))
    if(objEvent.ctrlKey) {
		return true;
	}
	
	//if not numeric and not keyboard control keys, then ignore them
	if (!reValidChars.test(strKey) && !reKeyboardChars.test(strKey)) {
		return false;
	}
}

/*
 * Object that contains subscription search related functionality
 */
var SubscriptionBasicSearch = {
	//function used for pagination (pageindicator2 tag)
	getResultsForPage : function(pageNumber) {
		var myForm = getElementsByClassName('paginationForm')[0];
		var currentPage = myForm.currentPage;
		currentPage.value = pageNumber;
		myForm.submit();
	}
};


/**
 * Method to simulate the hover pseudo class to any element.
 * It adds/removes the class "hover" while the mouse is moving over the element.
 */
function makeHover(element) {
	element.onmouseover=function() {
		this.className+=" hover";
	};
	element.onmouseout=function() {
		this.className=this.className.replace(new RegExp(" hover\\b"), "");
	};	
};

/* 
 * function used to count the number of selected 
 * document delivery providers.
 */
function countSelectedDocDelProviders() {

	var e = document.getElementsByTagName('input');
	var checkedProviders = 0
	for (var i = 0; i < e.length; i++) {
		// count the checked doc del providers.
		if (e[i].type == 'checkbox' && e[i].checked == true 
			&& (e[i].name == 'documentDeliveryProviderIDs' || e[i].name == 'libDocDel')) {
	        checkedProviders++;
		}
	}
	return checkedProviders;
}

/* 
 * function used to enable the document delivery povider checkboxes 
 * (called in case the document delivery provider functionality is enabled.
 */
function enableDocDelProviderCheckBoxes() {
	var e = document.getElementsByTagName('input');
	var checkedProviders = 0
	for (var i = 0; i < e.length; i++) {
		// count the checked doc del providers.
		if (e[i].type == 'checkbox'
			&& (e[i].name == 'documentDeliveryProviderIDs' || e[i].name == 'libDocDel')) {
	        e[i].checked = false;
	        e[i].disabled = false;
		}
	}
}

/* 
 * function used to disable the document delivery povider checkboxes 
 * (called in case the document delivery provider functionality is disabled.
 */
function disableDocDelProviderCheckBoxes() {
	var e = document.getElementsByTagName('input');
	var checkedProviders = 0
	for (var i = 0; i < e.length; i++) {
		// count the checked doc del providers.
		if (e[i].type == 'checkbox'
			&& (e[i].name == 'documentDeliveryProviderIDs' || e[i].name == 'libDocDel')) {
	        e[i].checked = false;
	        e[i].disabled = true;
		}
	}
}

function expand(x) {
    var section = $(x).parents(".section");
    if (typeof updateExpander == 'undefined') {
	    section.find(".full").slideToggle(100);
    } else {
	    section.find(".full").slideToggle(100, updateExpander);
    }
    section.find(".collapse, .expand").toggleClass("invisible");
};

