/**
 * @author mark.priatel
 */
C.SpecialsController = Class.create( C.BaseAjax,
{

	/**
	 * controller constructor.  performs page initialization.
	 */
	initialize: function()
	{
		this.bindButtonActions();		
		this.ajaxBase = "/index.php?action=ajax,specials";
		this.imageBase = C.WS_IMAGES  + "/flyer";
		this.sectTitlePane = $('c-section-title-pane');
		this.sectTitlePane.hide();
		this.shoppingListC = false; // shopping list controller
		this.currentSectionName;
	},
	
	
	/**
	 * attaches 'click' handlers to the carousel buttons which invoke
	 * ajax calls to fetch their respective flyer data
	 */
	bindButtonActions : function()
	{
		
	},
	
	
	/**
	 * invokes AJAX call to WS to load flyer data for a section.
	 * @param {Object} catId
	 */
	selectSection : function(sectId)
	{
		
		if ( sectId == this.currentSectionName ) return;
		
		var params = { 'xid' : sectId , 'op' : 'section' }
		var cfg = { onSuccess: this.sectionLoaded.bind(this) }
		
		// update the title box
		// --------------------
		this.currentSectionName = sectId;

		this.doAjax(cfg,params);
	}, 

	/**
	 * ajax callback invoked once section data is loaded
	 */
	sectionLoaded : function(obj)
	{
		var self = this;
		var data = this.evalJSON(obj.transport);
		// clear the section HTML
		// ----------------------
		this.sectTitlePane.remove();		

		var container = $('c-specials-items');
		container.update("");
		var pageCurrent = 0;	
		var pageDiv = false
		var clickCallback =  this.elementClicked.bind(this);
	

		
		$(data).each( function(e,idx){
			
			// give product details to the shoppingList controller (which handles popups)
			// by popuplating its data cache with product code and title
			// --------------------------------------------------------------------------
			self.shoppingListC.cache[ e.pcd ] = { description: e.title , productCode: e.pcd }
			
			if ( e.page != pageCurrent )
			{
				pageDiv = new Element("div",{style:'height:380px;position:relative'});
				container.insert( {bottom:pageDiv} );
				pageCurrent = e.page;
			}
			var imgEl = new Element("img",{src: self.imageBase + "/" + e.image });
			var divEl = new Element("div",{style:'width:380px;position:absolute;top:' + e.y + 'px;left:'+e.x+'px'});
			imgEl.observe('click', clickCallback );
			divEl.writeAttribute('pcd',e.pcd);
			divEl.insert({bottom:imgEl});
			pageDiv.insert({bottom:divEl})
			if ( idx == 0 ) container.insert( {bottom:self.sectTitlePane} );
		});

		$('c-sect-title').update( this.currentSectionName );
		this.sectTitlePane.show();
	},
	
	
	elementClicked : function(evt)
	{
		var src  =Event.element(evt);
		var divC = src.up();
		var pcd = divC.readAttribute('pcd');
		this.shoppingListC.showDetailsPopup( {pid:pcd} );
	}
	

});
