//Moving forward.. please add custom objects to the fox namespace. some objects are colliding with external scripts 
var fox = { 
	widgets: {},
	site: {},
	utils: {}
};

/* 	NEW UTILS NAMESPACE 
	New Global utils should be added to the fox.utils namespace.
	Requirements: 
	- Use native functions. Avoid using jQuery or other js framework when building new util files
	- Comment appropriately
*/
fox.utils = {

	//Gets querystring values from the document's location
	queryString: {
		empty: function(){ return (window.location.search=="")?true:false; },
		get: function(){ return (this.empty())?null:window.location.search.substring(1); },
		param: {
			exists: function(p) { return (!utils.queryString.empty() && utils.queryString.get().toLowerCase().indexOf(p.toLowerCase()+'=') > -1)?true:false; },
			get: function(p) {
				var value = null;
				if (this.exists(p)) {
					var s = fox.utils.queryString.get().split('&');
					for (var i=0;i<s.length;i++) {
						var e = s[i].split('=');
						if(e[0].toLowerCase() == p.toLowerCase() && e[1]) { value = e[1] };
					}
				}
				return (value!=null)?decodeURIComponent(value):null;
			}
	   }
	},
	
	// Gets a select set of properties from the object passed. 
	// This is useful for assisting factory methods
	getObjectProperties: function(prefix, object){
		var newobject = {};
		for (var o in object) { 
			if (o.indexOf(prefix)==0) {
				var propertyname = o.substr(prefix.length);
				newobject[propertyname] = object[o];
			}
	 	}
		return newobject;
	},
	
	// Same logic as the jQuery.extend function.. but without the jQuery dependency
	extendObject: function(objTarget, objSource) {
		for (i in objSource) { objTarget[i] = objSource[i]; }
	    return objTarget;
	},
	
	// Shallow copy of object
	cloneObject: function(obj) {
	    var temp = {};
	    for (i in obj) { temp[i] = obj[i]; }
	    return temp;
	},
	
	// Debug console
	debug: function(data) {
		if( fox.utils.queryString.param.get("_debug") === "true") {
			try { fox.utils.console(data); } 
			catch(err) { fox.utils.console("[global.js] debug error: "+err); }
		}
	},
	
	// Utilizes firebug console
	console: function(data) {
		data = data||null;
		if (typeof(window.console)==='object' && data!=null) { console.log(data); }
	},
	
	// Programmatically add a javascript include/execute after the execution of the current tag the script is running
	runJsSrcAfterThisScriptTag: function(url) {
		try { document.write(unescape("%3Cscript src='" + url + "' type='text/javascript'%3E%3C/script%3E")); }
		catch(err) { fox.utils.console("[global.js] js code source tag error: "+err); }
	},
	
	// Programmatically add a javascript code to execute after the execution of the current tag the script is running
	runJsCodeAfterThisScriptTag: function(jscode) {
		try { document.write(unescape("%3Cscript type='text/javascript'%3E" + jscode + "%3C/script%3E")); } 
		catch(err) { fox.utils.console("[global.js] js code include tag error: "+err); }
	},
	
	// IFrame resizer - will get the iframe content's specified outer height; iframe source should call this
	// Limitations: non cross-browser compatible
	resizeIFrame: function(obj) {
		obj = obj || false;
		if (!obj) return false;
		var target = obj.target;
		// if not jquery object
		if (typeof target.jquery==='undefined') { target = $(target); }
		var src = obj.src;

		$("iframe").each(function(){
			var IF = $(this);
			if (typeof IF.attr("src")!=='undefined') {
				if (IF.attr("src").indexOf(src)>-1 && !IF.data("resized")) {
					IF.css({
						height: target.outerHeight(true),
						width: IF.parent().innerWidth()
					});
					IF.data("resized",true); // set listener
				}
			}
		});
	}
};
	
