/** RSH must be initialized after the
    page is finished loading. */
    

function dhtml_initialize() {
  // initialize RSH
  dhtmlHistory.initialize();
  
  // add ourselves as a listener for history
  // change events
  dhtmlHistory.addListener(handleHistoryChange);

  // determine our current location so we can
  // initialize ourselves at startup
  var initialLocation = dhtmlHistory.getCurrentLocation();
  // if no location specified, use the default
  if (initialLocation == null)
    initialLocation = TabNames[iView]; //initial location is set by outside factors
    
  // now initialize our starting UI
  updateUI(initialLocation, null);
}

/** A function that is called whenever the user
    presses the back or forward buttons. This
    function will be passed the newLocation,
    as well as any history data we associated
    with the location. */
function handleHistoryChange(newLocation, historyData) {
  // use the history data to update our UI
  updateUI(newLocation, historyData);                           
}

/** A simple method that updates our user
    interface using the new location. */
function updateUI(newLocation, historyData) {
   var historyMessage;
  if (historyData != null){
    eval(historyData.message);
  }
}

	
function RefreshReviews(store,sort,page)
{
	document.getElementById("Reviews_at").innerHMTL = "Loading....";
	new Ajax("Ajax/StoreTabs.asp", {method: "get",update: $("Reviews_in")}).request("type=reviews&id="+store+"&sort="+sort+"&page="+page);
	ContentLoaded[0] = true;
}

	
function BuildEditBox(editElement)
{
	editButon = document.getElementById('editButton'+editElement);

	if(!CheckLogin(null,'Please sign in <br> to make changes','BuildEditBox('+editElement+');'))
	{
		editButon.innerHTML = 'Loading...';
		return;
	}
	else
		editButon.innerHTML = 'edit';

	$('wikiBox'+editElement).style.display='none';
	$('editBox'+editElement).style.display='block';
	
	$("WikiEditBox"+editElement).focus();
}
	
function CancelEditBox(editElement)
{
	$('editBox'+editElement).style.display='none';
	$('wikiBox'+editElement).style.display='block';
}

function ShowReviewArea(buttonElm)

{
	if(!CheckLogin(buttonElm,'Please sign in <br> to enter a review','ShowReviewArea();'))
		return;

	$('Review_div').style.height = $('button_ReviewStore').style.height;			
	$('Review_div').style.display='block';
	$('button_ReviewStore').style.display='none';  
	ButtonOff($('button_ReviewStore'));
	OpenObject('Review_div', 150, 20, 15)
	setTab(0);
	
	document.getElementById("ReviewText").focus();
}
		
		
//#######################   The Ajax functions
function submitTag(tagName){
	new Json.Remote("Ajax/setStoreTag.asp", {onComplete: submitTagAction,method: 'get'}).send({'store': PageID,'tag': tagName, 'retry':'submitTag("'+tagName+'");','rndId':Math.random()});
	return false;
}

function submitTagAction(response){

	if(response.success)
	{
		//tag now associated with the store..
		
		//try to match a current tag
		var tagElm;
		var curTags = $('Tag_Collection_Tags').getElements('a');
		for(i = 0; i < curTags.length;i++)
		{
			if(curTags[i].getProperty("name") == response.success.tag)
			{
				tagElm = curTags[i];
				break;
			}
		}
		
		if(!tagElm) 
		{
			tagElm = document.createElement("a");
			
			tagElm.setAttribute('Name',response.success.tag);
			$("Tag_Collection_Tags").appendChild(tagElm);
		}
		
		//set all parameters
		tagElm.setAttribute("score",response.success.score);
		tagElm.setAttribute("weight",response.success.weight);
		tagElm.setAttribute("yourscore",response.success.yourScore);
		
		//fill in the details
		tagElm.innerHTML = response.success.tag;
		tagElm.style.backgroundColor='#666';
		
		//now animate it to call attention to the change
		fx = new Fx.Styles(tagElm, {duration:400, wait:false});
		fx.start({
			'background-color': '#666'
		}).chain(function() {
			this.start.delay(2000, this, {
				'background-color': '#FFFFFF'
			});
		});
		
		
	}
	else if(response.error)
	{
		if(response.error.errorCode == 1 && response.error.retry)
			CallSignInDiv("Sign in to add a tag",response.error.retry);
		else
			alert(response.error.errorDescription);
	}		
	else
			alert("An unknown error has occured. Please report this to cooks compass");
}

