// instantiate object namespace
if (typeof (SNI) == 'undefined') {
    SNI = {};
}



/**
 * MetaData Manager
 */

// instantiate object namespace
if (typeof (SNI.MetaData) == 'undefined') {
    SNI.MetaData = {};
}

SNI.MetaData.Parameter = function(){
	var parameters = {};		// object to store parameters

	this.addParameter = function(key, value){
		key = key.toUpperCase();		// always force key to uppercase before insert (case-insensitive insert and lookup)
		if(!parameters[key]) {
			parameters[key] = [];
		}
		parameters[key].push(value);
	};

	this.getParameter = function(key, separator){
		key = key.toUpperCase();		// always force key to uppercase before retrieval (case-insensitive insert and lookup)
		if(!parameters[key]) {
			return;
		}
		return parameters[key].join(separator);
	};

	this.getKeys = function(){
		return parameters;
	};
};



/* -------------------------------------------
			MetaDataManager
------------------------------------------- */
SNI.MetaData.Manager = function(){
	var m = new SNI.MetaData.Parameter();
	this.addParameter = m.addParameter;
	this.getParameter = m.getParameter;
	this.getKeys = m.getKeys;

	// gets the value of the parameter, but returns empty string if parameter doesn't exist
	this.getParameterString = function(key) {
		var s =  this.getParameter(key," ");
		if ( s == null ) {
			s = "";
		}
		return s;
	};

	// these getters are for backwards compatibility; should use getParameterString() now

	// generic getters
	this.getPageType = 		function() { return this.getParameterString("Type"); };
	this.getPageTitle = 	function() { return this.getParameterString("Title"); };
	this.getSite = 			function() { return this.getParameterString("Site"); };
	this.getSctnId = 		function() { return this.getParameterString("SctnId"); };
	this.getSctnName = 		function() { return this.getParameterString("SctnName"); };
	this.getSponsorship = 	function() { return this.getParameterString("Sponsorship"); };
	this.getAbstract = 		function() { return this.getParameterString("Abstract"); };
	this.getKeywords = 		function() { return this.getParameterString("Keywords"); };
	this.getClassification =function() { return this.getParameterString("Classification"); };
	this.getSctnDspName = 	function() { return this.getParameterString("SctnDspName"); };
	this.getCategoryDspName=function() { return this.getParameterString("CategoryDspName"); };
	this.getShowAbbr = 		function() { return this.getParameterString("Show_Abbr"); };
	this.getRole = 			function() { return this.getParameterString("Role"); };
	this.getDetailId = 		function() { return this.getParameterString("DetailId"); };
	this.getPageNumber = 	function() { return this.getParameterString("PageNumber"); };
	this.getUniqueId = 		function() { return this.getParameterString("UniqueId"); };
	this.getUserId = 		function() { return this.getParameterString("UserId"); };
	this.getUserIdEmail = 	function() { return this.getParameterString("UserIdEmail"); };
	this.getUserIdCreateDt =function() { return this.getParameterString("UserIdCreateDt"); };
	this.getUserIdVersion = function() { return this.getParameterString("UserIdVersion"); };
	this.getFilters = 		function() { return this.getParameterString("Filters"); };

	// food specific getters
	this.getMultimediaFlag =function() { return this.getParameterString("MultimediaFlag"); };
	this.getChefName = 		function() { return this.getParameterString("ChefName"); };
	this.getMealPart = 		function() { return this.getParameterString("MealPart"); };
	this.getCuisine = 		function() { return this.getParameterString("Cuisine"); };
	this.getOccasion = 		function() { return this.getParameterString("Occasion", " "); };
	this.getMainIngredient =function() { return this.getParameterString("MainIngredient"); };
	this.getTechnique = 	function() { return this.getParameterString("Technique", " "); };
	this.getDish = 			function() { return this.getParameterString("Dish", " "); };
	this.getMealType = 		function() { return this.getParameterString("MealType", " "); };
	this.getNutrition = 	function() { return this.getParameterString("Nutrition", " "); };
	this.getDifficulty = 	function() { return this.getParameterString("Difficulty", " "); };

	// other methods

	this.getSearchTerm = function() {
		var args = parseQueryString ();
		for (var arg in args) {
			var s = arg.toUpperCase();
			if ( s == 'SEARCHSTRING' ){
				return args[arg];
			}
		}
		return "";
	};

	this.setMultimediaFlag = function(flag) {
		if ( flag != null ) {
			this.addParameter("MultimediaFlag",flag);
		} else {
			this.addParameter("MultimediaFlag","");
		}
	};

	this.parseQueryString = function(str) {
	  str = str ? str : document.location.search;
	  var query = str.charAt(0) == '?' ? str.substring(1) : str;
	  var args = {};
	  if (query) {
	    var fields = query.split('&');
	    for (var f = 0; f < fields.length; f++) {
	      var field = fields[f].split('=');
	      args[unescape(field[0].replace(/\+/g, ' '))] =
			unescape(field[1].replace(/\+/g, ' '));
	    }
	  }
	  return args;
	};

};


