
// UserSkinInfo:
// This class gets the user's personalized skin consultation.
// There are two ways to load data into this class.
// If you do NOT have the user's answers handy, then call the fetchSkinAnswers() method.
// This will first fetch the user's answer from the db and then get all the tab data.
// If you DO have the user's answers handy, then you can skip the first fetch and just
// call fetchSkinResults() with the "answers" array, formatted as: [[1, 6], 1, 4, 3, 3, 2, 2, 2, 3]
// (of course, with the correct answer values... :-)
// You can specify a callback function in the constructor, and when ALL the fetch's
// are done and data loaded, you'll be called back.
//
// See dashboard.js to see this in action.  Simple example is:
//	this.skinInfo = new UserSkinInfo({callback: this._skininfoLoaded.bind(this)});
//	this.skinInfo.fetchSkinAnswers();
//

// WDR 2/25/10: updated for CLDE.  Hopefully this will be consistent with all
// future PerlGem sites, EXCEPT (very unfortunately) the Asia sites will apparently
// be using a different version.  Grrr....


var UserSkinInfo = Class.create({
    initialize: function(args) {
        
		this.callback = null;	
		this.skininfo = null;
		this.skinresults = null;
		this.skincpd = null;
		this.tabprods = [];
		this.tabids = [];
		this.concerns = [];
		
		// Load up passed params
        Object.extend(this, args || {});
    },
    
    fetchSkinAnswers: function() {
		var id = jsonRpcWrapper.fetch({
		    method: 'quiz.get', 
			params: [{"type": "skin_consultation_quiz"}],
			onSuccess: this.loadSkinInfo.bind(this),
			onError: function () { console.log( 'SkinInfo JSON failed to load ' ) }
		});
		return id;
    },
    
	loadSkinInfo: function (jsonRpcResponse) {
        var data = jsonRpcResponse.getValue();
		if ( data && data.answers && data.answers.length > 2 ) {
			this.skininfo = data;
			
			if ( this.haveAnswers() ) {
				// Do the next thang
				this.fetchSkinResults(this.makeArrayOfAnswers());
			} else {
				this.doCallback();
			}
		} else {
			this.doCallback();
		}
	},
	
    fetchSkinResults: function(answerArray) {
        
        var params = Object.extend ( {'answers': answerArray} );
        params = Object.extend ( params, productPage.DETAIL_VIEW_QUERY.PRODUCT_FIELDS );
        params = Object.extend ( params, productPage.DETAIL_VIEW_QUERY.SKU_FIELDS );
    	params = [params];
    	
		var id = jsonRpcWrapper.fetch({
		    method: 'skin_consultation_quiz.results', 
            params: params,
			onSuccess: this.loadSkinResults.bind(this),
			onError: function () { console.log( 'SkinResults JSON failed to load ' ); }
		});
		return id;
    },
    
    // Here's where we parse the actual skin results.
    // We'll pre-load the product data so it's handy for later.
	loadSkinResults: function(jsonRpcResponse) {
        var data = jsonRpcResponse.getValue();
		if (data) {
			// Store actual data from rpc call.
			this.skinresults = data;
			
			/*
			Format of data is something like:
	            "tab_1" : [
	               {
	                  "CONCERN" : 1,
	                  "NAME" : "LFS Extra Mild, Clarifying Lotion 1, DDML",
	                  "SKU_ID" : "SKU14888",
	                  "PRODUCT_ID" : "PROD4792"
	               },
	               {
	                  "CONCERN" : 1,
	                  "NAME" : "LFS Extra Mild, Clarifying Lotion 1, DDML",
	                  "SKU_ID" : "SKU19481",
	                  "PRODUCT_ID" : "PROD5635"
	               }
	            ],
	            "tab_2" : [ etc... ],
	            "skus" : { hash of sku data },
	            "products" : { hash of product data },
	       	
	       	Except, of course, the data format seems to change whenever we do new sites.
	       	So pay attention....
			*/
			
			var i,j,tabdata;
			for ( i=1; i<=3; i++ ) {
				var tabid = 'tab_'+i;
				tabdata = this.skinresults[tabid];
				if ( tabdata ) {
					this.tabids[this.tabids.length] = tabid;
					
					// Tab 1 is always the basic regimen.
					// Tabs 2 & 3 are concerns.
					// ".CONCERN" is a numeric indicator of the user's concern
					// (indicating the answer to the items in the quiz).
					if ( i >= 2 ) {
						this.concerns[this.concerns.length] = tabdata[0].CONCERN;
					}
					
					// Look for the products on this tab.
					this.tabprods[tabid] = [];
					for ( j=0; j<tabdata.length; j++ ) {
						this.tabprods[tabid][j] = this.getProductInfo(tabdata[j]['PRODUCT_ID'], tabdata[j]['SKU_ID']);
					}
				}
			}

			this.doCallback();			
		}

	},
	
    doCallback: function() {
		if ( this.callback ) {
			this.callback();
		}
    },
    
	// Makes the array of answers we can pass to the skin result forms.
	// Handles ordering of stuff.
	makeArrayOfAnswers: function() {
		// Just return answer hash, if present
		return ( this.skininfo ? this.skininfo.answers : null );
	},
	
	// Return true if we think we have actual answers.
	haveAnswers: function() {
		return ( this.skininfo && this.skininfo.answers && this.skininfo.answers.length > 2 );
	},
	
	// How many concerns did the user give?
	concernCount: function() {
		return this.concerns.length;
	},
	
	// Get the user concern of the given index
	// (one-based index!)
	getConcern: function(i) {
		return ( i > 0 && i <= this.concerns.length ? this.concerns[i-1] : 0 );
	},
	
	// Digs the user's skin type number (1-4) out of the skin result data.
	getSkinTypeNumber: function() {
		var num = 1;
		
		if ( this.skinresults ) {
			num = this.skinresults['skintype'];
		}
		
		return num;
	},
	
	// Returns array of tab id's we should use.
	getTabIds: function() {
		return this.tabids;
	},

	// Get the label to use for the given tab id
	getTabLabel: function(tabid) {
		if ( tabid == 'tab_1' ) {
			return prodrb.get('dashboard_3step_label');
		}
		
		var concern = this.getTabConcern(tabid); // tab[0].CONCERN;
		var key = 'dashboard_concern_label'+concern;
		var label = prodrb.get(key) || key;
		return label;
	},
	
	// Return concern info for the given tab id, if present.
	// This will be a number from 1-9 (or so...)
	getTabConcern: function(tabid) {
		var i = ( tabid == 'tab_3' ? 1 : 0 );
		return this.concerns[i];
	},
	
	getTabHeader: function(tabid) {
		if ( tabid == 'tab_1' ) {
			return prodrb.get('dashboard_3step_header') + ' ' + this.getSkinTypeNumber()+':';
			//return this.getSkinTypeHeader();
		}
		var lbl = this.getTabLabel(tabid);
		var txt = prodrb.get('dashboard_concern_header')
		if ( lbl ) {
			//lbl = new String(lbl).capitalize();
			txt += ' '+lbl;
		}
		txt += ':';
		return txt;
	},
	
	// Get the dashboard tab header (text at top of tab)
	getDBTabHeader: function(tabid) {
		var html = '';
		if ( tabid == 'tab_1' ) {
			html += '<img src="' + this.getImagePath(true) + '" />';
		}
		html += this.getTabHeader(tabid);
		return html;
	},
	
	getImagePath: function(isDB) {
		var imgPath = '/images/skinreport/';
		if ( isDB ) imgPath += 'dbicons/';
		var imgName = this.skinresults['image'];
		if ( !imgName ) imgName = 'type1.jpg';
		return imgPath + imgName;
	},
	
    getProductInfo: function(prodid,skuid) {
    	var prod = {};
    	if ( this.skinresults.products && this.skinresults.products[prodid] ) {
    		prod = this.skinresults.products[prodid];
    		
    		if ( skuid && this.skinresults.skus && this.skinresults.skus[skuid] ) {
    			prod.sku = this.skinresults.skus[skuid];
    		} else if ( prod.skus ) {
    			prod.sku = prod.skus;
    		}
    	}
    	return prod;
    },
    
    getTabProducts: function(tabid) {
    	var prods = [];
    	
    	if ( this.tabprods[tabid] ) {
    		prods = this.tabprods[tabid];
    	}
    	
    	return prods;
    },
    
	getResultsPageCopy: function(tabid) {
		var text = this.skinresults["copy"];
		var text2 = this.skinresults["copy2"];
		var disclaimer = this.skinresults["disclaimer"];
//		console.log('disclaimer:' + disclaimer);
		if(disclaimer){text = text + '<div id="disclaimerbox">' + disclaimer + '</div>';}
		text = text + text2;
		return text;
	}

    
});



