/**
 * manages lifecycle for displaying recipes and various UI behaviours
 */
C.RecipeController = Class.create( C.BaseAjax,
{

	/**
	 * cfg params:
	 *  - ajaxBase
	 */
	initialize : function( cfg )
	{
		this.imageBase = C.WS_IMAGES + "/recipe/";
		this.printVersionUrl = "/bloom/recipe_print&rid=";
		this.ajaxBase = "/index.php?action=ajax,recipe";
		this.cache = {};
		this.activeRecipeId = false; // the id of the recipe in focus/popup
		this.popupWin = false; // the Window object
		this.popupWinEl = false; // the HTML element 
		this.loadingIndicator = false;
		Object.extend(this,cfg);
	},
	
	/**
	 * called by UI when a recipe is selected for popup window.
	 * 
	 * this function operates in two modes depending on the cfg param.  If cfg is an id,
	 * an ajax request is sent to the server with instructions to use this method as the callback;
	 * if cfg has a transport property (cfg.transport) then this method assumes it is operating
	 * in 'callback' mode.
	 */
	recipeSelected : function( cfg )
	{
		if ( cfg.transport ) // is ajax callback response
		{
			var data = this.evalJSON(cfg.transport);
			this.cache[data.rid] = data;
			this.renderPopup(data.rid);
		}
		else if ( cfg.rid )
		{
			// if there is no cached version of this recipe, get data VIA ajax
			// ----------------------------------------------------------------
			if ( !this.cache[cfg.rid] )
			{
				if ( cfg.rid )
				{
					var params = { 'rid' : cfg.rid , 'op' : 'popupDetails' }
					var cfg = { onSuccess: this.recipeSelected.bind(this) }
					this.doAjax(cfg,params);
				}
			}
			// if there IS data in the cache, render the popup
			// ------------------------------------------------
			else
			{
				this.renderPopup(cfg.rid);
			}
		}
		
	},
	
	/**
	 * adds or removes a recipe to the user's favorite list.  
	 * 
	 * @param {string} rid 	if false, rid uses the id the recipe in focus/popup window
	 * @param {boolean} addItem  true to add, false to remove
	 */	
	toggleRecipeFav : function(rid,addItem)
	{
		if ( !rid ) rid = this.activeRecipeId;
		var params = { 'rid' : rid , 'op' : addItem ? "addFav" : "removeFav" };
		this.doAjax(false,params);
	},
	
	
	//--------------------
	// popup window
	//----------------------	
	
	/**
	 * opens a new popup window containing/pointing to the print-friendly version 
	 */
	openPrintVersion : function()
	{
		var x = (screen.width / 2) - (720/2);
		var y = (screen.height/ 2) - (700/2) - 100;	
		var win = window.open( this.printVersionUrl + this.activeRecipeId ,'print_version','width=720,height=700,scrollbars=yes,menubar=yes,screenx=' + x + ',screeny=' + y );
		win.focus();
	},
	
	
	/**
	 * fetches full product info from server and calls renderPopup when the data 
	 * is availabled/returned.
	 *
	 * this function operates in two modes depending on the cfg param.  If cfg is an id,
	 * an ajax request is sent to the server with instructions to use this method as the callback;
	 * if cfg has a transport property (cfg.transport) then this method assumes it is operating
	 * in 'callback' mode.
	 *
	 * @param cfg:
	 *    - in query mode: cfg.rid = recipe id
	 *
	 * testwith: _rc.showDetailsPopup({rid:"17926709715273971402"});
	 */
	showDetailsPopup : function( cfg )
	{
		if ( cfg.transport )
		{

			if ( this.loadingIndicator ) this.loadingIndicator.hide();

			var recipeDetails = this.evalJSON(cfg.transport);
			var rid = recipeDetails.rid + "";
			this.activeRecipeId = rid;
			Object.extend(this.cache[rid],recipeDetails);
			this.renderPopup(rid);
		}
		else if ( cfg.rid )
		{
			var target = $$("div[rid=" + cfg.rid +"]")[0];
			if ( this.loadingIndicator ) this.loadingIndicator.show( {centerOn: target});			
			this.doAjax( { onSuccess: this.showDetailsPopup.bind(this) } , { 'op':'popupDetails','rid':cfg.rid} );
		}
	},
	
	renderPopup : function( rid )
	{
		var win = this.popupWin;

		if (!win)
		{
			win = new Window({className: "c-window",  zIndex:100, height:"670px",width:"730px",  destroyOnClose: false, recenterAuto:false, showEffectOptions:{duration:0.3}, showEffect: Element.show, hideEffect: Element.hide});
			win.getContent().update( $('win-tpl').innerHTML  );
			$('c-infowin-close').observe('click',this.closePopup.bind(this));
			this.popupWin = win;
		}
		
		var winId = win.getId();
		var winContentElId = winId + "_content";
		var winEl = $(winContentElId);
		

		
		$('b_print_version').observe('click', this.openPrintVersion.bind(this));
		
		
		// replace template elements with data
		// -----------------------------------
		
		var data = this.cache[rid];
		



		winEl.down('.c-infowin-title').update( data.title);
		winEl.down('.c-infowin-details').update(""); // erase details
		winEl.down('.c-infowin-addtofav').down('input').checked = data.inFavList;
		winEl.down('.c-infowin-addtocart').hide();
		
		winEl.down('.c-infowin-img').replace("<img class='c-infowin-img' src='"+this.imageBase + data.info.image+"' />");
		/*
		winEl.down('.c-infowin-img').writeAttribute('src', )
		*/		
		$('rtab-directions-content').update( data.instructions );		
		
		
		// render ingredients list
		// -----------------------
		var ingredientsPane = $('rtab-ingredients-content');
		ingredientsPane.update("") // erase any previous content
		data.ingredients.each( function(i){
			var row = new Element('div',{className:'c-ingredient-row'});
			var q = new Element('span',{className:'c-ingredient-q'}).update( i.quantity );
			var name = new Element('span',{className:'c-ingredient-name'}).update(i.name);
			
			row.insert( {bottom:q });
			row.insert( {bottom:name } );
			if ( i.notes ){
				var notes =  new Element('span',{className:'c-ingredient-notes'}).update("("+i.notes+")");
				row.insert( { bottom:notes })
			}  
			
			// add row to container
			// --------------------
			ingredientsPane.insert({bottom:row});
		});
		
		// render nutrition info
		// ---------------------
		$('rtab-nutrition-content').update( data.nutrition_html );
		
		// reposition window's Y-pos if client is scrolled to top.
		// -------------------------------------------------------	
		var scrollDim =	WindowUtilities.getWindowScroll();
		
		var topOffset = false;
		if ( scrollDim.top < 240 ) topOffset = 240 - scrollDim.top;
		
		win.showCenter(true,topOffset);
		$(this.popupWin.getId()).setStyle({width:"730px"})
	},
	
	
	/**
	 * closes Recipe popup window
	 */
	closePopup : function()
	{
			this.popupWin.close();
	}	
		

});


var _rc = new C.RecipeController();

