//
// EndecaMeta class.
// This provides a convenience wrapper for parsing the metadata of Endeca results.
// After parsing, we can access the properties we care about as valid js properties.
// There is no other use for this class (please don't add page/state specific
// code in this module).
//

var EndecaMeta = Class.create({
	
	initialize: function(args) {
		
		this.metaInfo = $H();
		this.refinements = $A();
		this.breadcrumbs = $A();
		this.supplemental = $A();
		this.searchInfo = $H();
		this.jsonResult = null;
		
		// Load up passed params
        Object.extend(this, args || {});
        
        // If we had data given to us, handle it now.
        if ( this.jsonResult ) {
        	this.parseData(this.jsonResult);
        }
	},
	
	parseData: function(jsonResult) {
  		this.metaInfo = ( jsonResult.MetaInfo ? $H(jsonResult.MetaInfo) : this.metaInfo );
  		this.refinements = ( jsonResult.Refinements ? $A(jsonResult.Refinements) : this.refinements );
  		this.breadcrumbs = ( jsonResult.Breadcrumbs ? $A(jsonResult.Breadcrumbs) : this.breadcrumbs );
  		this.supplemental = ( jsonResult["Supplemental Objects"] ? $A(jsonResult["Supplemental Objects"]) : this.supplemental );
  		this.searchInfo = ( jsonResult["Search Info"] ? $H(jsonResult["Search Info"]) : this.searchInfo );
  		
  		this.searchTerm = ( jsonResult["Search Info"] && 
  							jsonResult["Search Info"]["all"] && 
  							jsonResult["Search Info"]["all"]["Search Term"]  ? 
  							jsonResult["Search Info"]["all"]["Search Term"] : '' );
  		
  		// Check for spell correction					
		this.searchCorrected = '';
  		var arTerms = 
  						( jsonResult["Search Info"] && 
  							jsonResult["Search Info"]["all"] && 
  							jsonResult["Search Info"]["all"]["Spell Correction"]  ? 
  							$A(jsonResult["Search Info"]["all"]["Spell Correction"]) : null );
  		if ( arTerms ) {
  			arTerms.each( function(el) {
  				// If we matched on a computed phrase AFTER the spell correction,
  				// then the "Spell Correction" flag is not set properly.
  				// Also, the "New Term" will have quotes around it, which further
  				// messes up the comparison.  So... to test for spell correction,
  				// see if the user's search term is NOT within the corrected term.
  				//if ( el["New Term"] && el["Spell Correction"] == "true" ) {
  				if ( el["New Term"] && el["New Term"].indexOf(this.searchTerm) < 0 ) {
  					if ( this.searchCorrected.length > 0 ) this.searchCorrected += ',';
  					this.searchCorrected += el["New Term"];
  				}
  			},this);
  		}
  		
  		// Check for did-you-mean
  		this.didYouMean = '';
  		this.didYouMeanLink = '';
  		arTerms = 
  						( jsonResult["Search Info"] && 
  							jsonResult["Search Info"]["all"] && 
  							jsonResult["Search Info"]["all"]["DYM Information"]  ? 
  							jsonResult["Search Info"]["all"]["DYM Information"] : null );
  							
  		// Note - we're only going to handle one dym term...
  		// Quirk: With computed phrases turned on, if the user enters
  		// an exact phrase that we have in our search config, we'll get
  		// a dym entry of the quoted phrase.  Since this is confusing and unnecessary,
  		// we'll just skip those dym's.
  		if ( arTerms && arTerms[0] && arTerms[0]["New Term"] && arTerms[0]["Pivot Link"] &&
  		     arTerms[0]["New Term"].indexOf(this.searchTerm) < 0 ) {
  			this.didYouMean = arTerms[0]["New Term"];
  			this.didYouMeanLink = arTerms[0]["Pivot Link"];
  		}
  		
  		// Parse supplemental object for:
  		//  - keyword redirect
  		//  - merch window top banner
  		//	- featured products
  		this.keywordRedirect = '';
  		this.mwBannerTop = '';
  		this.arFeaturedProducts = $A();
  		if ( this.supplemental ) {
  			this.supplemental.each(function(elSup){
  				// elSup is a hash with (perhaps) Dimensions and Properties
  				if ( elSup["Properties"] ) {
  					
  					if ( elSup["Properties"]["DGraph.KeywordRedirectUrl"] ) {
  						this.keywordRedirect = elSup["Properties"]["DGraph.KeywordRedirectUrl"];
  					}
  					
  					// "Zone" is something we set up in the Endeca Dev Studio.
  					// It's fairly hard-coded into the Endeca config.
  					// We defined several zones, which correspond to the
  					// areas on the search page that we want to put stuff.
  					
  					// DGraph.SeeAlsoMerchId is an Endeca property.
  					// m_merchwin_banner_top is ours, created in the Merch Workbench.
  					if ( elSup["Properties"]["DGraph.SeeAlsoMerchId"] &&
  					     elSup["Properties"]["Zone"] == "Top Offer Banner" ) {
  					  	this.mwBannerTop =
  					  		( elSup["Properties"]["m_merchwin_banner_top"] ? elSup["Properties"]["m_merchwin_banner_top"] :
  					  		  elSup["Properties"]["banner_template"] ? elSup["Properties"]["banner_template"] :
  					  		  '' );
  					}
  					
  					// See if there are featured products.
  					if ( elSup["Properties"]["DGraph.SeeAlsoMerchId"] &&
  					     elSup["Properties"]["Zone"] == "Featured Product Banner" &&
  					     elSup["Records"] ) {
  						// There are featured products.  Go dig them out of the record specs.
  						$A(elSup["Records"]).each( function(eFeatRec){
  							if ( eFeatRec["Record Spec"] ) {
  								this.arFeaturedProducts.push(eFeatRec["Record Spec"]);
  							}
  						},this);
  					}
  				}
  			},this);
  		}
  		
  		// Parse out some specifics for convenience
  		this.numberOfPages       = this.getMetaProp ( "Number of Pages" , 1, true );
  		this.numberOfCurrentPage = this.getMetaProp ( "Page Number" , 1, true );
  		this.directPageLinkStart = this.getMetaProp ( "Direct Page Link Start Page", 1, true );
  		this.directPageLinks     = this.getMetaProp ( "Direct Page Links", [] );
  		this.nextPageLink        = this.getMetaProp ( "Next Page Link", '' );
  		this.prevPageLink        = this.getMetaProp ( "Previous Page Link", '' );
  		this.nextPageSetLink     = this.getMetaProp ( "Next Page Set Link", '' );
  		this.prevPageSetLink     = this.getMetaProp ( "Previous Page Set Link", '' );
  		this.startingRecord      = this.getMetaProp ( "Starting Record Number", 1, true );
  		this.endingRecord        = this.getMetaProp ( "Ending Record Number", 1, true );
  		this.recordsReturned     = this.getMetaProp ( "Number of Records Returned", 0, true );
  		this.recordsPerPage      = this.getMetaProp ( "Number of Records per Page", 0, true );

  		this.totalMatchRecords   = this.getMetaProp ( "Total Number of Matching Records", 0, true );
  		this.totalAggrRecords    = this.getMetaProp ( "Total Number of Matching Aggregate Records", 0, true );
  		this.totalRecords        = ( this.totalAggrRecords ? this.totalAggrRecords : this.totalMatchRecords );
	},
	
	// Convenience function to look for prop and return default if not found
	getMetaProp: function(prop,def,isNum) {
		var val = ( this.metaInfo.get(prop) ? this.metaInfo.get(prop) : def );
		if ( isNum ) {
			val = String(val).toInt();
		}
		return val;
	}
	
});

