/**
 * @description [get My List count - save record to My List]
 */
 
jQuery(document).ready(function() {

	//	calls fireJs in cases where the user is not logged in, and clicks 'add to my list' 
	if(getUrlVars()["addToMyList"]){
		fireJs();
	}
});

/*
	name		fireJs
	returns		void
	purpose		runs the JS in the fireJs attribute for the specified ID
	used by		(the above document.ready() call, dsp_actionBar.cfm, others
	uses		n/a
	arguments	
		name		type	description
		----		----	-----------
		elementId	string	the id of the href to fire
*/
function fireJs(){
	if(jQuery("#actionBarAddToMyList").attr("fireJs")){
		eval(jQuery("#actionBarAddToMyList").attr("fireJs"));
	}
}

//	TODO:	add comment for this function
function getUrlVars()
{
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
} 

/*	
	name		addToMyListHandler
	returns		void
	purpose		gate-keeper for (most) 'Add to My List' features on PsycNET.
				enforces the 'no more than 250 my list items' rule.
	used by		see cases below in case statement (matches fuse actions on pages)
	uses		getSelectedUIDs()
				setMyList()
				addArticleToMyList()
	arguments
		name		position	type	description
		----		--------	----	-----------
		fa			0			string	in cases where fa is not in url string, specify it here
		idUIDs		1			string	the id prefix associated with the checkbox items
		myListCount	2			number	current number of items in 'My List'
		totalOnPage	3			number	total number of records displayed on the current page
		uid			4			string	the item's unique identifier!
	
*/
function addToMyListHandler(fa,idUIDs,myListCount,totalOnPage,uid){

	var maxMyListCount = 250;	//	TODO: move this to the place where global js vars are stored
	var myListAlertString = "My List can contain a maximum of " + maxMyListCount + " items.";
	
	//	set the fa
	if(getUrlVars()["fa"]){
		fa = getUrlVars()["fa"];
	}
	
	//	search.searchResults and search.citedRefsRecord share the same case below
	if(fa == "search.citedRefsRecord"){
		fa = "search.searchResults";
	}else if(fa == "search.displayTestRecord"){
		fa = "search.displayRecord";
	}	
			
	switch(fa){

		//	uses args: 	myListCount, uid
		//	used in: 	in lay_fulltextReview.cfm, lay_fulltextJournal.cfm
		case "addFullTextToMyList":{

			if(myListCount + 1 > maxMyListCount){
				displayMyListMaxAlert(myListAlertString, 'fullText');
			}else{
				addFullTextToMyList(uid);
			}
			break;
		}
 	
		//	uses args: 	idUIDs, totalOnPage, myListCount
		//	used in:	fa search.searchResults, search.citedRefsRecord
		case "search.searchResults":{
		
			selectedUIDs = getSelectedUIDs(idUIDs,totalOnPage);
			selectedUIDsArray = selectedUIDs.split(",");
			selectedUIDsCount = selectedUIDsArray.length;
			if(selectedUIDs == ''){
				selectedUIDsCount = 0;
			}

			/*
			alert('setMyList.js > addToMyListHandler() '
				+ ' selectedUIDs is ' + selectedUIDs 
				+ ' , selectedUIDsCount is ' + selectedUIDsCount 
				+ ' , myListCount is ' + myListCount 
				+ ', selectedUIDsCount + myListCount = ' + (selectedUIDsCount + myListCount)
				+ ', selectedUIDsCount + myListCount > maxMyListCount returns ' + (selectedUIDsCount + myListCount > maxMyListCount)
				);
			*/
		
			if(selectedUIDsCount + myListCount > maxMyListCount){
				displayMyListMaxAlert(myListAlertString);	
			}else{
				setMyList(idUIDs,totalOnPage);
			}
			break;
		}
		
		//	uses args: 	myListCont, uid
		//	used in:	search.displayRecord (includes '/psycextra/#uid#/')
		case "search.displayRecord":{
			
			if(myListCount + 1 > maxMyListCount){
				displayMyListMaxAlert(myListAlertString);
			}else{
				addArticleToMyList(uid);
			}
			break;
		
		//	TODO: add a behavior for handling any cases that I may have missed (?)	
		}default:{
			//	alert("Unable to add item to My List.");
			break;
		}
	}	
}

