
/**
 * This is the main search databases method - gets a searchType and calls ajax calls to MetaLib.
 * The calls return HTML fragments that are then used to refresh different tabs in the FDB screen
 * @param searchType (select - checkbox selected; AZ- a to z clicked;
 *  Find - a search executed; Info - More info request)
 * @param searchTerm
 * @param currentDiv
 * @return HTML fragments
 */
function performDbSearch(searchType,searchTerm,currentDiv){
	var fn;
	var url;
	fn='go';
	$('#CategoryOnly').hide();
	$('#ErrorMessageNotAvailable').hide();
	$('#NoDbSelected').hide();
	$('#NoSearchTerm').hide();
	if(parseInt(document.getElementById("metalibLimit").value) == $("#SelectedDbs input:checkbox").length){
		$('#ErrorMessageSdbReached').show();
		document.getElementById('scrollToTopHere').scrollTop = 0;
	}else{
		$('#ErrorMessageSdbReached').hide();
	}
	if(searchType == "AZ"){
		$('#AllResults').html(' ');
		$('#AllResults').addClass('exliLoadingAz');
		//change the AZ letter header to be selected
		$('#EXLFindDBListAtoZList li[id='+searchTerm+']').addClass('EXLFindDBListHeaderAtoZSelected');
		$('#EXLFindDBListAtoZList li[id != '+searchTerm+']').removeClass('EXLFindDBListHeaderAtoZSelected');
		if(currentDiv != "hideSearch"){
			$('#SearchingMessage').show();
		}
		url = "searchDB.do"+"?fn="+fn+"&searchTerm="+encodeURIComponent(searchTerm)+"&AzSearch=true&exlidIncludeRestricted="+document.getElementById("exlidIncludeRestricted").value+"&languagePrefix="+document.getElementById("languagePrefix").value;
	}else{
		if(searchType == "Find"){
			var resultHtml = $('#AllResults').html();
			$('#AllResults').html(' ');
			$('#ResultsDbs').html(' ');
			$('#AllResults').addClass('exliLoadingAz');
			$('#ResultsDbs').addClass('exliLoadingAz');
			if(document.getElementById('searchTerm').value.length == 0 && document.getElementById('exlidCategory').value.length == 0 && document.getElementById('exlidSearchTermPublisher').value.length == 0 && document.getElementById('exlidSearchTermKeywords').value.length == 0 && document.getElementById('exlidIrdType').value.length == 0){
				$('#NoSearchTerm').show();
				$('#ResultsDbs').removeClass('exliLoadingAz');
				$('#AllResults').removeClass('exliLoadingAz');
				return false;
			}
			$('#SearchingMessage').show();
			url = "searchDB.do"+"?fn="+fn+"&searchTerm="+encodeURIComponent(document.getElementById('searchTerm').value)+"&AzSearch=false&selectSearchMethod="+document.getElementById("selectSearchMethod").value+
			"&exlidSearchTermKeywords="+encodeURIComponent(document.getElementById("exlidSearchTermKeywords").value)+
			"&exlidIncludeRestricted="+document.getElementById("exlidIncludeRestricted").value+
			"&exlidIrdType="+encodeURIComponent(document.getElementById("exlidIrdType").value)+
			"&exlidCategory="+document.getElementById("exlidCategory").value+
			"&exlidSubCat="+document.getElementById("exlidSubCat").value+
			"&exlidSearchTermPublisher="+encodeURIComponent(document.getElementById("exlidSearchTermPublisher").value) ;
		}else{
			if(searchType == "Info"){
				$('#'+currentDiv + ' div[id ^= moreInfo'+searchTerm+']').removeClass('EXLFindDBListInfoHide');
				$('#'+currentDiv + ' div[id ^= moreInfo'+searchTerm+']').addClass('EXLFindDBListInfo');
				url = "searchDB.do"+"?fn=moreInfo&searchTerm="+searchTerm ;
			}else{
				if(searchType == "Select"){
					url = "searchDB.do"+"?fn=buildScope&searchTerm="+searchTerm+"&items=" +searchTerm;
					getSelectedTabHTMLContent(url);
					applyClickOnAllTabs(searchTerm+'_dummyId',document.getElementById('currentShownDiv'));
					$('#SelectedDbs div[id ^= NoResultsMessage]').hide();
					return;
				}else{
					url = "searchDB.do"+"?fn="+fn+"&AzSearch=false&selectSearchMethod="+document.getElementById("selectSearchMethod").value;
				}
			}
		}
	}

	var data = $.ajax({
		url:url,
		global:false,
		beforeSend: function(request){
			setAjaxRequestHeader(request);
		},
		error: function(request,errorType,exceptionOcurred){
			if (errorType=='timeout'){
				notifyAjaxTimeout();
				document.getElementById('exliLoadingFdb').style.display='none';
			}else{
				if(searchType != "Find"){
					$('#ErrorMessageNotAvailable').show();
				}
				document.getElementById('exliLoadingFdb').style.display='none';;
			}
		},
		async:false
	}).responseXML;
	if (isAjaxXmlRedirect(data)){
		handleAjaxXmlRedirect(data);
	}
	var elm = $(data).find('dbResultsXml');
	var cdata = $(elm).text();
	var n;
	if(searchType == "AZ"){
		n = document.getElementById("AllResults");
	}else{
		if(searchType == 'Find'){
			n = document.getElementById("ResultsDbs");
		}else{
			if(searchType == "Info"){
				n = document.getElementById("moreInfo"+searchTerm);
			}else{

					n = document.getElementById("SelectedDbs");

			}
		}
	}
	if(searchType != 'Select'){
		if(searchType == "Info"){
			$('.exliLoadingFdbMoreInfo').hide();
			$('#'+currentDiv + ' div[id ^= moreInfo'+searchTerm+']').html(cdata.replace(/\n\n/g, "\n").replace(/&lt;/g,"<").replace(/&gt;/g,">"));
			if($('#'+currentDiv + ' div[id ^= moreInfo'+searchTerm+']').children('input[name = numberOfDisplayedFields]').val() == 0){
				$('#'+currentDiv + ' div[id ^= moreInfo'+searchTerm+']').html(exlFdbNoInfoMessage);
			}
		}else{
			$('#AllResults').html(resultHtml);
			$('#ResultsDbs').removeClass('exliLoadingAz');
			$('#AllResults').removeClass('exliLoadingAz');
			$('#SearchingMessage').hide();
			$('#AllResults').show();
			$('#ResultsDbs').show();
			n.innerHTML = cdata.replace(/\n\n/g, "\n").replace(/&lt;/g,"<").replace(/&gt;/g,">");;
			document.getElementById('scrollToTopHere').scrollTop = 0;
		}
	}
	if(searchType == 'Find'){
		if(document.getElementById("exlidCategory").value.length > 0){
			if($("#searchTerm").val().length > 0 || $("#exlidSearchTermPublisher").val().length > 0 || $("#exlidSearchTermKeywords").val().length > 0 || $("#exlidIrdType").val().length > 0 ){
				$('#CategoryOnly').show();
			}
		}
		$('#numberOfResultsDbs').html($('#ResultsDbs input[type=checkbox]').length);
	}
}
/**
 * This method makes sure that once a resource is clicked (checkbox) if the resource appears in any other
 * tab it is updated on the fly
 * @param id
 * @param inCurrentDiv
 * @return
 */
