/**
	This File contains the constant and funtions that will be required for Site Wide Search.
*/

//URL of the result page to be used.
var resultPageURL = '/cnams/search/SearchResultContainer.jsp';

//Default tab index that is active.
var activeTabIndex = 0;

//Variable that indicates search is from top nav OR from result page.
var RESULTPAGESEARCH = "searchFromResultsPage";

//Variable that indicates tabs are already randered on screen or not.
//This variable is used in onchange function.
var tabsRandered = false;

//Navigation list to be shown on screen.
expandedNavItemsAcadSearch = ['cnamsswresourcesnav', 'cnamsswcurriculumnamenav', 'cnamsswcontenttypenav', 'cnamsswlanguagenamenav','formatnav'];
navigationOrderAcademy={"navigationFieldList":[{"name":"cnamsswresourcesnav"},{"name":"cnamsswcurriculumnamenav"},{"name":"cnamsswcontenttypenav"},{"name":"cnamsswlanguagenamenav"},{"name":"formatnav"}]};

var qs = null;

//Calculate the width for tabber page body.
if(screen.width > 1280){
	var width = 1280;
}else if(screen.width == 800){
	var width = screen.width;
}
else {
	var width = screen.width - 26;
}

var tab_width = width;

//Set the padding of tabs. This is equal to left nav on result page.
var tabs_paddingWidth = 85;
var isIE = (navigator.appName=="Microsoft Internet Explorer");

if(isIE){
	tabs_paddingWidth = 75;
}
tabs_paddingWidth = tabs_paddingWidth + 'px';

