
// 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();
//
// Then, get the array of tabid's by calling getTabIds(), and get the rest of the info:
// arTabIds = skinInfo.getTabIds();
// arTabIds.each(function(tabid){
//		products = skinInfo.getTabProducts(tabid);
// });


var UserSkinInfo = Class.create({
    initialize: function(args) {
        
		this.callback = null;	
		this.skininfo = null;
		this.skinresults = null;
		this.skincpd = null;
		this.tabprods = $H();
		
		// Note - order of these items must match Clinique2::User.pm::@SKINREPORT_QUESTIONS
		this.qlist = new Array ( 'PC_CONCERNS','PC_EYECOLOR','PC_HAIRCOLOR','PC_SUNRESPONSE','PC_SKINCOLOR','PC_PORESIZE','PC_BREAKOUT','PC_OILINESS','PC_LINES' );
    	
		// Load up passed params
        Object.extend(this, args || {});
    },
    
    fetchSkinAnswers: function() {
		var id = jsonrpc.fetch( 'user.skininfo', 
			[],
			{ 
				onSuccess: this.loadSkinInfo.bind(this),
				onFailure: function () { console.log( 'SkinInfo JSON failed to load ' ) }
			}
		);
		return id;
    },
    
	loadSkinInfo: function (t) {
		var o = t.responseText.evalJSON()[0];
		if (o.error == null) {
			this.skininfo = $H(o.result);
			
			if ( this.haveAnswers() ) {
				// Do the next thang
				this.fetchSkinResults(this.makeArrayOfAnswers());
			} 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 = jsonrpc.fetch( 'skintype.results', 
            params, //params
            {
				onSuccess: this.loadSkinResults.bind(this),
				onFailure: function () { console.log( 'SkinResults JSON failed to load ' ); }
			}
		);
		return id;
    },
    
	loadSkinResults: function(t) {
		var o = t.responseText.evalJSON()[0];
		if (o.error == null) {
			this.skinresults = $H(o.result);
			this.skincpd = new CatProdPageData();
			this.skincpd.fillinData(this.skinresults);
			
			mergeIntoGlobalCatProdData ( this.skincpd );
			
			this.doCallback();			
		}

	},
	
    doCallback: function() {
		if ( this.callback ) {
			this.callback();
		}
    },
    
	// Gets the value for the key "s".
	// s can be the question index (1-9) OR the key string.
	// Returns zero if not found.
	getQ: function(s) {
		var value = 0;
		if ( this.skininfo ) {
			if ( typeof s == 'number' ) {
				if ( s > 0 && s <= this.qlist.length ) {
					value = this.skininfo.get(this.qlist[s-1]);
				}
			} else {
				var i = this.qlist.indexOf(s);
				if ( i >= 0 ) {
					value = this.skininfo.get(this.qlist[i]);
				}
			}
		}
		return value;
	},
	
	// Makes the array of answers we can pass to the skin result forms.
	// Handles ordering of stuff.
	makeArrayOfAnswers: function() {
		var arRet = new Array();
		
		this.qlist.each( function(s) {
			arRet[arRet.length] = this.getQ(s);
		}, this );
		
		return arRet;
	},
	
	// Return true if we think we have actual answers.
	haveAnswers: function() {
		// Return true if user answered q's 4/7/8
		return ( this.getQ(4) || this.getQ(7) || this.getQ(8) );
	},
	
	// How many concerns did the user give?
	concernCount: function() {
		// First skin question (subscript 0) is user concerns.
		// This should be an array of answers, if present.
		var arConcerns = this.getQ(1);
		return ( arConcerns ? arConcerns.length : 0 );
	},
	
	// Get the user concern of the given index
	getConcern: function(i) {
		var arConcerns = this.getQ(1);
		return ( arConcerns && i > 0 && i <= arConcerns.length ? arConcerns[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.get('skintype');
		}
		
		return num;
	},
	
	// This will return a few characters to indicate what skin "formula" you are.
	// The logic for this is "my interpretation" of the information given to me.
	// Formula is two characters as:	SN
	// Where:
	//	"S" is the skin type number (1-4)
	//	"N" is a sub-type number, which is determined as:
	//		a - if user indicated "acne" is a concern
	//		r - if user indicated "redness" is a concern
	//		D - if user chose 1 or 2 (dryness) for question 4
	//		O - if user chose 3 or 4 (oily) for question 4
	// Note that the precendence is as listed, which means if the user indicated
	// "acne", that overrules the answer to question 4.
	getSkinFormulaId: function() {
		var num  = this.getSkinTypeNumber();
		var q4   = this.getQ(4);
		var con1 = this.getTabConcern('tab_2');
		var con2 = this.getTabConcern('tab_3');
		var subnum = ( con1 == 1 || con2 == 1 ? 'a' :
		               con1 == 2 || con2 == 2 ? 'r' :
		               q4 == 1 || q4 == 2 ? 'D' :
		               q4 == 3 || q4 == 4 ? 'O' :
		               '' );
		return num + subnum;
	},
	
	getTabIds: function() {
		var arTabs = [];
		
		if ( this.skinresults ) {
			// This is sorta fake...
			var i;
			for ( i=1; i<=3; i++ ) {
				var tabid = 'tab_'+i;
				if ( this.skinresults.get(tabid) ) {
					arTabs[arTabs.length] = tabid;
				}
			}
		}
		
		return arTabs;
	},

	getTabLabel: function(tabid) {
		if ( tabid == 'tab_1' ) {
			return 'BASIC REGIMEN';
		}
		
		var concern = this.getTabConcern(tabid); // tab[0].CONCERN;
		if ( concern ) {
			var label = productPage.SkinConsult.concerns[concern-1];
			return label;
		}
		
		return '';
	},
	
	getTabData: function(tabid) {
		var tab = this.skinresults.get(tabid);
		return tab;
	},
	
	getTabConcern: function(tabid) {
		var tab = this.skinresults.get(tabid);
		return ( tab ? tab[0].CONCERN : 0 );
	},
	
	getTabHeader: function(tabid) {
		if ( tabid == 'tab_1' ) {
			return 'Your custom-fit<br/>3-Step for<br/>Skin Type '+this.getSkinTypeNumber()+':';
			//return this.getSkinTypeHeader();
		}
		var lbl = this.getTabLabel(tabid);
		var txt = 'Recommended for your skin concern';
		if ( lbl ) {
			lbl = new String(lbl).capitalize();
			txt += ' '+lbl;
		}
		txt += ':';
		return txt;
	},
	
	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.get('image');
		if ( !imgName ) imgName = 'type1.jpg';
		return imgPath + imgName;
	},
	
	getSkinTypeHeader: function() {
        var skintypeTitles = [
            'You are a Skin Type 1 - Very Dry to Dry',
            'You are a Skin Type 2 - Dry Combination',
            'You are a Skin Type 3 - Oily',
            'You are a Skin Type 4 - Very Oily' ];
        return skintypeTitles[this.getSkinTypeNumber() - 1];
    },
    
    getTabProducts: function(tabid) {
    	var prods = [];
    	
    	if ( this.tabprods[tabid] ) {
    		prods = this.tabprods[tabid];
    	} else {
			var tab = this.skinresults.get(tabid);
			tab.each(function(tabdata) {
				var prod = this.skincpd.getProductBySku ( tabdata.SKU_ID, tabdata.PRODUCT_ID );
				if ( prod ) {
					prods[prods.length] = prod;
				}
			}, this);
			this.tabprods[tabid] = prods;
		}
    	
    	return prods;
    },
    
	getResultsPageCopy: function(tabid) {
		var text = this.skinresults.get("copy");
		var text2 = this.skinresults.get("copy2");
		var disclaimer = this.skinresults.get("disclaimer");
//		console.log('disclaimer:' + disclaimer);
		if(disclaimer){text = text + '<div id="disclaimerbox">' + disclaimer + '</div>';}
		text = text + text2;
		return text;
	}

    
});



