// Color visualizer class.
var ColorVisualizer = Class.create();
ColorVisualizer.prototype = {

	initialize : function() {},

	// Loads the main Flash component.
	//
	loadFlash : function(
		value_chipBackUrl,
		value_roomPhotoUrl,
		value_extraArtUrl,
		value_configXmlUrl,
		value_urlGetRoomConfigurations,
		value_urlCreateRoomConfiguration,
		value_urlUpdateRoomName,
		value_urlGetMaterialsPdf,
		value_storeLocatorXmlUrl,
		value_urlGetInteriorProductsXml,
		value_urlGetRoomConfigurationXml,
		value_urlCreatePaintedObject,
		value_urlGetPrimerSurfacesXml,
		value_urlGetAreasXml,
		value_urlGetRoomsXml,
		value_urlGetSheenXml,
		value_urlGetDurabilitiesXml,
		value_urlInteriorPaintCalculator,
		value_urlTop10Thumbnails) {

		// Check if starting params have been set.
		var url = window.location.href;
		var urlParams = url.toQueryParams();
		if ( urlParams.startCid1
		  && urlParams.startCid2
		  && urlParams.startCid3
		  && urlParams.startCid4
		  && urlParams.startCid5
		  && urlParams.startCid6
		  && urlParams.startCid7
		  && urlParams.startCid8 ) {
			var hashObj = {
				cid1 : urlParams.startCid1,
				cid2 : urlParams.startCid2,
				cid3 : urlParams.startCid3,
				cid4 : urlParams.startCid4,
				cid5 : urlParams.startCid5,
				cid6 : urlParams.startCid6,
				cid7 : urlParams.startCid7,
				cid8 : urlParams.startCid8
			};
			window.location.hash = '#' + Object.toQueryString( hashObj );
		} // End if.

		// Listen for login and logout events.
		account.addListener( this );

		// Get the filename of the SWF to use.
		var swfFileName = 'Core.swf';

		// Determine if the debug console should show.
		var showConsole = urlParams.debug;

		var flashvars = {
			hash                       : escape( window.location.hash.replace( /^#/, '' ) ),
			cookies                    : getSerializedCookies(),
			showConsole                : showConsole,
			chipBackUrl                : value_chipBackUrl,
			roomPhotoUrl               : value_roomPhotoUrl,
			extraArtUrl                : value_extraArtUrl,
			configXmlUrl               : value_configXmlUrl,
			urlGetRoomConfigurations   : value_urlGetRoomConfigurations,
			urlCreateRoomConfiguration : value_urlCreateRoomConfiguration,
			urlUpdateRoomName          : value_urlUpdateRoomName,
			urlGetMaterialsPdf         : value_urlGetMaterialsPdf,
			storeLocatorXmlUrl         : value_storeLocatorXmlUrl,
			urlGetInteriorProductsXml  : value_urlGetInteriorProductsXml,
			urlGetRoomConfigurationXml : value_urlGetRoomConfigurationXml,
			urlCreatePaintedObject     : value_urlCreatePaintedObject,
			urlGetPrimerSurfacesXml    : value_urlGetPrimerSurfacesXml,
			urlGetAreasXml             : value_urlGetAreasXml,
			urlGetRoomsXml             : value_urlGetRoomsXml,
			urlGetSheenXml             : value_urlGetSheenXml,
			urlGetDurabilitiesXml      : value_urlGetDurabilitiesXml,
			urlInteriorPaintCalculator : value_urlInteriorPaintCalculator,
			urlTop10Thumbnails         : value_urlTop10Thumbnails
		};

		var params = {
			menu            : 'false',
			wmode           : 'transparent',
			bgcolor         : '#ffffff',
			base            : '../flash/color/color-visualizer/',
			allowFullScreen : 'true'
		};

		swfobject.embedSWF( '../flash/color/color-visualizer/' + swfFileName,
				'my_flashContent', '100%', '780', '9.0.0',
				null, flashvars, params, null );

	}, // End loadFlash().


	// Called from the Flash component when initialized.
	//
	onFlashInit : function() {

		// Update the display specs and send them to the Room Painter.
		this.updateSpecs();
		Event.observe( window, 'scroll', this.updateSpecs.bind( this ) );
		Event.observe( window, 'resize', this.updateSpecs.bind( this ) );

		// Re-send the login information to the Room Painter in case
		// it initialized after the login check completed.
		this.onLoginChange();

	}, // End onFlashInit().


	// Called from the Flash component when the display gets updated.
	//
	onUpdateDisplay : function( roomPainterState ) {

		// Save the color information in the URL as an anchor.
		var hash = {
			path : roomPainterState.path,
			cid0 : roomPainterState.cid0,
			cid1 : roomPainterState.cid1,
			cid2 : roomPainterState.cid2,
			cid3 : roomPainterState.cid3,
			cid4 : roomPainterState.cid4,
			cid5 : roomPainterState.cid5,
			cid6 : roomPainterState.cid6,
			cid7 : roomPainterState.cid7,
			cid8 : roomPainterState.cid8
		}
		window.location.hash = '#' + Object.toQueryString( hash );

		// Save the recent colors to the browser as a cookie.
		var cookieObject = {
			cid1 : roomPainterState.cid1,
			cid2 : roomPainterState.cid2,
			cid3 : roomPainterState.cid3,
			cid4 : roomPainterState.cid4,
			cid5 : roomPainterState.cid5,
			cid6 : roomPainterState.cid6,
			cid7 : roomPainterState.cid7,
			cid8 : roomPainterState.cid8,
			cid1History : roomPainterState.cid1History,
			cid2History : roomPainterState.cid2History,
			cid3History : roomPainterState.cid3History,
			cid4History : roomPainterState.cid4History,
			cid5History : roomPainterState.cid5History,
			cid6History : roomPainterState.cid6History,
			cid7History : roomPainterState.cid7History,
			cid8History : roomPainterState.cid8History,
			savedStoreId : roomPainterState.savedStoreId,
			savedZipCode : roomPainterState.savedZipCode
		};
		setCookie( 'roomPainterState', escape( Object.toQueryString( cookieObject ) ), true );

	}, // End onUpdateDisplay().


	// Updates positioning within the Flash component.
	//
	updateSpecs : function() {

		// Send the position of the fold to the Flash component. 
		var headerBottom = $( 'headerBottom' );
		var my_flashContent = $( 'my_flashContent' );
		var foldY = ( document.viewport.getHeight() - headerBottom.offsetTop ) + document.viewport.getScrollOffsets().top;
		my_flashContent.setSpecs( foldY );

	}, // End updateSpecs().


	// Scrolls to the bottom of the screen.
	// Used for clicking the floating toolbar tab.
	//
	scrollToBottom : function() {

		Effect.ScrollTo( 'pageFooter' );

	}, // End scrollToBottom().


	// Tracks a specified path.
	//
	trackPath : function( path ) {

		var eventName = null;

		// Track using Google Analytics
		pageTracker._trackPageview( '/color/color-visualizer/tracking/' + path );

		// Track particular events using Floodlight Tags.
		// First, get an event name.
		if ( path.startsWith( 'selectPaletteChip/' ) ) {
			eventName = 'SelectColorChip';
		} else if ( path.startsWith( 'selectHistoryChip/' ) ) {
			eventName = 'SelectColorChipFromHistory';
		} else if ( path.startsWith( 'wallPainted/' ) ) {
			eventName = 'PaintAWall';
		} else if ( path == 'printMaterialsList' ) {
			eventName = 'PrintMaterialsList';
		} else if ( path == 'profile/gliddenLoginSuccess' ) {
			eventName = 'GliddenLoginSuccess';
		} else if ( path == 'profile/facebookLoginSuccess' ) {
			eventName = 'FacebookLoginSuccess';
		} else if ( path == 'profile/paintCalculator/calculationSaved' ) {
			eventName = 'SavedPaintCalculatorResults';
		} else if ( path == 'storeLocator/results' ) {
			eventName = 'StoreLocatorResults';
		} else if ( path == 'storeLocator/saveStore' ) {
			eventName = 'SaveStoreLocation';
		} else if ( path.startsWith( 'profile/sheenWizard/' ) ) {
			eventName = 'SaveSheenResults';
		} // End if.

		// If an event name is specified, load it into a Floodlight Tag.
		if ( eventName != null ) {
			this.createFloodlightTag( eventName );
		} // End if.

	}, // End trackPath().


	createFloodlightTag : function( eventName ) {

		new FloodlightTag( 'http://fls.doubleclick.net/activityi;src=2344780;type=landi542;cat=roomp625;u1=' + eventName + ';ord=' );

	}, // createFloodlightTag().


	// Share the tool.
	//
	sharePage : function() {

		this.trackPath( 'sharePage' );
		shareDialog.show( this.getBaseUrl(), 'Want To Find Your True Style?', 'Share This Tool' );

	}, // End sharePage().
	
	
	// Share a color combination.
	//
	shareColors : function() {

		// Get the current colors from the URL anchor.
		var params = this.getAnchorParameters();
		if ( !params.cid1 ) params.cid1 = '';
		if ( !params.cid2 ) params.cid2 = '';

		this.trackPath( 'shareColors/' + params.cid1 + '-' + params.cid2 );
		this.createFloodlightTag( 'ShareColors' );

		// Get the base URL to share.
		var shareUrl = this.getBaseUrl();

		// Add the current colors' start parameters to the share URL.
		shareUrl += '?startCid1=' + params.cid1
		         + '&startCid2=' + params.cid2
		         + '&startCid3=' + params.cid3
		         + '&startCid4=' + params.cid4
		         + '&startCid5=' + params.cid5
		         + '&startCid6=' + params.cid6
		         + '&startCid7=' + params.cid7
		         + '&startCid8=' + params.cid8;

		// Share the generated URL.
		shareDialog.show( shareUrl, 'Check Out My Style!', 'Share Your Room' );

	}, // End shareColors().


	// Returns the base URL without session or query information.
	//
	getBaseUrl : function() {
	
		var retVal = window.location.href;
	
		// Remove the anchor information.
		var anchorPos = retVal.indexOf( '#' );
		if ( anchorPos > 0 ) {
	
			var retVal = window.location.href.substr( 0, anchorPos );
	
		} // End if.
	
		// Remove the session ID information.
		var sessionIdPos = retVal.indexOf( ';' );
		if ( sessionIdPos > 0 ) {
	
			var retVal = window.location.href.substr( 0, sessionIdPos );
	
		} // End if.
	
		// Remove the query variables.
		var queryPos = retVal.indexOf( '?' );
		if ( queryPos > 0 ) {
	
			var retVal = window.location.href.substr( 0, queryPos );
	
		} // End if.
	
		return retVal;
	
	}, // End getBaseUrl().

	// Returns an associative array of parameters defined as an anchor in the URL.
	//
	getAnchorParameters : function() {

		var params = new Array();
	
		// Get the position of the URL's hash character.
		var anchorPos = window.location.href.indexOf( '#' ) + 1;
		if ( anchorPos > 0 ) {
	
			var paramStr = window.location.href.substr( anchorPos );
			params = paramStr.toQueryParams();
	
		} // End if.
	
		return params;
	
	}, // End getAnchorParameters().

	goToStoreLocator : function( zipCode ) {

		$( 'my_locatorZip' ).value = zipCode;
		$( 'my_locatorForm' ).submit();

	}, // End goToStoreLocator().

	login : function() {
		account.login(); // Use Glidden.com's authentication module.
	},

	logout : function() {
		account.logout(); // Use Glidden.com's authentication module.
	},

	onLoginChange : function() {

		// Get the logged in user's info.
		var userInfo = ( account.isLoggedIn() ) ? account.getUserInfo() : null ;

		// Send the event to the Flash component. 
		var my_flashContent = $( 'my_flashContent' );
		my_flashContent.onLoginChange( userInfo );

	}, // End onLoginChange().

	onLoginCancel : function() {

		// Send the event to the Flash component. 
		var my_flashContent = $( 'my_flashContent' );
		my_flashContent.onLoginCancel();

	} // End onLoginCancel().

} // End class ColorVisualizer.

var colorVisualizer = new ColorVisualizer();

//----- Called from the Flash component.

function trackPath( path ) {

	colorVisualizer.trackPath( path );

} // End trackPath().

function sharePage() {

	colorVisualizer.sharePage();

} // End sharePage().

function shareColors() {

	colorVisualizer.shareColors();

} // End shareColors().

function goToCalculator() {

	window.location.href = '../products/index.do?s=interior-paint-calculator';

} // End goToCalculator().

function goToStoreLocator( zipCode ) {

	colorVisualizer.goToStoreLocator( zipCode );

} // End goToStoreLocator().

function linkToOther( linkID ) {

	if ( linkID == "top10" ) {
		window.location.href = '../inspiration/top-10-color-palettes.do';
	} else if ( linkID == "tester" ) {
		window.location.href = '../products/paint-testers.do';
	} else if ( linkID == "flash" ) {
		window.location.href = 'http://www.adobe.com/go/getflashplayer';
	}

} // End linkToOther().

function setCookie (name, value, shouldPersist) {
	var expiration = "";
	if (shouldPersist) {
		var expdate = new Date();
		expdate.setDate(expdate.getDate() + 3660);
		expiration = ";expires=" + expdate.toGMTString();
	}
	document.cookie = name + "=" + escape(value) + expiration;
	
} // End setCookie().

function getSerializedCookies () {
	var cookies = new Object();
	if (document.cookie && document.cookie != '') {
		var nvpairs = document.cookie.split(';');
		for (var i = 0; i < nvpairs.length; i++) {
			var name_value = nvpairs[i].split("=");
			name_value[0] = name_value[0].replace(/^ /, '');
			name_value[1] = name_value[1].replace('%26', '%26%26');
			cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
		}
	}
	return Object.toQueryString( cookies );
} // End getSerializedCookies().

function updateSpecs() {

	colorVisualizer.updateSpecs();

} // End updateSpecs().

function scrollToBottom() {

	colorVisualizer.scrollToBottom();

} // End scrollToBottom().