function applyClickOnAllTabs(id,inCurrentDiv){
	var divArray = ["AllResults","ResultsDbs"];
	var comparableId = id.substring(0,id.indexOf('_'));
	for(i=1; i<=2; i++){
		if(divArray[i-1] != inCurrentDiv.value){
			if($('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']')[0] != null){
				if($('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']')[0].checked == true){
					$('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']').attr('checked', false);
				}else{
					$('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']').attr('checked', true);
				}
			}
		}else{
			//if limit didnt allow addition uncheck the IRD checkbox
			//This part makes sure that no matter what at the end in the
			// current tab the checkbox clicked has the same value as represented
			// on the selected databases tab which represents the server
			if($('#SelectedDbs input[type=checkbox][id ^= '+comparableId+']').length == 0){
				$('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']').attr('checked', false);
			}else{
				if($('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']')[0].checked == false){
					$('#'+divArray[i-1]+' input[type=checkbox][id ^= '+comparableId+']').attr('checked', true);
				}
			}
		}
	}
}
/**
 * Show the specific info for a databases after clicking more info
 * @param parentDiv
 * @param childDiv
 * @return
 */
function showMoreInfoDiv(parentDiv,childDiv){
	//close all open show info div's

	$('#'+parentDiv + ' div[id ^= moreInfo]').addClass('EXLFindDBListInfoHide');
	$('#'+parentDiv + ' div[id ^= hideInfoLink]').addClass('EXLFindDBListInfoHide');
	$('#'+parentDiv + ' div[id ^= showInfoLink]').removeClass('EXLFindDBListInfoHide');
	$('.exliLoadingFdbMoreInfo').hide();
	$('#'+parentDiv + ' div[id ^= moreInfo'+childDiv+']').removeClass('EXLFindDBListInfoHide');
	$('#'+parentDiv + ' div[id ^= moreInfo'+childDiv+']').addClass('EXLFindDBListInfo');
	$('#'+parentDiv + ' div[id ^= showInfoLink'+childDiv+']').addClass('EXLFindDBListInfoHide');
	$('#'+parentDiv + ' div[id ^= hideInfoLink'+childDiv+']').removeClass('EXLFindDBListInfoHide');
	$('#'+parentDiv + ' div[id ^= hideInfoLink'+childDiv+']').addClass('EXLFindDBListShowInfo');
}

