// *********************** ES COPYRIGHT START  *********************************
// @copyright(disclaimer)
// Licensed Materials - Property of IBM
// IBM OmniFind Enterprise Edition Version 8.5 (Program Number:  5724-L31)
// (c ) Copyright IBM Corp. 2003, 2008. All Rights Reserved.
//
// US Government Users Restricted Rights
// Use, duplication or disclosure restricted by GSA ADP Schedule
// Contract with IBM Corp.
//
// DISCLAIMER OF WARRANTIES :
//
// Permission is granted to copy and modify this  Sample code, and to
// distribute modified versions provided that both the copyright
// notice,- and this permission notice and warranty disclaimer appear
// in all copies and modified versions.
//
// THIS SAMPLE CODE IS LICENSED TO YOU AS-IS.
// IBM  AND ITS SUPPLIERS AND LICENSORS  DISCLAIM
// ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, IN SUCH SAMPLE CODE,
// INCLUDING THE WARRANTY OF NON-INFRINGEMENT AND THE IMPLIED WARRANTIES
// OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT
// WILL IBM OR ITS LICENSORS OR SUPPLIERS BE LIABLE FOR ANY DAMAGES ARISING
// OUT OF THE USE OF  OR INABILITY TO USE THE SAMPLE CODE, DISTRIBUTION OF
// THE SAMPLE CODE, OR COMBINATION OF THE SAMPLE CODE WITH ANY OTHER CODE.
// IN NO EVENT SHALL IBM OR ITS LICENSORS AND SUPPLIERS BE LIABLE FOR ANY
// LOST REVENUE, LOST PROFITS OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL,
// CONSEQUENTIAL,INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS
// OF THE THEORY OF LIABILITY,-, EVEN IF IBM OR ITS LICENSORS OR SUPPLIERS
// HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
//
// @endCopyright
//*********************** ES COPYRIGHT END  ***********************************
 
    function hideShowDetailsFields(hideShow) {
       if (hideShow == "show") {
          for (var i = 0 ; ; i++) {
          	var f = document.getElementById("fields"+i);
          	if (f == null) {
          	   break;
          	} else {
          	   f.style.display = "block";
          	}   
          }	
       } else {
          for (var i = 0 ; ; i++) {
          	var f = document.getElementById("fields"+i);
          	if (f == null) {
          	   break;
          	} else {
          	   f.style.display = "none";
          	}   
          }	
       }
    }
    
	function toggleHideShowDetails() {
	    var prefix = "hideShowDetails";
		var link1El = document.getElementById(prefix+"Link1");
		var link2El = document.getElementById(prefix+"Link2");
		if (link1El.firstChild.nodeValue == SHOW_TEXT) {
    	    link1El.firstChild.nodeValue = HIDE_TEXT;
        	link1El.title = HIDE_TEXT_ALT;
	        link2El.firstChild.nodeValue = HIDE_TEXT;
    	    link2El.title = HIDE_TEXT_ALT;
            hideShowDetailsFields("show");
			SetCookie(prefix, "true");
		} else {
    	    link1El.firstChild.nodeValue = SHOW_TEXT;
        	link1El.title = SHOW_TEXT_ALT;
	        link2El.firstChild.nodeValue = SHOW_TEXT;
        	link2El.title = SHOW_TEXT_ALT;
            hideShowDetailsFields("hide");
			SetCookie(prefix, "false");
		}	
		return false;
	}
	
	function onloadHideShowDetails() {
	    var prefix = "hideShowDetails";
		var link1El = document.getElementById(prefix+"Link1");
		if (link1El) {
			var link2El = document.getElementById(prefix+"Link2");
			var cookie = GetCookie(prefix);
        	if (cookie != null && cookie == "true") {
				if (link1El) {
	    	       link1El.firstChild.nodeValue = HIDE_TEXT;
    	    	   link1El.title = HIDE_TEXT_ALT;
        		}   
				if (link2El) {
		           link2El.firstChild.nodeValue = HIDE_TEXT;
    		       link2El.title = HIDE_TEXT_ALT;
        		}   
       	    	hideShowDetailsFields("show");
		    } else {
				if (link1El) {
    		       link1El.firstChild.nodeValue = SHOW_TEXT;
        		   link1El.title = SHOW_TEXT_ALT;
	        	}   
				if (link2El) {
	    	       link2El.firstChild.nodeValue = SHOW_TEXT;
    	    	   link2El.title = SHOW_TEXT_ALT;
	        	}   
    	   	    hideShowDetailsFields("hide");
        	}
        }
	}
	
	function initPage() {
	   onloadHideShowDetails();
	   verifyBackgroundImagePadding();        
	}

	
	// Asynchronously call /search.do, /advancedSearch.do, or /categoryTree.do and request either
	// the next page of results or the previous page of results.    
   	function startLoadSearchResultsTable(url) {
   	    try {
    		var request;
        	if( window.ActiveXObject ) {
		    	request = new ActiveXObject( "Microsoft.XMLHTTP" );
	        } else if( window.XMLHttpRequest ) {
        	    request = new XMLHttpRequest();
		    } else {
	        	alert( "Ajax is not supported by your browser !" );
    	    }
		    	
		    request.open( "GET", url, true );
		    changeCursorStyle('wait');
		    // change the cursor to the hourglass to let the user know that
		    // the request has been submitted
		    request.onreadystatechange = function() {
		    	loadSearchResultsTable(request);
	        }	
	        request.send( null );
	    } catch( e ) {
	        alert( "An error occured while trying to request the search results table:\"" + e + "\n try reloading this page and contact your system administrator if the problem persits.");
       	}
    }
    
    // Process the response from searchResultsTable.jsp to display the next/previous page of results
    function loadSearchResultsTable(req) {
        if( 4 == req.readyState ) {
        	// set the cursor back to it's default
        	changeCursorStyle('default');
        	// Make sure the response was successfull (http return code 200)
	        if( 200 != req.status ) {
		    	alert( "The following error occured while processing the search results response: " + req.status + ": " + req.statusText + "\nMake sure the search Server is still availabe and contact your system administrator" );
			} else {
				window.location.hash = 'main';

			    // The response from a Struts action is "wrapped" with the framework of the Portal automatically.
			    // Since the response is more than what we need, we had to add these DIV elements to
			    // the searchResultsTable.jsp and then use string manipulation to find them in the
			    // response so that we can then extract just the OmniFind search results.
				var start = req.responseText.indexOf("<div id=\"omnifind_search_results_start\">");
				var startText = req.responseText.substring(start);
				var end = startText.indexOf("<div id=\"omnifind_search_results_end\">");
				var ajaxResponse = startText.substring(0, end + 38);
				var theSearchResultsTableEle = document.getElementById("theSearchResultsTable");
				theSearchResultsTableEle.innerHTML = ajaxResponse;
				
				onloadHideShowDetails();
			}    
		}
	}	
	
	function changeCursorStyle(style) {
		document.body.style.cursor = style;
	}

    // ***************************************************
    // Top Results Charts
    // ***************************************************
   	function hasTopResultsDiagrams() {
   	   var chartHeader = document.getElementById('topChartHeader');
   	   if (chartHeader) {
	   	   return true;
	   } else {
	       return false;
	   }	   
   	}
   	
   	function startLoadTopResultsDiagrams() {
  	   if (hasTopResultsDiagrams()) {
	       setAllTopResultsChartTwistyStyleImage();
	       
	       try {
    		   var request;
        	   if( window.ActiveXObject ) {
		           request = new ActiveXObject( "Microsoft.XMLHTTP" );
	           } else if( window.XMLHttpRequest ) {
        	       request = new XMLHttpRequest();
		       } else {
	        	   alert( "Ajax is not supported by your browser !" );
    	       }
		    
			   // When select an item from the topQuery chart, then add the selected 
			   // term to the query (& rerun the query)
			   var url = REQUEST_CONTEXT_PATH + "/DynamicChartServlet";
		       request.open( "GET", url, true );
		       request.onreadystatechange = function() {
	    	    	loadTopResultsDiagrams(request);
	           }	
		       request.send( null );
		   } catch( e ) {
	    	   alert( "An error occured while trying to request the top result charts:\"" + e + "\n try reloading this page and contact your system administrator if the problem persits.");
	       }
       }
    }

   	function startLoadTopResultsDiagramsFor(chartName, selectHTMLField) {
    	try {
			var fieldName = selectHTMLField.options[selectHTMLField.selectedIndex].value;
			if (!fieldName || fieldName == '') return;
			
			// Hide messages
			var chartNameMessageDiv = document.getElementById(chartName + "_message");
			chartNameMessageDiv.style.display = 'none';
			
			// Show the collapsedDiv & animated gif. Hide the collapsed chart image
			var collapsedChartDiv = document.getElementById(chartName + "_collapsedDiv");
			collapsedChartDiv.style.display = '';
			var animatedImage = document.getElementById(chartName + '_animated_image');
			animatedImage.style.display = '';
			var collapseImage = document.getElementById(chartName + '_collapsed_image');
			collapseImage.style.display = 'none';
			//var map = document.getElementById(chartName + "_collapsed_map");
			//map.innerHTML = '';
			
			// Hide the expandedDiv
			var expandedChartDiv = document.getElementById(chartName + "_expandedDiv");
			expandedChartDiv.style.display = "none";
			
			// Hide the expand/collapse button
			var expandButtonDiv = document.getElementById(chartName + "_buttonDiv");
			expandButtonDiv.style.display = "none";
			var button = document.getElementById(chartName+ "_button");
			button.value = expandButtonText;
			
    		var request;
        	if( window.XMLHttpRequest ) {
		        request = new XMLHttpRequest();
		    } else if( window.ActiveXObject ) {
	        	request = new ActiveXObject( "Microsoft.XMLHTTP" );
	        } else {
	        	alert( "Ajax is not supported by your browser !" );
    	    }
		    	    
		    // When the user selects an item from the topQuery chart, add the selected term 
		    // to the query (& rerun the query)
		    var url = REQUEST_CONTEXT_PATH + "/DynamicChartServlet?chartName=" + chartName + "&fieldName=" + encodeURIComponent(fieldName);
			
	        request.open( "GET", url, true );
	        request.onreadystatechange = function() {
	        	loadTopResultsDiagrams(request);
	        }	
	        request.send( null );
	    } catch( e ) {
	        alert( "An error occured while trying to request the top result charts:\"" + e + "\n try reloading this page and contact your system administrator if the problem persits.");
       	}
    }

    function loadTopResultsDiagrams(req) {
        if( 4 == req.readyState ) {
        	// Make sure the response was successfull (http return code 200)
	        if( 200 != req.status ) {
		    	alert( "The following error occured while processing the diagram response: " + req.status + ": " + req.statusText + "\nMake sure the search Server is still availabe and contact your system administrator" );
			} else {
				var xmlDocument = req.responseXML.documentElement;
				if (xmlDocument == null) {
					alert(req.responseText);
				}
												
				var fields = xmlDocument.getElementsByTagName("field"); 					
				var fieldArray = [];
				if (fields && fields.length > 0) {
				    fieldArray.length = 0;
					for (var i=0 ; i<fields.length ; i++) {
		        		if (fields[i].getElementsByTagName('id') && 
		        		    fields[i].getElementsByTagName('id')[0] && 
	    	    		    fields[i].getElementsByTagName('id')[0].firstChild &&
	    	    		    fields[i].getElementsByTagName('label') &&
	    	    		    fields[i].getElementsByTagName('label')[0] &&
	    	    		    fields[i].getElementsByTagName('label')[0].firstChild)  {
						    var id = fields[i].getElementsByTagName('id')[0].firstChild.data;
						    var label = fields[i].getElementsByTagName('label')[0].firstChild.data;
						    var o = {};
						    o.id = id;
						    o.label = label;
		    	    		fieldArray[fieldArray.length] = o;
	        			}
					}
	        	}
				
				var diagrams = xmlDocument.getElementsByTagName("chart"); 					
				for (var i=0 ; i<diagrams.length ; i++) {
				    var id = diagrams[i].getElementsByTagName('id')[0].firstChild.data;
	        		var errorMsg = null;
	        		if (diagrams[i].getElementsByTagName('error') && 
	        		    diagrams[i].getElementsByTagName('error')[0] && 
	        		    diagrams[i].getElementsByTagName('error')[0].firstChild) {
					    errorMsg = diagrams[i].getElementsByTagName('error')[0].firstChild.data;
	        		}
				    var displayData = null;
	        		if (diagrams[i].getElementsByTagName('displayData') && 
	        		    diagrams[i].getElementsByTagName('displayData')[0] && 
	        		    diagrams[i].getElementsByTagName('displayData')[0].firstChild) {
					    displayData = diagrams[i].getElementsByTagName('displayData')[0].firstChild.data;
	        		}
				    var fieldName = null;
	        		if (diagrams[i].getElementsByTagName('fieldName') && 
	        		    diagrams[i].getElementsByTagName('fieldName')[0] && 
	        		    diagrams[i].getElementsByTagName('fieldName')[0].firstChild) {
					    fieldName = diagrams[i].getElementsByTagName('fieldName')[0].firstChild.data;
	        		}
				    var title = null;
	        		if (diagrams[i].getElementsByTagName('title') && 
	        		    diagrams[i].getElementsByTagName('title')[0] && 
	        		    diagrams[i].getElementsByTagName('title')[0].firstChild) {
					    title = diagrams[i].getElementsByTagName('title')[0].firstChild.data;
	        		}
				    var collapsedImageLocation = diagrams[i].getElementsByTagName('collapsedChartImage')[0].firstChild.data;
				    var collapsedChartMap = diagrams[i].getElementsByTagName('collapsedChartMap')[0].firstChild.data;
				    var expandedImageLocation = diagrams[i].getElementsByTagName('expandedChartImage')[0].firstChild.data;
				    var expandedChartMap = diagrams[i].getElementsByTagName('expandedChartMap')[0].firstChild.data;
				    
				    var selectFields = document.getElementById(id + '_SelectFields');
				    if (selectFields) {
				        selectFields.options.length = 0; 
				        for (var j=0 ; j<fieldArray.length ; j++) {
					        selectFields.options[j] = new Option(fieldArray[j].label, fieldArray[j].id);
					        if (fieldName && fieldArray[j].id == fieldName) {
					           selectFields.options[j].selected = "selected";
					        }
					    }    
				    }
				    if (title && title != '') {
				        var titleDiv = document.getElementById(id + '_title');
				        if (titleDiv) {
					        for (var x=1 ; x<titleDiv.childNodes.length ; x++) {
					            if (titleDiv.childNodes[x].nodeType == 3) {
					               titleDiv.childNodes[x].nodeValue = title;
					            }
					        }
				        }
				    }
				    
				    if (errorMsg && errorMsg != "") {
						// Hide the animation 
						var collapsedImage = document.getElementById(id + "_collapsed_image");
						collapsedImage.style.display = "none";
						var animatedImage = document.getElementById(id + '_animated_image');
						animatedImage.style.display = 'none';
								
						// Make the "not applicable" message appear 
						var notApplicable = document.getElementById(id + "_message");
						notApplicable.style.display = "block";
						notApplicable.innerHTML = "<div style='text-align: center'>" + errorMsg + "</div>";
				    } else if (displayData && displayData != "") {
						// Hide the animation 
						var collapsedImage = document.getElementById(id + "_collapsed_image");
						collapsedImage.style.display = "none";
						var animatedImage = document.getElementById(id + '_animated_image');
						animatedImage.style.display = 'none';
								
						// Make the displayData message appear 
						var notApplicable = document.getElementById(id + "_message");
						notApplicable.style.display = "block";
						notApplicable.innerHTML = "<div style='text-align: left'>" + displayData + "</div>";
				    } else {
					    //Preload the collapse image 
						var collapsedPreloadedImage = new Image();
						collapsedPreloadedImage.src = collapsedImageLocation;
						var animatedImage = document.getElementById(id + '_animated_image');
						animatedImage.style.display = 'none';
						var collapsedImage = document.getElementById(id + "_collapsed_image");
						collapsedImage.style.display = "block";
						collapsedImage.src = collapsedPreloadedImage.src;
						//collapsedImage.alt = ''; ;
						    
						// set the pixel map (if chart is clickable) 
						if (collapsedChartMap != "") {
							var map = document.getElementById(id + "_collapsed_map");
							map.innerHTML = collapsedChartMap;
						}
							
						// Set the expanded chart (if applicable) 
						if (expandedImageLocation && expandedImageLocation != "") {
						    //Preload the expanded image 
							var expandedPreloadedImage = new Image();
							expandedPreloadedImage.src = expandedImageLocation;
							var expandedImage = document.getElementById(id + "_expanded_image");
							expandedImage.src = expandedPreloadedImage.src;
							
							// Show the expand button
							var expandButtonDiv = document.getElementById(id + "_buttonDiv");
							expandButtonDiv.style.display = "block";
							
							// Set the expanded charts pixel map (if applicable) 
							if (expandedChartMap && expandedChartMap !="") {
								var map = document.getElementById(id + "_expanded_map");
								map.innerHTML = expandedChartMap;
							}
						}
					}	
				}
	        }
      	}
	}
		    
   	// Expands/collapses the chart with the specified name. The expansion is done by making the collapsed chart
   	// invisible and making the expanded chart visible. The collapse is done the other way round.
   	// the display style "block" stands for "visible" whereas "none" means invisible
    function expandTopResultsChart(chartName) {
		var expandedChartDiv = document.getElementById(chartName + "_expandedDiv");
		var collapsedChartDiv = document.getElementById(chartName + "_collapsedDiv");
		var button = document.getElementById(chartName+ "_button");
		if (expandedChartDiv.style.display == "none") {
			collapsedChartDiv.style.display = "none";
			expandedChartDiv.style.display = "block";
			button.value = collapseButtonText;
		} else {
			expandedChartDiv.style.display = "none";
			collapsedChartDiv.style.display = "block";					
			button.value = expandButtonText;
		}
    }
    
	function toggleTopResultsChartTwisty(twistyId) {
		var twistyContent = document.getElementById(twistyId+"Content");
		var twistyImage = document.getElementById(twistyId+"Image");
		if (twistyContent.style.display == "none") {
			twistyImage.src = REQUEST_CONTEXT_PATH + COLLAPSE_GIF;
			twistyImage.alt = COLLAPSE_TEXT_ALT;
			twistyImage.title = COLLAPSE_TEXT_ALT;
			twistyContent.style.display = "block";
			SetCookie(twistyId, "true");
		} else {
			twistyImage.src = REQUEST_CONTEXT_PATH + EXPAND_GIF;
			twistyImage.alt = EXPAND_TEXT_ALT;
			twistyImage.title = EXPAND_TEXT_ALT;
			twistyContent.style.display = "none";
			SetCookie(twistyId, "false");
		}	
	}
	
   	function setAllTopResultsChartTwistyStyleImage() {
	    // Set all the twisty images & open/collapse state
  	    for (var i=0 ; ; i++) {
  	        var chartID = 'topChartItem' + i;
  	        var chartElement = document.getElementById(chartID);
  	        if (!chartElement) {
  	            break;
  	        }
	  	    setTopResultsChartTwistyStyleImage(chartID);
	    }
   	}
   	
	function setTopResultsChartTwistyStyleImage(twistyId) {
		var cookie = GetCookie(twistyId);
		var twistyContent = document.getElementById(twistyId+"Content");
		var twistyImage = document.getElementById(twistyId+"Image");
		if (twistyContent && twistyImage) {
			if (cookie == null || cookie == "true") {
				twistyImage.src = REQUEST_CONTEXT_PATH + COLLAPSE_GIF;
				twistyImage.alt = COLLAPSE_TEXT_ALT;
				twistyImage.title = COLLAPSE_TEXT_ALT;
				twistyContent.style.display = "block";
			} else {
				twistyImage.src = REQUEST_CONTEXT_PATH + EXPAND_GIF;
				twistyImage.alt = EXPAND_TEXT_ALT;
				twistyImage.title = EXPAND_TEXT_ALT;
				twistyContent.style.display = "none";
			}
		}
	}
	
