//These scripts are used by the library home page
//the excepetion is the NewsFeed scripts and the Alert scrips - those reside elsewhere


//Show Random Image scripts

//set some initial constants (ok, vars really)
var CONST_RandomImageBaseLocation='/_design/images/Front_Page_Random_Images/'; //don't foget the closing "/"
var CONST_RandomImageBackstopFile='Backstop_Image.jpg'; //don't foget the closing "/"
var CONST_RandomImageListFile='Front_Page_Random_Images_List.txt'; //where to get the lst of file to pick from
var CONST_RandomImageDisplayDiv='RandomImage'; //where to drop the image file into
var tempImg=new Image();
//var CONST_RandomImageDebugDiv='RandomImageDebug';

//select a random image from an external list of files
function ShowRandomFrontPageImage() {
	FetchImageListData();
	return 1;
}

//the image size check need to run as a separate function because the image load happens in parallel with the code execution. 
//By running as a function, the image will be checked once the image loads (or fails to load) even if the script finishes 
//executing before the image load has completed.
function CheckImageSize() {
	//verify that the image is valid by getting the height and width of the future image
	if(tempImg.height>0) {
		//is it valid? ok, then show it
		$('#'+CONST_RandomImageDisplayDiv).html('<img src="'+tempImg.src+'">\n');
	} else {
		//if not, show the backstop image so that we at least show SOME image
		$('#'+CONST_RandomImageDisplayDiv).html('<img src="'+CONST_RandomImageBaseLocation+CONST_RandomImageBackstopFile+'">\n');
	} //end tempImg check if	
	return 1;
} //end function

function FetchImageListData() {
	//reqest the data from the server
	$.ajax({
		url: CONST_RandomImageBaseLocation+CONST_RandomImageListFile,
		success: function(data) {
			//need to preprocess the data to remove the leading spaces, tabs and comments, then convert into a JS data array
			//why do we do this? because windows has an annoying habbit of adding spaces when performing copy/paste operations
			var lineArray = data.split('\n');
			var ImageListArray=[];
			//foreach image list item, add it to the array after cleaning up the text
			for (var i = 0; i < lineArray.length; i++) {
				var doProcessLine=1;
				//remove leading and trailing white spaces from lines
				lineArray[i]=lineArray[i].replace(/[\r|\n]/gim, ''); //get rid of the CR/LF chars
				lineArray[i]=lineArray[i].replace(/\t+/gim, ''); //remove any tabs anywhere
				lineArray[i]=lineArray[i].replace(/^\s+/gim, ''); //remove leading spaces
				lineArray[i]=lineArray[i].replace(/\s+$/gim, ''); //remove trailing spaces (\z not supported, use $)
				
				//if a line is a comment, toss it
				if(lineArray[i].substr(0,1)==';') {doProcessLine=0;}
				//if a line is blank, toss it
				if(lineArray[i]=='') {doProcessLine=0;}
				
				//anything left to work with?
				if(doProcessLine) {
					ImageListArray.push(lineArray[i]);
				} else {
					//do nothing
				}//end doProcess check if 
			} //end for
			
			//pick a random image file from the list of valid lines in ImageListArray
			var TargetImageFileName=ImageListArray[Math.floor(Math.random()*ImageListArray.length)];
			tempImg.src=CONST_RandomImageBaseLocation+TargetImageFileName;
			tempImg.onload=function() {CheckImageSize();}

		}, //end success handling
		error: function(xhr, ajaxOptions, thrownError) {
			//oh dear, this didn't go as expected
			//$('#'+CONST_RandomImageDebugDiv).text(xhr.status+'<br/>'+thrownError);
			
			//in the event of an error, just hide the newsfeed continer and pretend nothing happened after first inserting the error message
			//$('#'+CONST_RandomImageDebugDiv).css('display', 'none');
		} //end error handling
	}); //end ajax handling
	return 1;
} //end function


//Menu related scripts

