var UserFoundationInfo = Class.create({
    initialize: function(args) {
		this.callback = null;	
		this.foundationInfo = null;
		this.foundationResults = null;
		this.foundationCpd = null;
		this.tabprods = null;
		
		// Load up passed params
        Object.extend(this, args || {});
    },
    
    fetchFoundationAnswers: function() {
    	/* fake data:
    	var ar = {"form": "Liquid", "benefit": "Moisturizing", "skin_type": "1", "coverage": "Moderate", "finish": "Luminous/Dewy", "skin_tone": "1"};
    	return this.fetchFoundationResults(ar);
    	*/
		var id = jsonrpc.fetch( 'foundation.fetch', 
			[],
			{ 
				onSuccess: this.loadFoundationInfo.bind(this),
				onFailure: function () { console.log( 'FoundationInfo JSON failed to load ' ) }
			}
		);
		return id;
    },
    
    loadFoundationInfo: function(t) {
		var o = t.responseText.evalJSON()[0];
		this.foundationInfo = $H(o.result);
		this.foundationInfo.answers = this.foundationInfo.get('answers');
			
		if ( this.foundationInfo.answers ) {
			this.fetchFoundationResults ( this.foundationInfo.answers );
		} else {
			this.doCallback();
		}
    },
    
    fetchFoundationResults: 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( 'foundation.results', 
            params, //params
            {
				onSuccess: this.loadFoundationResults.bind(this),
				onFailure: function () { console.log( 'SkinResults JSON failed to load ' ); }
			}
		);
		return id;
    },
    
	loadFoundationResults: function(t) {
		var o = t.responseText.evalJSON()[0];
		if (o.error == null || o.error == "") {
			this.foundationResults = $H(o.result);
			this.foundationCpd = new CatProdPageData();
			this.foundationCpd.fillinData(this.foundationResults);
			
			mergeIntoGlobalCatProdData ( this.foundationCpd );
	
			this.doCallback();			
		}

	},
	
    doCallback: function() {
		if ( this.callback ) {
			this.callback();
		}
    },
    
    getSkus: function() {
    	var prods = this.getProducts();
    	var skusToReturn = [];
    	
    	prods.each(function(p){
    		p.skus.each(function(s){
    			skusToReturn.push(s);
    		});
    	});
    	
    	return skusToReturn;
    },
    
    getProducts: function() {
    	var prods = [];
    	
    	if ( this.tabprods ) {
    		prods = this.tabprods;
    	} else if ( this.foundationCpd ) {
			prods = this.foundationCpd.getProducts();
			this.tabprods = prods;
		}
    	
    	return prods;
    }
	
});