function hideMoreInfoDiv(parentDiv,childDiv){
	$('#'+parentDiv + ' div[id ^= moreInfo'+childDiv+']').html('');
	$('#'+parentDiv + ' div[id ^= moreInfo'+childDiv+']')[0].className = '';
	$('#'+parentDiv + ' div[id ^= showInfoLink'+childDiv+']').removeClass('EXLFindDBListInfoHide');
	$('#'+parentDiv + ' div[id ^= showInfoLink'+childDiv+']').addClass('EXLFindDBListShowInfo');
	$('#'+parentDiv + ' div[id ^= hideInfoLink'+childDiv+']').addClass('EXLFindDBListInfoHide');
}


/**
 * When the select all is clicked - we want to make sure we are not paasint the allowed limit.
 * If we exceed the limit nothing will be selected.
 * If we reach the limit the resource will be added
 * In both cases appropriate messages will appear
 * When calculating if we reached the limit need to dissregard the databases that are disabled, since
 * they will not be added
 * @param selectedDiv
 * @param action
 * @return
 */
function selectAllckboxes(selectedDiv,action){
	var selectedDiv;
	var action;
	var cb = $("#" + selectedDiv + " input[type='checkbox']");
	var checkedCb = $("#" + selectedDiv + " input:not(:checked)[type='checkbox']:enabled");
	var params = "searchDB.do"+"?fn=buildScope&";
	var cbLength = 0 ,checkedCbLength;
	var counterSelectedAddition = 0 ;
	if(action == "select"){
		cbLength = cb.length;
		checkedCbLength = checkedCb.length;
		$('#numberOfSelectedDbs').html($("#SelectedDbs input:checkbox").length);
		$('#ErrorMessageSdbExceed').hide();
		$('#ErrorMessageSdbReached').hide();
		if((parseInt(document.getElementById("metalibLimit").value) < $("#SelectedDbs input:checkbox").length + checkedCbLength)||(parseInt(document.getElementById("metalibLimit").value) == $("#SelectedDbs input:checkbox").length + checkedCbLength)){
			if((parseInt(document.getElementById("metalibLimit").value) < $("#SelectedDbs input:checkbox").length + checkedCbLength)){
				$('#ErrorMessageSdbExceed').show();
			}else{
				$('#ErrorMessageSdbReached').show();
			}
			document.getElementById('scrollToTopHere').scrollTop = 0;
		}
		if((parseInt(document.getElementById("metalibLimit").value) >= $("#SelectedDbs input:checkbox").length + checkedCbLength)){
			for (var i=0; i<cb.length; i++) {
				if (!cb[i].checked && !cb[i].disabled) {
					applyClickOnAllTabs(cb[i].id,document.getElementById('currentShownDiv'));
					params += "items=" + cb[i].id + "&";
					counterSelectedAddition++;
				}
			}
			$("#" + selectedDiv + " input[type='checkbox']:enabled").attr('checked', true);
		}else{
			return;
		}
	}else{
		for (var i=0; i<cb.length; i++) {
			if (cb[i].checked) {
				applyClickOnAllTabs(cb[i].id,document.getElementById('currentShownDiv'));
				params += "items=" + cb[i].id + "&";
           	}
		}
		$("#" + selectedDiv + " input[type='checkbox']:enabled").attr('checked', false);

	}

	getSelectedTabHTMLContent(params);
	if(selectedDiv == 'SelectedDbs' && action != "select"){
		$('#SelectedDbs div[id ^= NoResultsMessage]').hide();
	}

}
/**
 * Get the content of the selected databases tab from the server and present it
 * @return HTML fragment
 */
