/**
 * Pagination Components related javascript module
 * 
 * @author Veeresh D.
 * @date March 2008
 */

var totalRecords, totalRecordsecordsTemp, showNRecords, nResultPageLinks, cur, prevPage, tempTresults; //Total records, number of pages, current records,

var searchKey;
var searchPageType;
var searchKeyCaption;

var firstPageOfPages = "";
var lastPageOfPages = "";

var recentPaginationInitCall = "";
/**
Initializes the result page with default result(first page) along with pagination component.
It also generates pagination component's page thumbnails for selecting result pages
*/
function initResultPages(tresults, npages, keyWord, searchItemType, searchItemCaption)
{
    recentPaginationInitCall = "initResultPages('" + tresults + "','" + npages + "','" + keyWord + "','" + searchItemType + "','" + searchItemCaption + "')";
    
	var rem, quo;
	searchKey = keyWord;		        //Used for pagination component's response over result page component
	searchPageType = searchItemType;	//Used for pagination component's response over result page component
	searchKeyCaption = searchItemCaption
	totalRecords		= Number(tresults);
	tempTresults        = totalRecords;
	nResultPageLinks	= Number(npages);   //Number of pagination thumbnails. By default is 10, so 10 thumbnails or links will be shown for 10 search result pages
	showNRecords		= 10;	            //Get n records from database to display
    
	totalRecordsecordsTemp	= Number(tresults);
	totalRecords			= Math.round(totalRecords / showNRecords);
	
	if( tresults<101 )
	{
	    document.getElementById("paginationNextButtonId").disabled = "disable";
	    document.getElementById("paginationLastButtonId").disabled = "disable";
	}
	else
	{
	    document.getElementById("paginationLastButtonId").disabled = false;
	    document.getElementById("paginationNextButtonId").disabled = false;
	}

	if (Number(totalRecordsecordsTemp % showNRecords) > 0 && Number(totalRecordsecordsTemp % showNRecords) < (showNRecords/2))
		totalRecords++;
    
	cur = (totalRecords > nResultPageLinks) ? nResultPageLinks : totalRecords;
	
	big = 1;
	end = cur;
	prevPage = "p_1_10";	//Default page link to reset and persist its initial place holder value
	
	if ( tempTresults > showNRecords )
	    document.getElementById("paginationCount").innerHTML = showNRecords + "/"+ tempTresults;	    
	else
    	document.getElementById("paginationCount").innerHTML = tempTresults + "/"+ tempTresults;
	
	getPages(big, end);
	setColors(prevPage, "ROYALBLUE", "WHITE");	//alert("here: " + searchItemCaption);
	
	document.getElementById("paginationPreviousButtonId").disabled = "disable";
	document.getElementById("paginationFirstButtonId").disabled = "disable";	
}

/**
Generates next set of pagination component't thumbnail for further reuslt pages
*/
function firstPage()
{
    var tempCur = cur / 10;
    for (var i = 0; i < tempCur - 1; i++)
    {
	    previousPage(0);
	}
	getResultPage("p_1_10");    //To get the first page
	
	document.getElementById("paginationPreviousButtonId").disabled = "disable";
	document.getElementById("paginationFirstButtonId").disabled = "disable";
	
	document.getElementById("paginationNextButtonId").disabled = false;	
	document.getElementById("paginationLastButtonId").disabled = false;
}

/**
Generates next set of pagination component't thumbnail for further reuslt pages
*/
function lastPage()
{
    for (var i = 0; i < totalRecords; i++)
    {
	    nextPage(0);
	}
	getResultPage(lastPageOfPages);    //To get the first page
	
	document.getElementById("paginationNextButtonId").disabled = "disable";
	document.getElementById("paginationLastButtonId").disabled = "disable";
	
	document.getElementById("paginationFirstButtonId").disabled = false;
	document.getElementById("paginationPreviousButtonId").disabled = false;
}