//function to toggle a block element item display to visible or hidden
function ShowHideItem(targetItem, targetImage) {
     if(!targetItem) {return 0;}
     
     //need to validate input here
     if($('#'+targetItem)) {
           //show the target element
           if($('#'+targetItem).css('display')=='none') {
                $('#'+targetItem).css('display', 'block');
                //check if this param exists since it is optional
                if(targetImage) {
                     if($('#'+targetImage)) {
                           $('#'+targetImage).attr('src', '/_design/images/minus11.gif');
                     } //end targetImage element check if
                } //end targetImage defined check if
           } else {
                $('#'+targetItem).css('display', 'none');
                //check if this param exists since it is optional
                if(targetImage) {
                     if($('#'+targetImage)) {
                           $('#'+targetImage).attr('src', '/_design/images/plus11.gif');
                     } //end targetImage element check if
                } //end targetImage defined check if
           } //end display check if
           
           return 1;
     } else {
           //do nothing
           return 0;
     } //end targetItem element exists check if
} //end function






// new tab related code below this point
var TabLookupObject=new Object();
TabLookupObject["tab_Summon"]=new Object();
TabLookupObject["tab_Summon"]["SearchContentContainerObjectID"]="Summon";
TabLookupObject["tab_Summon"]["SearchTextObjectID"]="cat_form_text";
TabLookupObject["tab_Summon"]["SearchTextObjectText"]="Find books, articles, videos, and more owned by UConn";
TabLookupObject["tab_Summon"]["SearchAboutObjectID"]="";
TabLookupObject["tab_Summon"]["SearchAboutObjectText"]="Searches <i>almost</i> everything physically at UConn libraries as well as UConn's online resources (articles, e-books, streaming media, etc.). Recommended starting point for most research.";

TabLookupObject["tab_WCL"]=new Object();
TabLookupObject["tab_WCL"]["SearchContentContainerObjectID"]="WCL";
TabLookupObject["tab_WCL"]["SearchTextObjectID"]="cat_form_text"; //this is a dupe ID, and needs to change somehow
TabLookupObject["tab_WCL"]["SearchTextObjectText"]="WCL Search";
TabLookupObject["tab_WCL"]["SearchAboutObjectID"]="";
TabLookupObject["tab_WCL"]["SearchAboutObjectText"]="Need text about WCL search";

/* TabLookupObject["tab_homer"]=new Object();
TabLookupObject["tab_homer"]["SearchContentContainerObjectID"]="homer";
TabLookupObject["tab_homer"]["SearchTextObjectID"]="homerSearch";
TabLookupObject["tab_homer"]["SearchTextObjectText"]="Homer search text";
TabLookupObject["tab_homer"]["SearchAboutObjectID"]="";
TabLookupObject["tab_homer"]["SearchAboutObjectText"]="Searches for physical stuff at UConn and other libraries.  Recommended for finding physical books, movies, scores, maps, etc, and for finding and requesting items through Interlibrary Loan.";

TabLookupObject["tab_ejournals"]=new Object();
TabLookupObject["tab_ejournals"]["SearchContentContainerObjectID"]="ejournals";
TabLookupObject["tab_ejournals"]["SearchTextObjectID"]="criteria";
TabLookupObject["tab_ejournals"]["SearchTextObjectText"]="eJournals Search";
TabLookupObject["tab_ejournals"]["SearchAboutObjectID"]="";
TabLookupObject["tab_ejournals"]["SearchAboutObjectText"]="Need text about journals search"; */

TabLookupObject["tab_databases"]=new Object();
TabLookupObject["tab_databases"]["SearchContentContainerObjectID"]="databases";
TabLookupObject["tab_databases"]["SearchTextObjectID"]="";
TabLookupObject["tab_databases"]["SearchTextObjectText"]="database Search";
TabLookupObject["tab_databases"]["SearchAboutObjectID"]="";
TabLookupObject["tab_databases"]["SearchAboutObjectText"]="Need text about database search";

//set up the default tab
CONST_Default_Tab="tab_Summon";

//this section needs to be coded out
var TabTextContent=new Array();
TabTextContent["books"]="You shouldn't be seeing this";
TabTextContent["articles"]="UConn and beyond";
TabTextContent["bm"]="UConn and beyond"; 
TabTextContent["av"]="You shouldn't be seeing this";
TabTextContent["everything"]="Books, articles, videos and more";
var DebugThis="";