function showSelectedTab()
{
	var fn;
	fn='showSelected';
	var url = "searchDB.do"+"?fn="+fn ;

	var data = $.ajax({
		url:url,
		global:false,
		beforeSend: function(request){
			setAjaxRequestHeader(request);
		},
		error: function(request,errorType,exceptionOcurred){
			if (errorType=='timeout'){
				notifyAjaxTimeout();
			}else{
				generalAjaxError();
			}
		},
		async:false
	}).responseXML;
	if (isAjaxXmlRedirect(data)){
		handleAjaxXmlRedirect(data);
	}
	var elm = $(data).find('dbResultsXml');
	var cdata = $(elm).text();
	var n = document.getElementById("SelectedDbs");
	if(cdata != null){
		xmlText = cdata.replace(/\n\n/g, "\n").replace(/&lt;/g,"<").replace(/&gt;/g,">");
		var newdiv = document.createElement("div");
		newdiv.innerHTML = xmlText;
		n.innerHTML = '';
		n.appendChild(newdiv);
	}
	document.getElementById("numberOfSelectedDbs").innerHTML = $("#SelectedDbs input:checkbox").length;
	if(parseInt(document.getElementById("metalibLimit").value) == $("#SelectedDbs input:checkbox").length){
		$('#ErrorMessageSdbReached').show();
		document.getElementById('scrollToTopHere').scrollTop = 0;
	}else{
		$('#ErrorMessageSdbReached').hide();
	}
}

/**
 * Handles the navigation between the tabs by hiding and unhiding tabs + setting style appropriatly
 * @param tabnum
 * @param numoftabs
 * @return
 */
function setTab(tabnum, numoftabs){
	  if(tabnum == 0) return;
	  var currTab;
	  var currLink;
	  var i;
	  var divArray = ["AllResults","ResultsDbs","SelectedDbs"];
	  $('#ErrorMessageSdbExceed').hide();
	  if(parseInt(document.getElementById("metalibLimit").value) > $("#SelectedDbs input:checkbox").length){
		  $('#ErrorMessageSdbReached').hide();
	  }
	  if(parseInt(document.getElementById("metalibLimit").value) == $("#SelectedDbs input:checkbox").length){
		  $('#ErrorMessageSdbReached').show();
	  }

	  for(i=1; i<=numoftabs; i++){
	    currTab = document.getElementById("tab"+i);
	    currDiv = document.getElementById(divArray[i-1]);
	    currShownDiv = document.getElementById('currentShownDiv');
	    if (i==tabnum) {
	    	$('#tab'+i).addClass("EXLFindDBSelectedTab");
	        currLink = document.getElementById("tab"+i+"Link");
	        //currLink.disabled=true; //causes problems in IE display - tab looks grey and does not seem to work at all
	        $('#EXLFindDBListAtoZList').hide();
	        $('#EXLFindDBListSelecteUnselect').show();
	        if(i == 1){
	        	$('#tab'+i).addClass("EXLFindDBFirstSelectedTab");
	        	$('#EXLFindDBListAtoZList').show();
	        	$('#EXLFindDBListSelecteUnselect').hide();
	        }
	        if(i == 3){
	        	$('#tab'+i).addClass("EXLFindDBLastTab");
	        	$('#SelectedDbs div[id ^= NoResultsMessage]').hide();
	        }
	        currDiv.style.visibility = 'visible';
	        currDiv.style.display='block';
	        currShownDiv.value = divArray[i-1] ;
	    }else{
	    	$('#tab'+i).removeClass("EXLFindDBSelectedTab").removeClass("EXLFindDBFirstSelectedTab").removeClass("EXLFindDBLastTab").removeClass("EXLFindDBFirstTab").removeClass("EXLFindDBTab").addClass("EXLFindDBTab");
	    	currDiv.style.visibility = 'hidden';
	    	currDiv.style.display='none';
	    }
	    if(i == 1){
	    	$('#tab'+i).addClass("EXLFindDBFirstTab");
        }
        if(i == 3){
        	$('#tab'+i).addClass("EXLFindDBLastTab");
        }
	  }
}