// MetaDataManager for backwards compatibility
var MetaDataManager = SNI.MetaData.Manager;











/**
 * ads core
 */

// requires SNI.MetaData


// instantiate Ads object/namespace
if( typeof(SNI.Ads)=='undefined' ) {
	SNI.Ads = {
		// should be adsremote.scrippsnetworks.com for production and devadsremote.scrippsnetworks.com for development/staging
		_adServerHostname: "adsremote.scrippsnetworks.com"
	};
}


// Url obj
SNI.Ads.Url = function() {
	var p = new SNI.MetaData.Parameter();

	// functions
	this.addParameter = p.addParameter;
	this.getParameter = p.getParameter;
	this.getKeys = p.getKeys;
	this.url = '';
	this.buildUrl = buildUrl;
	this.buildExpandedUrl = buildExpandedUrl;
	this.setUrl = setUrl;
	this.getUrl = getUrl;
	this.buildQueryStringValuePairs = buildQueryStringValuePairs;
	this.buildExpandedQueryStringValuePairs = buildExpandedQueryStringValuePairs;

 	// setUrl
	function setUrl(u) { this.url = u; }

	// getUrl
	function getUrl() { return this.url; }

	// buildQueryStringValuePairs
	function buildQueryStringValuePairs() {
			var queryString = "";
			for ( key in this.getKeys() ) {
				if (queryString !== "") {
					queryString += '&';
				}
				queryString += key +'='+ this.getParameter(key, ',');
	    	}
	    	return queryString;
	}

	// buildUrl
	function buildUrl() {
		return this.getUrl() + this.buildQueryStringValuePairs();
	}


	// buildExpandedQueryStringValuePairs
	function buildExpandedQueryStringValuePairs() {
			var queryString = "";

			for ( key in this.getKeys() ) {

					var item = this.getParameter(key, ",");
					var iArray = item.split(",");

					for(i = 0; i < iArray.length; i++) {
						if (queryString !== "" && iArray[i] !== "" && iArray[i] !== undefined) {
							queryString += '&';
						}
						if (iArray[i] !== "" && iArray[i] !== undefined) {
							queryString += key +'='+ iArray[i];
						}

					}
	    	}
	    	return queryString;
	}

	// buildUrl
	function buildExpandedUrl() {
		// for any jitterbug previews, append string to adserver call
		var sJitterbug = "";
		if( window.location.hostname.indexOf("jitterbug") != (-1) ) {
			sJitterbug = "&domain=jitterbug";
		}

		return this.getUrl() + this.buildExpandedQueryStringValuePairs() + sJitterbug;
	}

};


Ad.prototype = new SNI.Ads.Url();
function Ad()
{
	var url = new SNI.Ads.Url();
	this.addParameter = url.addParameter;
	this.getParameter = url.getParameter;
	this.getKeys = url.getKeys;
	this.buildUrl = url.buildUrl;
	this.buildExpandedUrl = url.buildExpandedUrl;

	var feature = new SNI.MetaData.Parameter();
	this.useFeature = useFeature;
	this.getFeature = getFeature;
	this.debug = debug;
	this.write = write;
    this.deferrable = 1;

	// add the parameter
	function useFeature(key) {feature.addParameter(key, "T");}

	// add the parameter
	function getFeature(key) {return feature.getParameter(key, ",");}

 	// this should be overloaded
	function debug() {document.write('<div style="background:red;color:white;">'+ this.buildExpandedUrl() +'</div>');}

	// this should be overloaded
	function write() {}
}


/* -------------------------------------------
Ad Object inherits paramter
------------------------------------------- */

