function showHideTerm(fromUrl){
	if(fromUrl.search('ViewRecipe.jsp')>0)
	{		
		dojo.removeClass(dojo.byId('term'), 'invisible');
		dojo.addClass(dojo.byId('term'), 'visible');				
	}
	else{
		dojo.removeClass(dojo.byId('term'), 'visible');
		dojo.addClass(dojo.byId('term'), 'invisible');	
	}
}
function setDivContents(fromUrl, loadTo, pageTitle)
{				
	showHideTerm(fromUrl);	
	var deferred = dojo.xhrGet
   	( 
  	    {
   			url: encodeURI(fromUrl),
   			headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
   			handleAs: "text",
   			preventCache: true,
   			timeout: 55000,
   			load: function(response, ioArgs) 
   			{	   				
      	    	var destroyThese = ['recipeForm','userReg','selectIngPanel', 'recipeCommentForm','frmCocktailLogin','frmRegistration','frmUserAccount'];
            	for (var i=0; i<destroyThese.length; i++) 
	            {
            		var db = dijit.byId(destroyThese[i]);
		           	if (db)
			        {			                	
			            	dijit.byId(destroyThese[i]).destroyRecursive();
		          	}
	            }
				var fred = document.getElementById(loadTo);
	        	fred.innerHTML = response;
          		dojo.parser.parse(dojo.byId(loadTo));
           		// document.title=pageTitle;
           		var scriptElement=document.getElementById("scripts");
           		if ((scriptElement)&&(scriptElement != null))
				{					
           			/*  
					The script is enclosed in html comment tags so that its not displayed on the page.
					Remove the comment tags before eval(uating) the script. IE cannot evaluate
					script within html comments. Firefox does this though. IE is probably right in this
					case.
					*/
					var loadedScript = document.getElementById("scripts").innerHTML;
					var stIdx = loadedScript.indexOf("<!--");
					var endIdx= loadedScript.indexOf("-->");
					loadedScript = loadedScript.substring( stIdx + 4, endIdx - 1);
					eval(loadedScript);
					document.getElementById("scripts").innerHTML="";					
				}
           	
           		updateGlossaryLinks();				
            if (pageTitle != '') {
              document.title = pageTitle;
            } else {
              var name=document.recipeForm.cocktailName.value;
              if (name != null) {
                document.title = "diffordsguide - " + name;
              } else {
                document.title = "Diffordsguide";
              }
            }
	         	return response;
	       		}, 
	       		//end load: 
        		error: function(response, ioArgs) 
         		{        	 	  		
						if(dojo.byId("message")){
        	 	  			document.getElementById("message").innerHTML = response;
        	 	  		}
		           		return response;
          	}
         });// end xhrGet
	
	deferred.addCallback(function(result){		
		protectImage();
		return result;
	});
}
 				  
function protectImage()
{		
	if(dojo.byId('protect'))
	{			
		var sir = new swfir();		
		sir.specify("src", "../js/swfir/swfir.swf");
		sir.swap("#protect img");		
	}
}
		
function sortResults(sortOrder)
{	
    sortOptions = dijit.byId('sortBy').value;	
	var sortvalue;
	if(sortOrder){
		sortvalue = sortOptions * -1;
	}else{		
		sortvalue = sortOptions;
	}	
	dijit.byId("recipeList").setSortInfo(sortvalue);
}
		
function postForm(toUrl, formName)
{	
	//TODO Rename funct() to indicate recipe search form
	clearSearchMsg();
	GLOBAL_SEARCHING = true;	
	dijit.byId('recipeList')._clearData();
	var deferred = dojo.xhrPost(
	{				
		url: toUrl,            	 
		preventCache: true,
		headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
		method: "POST",            	 
		form: formName,            	 
		handleAs: "json",            	 
		load: function(response, ioArgs) 
		{					
			var aStore = new dojo.data.ItemFileReadStore({data:response});
			dijit.byId("recipeList").store = aStore;
			dijit.byId("recipeList")._refresh();
					
			var recCount = dijit.byId("recipeList").store._getItemsArray().length;
			if (recCount==0)
			{
				dojo.byId("searchMessage").innerHTML="<i>No recipes found matching your search criteria. Please try again.</i>";
				dojo.addClass('result_sorter', 'invisible');
			}
			else if(recCount==1){
				dojo.addClass('result_sorter', 'invisible');
			}
			else{
				dojo.removeClass('result_sorter', 'invisible');
			}
			GLOBAL_SEARCHING = false;
			return response;
		},            	 
		error: function(response, ioArgs)
		{		            		
			GLOBAL_SEARCHING = false;
			dojo.addClass('loading', 'invisible');
			return response;
		}		 
	}
	);	
	
	deferred.addCallback(function(result){
		dojo.removeClass('loading', 'visible');
		dojo.addClass('loading', 'invisible');
		dijit.byId('recipeList').selection.deselectAll();
		return result;
	});
}	

