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

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

fox.site.insertHeader = function(){
	if(typeof fnc === "object"){
		if(typeof fnc.get_fnc_header === "function"){
			fnc.get_fnc_header();
		}	
	}
};

fox.site.insertFooter = function(){
	if(typeof fnc === "object"){
		if(typeof fnc.get_fnc_footer === "function"){
			fnc.get_fnc_footer();
		}	
	}
};

fox.site.topInit = function(){
	vcs.init();
	this.pdata = window.pd; 
	window.pd = this.pdata;
	this.ads.init();
};

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

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();
			utils.runJsCodeAfterThisScriptTag("fox.site.tracking.googleAnalyticsInit();");
			utils.runJsCodeAfterThisScriptTag("fox.site.tracking.loomiaInit();");
		},
		
		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) {}
		},
		
		loomiaInit : function(){
			//loads the script include for google analytics 
			utils.runJsSrcAfterThisScriptTag("http://fox-recs.loomia.com/pub/1566965288/item/home/related?zone=5&callback=parseLoomia");
			$.ad.loom.pre();
		},
		
		hitboxInit : function() {
			// global
		    loc = location.href;

		    // 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
		    if (location.host.match(/^www\./i) == null)
		      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);
		} 	
}; 
	
fox.site.ads = {
		
	writeInline : function(id, type){
		
		utils.debug("starting writeInline");
		
		if( !this.isNewLibrary() ){
			if("dc" === type){
				utils.debug("doing inline dc ad");
				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 {
				utils.debug("inline ads are not enabled");
			}
		}
	},
	
	isNewLibrary : function() {
		return (utils.queryString.param.get("t") === "newads");
		//return false;
	},
	
	init : function() {
		
		if( this.isNewLibrary() ){

			window.ad = $.ad;
			
			$(document).ready(function(){
				var pd= fox.site.pdata;
				ad.init({channel: pd.breadcrumb, ptype: pd.page_type, ctype: pd.channel_type, pageid: pd.vcmid, categories: pd.categories}, "server");
			});
		
			
		} else {

			try{ // this function will be removed once the new framework is working
				var pd = fox.site.pdata;
				var site = pd.top_site_name==="sbc"?"fsb":"fnc";				
				window.adata = ad.lookup( {site: site, channel: ad.util.getLRC(pd.breadcrumb), path: pd.breadcrumb, leaf: pd.channel, ptype: pd.page_type, ctype: pd.channel_type, pageid: pd.vcmid, categories: pd.categories} );
			} catch(err) { utils.debug("can't load ad lib"); }			
			
			
			
		}

		utils.runJsSrcAfterThisScriptTag("http://www.foxnews.com/js/dm_client.js");
		utils.runJsSrcAfterThisScriptTag("http://js.revsci.net/gateway/gw.js?csid=E05510");

	}	
};

var utils = new Object();

/*
 * Gets querystring values from the document's location
 */
utils.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 = 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
 */
utils.getObjectProperties = function(prefix, object){
	var newobject = new Object();
	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
 */
utils.extendObject = function(object_target, object_source){
	//return $.extend(object_target,object_source);
	for (myvar in object_source) {
		object_target[myvar] = object_source[myvar];
    }
    return object_target;
};

/*
 * Shallow copy of object
 */
utils.cloneObject = function(obj){
    var temp = new Object();
    for (myvar in obj) {
        temp[myvar] = obj[myvar];
    }
    return temp;
};

utils.debug = function(data) {
	if( utils.queryString.param.get("_debug") === "true" && ! $.browser.msie){
		try {
			console.log(data)
		} catch(err) {}
	}
};

/*
 * Programmatically add a javascript include/execute after the execution of the current tag the script is running
 */
utils.runJsSrcAfterThisScriptTag = function (url){
	document.write(unescape("%3Cscript src='" + url + "' type='text/javascript'%3E%3C/script%3E"));
};

/*
 * Programmatically add a javascript code to execute after the execution of the current tag the script is running
 */
utils.runJsCodeAfterThisScriptTag = function(jscode){
	document.write(unescape("%3Cscript type='text/javascript'%3E" + jscode + "%3C/script%3E"));
};

/*
 * format a js date object to a string like "September 02, 2009"
 */
utils.formatUTCDate = function(jsDate){
	var month = utils.getUTCMonthString(jsDate.getUTCMonth());
	var dateString = jsDate.toDateString(); //Wed Sep 02 2009
	return month + ' ' + dateString.substr(8).replace(' ', ', ');
};

utils.getUTCMonthString = function(utcMonthNumber){
    var month=new Array(12);
	month[0]="January";
	month[1]="February";
	month[2]="March";
	month[3]="April";
	month[4]="May";
	month[5]="June";
	month[6]="July";
	month[7]="August";
	month[8]="September";
	month[9]="October";
	month[10]="November";
	month[11]="December";	
	return month[utcMonthNumber];
};


/**
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;}


/**
 * Functions for Featured Slider
 */
var btRotate = true;
var btCounter = 1;
var btTimeout;
var btMouseOver = false;
function featureBtItem(t) {
    if (!btMouseOver && !$(t).parent('h2').hasClass('selected')) {
        btMouseOver = true;
        $('#big-top ul li h2.selected').removeClass('selected');
        $(t).parent('h2').addClass('selected');
        $('#big-top > p > span').html($(t).parent('h2').html());
        $('#big-top > p > span > a > span.title').css('display','none');
        $('#big-top > p > span > a > span.deck').css('display','block');
        var thisImage = $(t).parent('h2').prev('a').children('img');
        $('#big-top ul li img:visible').fadeOut(50,
        function() {
            $(thisImage).fadeIn(50,
            function() {
                btMouseOver = false;
            });
        });
    }
}
function rotateBt() {
    if (btCounter == $('#big-top ul li').size()) {
        btCounter = 0;
        btRotate = false;
    }
    featureBtItem($('#big-top ul li:eq(' + btCounter + ') h2 a'));
    btCounter++;
    startTimeout(5000);
}
function startTimeout(t) {
    clearTimeout(btTimeout);
    if (btRotate) {
        btTimeout = setTimeout("rotateBt()", t);
    }
}       

/*
 * 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 = new Object();
pagedescriptor.isSiteInit    = false;
pagedescriptor.isSectionInit = false;
pagedescriptor.isPageInit    = false;

/*
 * Meta initialization functions
 */
pagedescriptor.initSiteMeta = function(params){
	if(this.isSiteInit === false){
		this.isSiteInit = true;
		this.sitemeta = params;	
	}
}
pagedescriptor.initSectionMeta = function(params){
	if(this.isSectionInit === false){
		this.isSectionInit = true;
		this.sectionmeta = params;	
	}
}
pagedescriptor.initPageMeta = function(params){
	if(this.isPageInit === false){
		this.isPageInit = true;
		this.pagemeta = params;	
	}
}
/*
 * Meta get functions
 */
pagedescriptor.getSiteMeta = function(){
	return this.sitemeta;
}
pagedescriptor.getPageMeta = function(params){
	return this.pagemeta;	
}
pagedescriptor.getSectionMeta = function(){
	return this.sectionmeta;
}
/*
 * Meta set functions
 */
pagedescriptor.setSiteMeta = function(params){
	utils.extendObject(this.sitemeta, params);	
}
pagedescriptor.setSectionMeta = function(params){
	utils.extendObject(this.sectionmeta, params);
}
pagedescriptor.setPageMeta = function(params){
	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]);    
          }
        }
    }   
}