DartAd.prototype = new Ad();
function DartAd()
{
	DartAd.prototype = new Ad();
	this.write = write;
	this.useFeature("site");
	this.useFeature("category");
	this.useFeature("vgncontent");
	this.useFeature("ord");
	this.useFeature("topic");
	this.useFeature("tile");
	this.useFeature("pagetype");
	this.useFeature("SECTION_ID");
	this.useFeature("SUBSECTION");
	this.useFeature("page");
	this.useFeature("uniqueid");
	this.useFeature("hubId");
	this.useFeature("hubType");
	this.useFeature("adkey1");
	this.useFeature("adkey2");
	this.useFeature("chef");
	this.useFeature("show");
	this.useFeature("delvfrmt");
	this.useFeature("source");
	this.useFeature("filter");
	this.useFeature("difficulty");
	this.useFeature("cuisine");
	this.useFeature("ingredient");
	this.useFeature("occasion");
	this.useFeature("mealpart");
	this.useFeature("technique");

	this.adClass = "AD_CLASS";

	function write() {
		if (navigator.userAgent.indexOf("#sni-loadtest#") !== -1) {
			// if this is a load-test (token detected in user agent string), don't make dart call
			return;
		}

		document.write('<script type="text/javascript" src="'+ this.buildExpandedUrl() +'"></script>');
	}
}

AdUrl.prototype = new Ad();
function AdUrl()
{
	AdUrl.prototype = new Ad();
	this.write = write;
	this.useFeature("site");
	this.useFeature("category");
	this.useFeature("vgncontent");
	this.useFeature("ord");
	this.useFeature("topic");
	this.useFeature("tile");
	this.useFeature("pagetype");
	this.useFeature("SECTION_ID");
	this.useFeature("SUBSECTION");
	this.useFeature("page");
	this.useFeature("uniqueid");
	this.useFeature("SearchKeywords");
	this.useFeature("SearchFilters");
	this.useFeature("hubId");
	this.useFeature("hubType");
	this.useFeature("adkey1");
	this.useFeature("adkey2");
	this.useFeature("chef");
	this.useFeature("show");
	this.useFeature("delvfrmt");
	this.useFeature("source");
	this.useFeature("filter");
	this.useFeature("difficulty");
	this.useFeature("cuisine");
	this.useFeature("ingredient");
	this.useFeature("occasion");
	this.useFeature("mealpart");
	this.useFeature("technique");

	function write() {}
}


DartAdvanceAd.prototype = new DartAd();
function DartAdvanceAd()
{
	DartAdvanceAd.prototype = new DartAd();
	this.write = write;
	this.align='';
	this.frameborder = 0;
	this.height='';
	this.longdesc='';
	this.marginheight=0;
	this.marginwidth=0;
	this.name='';
	this.scrolling = 'no';
	this.width = '100%';
	this.useIframe = false;

	function write() {
		if (navigator.userAgent.indexOf("#sni-loadtest#") !== -1) {
			// if this is a load-test (token detected in user agent string), don't make dart call
			return;
		}

		if(this.useIframe == false) {
			this.setUrl("http://"+SNI.Ads._adServerHostname+"/js.ng/");
			document.write('<script type="text/javascript" src="'+ this.buildExpandedUrl() +'"></script>');
		} else {
			this.setUrl("http://"+SNI.Ads._adServerHostname+"/html.ng/");
			document.write('<iframe src ="'+this.buildExpandedUrl()+'" align ="'+this.align+'" frameborder ="'+this.frameborder+'" height ="'+this.height+'" longdesc ="'+this.longdesc+'" marginheight ="'+this.marginheight+'" marginwidth ="'+this.marginwidth+'" name ="'+this.name+'" scrolling ="'+this.scrolling+'" width ="'+this.width+'"></iframe>');
		}
	}
}

/* -------------------------------------------
AdManager
------------------------------------------- */
function AdManager()
{
	var p = new SNI.MetaData.Parameter();
	this.addParameter = p.addParameter;
	this.getParameter = p.getParameter;
	this.getKeys = p.getKeys;
	this.createAd = createAd;
	this.createDeferredAd = createDeferredAd;
	this.moveAds = moveAds;
	this.ads = [];
	this.defer = false;

	if(document.deferAds !== null &&
	 	   document.deferAds == 1 &&
	   	   document.deferEnabled !== null &&
	   	   document.deferEnabled == 1) {
	   	   this.defer = true;
	 }

	// add the parameter
	function createAd(ad) {
		// add the site params
		for ( key in this.getKeys()) {
			if ( ad.getFeature(key) !== undefined) {
				ad.addParameter(key, this.getParameter(key, ','));
			}
 		}

		if(document.debug == 1) {
 			ad.debug();
		}
		ad.write();
	}

	// Create Deferred Ad
	function createDeferredAd(i) {
	}

	// Move Ads
	function moveAds() {
	}
}


// Url obj
function AdRestriction()
{
	var p = new SNI.MetaData.Parameter();
	// functions
	this.addParameter = p.addParameter;
	this.getParameter = p.getParameter;
	this.getKeys = p.getKeys;
	this.isActive = true;
	this.isIframe = false;

}