function DoInit() {
	//set up the default search tab and adjust the search tab heights (if needed)
	EnableTab(CONST_Default_Tab);
} //end function

function DoResizeItems() {
	//remove page elements based on size 
	if($(document).width()>=800) {
		$("."+"nav_col").css("display", "inline");
		$("."+"news_col").css("display", "inline");
		$("."+"nav_col").css("width", "20%");
		$("."+"main_col").css("width", "60%");
		$("."+"news_col").css("width", "19.91%");

		$("."+"main_container").css("marginLeft", "8px");
		$("."+"main_container").css("marginRight", "8px");
		$("."+"menu_item").css("width", "16.5%"); //less than 16.66% due to IE rounding bug
		$("."+"menu_item_optional1").css("display", "inline");
		$("."+"menu_item_optional2").css("display", "inline");
	} //end if
	//if($(document).width()<800 && $(document).width()>650 ) {
	//	$("."+"news_col").css("display", "none");
	//	$("."+"nav_col").css("display", "inline");
	//	$("."+"nav_col").css("width", "20%");
	//	$("."+"main_col").css("width", "79.91%");
	//	$("."+"news_col").css("width", "0");
	//	
	//	$("."+"main_container").css("marginLeft", "8px");
	//	$("."+"main_container").css("marginRight", "0px");
	//	$("."+"menu_item").css("width", "19.5%"); //less than 16.66% due to IE rounding bug
	//	$("."+"menu_item_optional1").css("display", "none");
	//	$("."+"menu_item_optional2").css("display", "inline");
	//} //end if
	if($(document).width()<800) { //was 650
		$("."+"nav_col").css("display", "none");
		$("."+"news_col").css("display", "none");
		$("."+"nav_col").css("width", "0");
		$("."+"main_col").css("width", "100%");
		$("."+"news_col").css("width", "0");

		$("."+"main_container").css("marginLeft", "0px");
		$("."+"main_container").css("marginRight", "0px");
		$("."+"menu_item").css("width", "24.6%"); //less than 20% due to IE rounding bug
		$("."+"menu_item_optional1").css("display", "none");
		$("."+"menu_item_optional2").css("display", "none");
	} //end if
	
	//adjust some element heights and widths - because CSS does this so well by itself
	CalcMenuItemHeight();
	CalcTabItemHeight();
	//CalcColHeight();
} //end function

//this function is not ready yet
function CalcColHeight() {
	var MaxHeight=0;
	$("."+"content_container").children().each(function (i) {
		if($(this).height() > MaxHeight) {MaxHeight=$(this).height();}
	});

	$("."+"content_container").children().each(function (i) {
		var TempColHeight=$(this).height();
		if(TempColHeight==MaxHeight) {
			$(this).children().last().css('background-color', 'green');
		} else {
			var position=$(this).children().last().position();
			$(this).children().last().css('background-color', 'red');
			NewHeight=MaxHeight-TempColHeight+$(this).children().last().height();
			//$(this).children().last().css('height', NewHeight);
			//alert(MaxHeight+", "+TempColHeight+", "+position.top);
		} //end is already heighest col check if
	});
	//alert(MaxHeight);
} //end function


function CalcMenuItemHeight() {
	//first, find the max height
	var MaxHeight=16;
	$("."+"menu_item_text").each(function (i) {
		$(this).height("auto");
		if($(this).height() > MaxHeight) {MaxHeight=$(this).height();}
	});

	//next, apply the max height
	$("."+"menu_item_text").each(function (i) {
		$(this).height(MaxHeight);
	});
} //end function

function CalcTabItemHeight() {
	//first, find the max height
	var MaxHeight=16;
	$("."+"tab_text").each(function (i) {
		$(this).height("auto");
		if($(this).height() > MaxHeight) {MaxHeight=$(this).height();}
	});

	//next, apply the max height
	$("."+"tab_text").each(function (i) {
		$(this).height(MaxHeight);
	});
} //end function