/*
This function will check for the keyword and start submit the form so that search result page comes up. 
	
*/
function startSiteWideSearch() {

 	var searchKeyword = document.getElementById("sitewideSearchKeywordTextBox").value;
 	searchKeyword=searchKeyword.replace(/^\s+|\s+$/g,"");
 	
 	//If seacrh keyword is blank then show error message
 	if (searchKeyword == null || searchKeyword == "") {
	  showErrorMsg();
	} 
	else {
	  
	  
	  var pathString = "http://"+document.domain + resultPageURL + "?keyword=" + (searchKeyword.replace(/\'/g,"\\\'")).replace(/%/g,'%25');

	  window.location.href = pathString;
	  /*
	  var element = document.createElement("input");
	  element.type = "hidden";
	  element.value = searchKeyword;
	  element.name = "sitewideSearchKeyword";
	  var formElement = document.getElementById("sitewideSearchFormId");
	  formElement.appendChild(element);
	  formElement.action = "http://"+document.domain + resultPageURL;
	  formElement.action = resultPageURL;
	  document.getElementById("submitSitewideSearch").click();
	  */
	}
 
 }
 
 //Hide the rror message div.
 function hideErrorMsgTopNavDiv() {
 	document.getElementById("errorMsgTopNavDiv").style.display = "none"; 
 }
 
 /*
 This method will be called from the result page.
 This method will initialise all the JS variable that needs to be reinitialise.
 This method will reload the data without page submit. This will also check if the search keyword is filled or not.
 	
 */
 function reloadSiteWideSearchResults() {
 
 	var keyword = document.getElementById("keyword").value;
	keyword=keyword.replace(/^\s+|\s+$/g,"");
	// create a new query
	initializeQuery();
	initializeUserNagiation();
	
	query.sortColumn = "";
	query.sortDir ="";
		
	displayUserNavigationSearchString = "";
	highLightJSONArray = null;
	
	query.searchKeyword = keyword;
	showDidUMean = true;
	if (keyword == null || keyword == "") {
		document.getElementById("errorMessageDiv").innerHTML = "Type a keyword and then press Search.";
	} else {
		//reLoadData("queryStr=" + query.toJSONString());
		getData();
	}
 }	

/*
This method will capture the keys presses in the serch text box
If enter key has been pressed then seacrh should be started OR data needs to be realoded.

*/
function captureKeyEvent(e,frmPageName) {
	
	var key;
   	if(window.event)
		key = window.event.keyCode;
   	else
        key = e.which;
   	if (key == 13)
   	{
   		if(frmPageName == RESULTPAGESEARCH){
   			if(qs != null && qs != undefined) {
				if (((document.getElementById(qs.__searchDropDownID).style.visibility) == "visible")  && qs.__index > -1 )
				{
					document.getElementById(qs.__query.id).value = qs.__query.value;
				}
				qs.hide();
			}
   			reloadSiteWideSearchResults();
   		}
   		else {
   			startSiteWideSearch();
 		}
   	}
}

function fetchAndDisplaySearchSuggestion (e) {
	if(qs != null && qs != undefined) {
		qs.keyUp(e, "keyword");
	}
}


function downArrawSuggestion(e) {
	if(qs != null && qs != undefined) {
		qs.keyDown(e, "keyword");
	}
}


//This method will perform the function of Tooltip error message hide
function hideErrorMsg() {
	popUpWithStaticPositionError("",'errorMsgTopNavDiv',getErrorPopUpWidth(),"hide");
}

//This method will show the error message using the tooltip.
function showErrorMsg() {
	document.getElementById("errorMsgTopNavDiv").innerHTML = "Type a keyword";
	popUpWithStaticPositionError("",'errorMsgTopNavDiv',getErrorPopUpWidth(),"show");
}

//This method will calculate the error tooltip width.
function getErrorPopUpWidth() {
	var errorPopUpWidth = document.getElementById("sitewideSearchKeywordTextBox").offsetWidth;
	
	var isIE = (navigator.appName=="Microsoft Internet Explorer");
	if(!isIE) {
		errorPopUpWidth = errorPopUpWidth - 12;
	}
	
	return errorPopUpWidth;
}


//This method will construct the result data using the JSON data received.
function createInnerHTMLResult(dataSet,otherInfoDataSet){
	
	//This fix is done to keep the back page URL even in case of browser back.
	//There is an issue with IE that link2's url gets blank.
	document.getElementById("goBackLink1").href="javascript:history.back(1);";
	document.getElementById("goBackLink2").href="javascript:history.back(1);";
	
	var stringVal=query.searchKeyword;

	var innerHTMLElement ='<table border="0" width="100%">'+
	'<tr class="resultHeader"><td  height="2" bgcolor="#D5D5D7"></td>'+
	'</tr></table><DIV style="overflow: scroll; overflow-y: scroll; overflow-x: hidden;"  id="idDivScrollingTBody" ><table width="100%" class= "resultBody"> ';
	
	var sizeToDisplay = 0;
	
	var target = '';
	//ALL Content will be paint here.
	var resultsFound = false;
	for (i=0;i<dataSet.length;i++){
	
		resultsFound = true;
		innerHTMLElement = innerHTMLElement + "<tr><td></td></tr>"	
	
		var record = dataSet[i];
			
		if((record.fileFormat == 'HTML') || (record.objectType == 'URL')) {
			target = 'blank';
		}
		else {
			target = '';
		}
		if (record.resources != null && (record.resources).indexOf("Headlines Archive") >= 0)
			innerHTMLElement = innerHTMLElement + '<tr><td><a href="javascript:showHeadlines(\''+escape(record.cnamsURL)+'\')" class="aunderLineSmallFont">'+((record.fastSuggestedTitle == "") ? record.title : record.fastSuggestedTitle)+'</a>';
		else {
		innerHTMLElement = innerHTMLElement + '<tr><td><a href="'+record.cnamsURL+'" class="aunderLineSmallFont" target="'+target+'">'+((record.fastSuggestedTitle == "") ? record.title : record.fastSuggestedTitle)+'</a>';
		}
		if(record.iconImagePath && (record.iconImagePath != "") ){
			innerHTMLElement = innerHTMLElement + '&nbsp;&nbsp;<img src="'+record.iconImagePath+'"/>';	
	
			innerHTMLElement = innerHTMLElement + '&nbsp;(.'+(record.fileFormat).toLowerCase()+'&nbsp;';
			
			if(record.fastSuggestedFileSize && record.fastSuggestedFileSize != ""){
			
				var sizeInMB = calculateFileSizeInMB(record.fastSuggestedFileSize);
								
				if(sizeInMB > 1024) {
					var sizeInGB = calculateFileSizeInGB(record.fastSuggestedFileSize);
					
					sizeToDisplay = sizeInGB + "GB"
				}
				else {
					sizeToDisplay = sizeInMB+"MB";
				}
				
				innerHTMLElement = innerHTMLElement + '-&nbsp;'+sizeToDisplay;
			}
			innerHTMLElement = innerHTMLElement + ')'; 
		}
		innerHTMLElement = innerHTMLElement + '</td></tr>';
		innerHTMLElement = innerHTMLElement + '<tr><td>'+record.fastSuggestedBody;
		
		if(record.fastSuggestedLastUpdateDate != "") {
			innerHTMLElement = innerHTMLElement + '&nbsp;&nbsp;['+record.fastSuggestedLastUpdateDate+']';
		}
		innerHTMLElement = innerHTMLElement + '</td></tr>';	
		
		innerHTMLElement = innerHTMLElement + '<tr><td></td></tr>';	
	}
	
	innerHTMLElement=innerHTMLElement+'</table></div>';
	
	innerHTMLElement = innerHTMLElement + '<div><table style="width:100%"><tr class= "resultBody" style="width:100%"><td  height="2" bgcolor="#D5D5D7"></td></tr></table></div>';
	document.getElementById('containerDiv').innerHTML=innerHTMLElement;	
	// hide didumean 
	if (resultsFound == true) {
		showDidUMean = false;
	}
	
}

 //This method will create the result page templet.
 //This  method will put the content from one tab to other when tabs changed.
 //This will also load the data.
 
 function createTempletPage(divNumber,tabDiv){
 	var searchKeyword = "";
 	if(document.getElementById("keyword")){
 		searchKeyword = document.getElementById("keyword").value;
 	}
 	if(divNumber == 0) {
 	//alert('inside 1');
		document.getElementById("tab1data").innerHTML = document.getElementById("templetDataDiv").innerHTML;
		document.getElementById("tab2data").innerHTML = "";
		query.sortColumn = "";
		query.sortDir ="";
	}
	else {
	 	//alert('inside 2');
		document.getElementById("tab2data").innerHTML = document.getElementById("templetDataDiv").innerHTML;
		document.getElementById("tab1data").innerHTML = "";
		query.sortColumn = "lastmodified";
		query.sortDir = SORT_DESC;
		filterClicked = "sws_desc";
	}
	
	if(document.getElementById("keyword")){
 		document.getElementById("keyword").value = searchKeyword;
 	}
 	//alert('tabDiv: '+tabDiv);
	if(tabDiv != undefined){
	//alert('inside create template page: historyChange --> ' + historyChange);
		if(tabChangedFromHistory){
		reLoadData("queryStr="+query.toJSONString());
		
		}else {
			getData();	
		}
	}
 }   
  
  /*
  This method will be used to create to create the tabs on the result page.
  Tabs are constructed using the EXT JS.
  
  */
  function renderTabs(){	
		var tabs = new Ext.TabPanel({
	        renderTo: 'tabs',
	        id: 'tabCmp',
	        width:width,       
	        activeTab: activeTabIndex,
	        //border:false,
	        //bodyBorder :true,
	        listeners:{
	           render:{
	               fn:function(){
	               	  var comId = "tabCmp__ext-comp-1001";
	                  var firstTab =  Ext.get(comId);
	                   firstTab.setStyle('margin-left', tabs_paddingWidth);  
	                   try{ 
	                   var tabMainDiv=document.getElementById(comId).parentNode;
	                   //alert(tabMainDiv.childNodes.length);
	                   var obj = new Array();
	                   for(var divIndex=0;divIndex<tabMainDiv.childNodes.length;divIndex++){
	                   	obj[divIndex] = tabMainDiv.childNodes[divIndex];
	                   	//alert(obj[divIndex]);
	                   }
	                   for(var divIndex=0,divEndIndex=tabMainDiv.childNodes.length;divIndex<divEndIndex;divIndex++){
	                   	tabMainDiv.removeChild[divIndex];
	                   	divIndex--;
	                   	divEndIndex--;	                   	
	                   }
	                   //tabMainDiv.innerHTML = "";
	                   
	                   var backLinkElement=document.createElement("li");
	                   backLinkElement.id="backTabId";
	                   backLinkElement.innerHTML="<a href='' id='goBackLink1' class= 'awithoutunderLine'>&nbsp;&nbsp;Back to previous page</a>";
	                   
	                   tabMainDiv.appendChild(backLinkElement);
	                   tabMainDiv.appendChild(obj[0]);
	                   tabMainDiv.appendChild(obj[1]);
	                   var errorMsgElement=document.createElement("li");
	                   errorMsgElement.id="errorDivId";
	                   errorMsgElement.innerHTML="<div id='errorMessageDiv' class= 'errorMessage' style='display:inline;margin-left:5px;'></div>";
	                   tabMainDiv.appendChild(errorMsgElement);
	                   tabMainDiv.appendChild(obj[2]);
	                   tabMainDiv.appendChild(obj[3]);

	                   }
	                   catch(e){}
	               }
	           },
	            tabchange:{
	            	fn:function(){           		
	            		//alert('tab change listner');       		
	            		if(tabsRandered) {
	            			if(activeTabIndex == 0){
	            				activeTabIndex = 1;
	            			}
	            			else {
	            				activeTabIndex = 0;
	            			}
	            		}
	            		else {
	            			tabsRandered = true;
	            		}           		
	            		createTempletPage(activeTabIndex,tabs);
	            	}
	           }
	        },
	       // frame:true,
	       plain:true,
	       defaults:{autoHeight: true},
	       //defaults:{autoScroll: true},
	         items:[
	            {contentEl:'tab1data', title: 'Sorted by Relevance'},
	            {contentEl:'tab2data', title: 'Sorted by Date'}
	        ]
	    });
	 }

//This method will be used to show the error message using tooltip.
	 
function popUpWithStaticPositionError(evt,oi,width,action) 
{	
	var wp = pw(); 
		ds = fd(oi,1); 
		dm = fd(oi,0); 
		st = ds.visibility; 
		if (dm.offsetWidth) 
			ew = dm.offsetWidth; 
		else if (dm.clip.width) 
			ew = dm.clip.width; 
	if (DH) 
	{

		if (action == "hide") 
		{ 
			ds.visibility = "hidden"; 
		} else 
		{
			ds.width = width;
			ds.visibility = "visible";
		}
	}
}

//This is an object that will be used to store the JS data when traversed between pages.
function StoreData() {
	this.queryData = query;
	this.displayString = displayUserNavigationSearchString;
	this.highLightArray = highLightJSONArray;
	
	this.toJSONString = function()
	{
		var stringifyString=YAHOO.lang.JSON.stringify(this);
		return ("{\"storeData\":" + stringifyString + "}");
	}

}

//This method will populate the required values to form and forwards the request to result page from the advance search page.
function goBackToResultPage() {
		var formElement = document.getElementById("formToBeUsedForForward");
		var hiddenText = document.createElement("input");
		hiddenText.type="hidden";
		hiddenText.name = "advanceSearchBackQuery";
		hiddenText.value = unescape(oldData);			
		formElement.appendChild(hiddenText);	
		
		document.getElementById(formElement.id).submit();
	}

//This method will populate the required values to form and forwards the request to advance search page from result page. 
function goToAdvanceSearchPage() {
		
	var storeData = new StoreData();
	
	var formElement = document.getElementById("formToBeUsedForForward");
	var hiddenText = document.createElement("input");
	hiddenText.type="hidden";
	hiddenText.name = "advanceSearchQuery";
	hiddenText.value = escape(storeData.toJSONString());			
	formElement.appendChild(hiddenText);
	
	document.getElementById(formElement.id).submit();
}

//This method will be used to align the banner image with rightnav links.
function alignRightNavLinkWithImage(){
	try{
		var imageWidth = 756+25;
		var balanceWidth = width - imageWidth;
		if(balanceWidth > 0) {
			document.getElementById("col1").style.width = balanceWidth/2;
			document.getElementById("col2").style.width = imageWidth;
			document.getElementById("col3").style.width = balanceWidth/2;
		}
			
	}
	catch(e){}
}

//This method will be used to clear the search box. This will be called when cursor is placed inside the text box.
function clearSearch() {
	
	if(document.getElementById("sitewideSearchKeywordTextBox").value == "Type a keyword")
	{
	document.getElementById("sitewideSearchKeywordTextBox").value = "";
	}
	hideErrorMsg();
}

//This method calculate the file size in MB. Input file size is assumed to be in bytes.
function calculateFileSizeInMB(fileSize) {
	var sizeInMB = fileSize;
	sizeInMB = sizeInMB / 1048576.00;
	sizeInMB =  (sizeInMB * 100);
	sizeInMB = Math.round(sizeInMB);
	sizeInMB = (sizeInMB) / 100.00;
	return sizeInMB;
}

//This method calculate the file size in GB. Input file size is assumed to be in bytes.
function calculateFileSizeInGB(fileSize){
	var sizeInGB = fileSize;
	sizeInGB = sizeInGB / 1073741824.00;
	sizeInGB =  (sizeInGB * 100);
	sizeInGB = Math.round(sizeInGB);
	sizeInGB = (sizeInGB) / 100.00;
	return sizeInGB;
}
	
//This method will be used to initialize the advance search page.	
function advanceSearchPageInitialize() {
	if(errormessage != null){
			document.getElementById("errorMessageDiv").style.display="block";
			document.getElementById("errorMessageText").innerHTML=errormessage;
	}
	
	var queryReceived = unescape(oldData);
	queryReceived = YAHOO.lang.JSON.parse(queryReceived);
	try {	
		document.getElementById("allWordsId").value= (queryReceived.storeData.queryData.searchKeyword == "") ? queryReceived.storeData.displayString : queryReceived.storeData.queryData.searchKeyword;
	}catch(e){}	
} 

//This method will reset the advance search page.
function advanceSearchPageReset() {
	document.getElementById("allWordsId").value = "";
	document.getElementById("exactPhraseId").value = "";
	document.getElementById("atleastWordsId").value = "";
	document.getElementById("withoutAnyWordsId").value = "";
	document.getElementById("withoutPhraseId").value = "";
	
	document.getElementsByName("searchCriteria")[0].checked = true;
	
	advanceSearchPageInitialize();

} 
document.onclick = function checkHideSuggestion () {
	if(qs != null && qs != undefined) {
		qs.hide();
	}
}		
		
function showHeadlines (urlParam) {
	var formToSubmit = document.getElementById("headlinesForm");
	if (formToSubmit) {
		formToSubmit.action = urlParam;
		formToSubmit.target = "new";
		
		var hiddenText = document.createElement("input");
		hiddenText.type="hidden";
		hiddenText.name = "fromSWS";
		hiddenText.value = "true";			
		formToSubmit.appendChild(hiddenText);	
		
		formToSubmit.submit();
	}
}		
