/* common.js begin */
/**
 * Can be used by any ajax call that send data to
 * the server but does not expect any response
 */

function onResponse()
{
	if(checkReadyState(request))
	{
		//alert(request.responseXML);
		//alert(request.responseText);

	}
}

/* used for switching tabs */
function getSearchField(tabLink, mode){
        if (mode == "Basic"){
                var searchField = document.getElementById("search_field");
                var hrefStr = tabLink.href.replace(/vl\(freeText0\)\=[^\&]*\&/,"vl(freeText0)="+searchField.value+'&');
                if (searchField.value==''){
                        hrefStr = hrefStr.replace("&fn=search","");
                }else if (tabLink.href.indexOf('vl(freeText0)')<0){ //take care of situation where we are sitting on home page and there was no previous search.
                        hrefStr += '&fn=search&vl(freeText0)='+searchField.value;
                }
                tabLink.href=hrefStr;
        }
}

/* used with Search And Link */

function submitForm(f) {

      w = openWindow(f.action, "searchAndLinkPopup", 'top=100,left=50,width=900,height=600,resizable=1,scrollbars=1');

      w.focus();

      f.submit();

}



function emptyFunction()
{
}

/**
 * AJAX call that allows asyncronic removing/adding items from
 * the current user basket
 */
function updateBasket(docid,isAdd,remote,scopes,index)
{

	if( isAdd ){
		fn='create';
	}else{
		fn='remove';
	}


	var basketPrefix = addSessionId("basket.do");
	ajaxGet(basketPrefix+"?fn="+fn+"&docs="+docid+"&exemode=async"+"&remote="+remote+"&scopes="+scopes+"&index="+index, onResponse);
}

function addSessionId(urlPrefix){
	if(!navigator.cookieEnabled){
		var path = window.location+"";
		var sessionId = path.substring(path.indexOf(";jsessionid"), path.indexOf("?"));
		urlPrefix = urlPrefix + sessionId;
	}
	return urlPrefix;

}

/*function updateDiv(divId,url){
	ajaxGet(url,function (){
		if(checkReadyState(request))
		{
			document.getElementById(divId).innerHTML = request.responseText;
		}
	});
}*/

/**
 * AJAX call that sends the server the current status for folder (open or closed)
 */
function toggleFolder(folderId,isOpen)
{
	ajaxGet("/basket.do"+"?fn=toggle"+"&folderId="+folderId+"&exemode=async"+"&isOpen="+isOpen, emptyFunction);
}

/**
 * handleing the remote test response

function onIsRemote()
{
	if(checkReadyState(request))
	{
		if(request.responseText=='remote'){
			//display the please wait popup
			delay();
		}
	}
}*/

/**
 * Testing if the list of scopes inclouds a remote location
 * This used to be an AJAX call that allows asyncronic test of
 * remote loaction using the action IsRemoeteAction but was
 * replaced with a naive test for numbers as remote location
 * due to bug 1227
 */
function isRemoteSearch(){
        //check if the selected scope is the Selected Databases scope
        var selectedDbDiv = document.getElementById('Selected_Databases-Div');
        if(selectedDbDiv != null){
                if($(selectedDbDiv).find('input:checked').size() > 0){
                        return true;
                }
        }else{
                var selectedDb = document.getElementById('Selected_Databases');
                if(selectedDb != null){
                	if(selectedDb.selected == true){
                        return true;
                	}
                }
        }

        var selectElement = document.getElementById('exlidSearchIn');
        var scopesid = '';
        if(!selectElement && !$('#scopesListContainer').hasClass('EXLDynamicSelectOnlyOneScope')){
                scopesid = $('.EXLSearchFieldRibbonFormCollectionsList input:checked').val();
                return checkForRemoteScope(scopesid);
        }else{
        	if(selectElement != null){//Advanced
                scopesid = selectElement.options[selectElement.selectedIndex].value;
        	}else{//simple single scope
        		scopesid = $('.EXLDynamicSelectBodyRadioFirst').children('input').val();
        	}
        	return checkForRemoteScope(scopesid);
        }
}
function checkForRemoteScope(scopesid){
        //We assume that number based id is a remote id
        //if we find one remote id we will mark this as remote and
        //will play animation
        var ids = scopesid.split(',');
        var isRemote = false;
        for(var i = 0 ; i<ids.length;i++){
                //only one or more digits
                if(ids[i].match(/^\d+$/)){
                        isRemote = true;
                        break;
                }
        }
        //play animation
        return isRemote;
}