function findSelectedTab(){
	var divArray = ["AllResults","ResultsDbs","SelectedDbs"];
	for(i=1; i<=divArray.length; i++){
		currTab = document.getElementById("tab"+i);
		if(document.getElementById("tab"+i).className.indexOf("EXLFindDBSelectedTab")>0){
			document.getElementById("selectedTab").value = i;
		}
	}
}

function highlightSelected(){
	$('#tab3').addClass('EXLFindDBTabHighlight')
	setTimeout("$('#tab3').removeClass('EXLFindDBTabHighlight')",2500);



}

/**
 * Go to the server with the category and get the appropriate subcategories (from MetaLib)
 * @return
 */
function populateSubCategories(){
	var firstBox = document.getElementById('exlidCategory');
	var secondBox = document.getElementById('EXLFindDBSubCatDiv');
	var selectedOption = firstBox.options[firstBox.selectedIndex].value;
	var selectedCatIndex = firstBox.selectedIndex;
	var xmlText;
	if(firstBox.selectedIndex == 0){
		$(".EXLFindDBFormRow :input").not("input[id=exlidIncludeRestricted]").not("select[id=exlidCategory]").not("select[id=exlidSubCat]").removeAttr("disabled");
		$('#CategoryOnly').hide();
		var newdiv = document.createElement("span");
		 $(newdiv).attr("class", "EXLFindDBFormRowInlineInput");
		newdiv.innerHTML = "<label for='exlidSubCat'>"+exlFdbSubCategoryLabel+":</label><select id='exlidSubCat' name='exlidSubCat'><option value='' ></option></select>";
		secondBox.innerHTML = '';
		secondBox.appendChild(newdiv);
	}else{
    // check that the fields are populated and only then disbale them
	$(".EXLFindDBFormRow :input").not("input[id=exlidIncludeRestricted]").not("select[id=exlidCategory]").not("select[id=exlidSubCat]").attr("disabled", true);
	fn='populateSubCategory';
	var url = "searchDB.do"+"?fn="+fn+"&catKey="+(selectedCatIndex - 1);
	var data = $.ajax({
		url:url,
		global:false,
		beforeSend: function(request){
			setAjaxRequestHeader(request);
		},
		async:false
	}).responseXML;
	if (isAjaxXmlRedirect(data)){
		handleAjaxXmlRedirect(data);
	}
	var elm = $(data).find('subcatResultsXml');
	var cdata = $(elm).text();
	xmlText = cdata.replace(/\n\n/g, "\n").replace(/&lt;/g,"<").replace(/&gt;/g,">");
	secondBox.innerHTML = xmlText;
	}
}

function checkUserSelectedDbs(){

	if($("#SelectedDbs input:checkbox").length == 0){
		return 0;
	}
	return 1;
}

/**
 * Wrapper to handle the return from the find databases lightbox to Primo When the selection completed button
 * was clicked, the behavior differs between simple and advanced search
 * @return
 */

function showSelectedSet(){

	var userSelectedDbs = checkUserSelectedDbs();
	if(userSelectedDbs == 0){
		$('#NoDbSelected').show();
		return;
	}
	document.getElementById('exliGreyOverlay').style.display='none';
	document.getElementById('exliWhiteContent').style.display='none';

	if(document.getElementById('Selected_Databases-Div') != null){
		mainMenuTileLnk("0");
	}else{
		advancedsLink("0");
	}
}
/**
 * Wrapper to handle the return from the find databases lightbox to Primo When the X button was clicked
 * was clicked, the behavior differs between simple and advanced search
 * @return
 */
function showSelectedSetNotActive(){
	document.getElementById('exliGreyOverlay').style.display='none';
	document.getElementById('exliWhiteContent').style.display='none';

	if(document.getElementById('Selected_Databases-Div') != null){
		mainMenuTileLnk("1");
	}else{
		advancedsLink("1");
	}
}
/**
 * Since the advanced scope list is a dropdown list (select + option elements)
 * we use remove to add and remove from the select element (because IE cannot hide() options)
 * @param closeFlag
 * @return
 */