function ClearSearchText(TargetID) {
	$("#"+TargetID).html('&nbsp;');
} //end function

function DoContentSearch() {
	//first, find the name of the active tab to get the name of the tab to work with
	var TargetID=$("."+"tab_active")[0].id; //grab the first one (even though there should only ever be one)
	
	//now that we know the active tab, pull out the search text content based on the tab name
	var TargetTabName=TargetID.replace(/tab_/i, "");
	var SearchText=$("#"+"tab_search_"+TargetTabName).text();
	
	//may also need to dig out search options here
	
	//show the search text
	alert("Content search for text: "+SearchText);
} //end function

//function DoSiteSearch() {
//	var SearchText=$("#"+"lib_search_text").text();
//	alert("Site search for text: "+SearchText);
//} //end function

//this adds text selection handling to browsers because native JS and jQuery don't do this
function SelectText(element) {
    var doc = document;
    var text = doc.getElementById(element);    
    if (doc.body.createTextRange) {
        var range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.setBaseAndExtent) {
            selection.setBaseAndExtent(text, 0, text, 1);
        } else {
            var range = document.createRange();
            range.selectNodeContents(text);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    }
} //end SelectText function

function EnableTab(TargetID) {
	//setup the event handler so we can remove it from the previous tabs and set it in the active tab
	//this part is working, but there are issues with the events being removed correctly - don't use just yet
	var KeyHandler=function(event) {
		//tab_everything -> tab_search_everything -> tab_search_button_everything
		//$("#"+TargetID.replace(/tab_/i, "tab_search_")).css("backgroundColor", "red");
		//$("#"+TargetID.replace(/tab_/i, "tab_search_button_")).css("backgroundColor", "green");
		
		//enter key
		if(event.which ==13){
			event.preventDefault();
			$("#"+"tab_search_text").text();
			DoContentSearch();
			alert(event.target.id);
			return false;
		} //end enter key search
		
		//escape key
		if(event.keyCode==27){
			//what should we do here? should we clear the text?
			//return false;
		} //end enter key search
		
		//check for the tab key here?
		
		//let the event pass normally
		return true;
	} //end KeyHandler
	
	//reset all tabs
	$("."+"tab_text").each(function (i) {
		//this.id=tab_articles, tab_bm, tab_everything, etc.
		$(this).removeClass('tab_active');
		//$("#"+this.id.replace(/tab_/i, "tab_search_")).css("backgroundColor", "blue");
		
		//this unbinding section seem to be missing the active tab each time it is called
		//this cuases events to stach up if tabs are clicked a few times
		//$("#"+this.id.replace(/tab_/i, "tab_search_")).unbind("keydown", false);
		//alert("unbinding on "+this.id.replace(/tab_/i, "tab_search_")); 
		$("#RandomImage").css('display',"none");
	}); //end each

	//hide all the tab control sections
	$("."+"tab_controls_container").each(function (i) {
		//alert("this="+this);
		$(this).css("display", "none");
	}); //end each
	
	//set the target tab as active and then check the resize function in case the tabe spans 2 lines now that the text is bold
	$("#"+TargetID).addClass('tab_active');
	DoResizeItems();

	//set the target search controls active
	$("#"+TabLookupObject[TargetID].SearchContentContainerObjectID).css("display", "block"); //inline displays some item widths like SPANs, block forces width more like DIVs
	
	//update the search text and set the focus
	if(TabLookupObject[TargetID].SearchTextObjectID) {
		if(TabLookupObject[TargetID].SearchContentContainerObjectID!="databases"){$("#RandomImage").css('display',"block");}
		//$("#"+TabLookupObject[TargetID].SearchTextObjectID).val(TabLookupObject[TargetID].SearchTextObjectText); //works, but no way to clear it just yet
		//SelectText(TabLookupObject[TargetID].SearchTextObjectID); //this does not work on forms, need to adjust
		$("#"+TabLookupObject[TargetID].SearchTextObjectID).focus();
		//$("#"+TabLookupObject[TargetID].SearchTextObjectID).bind("keydown", KeyHandler);
	} //end object exists check if
	
} //end function