function delay4Remote(isRemote){
		if(isRemote=='remote'){
			doPleaseWait(true,true);
		}
}
function delay4Remote(isRemote, tabsRemote, tab){
		if(isRemote=='remote' && tabsRemote){
			doPleaseWait(true,true,tabsRemote,tab);
		}
}

//will return the string Firefox,IE, or Opera
function getBrowserType(){

		if(navigator.userAgent.indexOf("Firefox")!=-1){
			var versionindex=navigator.userAgent.indexOf("Firefox")+8
			if (parseInt(navigator.userAgent.charAt(versionindex))>=1)
				return "Firefox";
		}

		version=0
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			temp=navigator.appVersion.split("MSIE")
			version=parseFloat(temp[1])
		}

		if (version>=5.5){ //NON IE browser will return 0
			return "IE";
		}

		if(navigator.userAgent.indexOf("Opera")!=-1){
			var versionindex=navigator.userAgent.indexOf("Opera")+6
			if (parseInt(navigator.userAgent.charAt(versionindex))>=8){
				return "Opera";
			}
		}
}

function focuscursor(){
      var searchBox = document.getElementById("search_field");
      searchBox.focus();
  }

function getScrollXY() {
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

/*****
AJAX code
*****/

var request = null;


function ajaxGet(uri,handlerFunction){

		if(window.XMLHttpRequest){ //mozilla, opera, safari, etc..
			request = new XMLHttpRequest();
		}else if(window.ActiveXObject){ //IE6+..
			request = new ActiveXObject("MSXML2.XMLHTTP");
		}
		request.onreadystatechange = handlerFunction; //the event handler for when we receive an asynchronous response
		// hack to get over IE caching URL responses

        if(uri.length>0){
                if( uri.indexOf('?')<0 ){
                        uri+= '?';
                }
        }
        uri += "&ms=" + new Date().getTime();

		request.open("GET", uri , true);
		request.send(null);
}

/**
 * Monitors the ajax execution state
 */
function checkReadyState(obj)
{
	if(obj.readyState == 4)	{
		try{
			if(obj.status == 200){
				return true;
			}else{
				 //alert("An error accured while accessing the server. Error code:" + obj.status );
			}
		}catch(err){
   		 //if firefox then assume known firefox bug and return true
		 return false;
		}
	}
}

/**
 * generic useful functions
 */
function e(id){ //get element
	return document.getElementById(id);
}
function l(str){ //log info to firebug console (if it exists, otherwise do nothing)
	try{
		if (console){
			console.log(str);
		}
	}catch(e1){}
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function openWindow(src,title,params){
	if (!params){
		params = 'top=100,left=50,width=665,height=580,resizable=1,scrollbars=1';
	}
	try{
		var win = window.open(src,title,params);
		if (win.focus){
			win.focus();
		}
		return win;
	}catch(ex){
		return true;
	}
}

function applyDisplayToTagClass(tagP,classP,displayP){
	var tags=document.getElementsByTagName(tagP);
	var numCells=tags.length;
	var classRegEx = eval ( "/" + classP + "/" );

	for(var i=0;i<numCells;i++){
		if(classRegEx.test(tags[i].className)){
			tags[i].style.display = displayP;
		}
	}
}

function isUpdateAllowed(overrideIsUpdateAllowed){
	if(overrideIsUpdateAllowed){
	 return true;
	}
	//this func should determine whether or not to run an ajax rtaUpdate.
	//if for some reason we can't find the checkbox or we run into any other problems,
	//we will go ahead w/ the ajax rtaUpdate, why? because 95% of the time it's useful to the user.
	try{
		var checkbox = document.getElementById("allowRefresh_chkbx");
		if (!checkbox.checked){ //we only don't update if we found the checkbox and it is unchecked.
			return false;
		}
	}catch(e){
	}
	//in any other case, do the update.
	return true;
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}

String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

/* common.js end */
