var PRODUCT_JSON_URL = "/rpc/jsonrpc.tmpl";

var purchaseParams = [{
    "query_key" : "dashboard-userpurchases"
}];

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.loadUser();
        this.haveDashboard = this.checkForDashboard();
        this.haveSignedInUser = this.checkForSignedInUser();
        
        if ( this.haveDashboard ) {
        	this.unloadAll();
       		this.loadLivePerson();
       	}
	},
	
	loadUser: function() {
		if ( !generic.user.session_id ) {
		    var userParams = {};
		    userParams.pageDataKey = 'globalnav.user';
		    generic.user.getUser(userParams);
		}
	},
	
	// 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.loadUser();
		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-skintype-content') ? true : false );
	},
	
	checkForSignedInUser: function() {
		var signedIn = ( generic.user.isSignedIn() ? true : false );
		console.log("dashboard.signedIn: " + signedIn);
		return signedIn;
	},
	
	checkForRecognizedUser: function() {
		return ( generic.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() {
	    /* no refills on jp
		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('/templates/dashboard-refill.tmpl'), 
					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.getLastOrder();
			/*
            {
               "TRANS_ID" : 1616788,
               "TRANS_DATE" : "19-JUN-2009 11:02:26",
               "TRACKING_NUMBER" : null,
               "ORDER_STATUS" : "???",
               "TOTAL_COST" : 32
            },
            */
			elemOrders.fillin(
				{
					template: templatefactory.get('/templates/dashboard-last-order.tmpl'), 
					object: lastOrder, 
					position: 'replace'
				});			
			
		} else {
			elemOrders.fillin(
				{
					template: templatefactory.get('/templates/dashboard-no-orders.tmpl'), 
					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();
		    
        	generic.jsonrpc.fetch({
                method : "user.pastPurchased",
                params : [{ query_key: 'dashboard-userpurchases', max_length: 2 }],
                onSuccess: this._purchasesLoaded.bind(this),
                onError: function (jsonRpcResponse) {
                    console.log(jsonRpcResponse.getMessages());
                }
            });
    	}
	},
	
	_purchasesLoaded: function(jsonRpcResponse) {
		var containerId = 'db-my-purchases-content';
		var prodContainerId = containerId + '-prods';
		var containerObj = $(containerId);
	    containerObj.update('');
	    $('db-my-purchases-signin').hide();
		
        var prods = this._getResponseProducts(jsonRpcResponse);
	    if ( prods && prods.length > 0 ) {
        
			// Make the product wrapper div
	        containerObj.insert ( new Element('div', { "id": prodContainerId } ) );
        
	        // 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"  : "/account/order_history/purchases.tmpl"
	        });
	        viewLink.innerHTML = productPage.rb.brand.get('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
		    };
		
		    args.tableData = prods;
		    var myTable = new productPage.miniThumbTable(args);
	    } else {
	    	// Just print a nice message
	    	containerObj.fillin(
				{
					template: templatefactory.get('/templates/dashboard-no-purchases.tmpl'), 
					position: 'replace'
				});			
	    	
		}
	},
	
	_getResponseProducts: function(jsonRpcResponse) {
		var responseData = jsonRpcResponse.getValue();
	    var prods = [];

		if ( responseData.skus && responseData.products ) {
			$A(responseData.skus).each( function(responseSkuObj) {
				
				// Did we create this product already?
				var tprod = $A(prods).find(function(lprod){
					return lprod.PRODUCT_ID == responseSkuObj.PRODUCT_ID;
				});
						
				if ( tprod ) {
					// Just add this sku to the product's sku list
					tprod.skus.push(responseSkuObj);
				}
				else {
					// Haven't see this prod.  Look it up in the response object
					var responseProdObj = responseData.products.find(function(rprod){
						return rprod.PRODUCT_ID == responseSkuObj.PRODUCT_ID;
					});
					
					// Null the product's sku list and start over.
					responseProdObj.skus = [];
					responseProdObj.skus[0] = responseSkuObj;
					prods[prods.length] = responseProdObj;
				}
				
			}, this);
		}
		
		return prods;
	},
	
	/////////////////////////////////////////////////////////////
	// Skin Consultation Logic

	resetSkinInfo: function() {
		$('db-skintype-content').hide();
		if ( this.checkForRecognizedUser() && generic.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-skintype-content').show();
			$('db-skintype-spinner').update(SpinnerHtml);
			$('db-skintype-spinner').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-skintype-content').hide();
		} else {
			// Got skin results.  Show stuff.
			$('db-my-skin-type-unpopulated').hide();
			$('db-skintype-spinner').hide();
			$('db-skintype-content').show();

			var tabs = this.skinInfo.getTabIds();
			$A(tabs).each( function(tabid,i) {
				var hdrLink = $('db-skintype-link'+(i+1));
				if ( hdrLink ) {
					hdrLink.update ( this.skinInfo.getTabLabel(tabid) );
					
					var tabDiv = $('db-skintype-content'+(i+1));
					var hdrDiv = new Element('div');
					var className = ( this.skinInfo.is3StepTabId(tabid) ? 'db-my-skin-3step' : 'db-my-skin-'+tabid );
					hdrDiv.addClassName (className);
					hdrDiv.update ( this.skinInfo.getDBTabHeader(tabid) );
					tabDiv.insert(hdrDiv);
					
					var prods = this.skinInfo.getTabProducts(tabid);
					if ( prods && prods.length ) {
						this.addTabProducts ( tabDiv, tabid+'new', prods );
					}
				}
			}, this);
			
			// Hide unused tabs
			for ( var i = tabs.length; i < 3; i++ ) {
				var tabHdr = $('db-skintype-label'+(i+1));
				if ( tabHdr ) tabHdr.hide();
			}
			
			//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() && generic.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);
			if ( prodDiv ) {
				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);
		    if ( shadeDiv ) {
			    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();
		}
		
	}
	
	
});

    	