//utils for date/time items
fox.utils.datetime = {
	
	/*	date/time formatting
		Sample usage:
			var dateObj = new Date();
			fox.utils.datetime.format(dateObj,"Today is: ${ddTH} of ${month} ${yr}");
			
			- will return string: Today is 9th of December 2009
	*/
	format: function(date,formatStr) {
		formatStr = formatStr||null; // format is optional
		
		var obj = {
			// date
			month: date.getUTCMonth(),
			day: date.getDay(),
			year: date.getFullYear(),
			"date": date.getDate(),
			// time
			hour: date.getHours(),
			minutes: date.getMinutes(),
			seconds: date.getSeconds(),
			ampm: ((date.getHours()<12)?'am':'pm'),
			
			fullStr: date.toString()
			
		};
		
		var replace = {
			"${mm}": (obj.month+1),
			"${month}": this.getUTCMonthString(obj.month),
			"${month:short}": this.getUTCMonthString(obj.month,'short'),
			
			"${day}": this.getDayString(obj.day),
			"${day:short}": this.getDayString(obj.day,'short'),
			
			"${yr}": obj.year,
			"${dd}": ((obj.date<10)?'0'+obj.date:obj.date),
			"${ddTH}": this.oldEnglish(obj.date),
			
			"${hr}": ((obj.hour>12)?obj.hour-12:obj.hour),
			"${hr:mil}": obj.hour,
			
			"${min}": ((obj.minutes<10)?'0'+obj.minutes:obj.minutes),
			"${sec}": ((obj.seconds<10)?'0'+obj.seconds:obj.seconds),
			"${ampm}": obj.ampm,
			"${AMPM}": (obj.ampm).toUpperCase(),
			"${AmPm}": ((obj.ampm).charAt(0)).toUpperCase()+(obj.ampm).charAt(1)
		};
		
		if (formatStr==null) { // from old format date
			var month = this.getUTCMonthString(obj.month);
			var dateString = date.toDateString(); //Wed Sep 02 2009
			return month + ' ' + dateString.substr(8).replace(' ', ', ');
		} else {
			for (i in replace) {
				formatStr = formatStr.replace(i,replace[i]);
			}
			return formatStr;
		}
		
	},
	
	// old english(?) format
	oldEnglish: function(num) {
		num+="";
		var lastDigit = parseInt(num.charAt(num.length-1));
		switch (lastDigit) {
			case 1: { num+="st";break; }
			case 2: { num+="nd";break; }
			case 3: { num+="rd";break; }
			default: { num+="th";break; }
		}
		return num;
	},
	
	// clone
	formatUTCDate: function(date,formatStr) { 
		return fox.utils.datetime.format(date,formatStr); 
	},
	
	// Return month string
	getUTCMonthString: function(monthNum,type) {
		type = type||'full'; //type is optional
		var month;
		switch (type) {
			case "short": { month = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];break; }
			default: { month = ["January","February","March","April","May","June","July","August","September","October","November","December"];break; }
		}
		return month[monthNum];
	},
	
	// Return week days string
	getDayString: function(dayNum,type) {
		type = type||'full';
		var day;
		switch (type) {
			case "short": { day = ["Sun","Mon","Tue","Wed","Thur","Fri","Sat"];break; }
			default: { day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];break; }
		}
		return day[dayNum];
	}
	
};

//Access for deprecated util calls. Use the new fox.utils namespace moving forward
var utils = {
	queryString: fox.utils.queryString,
	getObjectProperties: fox.utils.getObjectProperties,
	extendObject: fox.utils.extendObject,
	cloneObject: fox.utils.cloneObject,
	debug: fox.utils.debug,
	runJsSrcAfterThisScriptTag: fox.utils.runJsSrcAfterThisScriptTag,
	runJsCodeAfterThisScriptTag: fox.utils.runJsCodeAfterThisScriptTag,
	formatUTCDate: fox.utils.datetime.formatUTCDate,
	getUTCMonthString: fox.utils.datetime.getUTCMonthString
};

/* ---- end fox utils ----- */

// VCS Object
var vcs = {};
vcs.init = function(){
	$.include(pagedescriptor.getSiteMeta().static_asset_all_js + '/vcs.js');
};

// header/footer insert
fox.site = {

	insertHeader: function(){
		if(typeof fnc === "object"){
			if(typeof fnc.get_fnc_header === "function") { fnc.get_fnc_header(); }	
		}
	},
	
	insertFooter: function(){
		if(typeof fnc === "object"){
			if(typeof fnc.get_fnc_footer === "function") { fnc.get_fnc_footer(); }	
		}
	},
	
	topInit: function(){
		vcs.init();
		this.pdata = window.pd; 
		window.pd = this.pdata;
		fox.site.ads.init();
	},

	bottomInit: function(){
		fox.site.tracking.init();
	}
	
}