//	TODO: add code comments for displayMyListMaxAlert()
function displayMyListMaxAlert(myListAlertString, messageType){

	if(! arguments[1]){
		messageType = "default";
	}

	switch(messageType){
	
		case "fullText":{
		
			myListAlertString = myListAlertString + ' <a href="/index.cfm?fa=search.myList" target="_blank">Go to My List</a>';
			jQuery("#addTomyListAlert").html(myListAlertString);

			Effect.SlideDown('divAddToMyList');
			setTimeout('Effect.Fade(\'divAddToMyList\')',5000);	
			break;

		}default:{
			alert(myListAlertString);
			break;
		}
	}
}

function clearMessage(){
	jQuery('#srMyListTotal').css('background', '');
}

//saves UID
function setMyList(idUIDs,totalOnPage)	{		
	var lstSelectedUIDs = "";
	
	//get the list of selected UIDs
	if(idUIDs.length){
		jQuery('#srMyListTotal').css('background', 'url(images/reloading.gif) no-repeat top left');

		//getSelectedUIDs is in file contentManagement.js
		lstSelectedUIDs = getSelectedUIDs(idUIDs,totalOnPage);

		//	add items to My List	
		DWREngine._execute(_ajaxConfig._cfscriptLocation + 'Navigation.cfc', null, 'addArticlesToListFromChecked',lstSelectedUIDs, updateMyListCount );
	}
}

function addFullTextToMyList(uid){
	DWREngine._execute(_ajaxConfig._cfscriptLocation + 'Navigation.cfc', null, 'isArticleInList',uid, function(response){
		var responseText = '';
		var responseTextInnerHtml = '';
		if(eval(response) == false) {
			responseText = 'Item added to My List.';
			DWREngine._execute(_ajaxConfig._cfscriptLocation + 'Navigation.cfc', null, 'addArticlesToList',uid, function(response){
			});			
		}else{
			responseText = 'This item is already in My List.';
		}
		responseTextInnerHtml = responseText + ' <a href="/index.cfm?fa=search.myList" target="_blank">Go to My List</a>';
		jQuery('#addToMyListAlert').html(responseTextInnerHtml);

		/*		
		jQuery('#divAddToMyList').slideDown('slow', function() {
	    	jQuery('#divAddToMyList').fadeOut('slow');
		});
		*/

jQuery('#divAddToMyList').slideDown('slow').delay(5000).fadeOut('fast');

/*
Effect.SlideDown('divAddToMyList');
setTimeout('Effect.Fade(\'divAddToMyList\')',5000);		
*/
	});
}

function addArticleToMyList(uid) {
	//	$('srMyListTotal').style.background = 'url(images/reloading.gif) no-repeat top left';	
	jQuery('#srMyListTotal').css('background','url(images/reloading.gif) no-repeat top left');
	DWREngine._execute(_ajaxConfig._cfscriptLocation + 'Navigation.cfc', null, 'addArticlesToList',uid, updateMyListCount );
}

//returns total saved UIDs
function updateMyListCount(responseStruct) {
	var plural ="s";
	
	if(responseStruct.totalselected == 1){
		plural ="";
	}	
	
	//	$('srMyListTotal').innerHTML = "My List("+responseStruct.totalselected+")";
	htmlString = 'My List (<span id="myListTotal">' + responseStruct.totalselected + '</span>)';
	jQuery('#srMyListTotal').html(htmlString);

	window.setTimeout('clearMessage()',1500);
}

function getMyListCount(){
	DWREngine._execute(_ajaxConfig._cfscriptLocation + 'Navigation.cfc', null, 'GetMyListCount', updateMyListCount);
}

function constructFuseboxLink(fa){
	BASE_PATH = 'index.cfm';	
	return BASE_PATH + '?fa=' + fa; 
}