/**
Generates next set of pagination component't thumbnail for further reuslt pages
*/
function nextPage(linkImmediateFlag)
{
    cur	= Number(cur);
	nResultPageLinks = Number(nResultPageLinks);
	totalRecords = Number(totalRecords);

	if(totalRecords < nResultPageLinks )
	{	
		getPages(1, totalRecords);		
		return ;	
	}

	if( (cur + nResultPageLinks) < totalRecords )
	{
		big = end + 1;
		end = end + nResultPageLinks;
		cur = cur + nResultPageLinks;
		getPages(big, end);
	}
	else if (cur >= (totalRecords-cur) && (totalRecords-cur)!=0)
	{
		big = end + 1;
		end = end + totalRecords-cur;
		cur = totalRecords;
		getPages(big, end);
	}
	prevPage= "";
	if ( linkImmediateFlag != 0)
	{
	    getResultPage(firstPageOfPages);
	}
	
	document.getElementById("paginationPreviousButtonId").disabled = false;
	document.getElementById("paginationFirstButtonId").disabled = false;
}

/**
Generates previous set of pagination component't thumbnail for previus reuslt pages
*/
function previousPage(linkImmediateFlag)
{
	cur = Number(cur);
	nResultPageLinks = Number(nResultPageLinks);
	totalRecords = Number(totalRecords);
	
	/* If number of result sets are less or equal to number of page link, Just do nothing */
	if(cur == nResultPageLinks || totalRecords < nResultPageLinks) 
		return ;

	if(cur >= totalRecords )
	{
		end = big - 1 ;
		big = big - nResultPageLinks;

		if ( (totalRecords % nResultPageLinks) == 0)
			cur = cur - nResultPageLinks;		//If cur==nResultPageLinks, if tr=8, nResultPageLinks=4, to keep first page constant
		else
			cur = cur - (totalRecords%nResultPageLinks);
		getPages(big, end);
	}
	else if((totalRecords-cur)>0)
	{
		big = big - nResultPageLinks;
		end = end - nResultPageLinks;
		cur = cur - nResultPageLinks;
		getPages(big, end);
	}
	prevPage= "";
	if ( linkImmediateFlag != 0)
	{
		getResultPage(lastPageOfPages);
	}
	
	if( cur<=10 )
	{
	    document.getElementById("paginationFirstButtonId").disabled = "disable";
	    document.getElementById("paginationPreviousButtonId").disabled = "disable";   
	}
	    
	document.getElementById("paginationNextButtonId").disabled = false;
	document.getElementById("paginationLastButtonId").disabled = false;
}

/**
Generates result page's thumbnails, so that user can click on those page's thumbs and
it will displays respective result page

@param m Begining page's number
@param n Ending page's number
*/
function getPages(m, n)
{
    var flag = 0;
	var pagerow = "<TABLE id=paginationTable cellspacing=2 cellpadding=0 border=1>";
	pagerow += "<TR>";
	for(var i = m; i <= n; i++)
	{
		if ( Number(i*showNRecords) > totalRecordsecordsTemp)
			pageRangeId = ((i*showNRecords)-(showNRecords-1)) + '_' + ((i*showNRecords)-showNRecords + Number(totalRecordsecordsTemp) % showNRecords);
		else
			pageRangeId = ((i*showNRecords)-(showNRecords-1)) + '_' + ((i*showNRecords));

		if (prevPage == "")		prevPage = pageRangeId;
            
		pagerow += "<TD id=p_" + pageRangeId + " class=paginationResultPageLinks onmouseover='focusPage(this.id)' onmouseout='unfocusPage(this.id)' onclick='getResultPage(this.id)' >" + i + "</TD>";
		lastPageOfPages = "p_" + pageRangeId;
		
		if ( flag == 0 )
		{
		    firstPageOfPages = "p_" + pageRangeId;
		    flag = 1;
		}
	}
	pagerow += "</TR>";
	pagerow += "</TABLE>";
	document.getElementById("paginationThumbs").innerHTML = pagerow;
	
	if( n == totalRecords )
	{
	    document.getElementById("paginationNextButtonId").disabled = "disable";
	    document.getElementById("paginationLastButtonId").disabled = "disable";
	} 
}

/**
Collects the nth result page and does necessary alteration and sets focuses on 
pagination component's thumbs

@param resultPageId Nth result page id with start and ending record number
*/
function getResultPage(resultPageId)
{
	var pageInfo, startPage, endPage, tempEle;
	
	latestSearchResultFunCall = "getResultPage('" + resultPageId + "')";
				
	pageInfo	= resultPageId.split("_");	//Page range id, ex: p_1_10, p_11_20, p_21_30
	startPage	= pageInfo[1];
	endPage	    = pageInfo[2];
    
	if (prevPage != "")	
		setColors(prevPage, "WHITE", "BLACK");
    
	document.getElementById("paginationCount").innerHTML = "" + endPage + "/"+ tempTresults;	//Updating pagination's count at footer
	
	if (Number(pageInfo[1]) >= 1)
	{
		//requestResultPage(Number(pageInfo[1]), Number(pageInfo[2]));
		requestResultPage(Number(startPage), Number(endPage));		
	}
	setColors(resultPageId, "ROYALBLUE", "WHITE");	//Focus the clicked page
	prevPage = resultPageId;
}