function clearSearchMsg()
{
	dojo.byId("searchMessage").innerHTML = "&nbsp;";
}

function clearMsg()
{
	dojo.byId("message").innerHTML = "&nbsp;";
}
		
function validateForm()
{	
	if (!dijit.byId("cocktailName").isValid())
	{
		showMessageDialog("Please enter a name for the cocktail recipe.",'Missing Data');
		return false;
	}
	else if(!dijit.byId("scoreBox").isValid())
	{
		alert("Please enter a valid score.");
		return false;
	}
	else
	{				
		return true;
	}
}

function lName(rowIdx,item)
{
	if (item != null)
	{
		return item.name.toLowerCase();
	}
	else
	{
		return "";
	}
}
		
function createViewLink(rowIdx,item)
{
	 /*  copied from dojocampus.org documentation :
		A JavaScript function that is called which returns the value to be shown in the cell.
 		The function is passed two parameters. 
 		The first is the row index in the DataGrid. 
 		The second is the DataStore record/item. 
 		Given these two parameters, the function is expected to know what to return. 
 		It should not be a dijit Widget as that is not parsed. 
 		Care should be taken that the item parameter is not null.
 	
  		**Tests have shown that the function may be called more often** 
  		**than it should be and this is highlighted with an item = null.**  				 
	 */			
	if (item != null)
	{		
		var url="../main/ViewRecipe.jsp?cocktailId="+item.id;				   
		var targetDiv = "ceditor";
		var buildView = "<span class=\"moonlink\">" + item.name + " <img width=\"41px\" height=\"7px\" src=\"../images/web/moons_" + item.score + ".gif\"></span>";
		if (rowIdx == 0)
		{				
			setDivContents(url,targetDiv,'');			
		}
		return buildView;		
	}
	return "";
}

function showRecipe(recipeId){
	setDivContents("../main/ViewRecipe.jsp?cocktailId="+recipeId,'ceditor','');		
  //document.title = "Diffordsguide - " + document.frmSearch.cocktailName.value;
}
		
function refreshTable()
{
	var oldValue="";
	var filter = dijit.byId("list1").attr("displayedValue") ;
	if ( oldValue == filter ) 
	{
		return;
	}
	oldValue = filter;
	// blank filter means show all but we want to show nothing if no
	// filter criteria is specified
	 if (filter == "") filter = -1;
	filter = filter + '*';
	dijit.byId("recipeList").filter({cName: filter },true);
}