function lookupIngredient(ingredientName){
	new Json.Remote("Ajax/lookupStoreIngredient.asp", {onComplete: lookupIngredientAction ,method: 'get'}).send({'store': PageID, 'ingredient': ingredientName, 'retry':'lookupIngredient("'+ingredientName+'");','rndId':Math.random()});
}

function lookupIngredientAction(response){

	if(response.success)
	{
		var widgetID = "w_0-"+response.success.storeID+"."+response.success.ingredientID
	
		//check if the ingredient is already on the page
		if($(widgetID))
		{
			var IngElm = $(widgetID).parentNode.parentNode;
			IngElm.style.backgroundColor='#666';
			
			var finalColor;
			if (IngElm.getAttribute('class')=="Shaded")
				finalColor = "#EEEEEE";
			else
				finalColor = "#FFFFFF";

			//it's on the page already.  animate it to call attention
			//now animate it to call attention to the change
			var fx = new Fx.Styles(IngElm, {duration:400, wait:false});
			fx.start({
				'background-color': '#666'
			}).chain(function() {
				this.start.delay(2000, this, {
					'background-color': finalColor
				});
			});
		}
		else
		{
			//add to the list of found ingredients
			var AppendTo=$('IngredientResults');
				
			//fill in the widget
			AppendTo.innerHTML = response.success.ingredientHMTL;
			AppendTo.style.display = "block";
		}
		
		//reset the search box
		$('InStoreSearchBox').value='';
			
	}
	else if(response.error)
	{
		if(response.error.action)
			eval(response.error.action);
		else
			alert(response.error.errorDescription);
	}		
	else
		alert("An unknown error has occured. Please report this to cooks compass");
}					

function CloseIngredientBox()
{
	$('IngredientResults').style.display = "none";
}

function NewIngredient(IngredientName)
{
	GetPopup($('InStoreSearchBox'), "HelpPopup", "AJAX/newIngredient2.asp", "ingredient="+escape(IngredientName)+"&rnd="+Math.random(), 0, 50);
}

function LearnIngredient(IngredientName)
{
	new Json.Remote("Ajax/UnknownIngredient.asp", {onComplete: learnIngredientAction ,method: 'get'}).send({'ingredient': IngredientName,  'retry':'LearnIngredient("'+IngredientName+'");','rndId':Math.random()});
}


function learnIngredientAction(response)
{
	if(response.success)
	{
		lookupIngredient(response.success.ingredientName);

	}
	else if(response.error)
	{
		if(response.error.errorCode == 1 && response.error.retry)
			CallSignInDiv("Sign in to add an ingredient",response.error.retry);
		else
			alert(response.error.errorDescription);
	}		
	else
			alert("An unknown error has occured. Please report this to cooks compass");
}

//For the quick recommend
		var QR_Data;
    	function setRarity(level)
		{
			new Ajax("ajax/QuickRecommend_inner.asp", {method: "get", evalScripts: true, update:$('QR_Box'), onComplete:function(){PostLoad(QR_Data.store);}}).request('Letter='+QR_Data.letter+'&Page=1&rare='+level);
		}
		
		function LoadIt(letter, page, store){
			new Ajax("ajax/QuickRecommend_inner.asp", {method: "get", evalScripts: true, update:$('QR_Box'), onComplete:function(){PostLoad(store);}}).request('Letter='+letter+'&Page='+page+'&Store='+store);
		}
		
		function PostLoad(store){
				//sets up the page navigation
			var nav = '<strong>Go to page</strong><br />';
			for(i=1;i<=QR_Data.pages;i++){
				nav=nav+"<a href=\"javascript:LoadIt('"+QR_Data.letter+"','"+i+"','"+store+"')\">"+i+"</a>&nbsp;&nbsp;&nbsp;"
			}
			$('PageNav1').innerHTML=nav;
			$('PageNav2').innerHTML=nav;
		}
		function hideQuickRecommend(){
			$('HelpPopup').innerHTML="";
			$('HelpPopup').style.display="none";
		}
//for the in-store-search

function iss_button(btn){
		iss_arr=["up","dn","no","idk"];
	
		btns=$('iss_buttons').getElementsByTagName('a');
		for(x=0;x<btns.length;x++)
			btns[x].className='gBtn iss_'+iss_arr[x]+((btns[x].id==btn)?'s':'x');
			
		//now refresh the instore search with the result
		
		oTimeOut = setTimeout("lookupIngredient('"+$("ingName").innerHTML+"');",500);
	}