function advancedsLink(closeFlag){
	var closeFlag;
	if(document.getElementById("numberOfSelectedDbs").innerHTML != 0){
		$(".EXLAdvancedSearchFormRowHide").show();
		$("#exlidSearchIn option").show();
		$("#exlidSearchIn").attr("disabled","");
		$("#exlidSearchIn").show();

		// if there is no selected Databases option in the Advanced drop down should be added using variables
		// inside the advancedSearchTile.jsp
		if($("#exlidSearchIn option").get($("#exlidSearchIn option").length - 1).id != 'Selected_Databases'){
			 $('#exlidSearchIn').append($("<option></option>").attr("value",$('#selectedDbValue').val()).attr("class",$('#selectedDbClass').val()).attr("id",$('#selectedDbId').val()).text($('#selectedDbText').val()));
		}

		if(closeFlag != "1"){
			$("#exlidSearchIn option").get($("#exlidSearchIn option").length - 1).selected = true;
			$("#exlidSearchIn").addClass('EXLSelectedDatabasesHighlight');
			setTimeout("$('#exlidSearchIn').removeClass('EXLSelectedDatabasesHighlight')",2500);
		}
		var cbList = $("#SelectedDbs input[type=checkbox]")

		var hrefsValue = "";
		var comparableId;
		for (i=0; i<cbList.length; i++) {
				if (cbList[i].checked) {
					comparableId = cbList[i].id.substring(0,cbList[i].id.indexOf('_'));
					hrefsValue +=  comparableId + ",";
	           	}
		}

		document.getElementById('Selected_Databases').value = hrefsValue;
	}else{
		//if we exited with cancel and there is only the selected db and default scopes we need to choose the default scope
		if($("#exlidSearchIn option").length == 2){
			$("#exlidSearchIn option")[0].selected = true;
			$("#scopesListAdvanced").hide();
		}
		$("#exlidSearchIn option[id=Selected_Databases]").remove();
	}
}
/**
 * The simple search uses <ul><li> structure so we use hide/show
 * We need to treat cases where the scopes list changes:
 * 1. from no scoped visible to 2 scopes visible
 * 2. from 2 scopes visible to none visible
 * 3. The former selected scope (Selected Databases) is hidden now so another one must be selected
 * In addition we need to update the locations by changing the value of the HTMl element
 * The function deals with 2 major cases :
 * 1. there are selected databases
 * 2. There are no selected databases
 * @param closeFlag
 * @return
 */