function refreshListStore()
{
	var listGrid=dijit.byId("recipeList");
	listGrid.store.close();
	listGrid.store.fetch();
	listGrid._refresh();
}
function deleteComment(commentId, cocktailId){
	var deleteUrl = '/AddCommentServlet';				
	dojo.io.iframe.send(
	{				
		method: 'POST',
		headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
		url: deleteUrl,
		handleAs: "text",
		preventCache: true,
		content:  { "action" : "DELETE", "cocktailId" : cocktailId, "commentId": commentId},
		load: function(response, ioArgs)
		{					
			//var jdata = dojo.fromJson(response);	
			// TODO display message or error message			
			var url="../main/ViewRecipe.jsp?cocktailId="+cocktailId;		
			setDivContents(url,'ceditor','diffordsguide');
		},
		error: function(response, ioArgs)
		{
		 //TODO display error
		 return response;
	    }
	});		
	
}
function saveCommentAndRefresh(formName, cocktailId)
{		
	var form = dijit.byId(formName);
	var commentText = dojo.string.trim(dijit.byId("commentBox").value);
	if(!form.validate())
	{
		showMessageDialog('Please tell us who you are.', 'Missing Data');
	    return false;
	}
	else if(commentText == "")
	{				  
		  showMessageDialog('Please enter your comment.','Missing Data' );
	      return false;
	}
			
	var spamResult = dijit.byId('spamValue').value;						
	if(!spamResult || dojo.string.trim(spamResult) == "")
	{		
		showMessageDialog('Please enter the value of the sum before you submit your comment.','Missing Data' );		
		return false;
	}
					
	var first = new Number(document.recipeCommentForm.value1.value);
	var operator = document.recipeCommentForm.value2.value;
	var second = new Number(document.recipeCommentForm.value3.value);
	var math;
			
	if(operator == 0)
	{				
		math = first * second;
	}
	else if(operator == 1)
	{
		math = first + second;
	}
	else
	{			
		math = first - second;
	}
			
	if(math != spamResult)
	{
		showMessageDialog('It appears your sums do not add up! please have another go.','Wrong Sum' );				
		return false;
	}
			
	var saveUrl = '/AddCommentServlet';				
	dojo.io.iframe.send(
	{				
		method: 'POST',
		headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
		url: saveUrl,
		handleAs: "text",
		preventCache: true,
		form: formName,
		load: function(response, ioArgs)
		{					
			var jdata = dojo.fromJson(response);						
			var url="../main/ViewRecipe.jsp?cocktailId="+cocktailId;		
			setDivContents(url,'ceditor','diffordsguide');
		},
		error: function(response, ioArgs)
		{
		 //TODO display error
		 return response;
	    }
	});					
}
		
function displayFormatter(item, store)
{
   var label=store.getValue(item, 'cName');	            
   return label;
}
		 
function displayStyleFormatter(item, store)
{
     var label=store.getValue(item, 'catName');	            
     return label;
}
		
function displayIngFormatter(item, store)
{
	var label=store.getValue(item, 'ingredient');	            
    return label;
}
		
function validateFilteringSelect(hasFocus)
{
	return true;			
}
	
function updateLinks()
{	
	if(dojo.byId('loggedIn').value == "true")
	{
		dojo.query("a.out").style('display', 'inline');
		dojo.query("a.in").style('display', 'none');
		dojo.query("a.reg").style('display', 'none');
		dojo.query(".greetings").style('display', 'inline');
	}	
}

function updateGlossaryLinks(){
	//TODO Refactor code
	var glossary_ = dojo.byId('method_');	
	if(glossary_)
	{	
		dojo.addClass(dojo.byId('term'), 'visible');	
		dojo.removeClass(dojo.byId('term'), 'invisible');
		
		if(dojo.byId('method_').innerHTML.indexOf('BLEND ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('BLEND ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_blend\");>BLEND</a> ");
		}
		if(dojo.byId('method_').innerHTML.indexOf('FLAME ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('FLAME ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_flame\");>FLAME</a> ");
		}
		if(dojo.byId('method_').innerHTML.search('GARNISH ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('GARNISH ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_garnish\");>GARNISH</a> ");						
		}
		if(dojo.byId('method_').innerHTML.search('GLASSWARE ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('GLASSWARE ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_glassware\");>GLASSWARE</a> ");
		}
		if(dojo.byId('method_').innerHTML.search('LAYER ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('LAYER ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_layer\");>LAYER</a> ");
		}
		if(dojo.byId('method_').innerHTML.search('MUDDLE ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('MUDDLE ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_muddle\");>MUDDLE</a> ");
		}		
		if(dojo.byId('method_').innerHTML.search('SHAKE ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('SHAKE ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_shake\");>SHAKE</a> ");
		}
		if(dojo.byId('method_').innerHTML.search('STIR ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('STIR ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_stir\");>STIR</a> ");
		}
		if(dojo.byId('method_').innerHTML.search('SWIZZLE ')>-1)
		{
			dojo.byId('method_').innerHTML = dojo.byId('method_').innerHTML.replace('SWIZZLE ',"<a class=\"term_link\" href=javascript:\showGlossary(\"t_swizzle\");>SWIZZLE</a> ");
		}
	}
}

function showGlossary(name)
{
	var theTerm =dijit.byId(name); 
	theTerm.toggle();
	toggleTerms(theTerm);
}

