var PRODUCT_JSON_URL = "/jsonrpc.json";

var purchaseParams = [{
	"sku_fields" : ["SKU_ID",
	"PRODUCT_ID",
	"DISPLAYNAME",
	"SHADENAME",
	"SHADE_DESCRIPTION",
	"SKIN_TYPE",
	"PRODUCT_SIZE",
	"skin_type_string",
	"shopping_id",
	"STRENGTH",
	"PRODUCT_PRICE",
	"SMOOSH_DESIGN",
	"smoosh_path",
	"INVENTORY_STATUS",
	"REFILLABLE",
	"PRICE",		
	"FORMATTED_PRICE",
	"HEX_VALUE",
	"hex_value_string",
	"FINISH",
	"COLOR_FAMILY_NAME",
	"LIFE_OF_PRODUCT",
	"product"
	],

	"product_fields" : ["PRODUCT_ID",
	"PRODUCT_NAME",
	"DESCRIPTION",
	"SHORT_DESC",
	"PROD_SKIN_TYPE",
	"prod_skin_type_string",
	"IMAGE_NAME",
	"DISPLAY_ORDER",
	"SMALL_IMAGE",
	"LARGE_IMAGE",
	"THUMBNAIL_IMAGE",
	"PRODUCT_USAGE",
	"WWW_SID_1",
	"WWW_SID_2",
	"WWW_SID_3",
	"url",
	"shaded",
	"sized",
	"sku",
	"category"],
	
	"category_fields" : ["CATEGORY_ID",
	"DISPLAY_NAME"]
	
}];