function mainMenuTileLnk(closeFlag){
	var closeFlag;
	if(document.getElementById("numberOfSelectedDbs").innerHTML != 0){
		$(".EXLSearchFieldRibbonFormSelectedCollection").removeClass('EXLDynamicSelectOnlyOneScope');
		$('.EXLSearchFieldRibbon').removeClass('EXLSearchFieldRibbonFormSearchForMaximized');
		$('#search_field').removeClass('EXLSearchFieldMaximized');

		var selecteddivArray = $("#scopesListContainer div");
		for (i=0; i<selecteddivArray.length; i++) {
			if(closeFlag != "1"){ //selection completed was clicked
				//selecteddivArray[i].className='EXLDynamicSelectBodyRadioHideItem';
				var allInputFields = $("#" + selecteddivArray[i].id + " input");
				for (j=0; j<allInputFields.length; j++) { // make all radio buttons unchecked
					allInputFields[j].checked = false;
				}
			}

			if(selecteddivArray[i].id == 'Selected_Databases-Div'){
				selecteddivArray[i].style.display = '';
				$("#Selected_Databases-Div input[type=radio]").attr("disabled","");
				if(closeFlag != "1"){
					$('#Selected_Databases-Div').addClass('EXLDynamicSelectBodyRadioTopBorder');
					var allInputFields = $("#" + selecteddivArray[i].id + " input");
					for (j=0; j<allInputFields.length; j++) { // make the selected db radio button checked
						allInputFields[j].checked = true;
					}
					$('.EXLSearchFieldRibbonFormSelectedCollection a').text($('#Selected_Databases-Div').text());
					$('.EXLSearchFieldRibbonFormSelectedCollection').addClass('EXLDynamicSelectBodyRadioHighlight');
					setTimeout("$('.EXLSearchFieldRibbonFormSelectedCollection').removeClass('EXLDynamicSelectBodyRadioHighlight')",2500);
				}else{
					//if we exited with cancel and there is only the selected db and default scopes we need to choose the default scope
					if($("#scopesListContainer input:radio").length == 2){
						$('.EXLSearchFieldRibbonFormSelectedCollection a').text($('	#defau	lt_scope-Div'	).text());
					}
				}
			}

		}
		var cbList = $("#SelectedDbs input[type=checkbox]")

		var hrefsValue = "";
		var comparableId;
		for (i=0; i<cbList.length; i++) {
				if (cbList[i].checked) {
					comparableId = cbList[i].id.substring(0,cbList[i].id.indexOf('_'));
					hrefsValue +=  comparableId + ",";
	           	}
		}

		$('#Selected_Databases-Div input')[0].value = hrefsValue;
	}else{
		//alert ('here');
		if($("#scopesListContainer input:radio").length <= 2){
			$(".EXLSearchFieldRibbonFormSelectedCollection").addClass('EXLDynamicSelectOnlyOneScope');
			$('.EXLSearchFieldRibbon').addClass('EXLSearchFieldRibbonFormSearchForMaximized');
			$('#search_field').addClass('EXLSearchFieldMaximized');
		}
		$('#Selected_Databases-Div').hide();
		//document.getElementById('Selected_Databases-Div').className='EXLDynamicSelectBodyRadioHideItem';
		//document.getElementById('Selected_Databases-Div').style.display = 'none';

		//if the selected db radio was the checked one choose the default scope instead
		if($("#Selected_Databases-Div input")[0].checked == true){
			$("#Selected_Databases-Div input")[0].checked = false;
			$('#scopesListContainer input')[0].checked = true;//check the first scope that appears in the dropdown
			$('.EXLSearchFieldRibbonFormSelectedCollection a').text($('#scopesListContainer div:first').text()); //set the display to the selected scope.

		}

		//There are only the default scope and the selected db scope
		//if($("#scopesListContainer input:radio").length == 2){
		//	document.getElementById('default_scope-Div').className='EXLDynamicSelectBodyRadioHideItem';
		//	document.getElementById('default_scope-Div').style.display = 'none';
		//}

		if(($("#exlidSearchIn option").length > 0 ) && ($("#exlidSearchIn option").get($("#exlidSearchIn")).children().length > 0)){
		 $("#exlidSearchIn option").get($("#exlidSearchIn").children().length - 1).selected = false;
		}
	}
	//setupSearch();
}

function setSelectedScope(){

	var params = "searchDB.do"+"?fn=setSelectedScope";

	$.ajax({
		url:params,
		global:false,
		beforeSend: function(request){
			setAjaxRequestHeader(request);
		},
		error: function(request,errorType,exceptionOcurred){
			if (errorType=='timeout'){
				notifyAjaxTimeout();
			}else{
				generalAjaxError();
			}
		},
		async:false
	});
	if (isAjaxXmlRedirect(data)){
		handleAjaxXmlRedirect(data);
	}
	//response doesnt matter
}

/**
 * Change the content of the selcted databases scope according to items clicked on the screen
 * And then create the HTML fragment to replace the selected databases tab and replace it.
 * Uses an ajax call that update the server/Oracle
 * @param url
 * @return
 */
function getSelectedTabHTMLContent(url){
	var data = $.ajax({
		url:url,
		global:false,
		beforeSend: function(request){
			setAjaxRequestHeader(request);
		},
		error: function(request,errorType,exceptionOcurred){
			if (errorType=='timeout'){
				notifyAjaxTimeout();
			}else{
				generalAjaxError();
			}
		},
		async:false
	}).responseXML;
	if (isAjaxXmlRedirect(data)){
		handleAjaxXmlRedirect(data);
	}
	var elm = $(data).find('dbResultsXml');
	var cdata = $(elm).text();
	var n = document.getElementById("SelectedDbs");
	if(cdata != null){
		xmlText = cdata.replace(/\n\n/g, "\n").replace(/&lt;/g,"<").replace(/&gt;/g,">");
		var newdiv = document.createElement("div");
		newdiv.innerHTML = xmlText;
		n.innerHTML = '';
		n.appendChild(newdiv);
	}
	document.getElementById("numberOfSelectedDbs").innerHTML = $("#SelectedDbs input:checkbox").length;
	if(parseInt(document.getElementById("metalibLimit").value) == $("#SelectedDbs input:checkbox").length){
		$('#ErrorMessageSdbReached').show();
		document.getElementById('scrollToTopHere').scrollTop = 0;
	}else{
		$('#ErrorMessageSdbReached').hide();
	}
}