function AdDefault()
{
	var p = new SNI.MetaData.Parameter();
	// functions
	this.addParameter = p.addParameter;
	this.getParameter = p.getParameter;
	this.getKeys = p.getKeys;
	this.display = false;
}

function AdRestrictionManager() {
	this.restriction = [];
	this.adDefaults = [];
	this.isActive = isActive;
	this.isIframe = isIframe;
	this.isMatch = isMatch;
	this.startMatch = startMatch;
	// is active
	function isActive(ad, mdm) {
		var value = false;
		var adDefaultMatch = false;
		var defaultReturnValue = true;

		for (var i = 0; i < this.adDefaults.length; i++){
			adDefaultMatch = this.startMatch(ad, mdm, this.adDefaults[i]);
			if (adDefaultMatch == true) {
				defaultReturnValue = this.adDefaults[i].display;
				break;
			}
		}

		for (var i = 0; i < this.restriction.length; i++){
			adRestriction = this.restriction[i];
			if(!adRestriction.isActive) {
				value = this.startMatch(ad, mdm, adRestriction);
			}
			if(value == true) {
				return !defaultReturnValue;
			}
		}

		return defaultReturnValue;
	}

	// is Iframe
	function isIframe(ad, mdm) {
		var value = false;
		for (var i = 0; i < this.restriction.length; i++){
			adRestriction = this.restriction[i];
			if(adRestriction.isIframe) {
				value = this.startMatch(ad, mdm, adRestriction);
			}

		}
		return value;

	}

	function startMatch(ad, mdm, adRestriction) {
		var match = true;
		for ( var key in adRestriction.getKeys() ) {
					var restrictions = adRestriction.getParameter(key, ',');

					// get it from the mdm
					var value = mdm.getParameter(key, '----');
					match = this.isMatch(value, restrictions);

					// ad
					if(!match) {
						value = ad.getParameter(key, '----');
						match = this.isMatch(value, restrictions);
					}
					if(!match) {return false;}

		}
		return match;
	}

	function isMatch(value, restrictions) {
		var match = false;
		if(value) {
			splitValue = value.split('----');
			for(var x = 0; x < splitValue.length; x++) {
				if(restrictions == splitValue[x]) {match = true;}
				for(var a; a < restrictions.length; a++) {
					if(splitValue[x] == restrictions[a]) {
						return true;
					}
				}
			}
		}
		return match;
	}

}




function initAdManager(adm, mdm) {
	// adm = ad manager
	// mdm = metadata manager

	function admAppendParam(key, val) {
		// appends the parameter to the ad manager if val is not empty string
		if( val != "" ) {
			val = val.replace(/-/g, "_");		// replace all dashes with underscores
			val = val.replace(/ /g, "_");		// replace all spaces with underscores

			s = val.split(',', 1);				// just grab the first val of any multi-value string separated by commas
			adm.addParameter(key, s);

			//alert("key = " + key + ", val = " + s);			// debug
		}
	}


	var ranNum = String(Math.round(Math.random()*10000000000));
	var now = new Date();
	var ad_ord = now.getTime()%10000000000;

	var amPageType = mdm.getPageType() ;
	var amSponsorship = mdm.getSponsorship();
	var amKeywords = mdm.getKeywords();
	amPageType = amPageType.replace(/-/g , "_");

	var amUniqueId = mdm.getUniqueId();
	amUniqueId = amUniqueId.replace(/-/g , "_");

	if (amSponsorship !== "" && amSponsorship !== undefined) {
		amSponsorship = amSponsorship.replace(/-/g , "_");
		amSponsorship = amSponsorship.replace(/ /g , "_");
	}

	if (amKeywords !=="" && amKeywords !== undefined) {
		amKeywords = amKeywords.replace(/,/g , "_");
	}

	amSctns = mdm.getClassification();
	amSctns = amSctns.split(",");

	if (amSctns.length > 1) {
		for (var i=0; i < amSctns.length; i++) {
			if (i == (amSctns.length-1)) {
				adm.addParameter("sitesection", amSctns[i]);
			} else if (i == (amSctns.length-2)) {
				adm.addParameter("category", amSctns[i]);
			} else if (i == (amSctns.length-3)) {
				adm.addParameter("vgncontent", amSctns[i]);
			} else {
				adm.addParameter("SUBSECTION", amSctns[i]);
			}
		}
	} else {
		var c = mdm.getClassification();
		adm.addParameter("category", c );
	}

	if (amPageType == 'SECTION') {
		if (!adm.getParameter("vgncontent", " ")) {
			adm.addParameter("page", "MAIN");
		}
	}
	var s = mdm.getSite();
	adm.addParameter("site",s );
	var gsId = mdm.getSctnId();
	adm.addParameter("tile", ranNum +  gsId );
	adm.addParameter("ord", ad_ord);
	adm.addParameter("topic", amSponsorship);
	adm.addParameter("keywords", amKeywords);
	adm.addParameter("pagetype", amPageType);
	adm.addParameter("uniqueid", amUniqueId);
	var sId = mdm.getSctnId();
	adm.addParameter("SECTION_ID", sId);

	// these first column keys need to match with this.useFeature(key) from the DartAd() and AdUrl() objects
	admAppendParam("hubId", mdm.getParameterString("HubId"));
	admAppendParam("hubType", mdm.getParameterString("HubType"));
	admAppendParam("adkey1", mdm.getParameterString("AdKey1").toUpperCase());
	admAppendParam("adkey2", mdm.getParameterString("AdKey2").toUpperCase());
	admAppendParam("delvfrmt", mdm.getParameterString("DelvFrmt"));
	admAppendParam("source", mdm.getParameterString("Source"));
	admAppendParam("filter", mdm.getParameterString("filter"));
	admAppendParam("chef", mdm.getParameterString("ChefName"));
	admAppendParam("show", mdm.getParameterString("Show_Abbr"));
	admAppendParam("difficulty", mdm.getParameterString("Difficulty"));
	admAppendParam("cuisine", mdm.getParameterString("Cuisine"));
	admAppendParam("ingredient", mdm.getParameterString("MainIngredient"));
	admAppendParam("occasion", mdm.getParameterString("Occasion"));
	admAppendParam("mealpart", mdm.getParameterString("MealPart"));
	admAppendParam("technique", mdm.getParameterString("Technique"));
}