var UserDashboard = Class.create({
	// Note - in theory, we should only have one instance of the dashboard... :-)
	userPurchases: null,
	orderList: null,
	refills: null,
	skinInfo: null,
	skinTabs: null,
	foundationInfo: null,
	haveDashboard: false,
	haveSignedInUser: false,	
	
    initialize: function(args) {
    	
		// Load up passed params
        Object.extend(this, args || {});
        
        this.haveDashboard = this.checkForDashboard();
        this.haveSignedInUser = this.checkForSignedInUser();
        
        if ( this.haveDashboard ) {
        	this.unloadAll();
       		this.loadLivePerson();
       	}
	},
	
	// Note - we need to be able to manually set the signed-in flag here
	// because we may need to check this flag before we have received the
	// "current user" response from the server.  (e.g. the user may have signed
	// in successfully, but user.isSignedIn() will not be true until we
	// also receive the user data, which comes separately from the signed-in msg.)
	handleSignin: function(loadit) {
		this.haveSignedInUser = true;
		if ( loadit )
			this.loadAll();
	},
	
	handleSignout: function() {
		this.haveSignedInUser = false;
		this.unloadAll();
	},
	
	// This does the main loading of the dashboard.
	// Note that all the other "load" methods assume you've already
	// checked for a valid signed-in user.
	loadAll: function() {
		this.haveSignedInUser |= this.checkForSignedInUser();
		this.haveDashboard |= this.checkForDashboard();
			
		if ( this.haveSignedInUser && this.haveDashboard ) {
	       	this.loadPurchases();
	       	this.loadOrders();
	       	this.loadRefills();
	       	this.loadSkinInfo();
	       	this.loadFoundationInfo();
	    } else {
	    	this.unloadAll();
	    }
	},
	
	// Unload the dashboard and reset to initial values.
	unloadAll: function() {
		if ( this.haveDashboard ) {
	       	this.resetPurchases();
	       	this.resetOrders();
	       	this.resetRefills();
	       	this.resetSkinInfo();
	       	this.resetFoundationInfo();
	    }
	},
	
	checkForDashboard: function() {
		// Check to see if the key db elements are on the page.
		// If not, we shouldn't bother trying anything...
		return (	$('db-my-refills-container') &&
		     		$('db-my-orders-container') &&
			 		$('db-my-purchases-content') &&
			 		$('db-my-skin-type-content') ? true : false );
	},
	
	checkForSignedInUser: function() {
		return ( typeof user == 'object' && user.isSignedIn() ? true : false );
	},
	
	checkForRecognizedUser: function() {
		return ( typeof user == 'object' && user.recognized_user ? true : false );
	},
	
	/////////////////////////////////////////////////////////////
	// LivePerson Logic
	
	loadLivePerson: function() {
		// Using global function now.
		//loadLiveChatButtons();
	},
	
	/////////////////////////////////////////////////////////////
	// Refills Logic
	
	resetRefills: function() {
		$('db-my-refills-container').update('');
		this.refills = null;
	},
	
	loadRefills: function() {
		if ( !this.refills ) {
			document.observe("refills:loaded", this._refillsLoaded.bind(this));
			this.refills = new AutoRefills();
		}
	},
	
	_refillsLoaded: function() {
		var elemId = 'db-my-refills-container';
		var elemRefills = $(elemId);
		var confRefill = this.refills.confirmed;
		if ( elemRefills && confRefill && confRefill.length > 0 ) {
			elemRefills.fillin(
				{
					template: templatefactory.get('dashboard-refill'), 
					object: confRefill, 
					position: 'replace'
				});			
		}
	},
	
	/////////////////////////////////////////////////////////////
	// Orders Logic
	
	resetOrders: function() {
		$('db-my-orders-container').update('');
		$('db-my-news-signin').show();
		this.orderList = null;
	},
	
	loadOrders: function() {
		if ( !this.orderList ) {
			$('db-my-orders-container').update(SpinnerHtml);
			$('db-my-news-signin').hide();

			this.orderList = new OrderList({callback: this._ordersLoaded.bind(this)});
		}
	},
	
	_ordersLoaded: function() {
		// If we're here, assume we don't need this
		$('db-my-news-signin').hide();
		
		var elemOrders = $('db-my-orders-container');
		elemOrders.update('');
		
		if ( this.orderList.hasOrders() ) {
			var lastOrder = this.orderList.getByIndex(0);
			
			// Massage some of the info:
			var stat = lastOrder.get('ORDER_STATUS');
			if ( stat.indexOf('SHIP') >= 0 ) { 
				lastOrder.set('UI_ORDER_STATUS', 'Shipped' )
				lastOrder.set('UI_CARRIER_INFO', 
							lastOrder.get('CARRIER') + ': #' + 
							lastOrder.get('TRACKING_NUMBER') + '<br />' );
			}
			else if ( stat.indexOf('CAN') >= 0 ) { 
				lastOrder.set('UI_ORDER_STATUS', 'Cancelled' )
			}
			else { 
				lastOrder.set('UI_ORDER_STATUS', 'Pending' )
			}
			
			elemOrders.fillin(
				{
					template: templatefactory.get('dashboard-last-order'), 
					object: lastOrder, 
					position: 'replace'
				});			
			
		}
	},
	
	
	/////////////////////////////////////////////////////////////
	// Purchases Logic
	
	resetPurchases: function() {
		$('db-my-purchases-content').update('');
		$('db-my-purchases-content').hide();
	    $('db-my-purchases-signin').show();
	    this.userPurchases = null;
	},
	
	loadPurchases: function() {
		// If we have a signed in user and have not already loaded the stuff
		if ( !this.userPurchases ) {
			$('db-my-purchases-content').show();
			$('db-my-purchases-content').update(SpinnerHtml);
		    $('db-my-purchases-signin').hide();
		    
    		this.userPurchases = new CatProdPageData ( purchaseParams, false, this._purchasesLoaded.bind(this), 'user.purchases' );
    	}
	},
	
	_purchasesLoaded: function() {
		var containerId = 'db-my-purchases-content';
		var prodContainerId = containerId + '-prods';
		var containerObj = $(containerId);
	    containerObj.update('');
	    $('db-my-purchases-signin').hide();
		
		// Make the product wrapper div
        containerObj.insert ( new Element('div', { "id": prodContainerId } ) );
        
        var prods = this.userPurchases.data.get('product');
	    if ( prods && prods.all.length > 0 ) {
        
	        // Make a "view all" button
	        var viewDiv = new Element('div', { "class" : "dashboard-view-past dotted-x-t" } );
	        var viewLink = new Element('a', {
	        	"class" : "details-arrow",
	        	"href"  : "/templates/user/account/purchases.tmpl"
	        });
	        viewLink.innerHTML = 'View All';
	        viewDiv.insert(viewLink);
	        containerObj.insert(viewDiv);
	
			// Make the args for the productPage object
		    var args = {
		        containerID: prodContainerId,
		        maxItems: 2,
		        cellsPerRow: 1,
		        startIndex: 0,
		        addToBagLink: false
		    };
		    
		    // Make the thing
	    	this.userPurchases.linkSkusToProducts();
	    	
			mergeIntoGlobalCatProdData ( this.userPurchases );
	    	
		    args.tableData = this.userPurchases.data.get('product').all;
		    var myTable = new productPage.miniThumbTable(args);

	    } else {
	    	// Just print a nice message
	    	containerObj.insert('You have no past purchases.');
		}
	},
	
	/////////////////////////////////////////////////////////////
	// Skin Consultation Logic

	resetSkinInfo: function() {
		$('db-my-skin-type-content').hide();
		if ( this.checkForRecognizedUser() && user.took_skin_quiz ) {
			// show signin box
			$('db-my-skin-type-unpopulated').hide();
			$('db-my-skin-type-signin').show();
		} else {
			// show take quiz box
			$('db-my-skin-type-unpopulated').show();
			$('db-my-skin-type-signin').hide();
		}
		this.skinInfo = null;
	},
		
	loadSkinInfo: function() {
		if ( !this.skinInfo ) {
			$('db-my-skin-type-content').update(SpinnerHtml);
			$('db-my-skin-type-content').show();
			$('db-my-skin-type-unpopulated').hide();
			$('db-my-skin-type-signin').hide();

			this.skinInfo = new UserSkinInfo({callback: this._skininfoLoaded.bind(this)});
			this.skinInfo.fetchSkinAnswers();
		}
	},

	_skininfoLoaded: function() {
		// Check if we actually got some skin results.
		// If not, show the unpopulated message
		if ( !this.skinInfo.haveAnswers() ) {
			$('db-my-skin-type-unpopulated').show();
			$('db-my-skin-type-signin').hide();
			$('db-my-skin-type-content').hide();
		} else {
			// Got skin results.  Show stuff.
			$('db-my-skin-type-unpopulated').hide();
			var skinDiv = $('db-my-skin-type-content');
			skinDiv.update('');
			
			var skinHdr = new Element('div').update("You're on your way to great skin!<br/><br/>");
			skinDiv.insert( skinHdr );
			
			var skinTabDiv = new Element('div', {id: 'db-my-skin-tab-container'});
			skinDiv.insert(skinTabDiv);
			
			this.skinTabs = new TabbedContent ({
				wrapperContainerID: skinTabDiv
			});
			
			var tabs = this.skinInfo.getTabIds();
			$A(tabs).each( function(tabid) {
				var tabDiv = this.skinTabs.createTab ({
					tabID: 'db-skin-tabs-'+tabid,
					tabLabel: this.skinInfo.getTabLabel(tabid)
				});
				
				var hdrDiv = new Element('div');
				hdrDiv.addClassName ('db-my-skin-'+tabid);
				hdrDiv.update ( this.skinInfo.getDBTabHeader(tabid) );
				tabDiv.insert(hdrDiv);
				
				var prods = this.skinInfo.getTabProducts(tabid);
				this.addTabProducts ( tabDiv, tabid, prods );
	
			}, this);
			
			this.skinTabs.setActiveTab('db-skin-tabs-'+tabs[0]);
		}
	},
	
	addTabProducts: function(tabDiv,tabID,prods) {
		var divId = 'db-skin-prods-' + tabID;
		var tabProdDiv = new Element("div", { id: divId });
		tabDiv.insert(tabProdDiv);
		
	    var args = {
	        containerID: divId,
	        cellsPerRow: 1,
	        startIndex: 0,
	        addToBagLink: false,
	        tableData: prods
	    };
	    
	    // Make sure we have some prods to actually show!
	    if ( prods.length > 0 ) {
	    	var myTable = new productPage.miniThumbTable(args);
	    }
	},
	
	/////////////////////////////////////////////////////////////
	// Foundation Finder Logic

	resetFoundationInfo: function() {
		$('db-my-foundation-content').hide();
		$('db-my-foundation-progress').hide();
		if ( this.checkForRecognizedUser() && user.took_foundation_quiz ) {
			// show signin box
			$('db-my-foundation-unpopulated').hide();
			$('db-my-foundation-signin').show();
		} else {
			// show take quiz box
			$('db-my-foundation-unpopulated').show();
			$('db-my-foundation-signin').hide();
		}
		this.foundationInfo = null;
	},
		
	loadFoundationInfo: function() {
		if ( !this.foundationInfo ) {
			$('db-my-foundation-progress').update(SpinnerHtml);
			$('db-my-foundation-progress').show();
			$('db-my-foundation-content').hide();
			$('db-my-foundation-unpopulated').hide();
			$('db-my-foundation-signin').hide();

			this.foundationInfo = new UserFoundationInfo({callback: this._foundationLoaded.bind(this)});
			this.foundationInfo.fetchFoundationAnswers();
		}
	},

	_foundationLoaded: function() {
		var prods = this.foundationInfo.getProducts();
		
		if ( prods && prods.length > 0 ) {
			// Got products.  Go show them.
			$('db-my-foundation-progress').hide();
			$('db-my-foundation-unpopulated').hide();
			$('db-my-foundation-signin').hide();
			$('db-my-foundation-content').show();
			
			var prodDivId = 'db-my-foundation-prods';
			var prodDiv = $(prodDivId);
			prodDiv.update('');
	
		    var args = {
		        containerID: prodDivId,
		        cellsPerRow: 1,
		        startIndex: 0,
		        addToBagLink: false,
		        tableData: prods
		    };
		    
		    // Make sure we have some prods to actually show!
		    if ( prods.length > 0 ) {
		    	var myTable = new productPage.miniThumbTable(args);
		    }
		    
		    var shadeDivId = 'db-my-foundation-shades';
		    var shadeDiv = $(shadeDivId);
		    shadeDiv.update('');
		    
		    var skus = this.foundationInfo.getSkus();
	    	var skuargs = {
	        	tableContainerID: shadeDivId,
	        	tableData       : skus,
	        	cellsPerRow     : 3
	    	};
	    	
	    	if ( skus.length > 0 ) {
	    		var tbl = new productPage.ShadePicker.Table.Small(skuargs);
	    	}
	    
		} else {
			// No products.  Assume user didn't take quiz.
			$('db-my-foundation-progress').hide();
			$('db-my-foundation-unpopulated').show();
			$('db-my-foundation-signin').hide();
			$('db-my-foundation-content').hide();
		}
		
	}
	
	
});

    	