function toggleTerms(term)
{	
	/*CALL THIS FUNCTION ONCE YOU HAVE OPEN THE TERM*/ 
	if(term.open == true){
		dojo.forEach(dojo.query('.termi'), function(obj){
			if(obj.id == term.id){				
				dojo.addClass(term.titleBarNode, 'termi_bold');
				/* IE ghost hack: so that the content is always visible in IE */
				if(isIE){
				dijit.byId(term).attr('content', dijit.byId(term)._getContentAttr());
				}
			}
			else{	
				var theTerm = dijit.byId(obj.id);
				if(theTerm.open == true)
				{					
					theTerm.toggle();
					dojo.removeClass(theTerm.titleBarNode, 'termi_bold');
				}				
			}
		});
	}
	else{
		dojo.removeClass(term.titleBarNode, 'termi_bold');		
	}
}

function doLogOut()
{		
	 setDivContents("../main/cocktailLogin.jsp?logout=true",'ceditor','diffordsguide');
	 /* Do we want to clear the recipe result? */
	 	dijit.byId('recipeList')._clearData();
	 	dijit.byId("recipeList").store = null;
	 /* */
	updateUI_logout();
}

function updateUI_logout(){
	 dojo.byId('loggedIn').value = '';
	 dojo.query("a.out").style('display', 'none');
	 dojo.query("a.in").style('display', 'inline');
	 dojo.query("a.reg").style('display', 'inline');
	 dojo.query(".greetings").style('display', 'none');
}

function doLogin()
{		
	 setDivContents("../main/cocktailLogin.jsp",'ceditor','diffordsguide');	
}
		 
function doRegister()
{
	setDivContents("../main/cocktailRegistration.jsp",'ceditor','diffordsguide');
	// TODO we might want the user to logout before registration?
}

function doShowSiteTerms(){
	setDivContents("../main/siteTerms.jsp",'ceditor','diffordsguide');
}

function doOpenAccountInfo(){	
	setDivContents("../main/userAccount.jsp",'ceditor','diffordsguide');
}

function submitAccountUpdateForm(formName_){
	dojo.xhrPost(
			{				
				url: '/CocktailUpdateAccountServlet',            	 
				preventCache: false,
				headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
				method: "POST",            	 
				form: formName_, 
				content: { "action" : "doUpdateUserLogin"},
				handleAs: "json",            	 
				load: function(response, ioArgs) 
				{	
					if(response.success == true){
						dojo.byId('msg_updateAccount').innerHTML = response.message;
						dojo.byId('accMgr').innerHTML = 'Welcome ' + response.nickName + '&nbsp;';
						dijit.byId('email_update')._setValueAttr(response.email);
					}
					else{	
						if(response.redirectLogin){
							 setDivContents("../main/cocktailLogin.jsp",'ceditor','diffordsguide');
							 updateUI_logout();
						}else{
							dojo.byId('msg_updateAccount').innerHTML = '<span class="error">' +response.message + '</span>';
						}
					}
					return response;
				},            	 
				error: function(response, ioArgs)
				{	
					dojo.byId('msg_updateAccount').innerHTML = '<span class="error">Server error, please try again later</span>';
					return response;
				}		 
			}	
	);
}

function doUpdateSection(section){
	document.frmUserAccount.section.value = section;
}

function validateAccountUpdateForm(form_){
	var SECTION = document.frmUserAccount.section.value;
	if(SECTION == 'password_section'){
		var currPass = dijit.byId('currPass_update').getDisplayedValue();
		if(currPass != "")
		{
			var newPass1 = dijit.byId('pass1_update').getDisplayedValue();
			var newPass2 = dijit.byId('pass2_update').getDisplayedValue();	
			if(newPass1 == "" || newPass2 == ""){
					return false;
			}		
			if(newPass1 != newPass2){
				dojo.byId('msg_updateAccount').innerHTML = '<span class="error">Your passwords does not match</span>';
				return false;
			}	
		}
		else
		{
			dojo.byId('msg_updateAccount').innerHTML = '<span class="error">Please type your current password for security reasons</span>';
			return false;
		}		
	}
	else if(SECTION == 'email_section')
	{
		var newEmail = dijit.byId('emailNew1_update').getDisplayedValue();
		var newEmail2 = dijit.byId('emailNew2_update').getDisplayedValue();
		
		if(newEmail != newEmail2)
		{
			dojo.byId('msg_updateAccount').innerHTML = '<span class="error">Your email address does not match</span>';
			return false;
			
		}else if(newEmail == "" || newEmail.indexOf('@') < 2)
		{
			dojo.byId('msg_updateAccount').innerHTML = '<span class="error">Please make sure your new email address is valid</span>';
			return false;
		}	
	}
	else if(SECTION == 'username_section')
	{
		
	}
	
	return form_.validate();
}

