﻿/// <reference path="../../../../../jQuery/1.3.2/jquery-1.3.2-vsdoc.js" />

/**
 *
 * FlowListFeature
 * 
 */
	
	if (!mrm.global.isNamespaceDefined("mrm.common.display.views")) mrm.global.createNamespace("mrm.common.display.views", "1.0");
	
	
	
	mrm.common.display.views.FlowListFeature = mrm.common.display.SwfExternalDataHost.subClass(
		{
			/*
			 =============================
			 CONSTANTS
			 =============================
			 */
				"CLASS_AUTO_DISABLE_DISPLAY"		: "AUTO-DISABLE-DISPLAY",
				"CLASS_SEARCH_RESULTS_CONTAINER"	: "result-items-container",
				
				"DEBUG"							: false,
					
				"AUTO_DISABLE_HTML"				: "<div class='png AUTO-DISABLE-DISPLAY'></div>",
				
				
				"SE_SS" : ".search-criteria-container",
				"SE_SS_LINK_DISPLAY_CONTROL" : ".display-control-link",
				"SE_SS_" : "",
				
				
				"CL_SS_OPEN" : "search-criteria-open",
				"CL_OPEN" : "open-settings",
				"CL_CLOSE" : "close-settings",
				
			
			
			/*
			 =============================
			 CONSTRUCTOR
			 =============================
			 */
				"init" : function (instanceReference, classInstanceID, replacementTargetParentID, replacementTargetID, swfInstanceID, swfData)
				{
					this.instanceReference = instanceReference;
					
					var targetFlashVersion		= "9.0.48";
					//var targetFlashVersion		= "100";
					
					var swfAttributes			= {};
					/*swfAttributes.data			= "http://www.lexus.ucl.dev.portfolio-europe.co.uk/assets/flash/FlowListDisplay.swf";*/
					swfAttributes.data			= "/assets/flash/FlowListDisplay.swf";
					swfAttributes.id			= swfInstanceID;
					swfAttributes.name			= swfInstanceID;
					swfAttributes.width			= "922px";
					swfAttributes.height		= "250px";
					swfAttributes.pluginspage	= "http://www.macromedia.com/go/getflashplayer";
					
					var swfParameters				= {};
					swfParameters.align				= "top";
					swfParameters.allowfullscreen	= true;
					swfParameters.allowscriptaccess	= "sameDomain";
					swfParameters.base				= "../../";/*"http://www.lexus.ucl.dev.portfolio-europe.co.uk";*/
					swfParameters.bgcolor			= "#0000ff";
					swfParameters.devicefont		= false;
					swfParameters.loop				= false;
					swfParameters.menu				= true;
					swfParameters.play				= true;
					swfParameters.quality			= "best";
					swfParameters.salign			= "tl";
					swfParameters.scale				= "noscale";
					swfParameters.wmode				= "transparent";
					
					var swfFlashVars = "";
					
					var swfData = swfData;
					
					// 
					this._htmlListItemHoverClass	= "vehicle-item-flow-hover";
					
					// Html items : loading data properties / assets
					this._loadingDataClass				= "result-items-container-data-loading";
					this._resultItemsContainerJQRef		= "div.results-details-container div.result-items-container";
					this._loadingDataContainerJQRef		= "div.results-details-container div.result-items-container div.loading-display";
					
					// work out sort by url from tools form action url
					this._mpToolsFormClass = 'form.mp-tools-form';
					this._mpToolsFormAction = $(document).find(this._mpToolsFormClass).attr("action");
	    	        this._sortByUrl = '/handlers/results.ashx' + this._mpToolsFormAction + '&pg=';
					
					this._loadingDataFlashReplaceID		= "flash-replace-target-loading-icon";
					this._loadingDataFlashTargetContent	= "<div id='" + this._loadingDataFlashReplaceID + "'></div>";
					
					//Instance (created empty)
					this._loadingDataSwf	= {};
					this._loadingDataSwfID	= "loading-data-swf";
					
					//Attributes / parameters
					this._loadingDataSwfAttributes				= {};
					this._loadingDataSwfAttributes.data			= "/assets/flash/DataLoadingDisplay.swf";
					this._loadingDataSwfAttributes.id			= this._loadingDataSwfID;
					this._loadingDataSwfAttributes.name			= this._loadingDataSwfID;
					this._loadingDataSwfAttributes.width		= "100px";
					this._loadingDataSwfAttributes.height		= "100px";
					this._loadingDataSwfAttributes.pluginspage	= "http://www.macromedia.com/go/getflashplayer";
					
					this._loadingDataSwfParameters						= {};
					this._loadingDataSwfParameters.align				= "top";
					this._loadingDataSwfParameters.allowfullscreen		= true;
					this._loadingDataSwfParameters.allowscriptaccess	= "sameDomain";
					this._loadingDataSwfParameters.base					= "http://www.lexus.ucl.dev.portfolio-europe.co.uk";
					this._loadingDataSwfParameters.bgcolor				= "#0000ff";
					this._loadingDataSwfParameters.devicefont			= false;
					this._loadingDataSwfParameters.loop					= false;
					this._loadingDataSwfParameters.menu					= true;
					this._loadingDataSwfParameters.play					= true;
					this._loadingDataSwfParameters.quality				= "best";
					this._loadingDataSwfParameters.salign				= "tl";
					this._loadingDataSwfParameters.scale				= "noscale";
					this._loadingDataSwfParameters.wmode				= "transparent";
					
					
					// Call superclass constructor
					this._super(classInstanceID, replacementTargetParentID, replacementTargetID, swfInstanceID, targetFlashVersion, swfAttributes, swfParameters, swfFlashVars, swfData, false);
					
					// Trigger setup on doc ready
//					var __this = this;
//					$(document).ready(function()
//					{
//						__this._setup();
//						__this._bindPagingCallbacks();
//						__this._setupSortOrderHtmlList();
//					});
						
					this._setup();
					this._bindPagingCallbacks();
					this._setupSortOrderHtmlList();
				},
			
			
			
			/*
			 =============================
			 INTERNAL RUN-TIME PROPERTIES
			 =============================
			 */
				"instanceReference" : undefined,
			
			
			
			/*
			 =============================
			 PUBLIC METHODS
			 =============================
			 */
			    
				"setSwfObjectReady" : function (b, swfObjectID)
				{
					this._super(b, swfObjectID);
					if (this.isSwfObjectInstanceDefined()) this.getSwfObject().triggerDataLoad();
				},
								
				
				"setSwfDisplayReady" : function ()
				{
					// Configure Html list items
					this._configureHtmlListItems();
					// Enable Html list items
					this._enableHtmlItems();
				},
				
				
				"selectHtmlListItem" : function (id)
				{
					var items = $("div.vehicle-list-mode-flow div.result-items-container div.vehicle-item");
					
					for (var i = 0; i < items.length; i++)
					{
						var item = $(items[i]);
						if (i == id) item.addClass(this._htmlListItemHoverClass);
						else item.removeClass(this._htmlListItemHoverClass);
					}
				},
				
				
				"unselectAllHtmlListItems" : function ()
				{
					var _this = this.instanceReference;
					
					$("div.vehicle-list-mode-flow div.result-items-container div.vehicle-item").each(function (i)
					{
						//$(this).removeClass(_this._htmlListItemHoverClass);
					});
				},
			
			
				"triggerResultsDataLoad" : function (next_bool)
				{
					// Set swfObject into loading new data state
					if (this.isSwfObjectInstanceDefined()) this.getSwfObject().prepareForNewDataLoad();
					
					// Display loading state for htmlListItems
					this._displayLoadingState();
						
					var _this = this;

					var pg = parseInt($("span.hdnCurrentPage").html());
					
					if (next_bool)
					{
					   pg = pg+1;
					}
					else
					{
					    pg = pg-1;
					}

					$.ajaxManager.updateUrl(_this._sortByUrl + pg);
					$.ajaxManager.onSuccess = function(p_response) {
					    _this._processUpdatedDisplayData(p_response);
					};
					$.ajaxManager.makeRequest();
				},
				
			
			
			/*
			 =============================
			 INTERNAL / PRIVATE METHODS
			 =============================
			 */
			 
			 callbackUtilities : {},
			 
				/*
				 =============================
				 SETUP
				 =============================
				 */
					"_setup" : function () 
					{
						this._disableHtmlItems();
						
						this._bindCollapsibleVehicleList();
						
						this._bindDisplayModeImageControl();
						
						//Bind the open / close search settings link
						this._bindDisplaySettingsLink();
					},
					
					"_bindCollapsibleVehicleList" : function(container)
					{
						if (container == null)
						{
							container = $('div.vehicle-list-container');
						}
						
						//wire up the collapsible vehicle list in photoflowview
						container.find('a.display-control').click(function(event)
							{
								event.preventDefault();
								var listContainer = $(this).parents('div.results-details-container');
								var isOpen = listContainer.hasClass('results-details-container-open');
								
								listContainer.toggleClass('results-details-container-open', !isOpen);
								listContainer.toggleClass('results-details-container-closed', isOpen);
							});
					},
					
					"_bindDisplayModeImageControl" : function(container)
					{
						if (container == null)
						{
							container = $('div.vehicle-list-container');
						}
						
						container.find('fieldset.displaymode img').click(function()
						{      
							//update the input that holds the viewmode value
							var container = $(this).parents('fieldset.imagegroup');
							var input = container.find('input:first');
							var displaymode = $(this).hasClass('photoflow') ? "photoflow" : "list";
					        
							if(input.val() != displaymode)
							{
								container.removeClass(input.val()).addClass(displaymode);
								input.val(displaymode);                
								$(this).parents('form.mp-tools-form').submit();
							}
						});
					
					},
					
					"_bindDisplaySettingsLink" : function()
					{
						var __this = this;
						
						// Get search settings container
						var t = $(this.SE_SS);
						
						// Get links
						var links = t.find(this.SE_SS_LINK_DISPLAY_CONTROL);
						
						// Atach click handler
						links.click(function(e)
						{ 
							e.preventDefault(); 
							__this._openSearchSettings(t, $(this).hasClass(__this.CL_OPEN)) 
						});
					},
					
										
					"_bindAjaxWorkflowLink" : function (container)
					{
						var _this = this;
						
						//makes a call to the global JS used to power the ajax enabled workflow links
						//bindAllAjaxConditionalLinks(container);

						//mrm.common.display.ajaxConditionalLinkManager.bindAllAjaxConditionalLinks(container);
						container.trigger(mrm.global.utilities.defaultControlBinder.MRM_RUN_INSTANCE, ["CompareCallBackLinks", container]);
						container.trigger(mrm.global.utilities.defaultControlBinder.MRM_RUN_INSTANCE, ["FavouritesCallBackLinks", container]);
					},
					
					"_bindToolTips" : function(container)
					{
						BindToolTips(container);
					},
					
					"_bindPagingCallbacks" : function()
					{
						var _this = this;
				    
						//bind up the callbacks used for the paging links
						$(document).find('.menu-results-pagination a').click(function(event) {
							//stop the default click through
							event.preventDefault();

							// Set swfObject into loading new data state
							if (_this.isSwfObjectInstanceDefined()) _this.getSwfObject().prepareForNewDataLoad();

							// Display loading state for htmlListItems
							_this._displayLoadingState();
							
							$.ajaxManager.updateUrl($(this).attr('href'));
							$.ajaxManager.onSuccess = function(p_response) {
								_this._processUpdatedDisplayData(p_response);
							};
							$.ajaxManager.makeRequest();
						});		    
					},
					
					"_setupSortOrderHtmlList" : function() {
					    var _this = this;

					    $(document).find('div.htmllist-container').each(function() {
					        var htmlListContainer = $(this);
					        var htmlListUiContainer = htmlListContainer.find('div.ui-htmllist-container');
					        htmlListUiContainer.htmllist({
					            delay: 0,
					            onChange: function(event, dataItem) {
					                // Set swfObject into loading new data state
					                if (_this.isSwfObjectInstanceDefined()) _this.getSwfObject().prepareForNewDataLoad();

					                // Display loading state for htmlListItems
					                _this._displayLoadingState();

					                $.ajaxManager.updateUrl(_this._sortByUrl + 1 + '&srt=' + dataItem.value);
					                $.ajaxManager.onSuccess = function(p_response) {
					                    _this._processUpdatedDisplayData(p_response);
					                };
					                $.ajaxManager.makeRequest();
					            }
					        });
					    });
					    
					},
									
				/*
				 =============================
				 DISPLAY CONTROL
				 =============================
				 */
					"_openSearchSettings" : function (jqSearchSettings, open)
					{
						var t = jqSearchSettings;
						var c = this.CL_SS_OPEN;
						if (open) 
							{ 
								t.addClass(c); 
								var document = "body";
								var e = new jQuery.Event("PHOTOFLOW_OPEN_DISPLAY_SETTINGS");
								// Trigger update event on target control
								t.trigger(e);	
							}
						else { t.removeClass(c); }

						
								
					},
					
					 
					"_disableHtmlItems" : function ()
					{
						//var container = $("#" + this._replacementTargetParentID);
						//container.append(this.AUTO_DISABLE_HTML);
						$("div." + this.CLASS_SEARCH_RESULTS_CONTAINER).append(this.AUTO_DISABLE_HTML);
					},
					
					
					"_enableHtmlItems" : function ()
					{
						$("div." + this.CLASS_SEARCH_RESULTS_CONTAINER + " ." + this.CLASS_AUTO_DISABLE_DISPLAY).remove();
					},
					
					
					"_configureHtmlListItems" : function ()
					{
						//Add roll-over and click finctionality to html search result items
						
						var __this = this; //-- Can seem to have negative effect on performance //var __this = mrm.runtime.searchResults.flowListFeature;
						
						var items = $("div.vehicle-list-mode-flow div.result-items-container div.vehicle-item");
						
						//Assignment utilising a function closure to avoid closure referencing of value i (otherwise always resolves to last definition of i)
						for (var i = 0; i < items.length; i++) (
							function (id) 
							{
								// If more than 5 items return so that only added to first five items
								if (id >= 5) return;
								
								// Get item
								var item = $(items[id]);
							
								// Add item hover
								item.hover(
									function (){
										__this._handleHtmlListItemOver(id);
									},
									
									function (){
										__this._handleHtmlListItemOut();
									}
								);
								//Add item click	
							}
						)(i);
						
					},
				
				
					"_displayLoadingState" : function ()
					{
						// Add display loading class
						if(!$.browser.msie && $.browser.version > 6)
				        {
							$(this._resultItemsContainerJQRef).addClass(this._loadingDataClass);
						}
						
						// Add flash object
						this._loadingDataSwf = swfobject.createSWF(this._loadingDataSwfAttributes, this._loadingDataSwfParameters, this._loadingDataFlashReplaceID);
					},
					
					
					"_removeLoadingState" : function ()
					{
						// Remove loading class
						if(!$.browser.msie && $.browser.version > 6)
				        {
							$(this._resultItemsContainerJQRef).removeClass(this._loadingDataClass);
						}
						
						// Remove flash object
						swfobject.removeSWF(this._loadingDataSwfID);
						this._loadingDataSwf = null;
						
						// Add replace target content (this gets removed when swf gets added)
						$(this._loadingDataContainerJQRef).append(this._loadingDataFlashTargetContent);
					},


				/*
				 =============================
				 DATA PROCESSING
				 =============================
				 */
//					_processPNGFix : function(jqContainer)
//					{
//						if (fix_PNGs && $.browser.msie && $.browser.version < 7)
//						{
//							fix_PNGs(jqContainer);
//						}
//					},
					
					"_processUpdatedDisplayData": function(data)
					{
						// replace html with returned controls (takes care of PNG and Tooltips)
						this.callbackUtilities.processResultControls(data);

						// Save new data
						this._swfData = PHOTOFLOW_VEHICLE_DATA;
					   
						// Trigger flash object to load new data 
						if (this.isSwfObjectInstanceDefined()) this.getSwfObject().triggerDataLoad();
					    
						//rebind the paging callbacks
						this._bindPagingCallbacks();

						//rebind the ajax workflowlink calls
						var pagedDataControl = this.callbackUtilities.findResultDataControl(data,"PagedCoverFlowViewResultsList");
						if (pagedDataControl != null)
						{
							jqPagedDataControl = $(pagedDataControl.targetDomId);
							
							var noresults = jqPagedDataControl.find("div.no-results");
							if (noresults.length > 0)
							{
								$(document).find("div.vehicle-list-container").addClass("list-container-no-results");
								$(document).find("div.flash-feature-container").hide();
							}
							
							//this._processPNGFix(jqPagedDataControl);
							
							//this._bindAjaxWorkflowLink(jqPagedDataControl);
							jqPagedDataControl.trigger(mrm.global.utilities.defaultControlBinder.MRM_RUN_INSTANCE, ["CompareCallBackLinks", jqPagedDataControl]);
							jqPagedDataControl.trigger(mrm.global.utilities.defaultControlBinder.MRM_RUN_INSTANCE, ["FavouritesCallBackLinks", jqPagedDataControl]);
						}
						
						//rebind the sIFR
				        this._debugMessage("Run delayded styling on sIFR.");
				       // sIFR.runDelayedStyling(sIFR.styles.STYLE_SEARCH_RESULTS_LIST_MODE);
						
						//rebind sIFR result count
						var pagedHeaderControl = this.callbackUtilities.findResultDataControl(data,"PagedListHeader");
				        if (sIFR && sIFR.styleResultsListResultsCount && pagedHeaderControl != null)
				        {
							// remove sIFR class, TODO look at replacing entire h3 instead
							$(pagedHeaderControl.targetDomId).removeClass("sIFR-replaced");
							
							sIFR.styleResultsListResultsCount();
						}
						
						//rebind the tooptips
						//this._bindToolTips($(document));
						
						// Remove loading state
						this._removeLoadingState();
					},
				
				
			"_debugMessage" : function(message)
		    {
				if (this.DEBUG)
				{
					alert("[StockListFeature] " + message);
				}
		     },
				
				
			
			/*
			 =============================
			 INTERNAL EVENT HANDLERS
			 =============================
			 */
				"_handleHtmlListItemOver" : function (id)
				{
					if (this.isSwfObjectInstanceDefined()) this.getSwfObject().selectVehicle(id);
				},
				
				
				"_handleHtmlListItemOut" : function ()
				{
					if (this.isSwfObjectInstanceDefined()) this.getSwfObject().resetVehicle();
				}
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
						////////////////////////////////////////////////////////////////////////////////////////////////
						// DATA LOAD SIMULATION
						////////////////////////////////////////////////////////////////////////////////////////////////
						
//							dataloadSimulationTimer : "",
//							
//							_setupDataloadSimulation : function ()
//							{
//								this._displayLoadingState();
//								
//								clearTimeout(this.dataloadSimulationTimer);
//								this.dataloadSimulationTimer = setTimeout(this._simulateDataLoad, 3000);
//							},
//							
//							_simulateDataLoad : function ()
//							{
//								var _this = this.instanceReference
//								
//								_this._removeLoadingState();
//								if (_this.isSwfObjectInstanceDefined()) _this.getSwfObject().triggerDataLoad();	
//							}
						
						////////////////////////////////////////////////////////////////////////////////////////////////
			
		}
	);
	
	
	//alert("mrm.common.display.FlowListFeature ::  Class definition successful");