/**
 * ad functions
 *
 * requires core ads functionality from sni-global.js
 * requires mdManager (uses mdManager within functions, but not during load)
 */


function writeAd(ad){
	if (typeof adRestrictionManager != 'undefined') {
		ad.useIframe = adRestrictionManager.isIframe(ad, mdManager);
		if( adRestrictionManager.isActive(ad, mdManager) != false) {
			adManager.createAd(ad);
		}
	} else {
		adManager.createAd(ad);
	}
}


//Video PreRoll & Overlay Ad functions for Maven, Pickle
function VideoPlayerAd(adtype, adsize, pos) {
	var ad = new AdUrl();

	ad.setUrl("http://"+SNI.Ads._adServerHostname+"/html.ng/");
	if (adtype != '') {	ad.addParameter("adtype", adtype); }
	if (adsize != '') { ad.addParameter("adsize", adsize); }
	if (!pos || pos=='') { pos = 1; }
	ad.addParameter("PagePos", pos);
	ad.useFeature("tile");
	writeAd(ad);

   return ad.buildExpandedUrl();
}


// Video Player Ad Integration
// The video player will make calls to the following javascript functions to
//    1. Get a Dart ad tag url for PRE_ROLL and OVERLAY ads.
//--Wrapper function which the video player calls to get a preroll ad tag url -->
function getDartEnterpriseUrl(adtype,pos){
   		adtype = adtype.toUpperCase();
   		var strUrl = VideoPlayerAd(adtype,'', pos);
   		return strUrl;
}


function setDartEnterpriseBanner(adType, sync_banner) {
	if (adType == 'LEADERBOARD') {
	  var oAd = document.getElementById('leaderboard');
	  if(oAd) {
			boxW = 728;
			boxH = 90;
			oAd.innerHTML = "<iframe src=\'" + sync_banner + "\' width=\'" + boxW + "\' height=\'" + boxH + "\'" + "frameborder='0' scrolling='no' marginheight='0' marginwidth='0'></iframe>";
		}
	} else { // assumes adType == 'BIGBOX' or should
	  var oAd = document.getElementById('bigbox');
		if(oAd) {
			boxW = 300;
			boxH = 250;
			if (sync_banner.indexOf("336x850") > -1) {
				boxW = 336;
				boxH = 850;
			} else if (sync_banner.indexOf("300x600") > -1)	{
				boxW = 300;
				boxH = 600;
			}
			oAd.innerHTML = "<iframe src=\'" + sync_banner + "\' width=\'" + boxW + "\' height=\'" + boxH + "\'" + "frameborder='0' scrolling='no' marginheight='0' marginwidth='0'></iframe>";
		}
	}
	return;
}