/**
Gets the result page from the server and passes it for rendering

@param pageStartId Begining record id of the result page
@param pageEndId Ending record id of the result page
*/
function requestResultPage(pageStartId, pageEndId)
{
	var ajaxRequest = zXmlHttp.createRequest();
	showTopNotification();//Supposed to be: paginationDivComponent
	
	ajaxRequest.onreadystatechange = function()
	{
		if(ajaxRequest.readyState == 4)
		{
			if (ajaxRequest.status == 200)
			{	
				searchResults.renderJSONSearchResults(ajaxRequest.responseText, searchKeyCaption, Math.round((pageStartId / 10) + 1), global.variables.sortSearchBy);
				
				historyIsItResultDetails = 1;
	            parityHistory.setInHistory();
			}
			else
			{
				hideTopNotification();
				alert("Unable to get requested set of articles. Please try again!: \n\n" + ajaxRequest.responseText.substring(1,2000)); 
			}
		}
	}
	pageStartId = pageStartId - 1;
	
	if ( searchPageType == "keyword")
    {
        ajaxRequest.open("GET", ROOT_DB_URL + "search.action?searchType=" + searchPageType + "&searchString=" + searchKey + "&nodeLabel=" + escape(searchKeyCaption) +"&articlePageID=" + Number((pageStartId/10) + 1 ) + searchResults.getSortByType() + "&nullParam=" +(new Date()).getTime(), true);
	    ajaxRequest.send(null);
	}
	else if ( searchPageType == "author")
    {
        ajaxRequest.open("GET", ROOT_DB_URL + "search.action?searchType=" + searchPageType + "&searchString=" + searchKey + "&nodeLabel=" + escape(searchKeyCaption) + "&articlePageID=" + Number((pageStartId/10) + 1 ) + searchResults.getSortByType() + "&nullParam=" +(new Date()).getTime(), true);
	    ajaxRequest.send(null);
	}
	else if ( searchPageType == "ontology")
	{
	    //alert("url=" + ROOT_DB_URL + "search.action?searchType=ontology&nodeID=" + searchKey +"&articlePageID=" + Number((pageStartId/10) + 1 ) + searchResults.getSortByType());
	    ajaxRequest.open("GET", ROOT_DB_URL + "search.action?searchType=ontology&nodeID=" + searchKey + "&nodeLabel=" + escape(searchKeyCaption) +"&articlePageID=" + Number((pageStartId/10) + 1 ) + searchResults.getSortByType() + "&nullParam=" + (new Date()).getTime(), true);
	    ajaxRequest.send(null);
    }
}

/**
Set the focussed page, accordingly it changes its styles

@param id Page id of pagination component's thumbnail
*/
function setPaginationPage(id)
{
	if(prevPage != id)
		setColors(id, "WHITE", "BLACK");
	else
		prevPage = id;
}

/**
Set the styles of current page's thumbnail

@param pageId Page id of pagination component's thumbnail
*/
function focusPage(pageId)
{
	if (prevPage != pageId)
		setColors(pageId, "ROYALBLUE", "WHITE");
}

/**
Reset the default styles of current page's thumbnail

@param pageId Page id of pagination component's thumbnail
*/
function unfocusPage(pageId)
{
	if (prevPage != pageId)
		setColors(pageId, "WHITE", "BLACK");
}

/**
Set the colors of a given page's thumbnail

@param elementId Page id of pagination component's thumbnail
@param bgClr Background color of the page's thumbnail
@param fontClr Font color of the page's thumbnail
*/
function setColors(elementId, bgClr, fontClr)
{
	var tempEle;
	tempEle = document.getElementById(elementId);
	if ( tempEle != null )
	{
		tempEle.style.backgroundColor = bgClr;
		tempEle.style.color = fontClr;
	}
}

/**
Shows the pagination component
*/
function showPagination()
{
    document.getElementById("paginationDivComponent").style.display = '';	
}

/**
Hides the pagination component
*/
function hidePagination()
{
    document.getElementById("paginationDivComponent").style.display = "none";	
}