// tracking
fox.site.tracking = { 

	init: function() {
		if( fox.site.pdata.is_mgmt === "false" ){
			// utils.runJsSrcAfterThisScriptTag("http://www.foxnews.com/js/hbx_1.js");
			// utils.runJsCodeAfterThisScriptTag("fox.site.tracking.hitboxInit();");
			// utils.runJsSrcAfterThisScriptTag("http://www.foxnews.com/js/hbx_3.js");
		}
		fox.site.tracking.googleAnalyticsInclude();
		fox.utils.runJsCodeAfterThisScriptTag("fox.site.tracking.googleAnalyticsInit();");
		fox.utils.runJsCodeAfterThisScriptTag("fox.site.tracking.loomia.tracker();");
	},
	
	googleAnalyticsInclude: function(){
		//loads the script include for google analytics 
		var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); 
		document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); 
	},
	
	googleAnalyticsInit: function() { //loads the script include for google analytics 
		try { 
			if(pd.top_site_name == "sbc"){ 
				var pageTracker = _gat._getTracker("UA-3128154-10"); pageTracker._setDomainName(".foxsmallbusinesscenter.com"); pageTracker._trackPageview(); 
			} else { 
				var pageTracker = _gat._getTracker("UA-3128154-2"); pageTracker._setDomainName(".foxnews.com"); pageTracker._trackPageview(); 
			} 
		} 
		catch(err) { fox.utils.console("[global.js] GA Init Error: " + err); }
	},
	
	loomia: {
		feed: { 
			sbc: "http://fox-recs.loomia.com/pub/4068804847/item/home/related?zone=5",
			fn: "http://fox-recs.loomia.com/pub/1566965288/item/home/related?zone=5"
		},
		getFeed: function(callback) { // loomia feeds
			if (!callback) { fox.utils.console("[global.js] Loomia Feed Callback Missing "); return false; } // no callback - don't trigger
			if (typeof this.feedLoaded==='undefined') { this.feedLoaded = false; } // initialize listener
			var site = pd.top_site_name;
			this.feedUrl = (typeof this.feed[site]!=='undefined') ? this.feed[site] : this.feed.fn;
			var feedUrl = this.feedUrl+"&callback="+callback;
			if (!this.feedLoaded) { // load feed only once
				fox.utils.runJsSrcAfterThisScriptTag(feedUrl);
				this.feedLoaded = true;
			}
		},
		tracker: function() { // loomia tracker
			if (typeof this.tracked==='undefined') { this.tracked = false; } // initialize listener
			try {
				if (!this.tracked) { // load only once
					$.ad.loom.pre(); 
					this.tracked = true;
				} 
			} catch(err) {
				fox.utils.console("[global.js] Loomia Tracker Error: " + err);
			}
		}
	},
	
	hitboxInit: function() {
	    var loc = location.href; // global
	    // remove url parameters and hash marks
	    loc = loc.replace(/\?.+$/, "");
	    loc = loc.replace(/#$/, "");		    
	    if (loc.substring(loc.length-1) != "/") { loc += "/"; }

	    // use development hbx account if we're not in production
	    hbx.acct = "DM550608L3WD";
		  
		var pd = fox.site.pdata;
	    var hbxSectionName = pd.channel.replace(/&/g, "and");
	    var hbxPageName = "";
	    var hbxPageType = (pd.page_type=="channel") ? pd.channel_type : pd.page_type;
	    var miscPage = "";
	    var columnName = (pd.page_type == "channel" && pd.channel_type == "column") ? pd.channel : "";
	    var hbxContentCat = "/" + pd.section_type + pd.breadcrumb.replace(/\/Home/i,"") + "/" + hbxPageType;

    	if (pd.page_type=="channel"&&pd.channel_type=="front") {
	      	hbxPageName = ad.hbx.strip(hbxSectionName);
	    } else if (pd.page_type=="slideshow") {
	      	hbxPageName = "/" + loc.split("/")[loc.split("/").length-2];
	      	hbxContentCat = "/news/" + pd.breadcrumb.replace(/^\/Home\//i,"") + "/slideshows";
	    } else if (pd.page_type=="column-archive") {
	      	hbxPageName = ad.hbx.strip(columnName);
	    } else if (pd.page_type=="story") {
	        //hbxPageName = ad.hbx.strip(pd.vcmid + " - " + hbxSectionName + " - " + pd.trackingmeta.title.replace(/"/g, ""));
	        hbxPageName = "/" + ad.hbx.strip(hbxSectionName + " - " +pd.trackingmeta.title.replace(/"/g, "")); 
	    } else {
	      	hbxPageName = ad.hbx.strip(hbxPageType);
	    }

	    //hbx calls
	    hbx.pn = hbxPageName; //PAGE NAME(S)
	    hbx.mlc = ad.hbx.strip(hbxContentCat); //MULTI-LEVEL CONTENT CATEGORY
		
	    if (pd.page_type=="story") {
	      	hbx.ci = "";//CUSTOMER ID
	      	if (pd.trackingmeta.byline) {
				hbx.hc1 = pd.trackingmeta.byline;//CUSTOM 1
			} else { hbx.hc1 = ""; }

	      	hbx.hc2 = ad.hbx.meta(3,hbx.pn);//CUSTOM 2
	      	hbx.hc3 = pd.vcmid + "|" + hbxPageName;//CUSTOM 3
	    }

	    //insert custom events
	    var cv = ad.hbx.evt("cv");

	    if (pd.page_type=="channel"&&pd.channel_type=="column") {
	      	cv.c8 = ad.hbx.strip(columnName) + "|" + hbxPageName;
	    }

	    cv.c9 = ad.hbx.strip(hbxSectionName) + "|" + hbxPageName;

	    if (pd.page_type=="channel"&&pd.channel_type=="front") {
	      	cv.c11 = ad.hbx.strip(hbxSectionName);
	    }
	
	    hbx.hc4 = ad.hbx.strip(hbxPageType) + "|" + ad.hbx.strip(hbxSectionName);
	
	} 	
}; 

//ads
fox.site.ads = {
		
	writeInline: function(id, type){
		
		fox.utils.debug("[global.js] starting writeInline");
		
		if("dc" === type){
			utils.debug("doing inline dc ad");
			$.ad.dc.inline(id);
			//document.write(ad.dc.tag(window.adata, ad.dc.tile(), id));
		} else if ("qu" === type) {
			//document.write(ad.qu.tag(window.adata, id));			
		} else if ("sponsor" === type){
			/*
			if (window.adata.spo!=undefined) {
                document.write(ad.dc.spo(window.adata, ad.dc.tile(), id));
            }
			*/
		} else {
			fox.utils.debug("[global.js] inline ads are not enabled");
		}
	
	},
	
	init: function() {
		
		$(document).ready(function(){ 
		    $.ad.init(); 
		}); 

	}	
};

/**
Number formatting function
copyright Stephen Chapman 24th March 2006, 22nd August 2008
permission to use this function is granted provided
that this copyright notice is retained intact
example: 
		formatNumber(3000000000,0,',','','','','-','');
**/
function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) {
	var x = Math.round(num * Math.pow(10,dec));
	if (x >= 0) n1=n2='';
	var y = (''+Math.abs(x)).split('');
	var z = y.length - dec; 
	if (z<0) z--; 
	for(var i = z; i < 0; i++) y.unshift('0'); 
	if (z<0) z = 1; y.splice(z, 0, pnt); if(y[0] == pnt) y.unshift('0'); 
	while (z > 3) {
		z-=3; y.splice(z,0,thou);
	}
	var r = curr1+n1+y.join('')+n2+curr2;
	return r;
}

/*
 * This object is used to store and manipulate page meta data. This meta data is used by services like, doubleclick, revenue science...
 * Each page has 3 data stores that are intended to mirror the business's need to classify areas of a site.
 * 
 * A html page is typically categorized by its: site/domain, site section, and page details. Each of these have 
 * initialization, set and get methods. 
 *  
 */
var pagedescriptor = {
	isSiteInit: false,
	isSectionInit: false,
	isPageInit: false,
	
	/*
	 * Meta initialization functions
	 */
	initSiteMeta: function(params){
		if(this.isSiteInit === false){
			this.isSiteInit = true;
			this.sitemeta = params;	
		}
	},
	initSectionMeta: function(params){
		if(this.isSectionInit === false){
			this.isSectionInit = true;
			this.sectionmeta = params;	
		}
	},
	initPageMeta: function(params){
		if(this.isPageInit === false){
			this.isPageInit = true;
			this.pagemeta = params;	
		}
	},
	
	/*
	 * Meta get functions
	 */
	getSiteMeta: function(){
		return this.sitemeta;
	},
	getPageMeta: function(params){
		return this.pagemeta;	
	},
	getSectionMeta: function(){
		return this.sectionmeta;
	},
	
	/*
	 * Meta set functions
	 */
	setSiteMeta: function(params){
		fox.utils.extendObject(this.sitemeta, params);	
	},
	setSectionMeta: function(params){
		fox.utils.extendObject(this.sectionmeta, params);
	},
	setPageMeta: function(params){
		fox.utils.extendObject(this.pagemeta, params);	
	}
	
};

/*
 * sharethis related functions
 */
function createShareThisMultiLink(shareBtn, linkName){
    if (shareBtn.length>=1) {
        if (typeof SHARETHIS !='undefined') {
          var shareThis = SHARETHIS.addEntry({},{button:false});
          if(linkName == 'email'){
            shareThis.attachChicklet("email", shareBtn[0]);
          }else{
            shareThis.attachButton(shareBtn[0]);    
          }
        }
    }   
}