function doResetPassword()
{		
	if(dijit.byId('resetPwdDialog')){
		dijit.byId('resetPwdDialog').destroyRecursive();
	}
	
	var html = "<table><tr><td><label>Email</label></td>";
	html += "<td><input dojoType=\"dijit.form.ValidationTextBox\" type\"text\" name=\"resetEmail\" id=\"resetEmail\" ";
	html += "required=\"true\" invalidMessage=\"Please enter your registered email address\" regExp=\"[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+\.[A-Za-z]{2,4}(\.[A-Za-z]{2,4})*\"/>";
	html += "</td></tr>";
	html += "<tr><td colspan=\"2\" align=\"right\"><button dojoType=\"dijit.form.Button\" type=\"submit\" onClick=\"return dijit.byId('resetPwdDialog').isValid();\">RESET</button></td></tr></table>";
	
	var resetPwdDialog = new dijit.Dialog(
		{
				id: 'resetPwdDialog',
				title: 'Reset my password',
				style: 'width: 300px',
				execute: submitResetPwdRequest,
				content: html
		}		
	);
	resetPwdDialog.show();	
}

function submitResetPwdRequest(){
	var toUrl = '/ResetPasswordServlet';				
	dojo.io.iframe.send(
	{				
		method: 'POST',
		headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},
		url: toUrl,
		handleAs: "text",
		preventCache: true,
		content: arguments[0],
		load: function(response, ioArgs)
		{					
			//var jdata = dojo.fromJson(response);						
			// var url="../main/ViewRecipe.jsp?cocktailId="+cocktailId;
			// setDivContents(url,'ceditor','Cocktail Recipe');
			alert('Response is back!!! ');
		},
		error: function(response, ioArgs)
		{
		 //TODO display error
		 return response;
	    }
	});				
}

function showError(data, ioArgs)
{
    //TODO Should we display a message dialog to user?
  	dojo.byId("message").innerHTML = "<b>"+data.message+"</b>";
}		
		
function registrationCompleted(data, ioArgs)
{
	dojo.byId("message").innerHTML = "<b>"+data.message+"</b>";
	dijit.byId("frmRegistration").reset();
}
		
function validateRegisterForm(formObj)
{		
	if (dijit.byId("frmRegistration").isValid())
	{
		if(dijit.byId('pass1').value != dijit.byId('pass2').value)
		{
			showMessageDialog('Your password does not match', 'Validation Error');
			dijit.byId('pass1').reset();
			dijit.byId('pass2').reset();
			return false;
		}
		return true;
	}
			
	var errorMsg = '';
	if(!dijit.byId("email").isValid())
	{
		errorMsg = errorMsg + 'Please enter a valid email address<br/>';
	}
	if(!dijit.byId("contactName").isValid())
	{
		errorMsg = errorMsg + 'Please tell us your name <br/>';
	}
	if(!dijit.byId("pass1").isValid() || !dijit.byId("pass1").isValid() )
	{
		errorMsg = errorMsg + 'Please enter a password</br>';
	}
	
	showMessageDialog(errorMsg, "Form Validation");
	return false;			
}	
		
function validateLoginForm(formObj)
{		
	if ( dijit.byId("username").isValid() && dijit.byId("password").isValid())
	{			 
		return true;
	}
	else
	{						
		showMessageDialog("Please enter a valid Username/Email address and your password.",'Authentication Error!');
		return false;
	}
}	
		
function submitRegistrationForm(action)
{		
	document.frmRegistration.actionType.value = action;		
}	
		
function showMessageDialog(message_, title_)
{
	var dialog = new dijit.Dialog(
	{
		title : title_,
		style: "width: 300px"
	});
		
	dialog.attr("content", message_);
	dialog.show();
}
function hightlight(eId){
	if(dojo.byId(eId)){
		 dojo.animateProperty({
			    node: dojo.byId(eId), duration: 5000,
			    properties: {
			      backgroundColor: { start: "#A8A754", end: "#FFF" },
			      color: { start: "#8C8C1A", end: "black" }
			    },
			    onEnd: function(){
			     // dojo.byId(eId).innerHTML = "Granted";
			    }
			  }).play();
	}
}