/*
"MetaInfo" : {
	"Number of Records per Page" : "10",
	"Number of Records Returned" : "10",
	"Starting Record Number" : "11",
	"Ending Record Number" : "20",
	"Total Number of Matching Records" : "2937",
	"Total Number of Matching Aggregate Records" : "1363",

	"Add Sort Key Links" : [
	],
	"Total Network and Compute Time" : "0.01",

	"Page Number" : "2",
	"Number of Pages" : "137"
	"Next Page Link" : "N=&Nao=20&Np=2?=p_PRODUCT_ID",
	"Previous Page Link" : "N=&Nao=0&Np=2?=p_PRODUCT_ID",
	"Next Page Set Link" : "N=&Nao=100&Np=2?=p_PRODUCT_ID",

	"Direct Page Links" : [
		"N=&Nao=0&Np=2?=p_PRODUCT_ID",
		"N=&Nao=10&Np=2?=p_PRODUCT_ID",
		"N=&Nao=20&Np=2?=p_PRODUCT_ID",
		"N=&Nao=30&Np=2?=p_PRODUCT_ID",
		"N=&Nao=40&Np=2?=p_PRODUCT_ID",
		"N=&Nao=50&Np=2?=p_PRODUCT_ID",
		"N=&Nao=60&Np=2?=p_PRODUCT_ID",
		"N=&Nao=70&Np=2?=p_PRODUCT_ID",
		"N=&Nao=80&Np=2?=p_PRODUCT_ID",
		"N=&Nao=90&Np=2?=p_PRODUCT_ID"
	],
	"Direct Page Link Start Page" : "1",
},

*/
