//Disqus Integration Service for V7 - updated: 09/13/2010
//Dependencies: jQuery
if (typeof fox === "undefined"){
	window.fox = {widgets:{environment:{}}};
}
(function($){

	var CONST_ThirdPartyConfig = {
			recaptcha: {
				url: "/ajax/authentication/recaptcha.jsp",
				elmId: "recaptcha_div",
				id: "6LcspgwAAAAAAPIfJ3yUt1aUl_Thr8TQfQmR1oRP", // this is a global ID newly defined for all of fox domains.
				settings: {
					theme: "clean"
				}
			},
			disqus: {
				widget: "DQIntegrationService",
				cookie: {
					name: "p_DQS",
					expires: 14 // days
				},
				hash: {
					empty: "e30=",
					expires: 60 // in minutes
				}
				, siteId: {
					qa: "fnqasite",
					fn: "foxnews",
					fnation: "nationfoxnews",
					fb: "foxbusiness",
					sbc: "foxsmallbusinesscenter",
					latino: "foxnewslatino",
					briansullivan : "briansullivanblog",
					gretawire : "gretawireblog",
					liveshots : "liveshots",
					politicsblog : "politicsblog"
				},
				ident: { // alway sync up if there are changes on the admin tool
					postCount: ["#dsq-total-posts","#dsq-num-posts"],
					postArea: "#dsq-new-post"
				}
			},
			idms: {
				cookie: {
					name: "p_IDMS",
					expires: 14 // days
				},
				hash: {
					empty: "e30=",
					expires: "5" // minutes
				},
				callback: {
					login: "FOX_IDMS_auth_logged_in",
					logout: "FOX_IDMS_auth_logged_in"
				}
			}
		};	
/*	function getDomainHost() {
		if (fox.widgets.environment.getDomainHost) {
			return fox.widgets.environment.getDomainHost(true,true);
		}
		
		var host = window.location.hostname;
		var pieces = host.split('.');
		return "http:\/\/www." + pieces[(pieces.length - 2)] +'.'+ pieces[(pieces.length - 1)];
	}
*/
	fox.widgets.environment = {
	get: function() {
		var host = document.location.hostname;
		return (this.isProd(host)) ? "dev" : "prod"; 
	},
	getDomainHost: function(useProtocol,prod) {
		useProtocol = useProtocol || false; // use protocol
		prod = prod || false; // add www if applicable
		
		var loc = window.location;
		var host = loc.hostname;
		//return host;
		var protocol = loc.protocol;
		return protocol + "\/\/" + host;
	},
	check: function(host,type) {
		host = host.toLowerCase();
		var env = [ "beta.", ".tpa.", "beta-drupal." ]; // production environment sub-domains
		var bool = true;
		var isProd = true;

		for (var x = 0; x < env.length; x++) {
			if (host.indexOf(env[x]) > -1) { isProd = false; break; }
		}

		if (type==="prod") { bool = isProd; } 
		else if (!isProd) {	bool = false; }
		return bool;
	},
	isProd: function(host) {
		host = host || document.location.hostname;
		return this.check(host,"prod");
	},
	isDev: function(host) {
		host = host || document.location.hostname;
		return this.check(host,"dev");
	}
};
/*	Third Party commenting system
	******************************/
	function DisqusAPI() {
		this.hasLoaded = false;
		this.hasTriggered = false;
		this.data = {};
		this.init();
	}

	DisqusAPI.prototype = {
		init: function(config) {
			for (i in config) {
				this.data[i] = config[i];
			}		
			this.ext.root = this.set.root = this;
		},
		isFoxLoggedIn: function() {
			if (typeof authentication_service!=="undefined") {
				return (authentication_service.isLoggedIn()) ? true : false ;
			}
			return false;
		}
	};

	DisqusAPI.prototype.set = {
		loaded: function() {
			var DQ = this;
			var root = this.root;
			var serviceCfg = this.root.data.serviceCfg;
		},
		postArea: function() {
			var root = this.root;
			var cfg = CONST_ThirdPartyConfig.disqus;
			
			// forcefully hide the post area if the user is actually "logged out" of our system
			// Disqus has a persistent cookie with session that still have the user as "looged in".
			if (!root.isFoxLoggedIn()) {
				$(cfg.ident.postArea).css("display","none");
			}
		},
		emailSubscription: function() {
			var root = this.root;
			var serviceCfg = this.root.data.serviceCfg;

			// hide email subscription if you are not FN logged in
			if (!root.isFoxLoggedIn()) {
				$(serviceCfg.target).find(".dsq-subscribe-email").children(":not(.dsq-subscribe-rss):not(hidden)").hide();
			}
		},
		commentButtons: function() {
			var root = this.root;
			var serviceCfg = this.root.data.serviceCfg;
			
			if (root.isFoxLoggedIn()) {
				// reply button			
				$(serviceCfg.target).find(".dsq-comment-footer-reply:is(hidden)").css("display","inline");
				
				// edit button
				$(serviceCfg.target).find(".dsq-post-edit:is(hidden)").css("display","inline");
				
			}
		}
	};

	// external calls
	DisqusAPI.prototype.ext = {
		loaded: function(info) {
			if (!this.root.hasLoaded) { this.root.hasLoaded = true; }
			this.root.set.loaded(); // set load requirements
			return this.root.hasLoaded;
		},
		serviceTrigger: function(cfg) {
			cfg = cfg || false;
			if (!cfg) { return false; }
			
			this.root.hasTriggered = true;
			this.root.data.serviceCfg = cfg;
			
			this.insertScript(false);
		},
		insertScript: function(force) { // insert disqus script for article commenting 
			force = (typeof force==="undefined") ? false : force;
			
			var self = this;
			
			var root = this.root;

			function trigger() {
				var cfg = CONST_config;
				if (!cfg) { showToConsole("[disqus.api] No Service Configuration set to insert API script file."); return false; }

				var disqusElm = $(cfg.target);
				if (disqusElm.size()===0) { return false; }

				var embedJS = cfg.url;
				var embedElm = $("script[src*='"+embedJS+"']");

				if (embedElm.size()>0) { // clear
					if (!force) { return false; } // only load once if not forced
					embedElm.remove();
					disqusElm.html("");
				}

				(function() {
					var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
					dsq.src = embedJS;
					(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
				})();
			}
			
			$.loadAttempt({
				maxAttempts: 30, // interval
				timeout: 500, // in ms
				callback: {
					check: function() {
						return (root.hasTriggered) ? true : false;
					},
					success: function() {
						trigger();
					}
				}
			});
			
		},
		getDomainId: function() {
			var root = this.root;
			var cfg = CONST_ThirdPartyConfig.disqus;
			
			var siteId = cfg.siteId.qa; // default value is qa site

			if (fox.widgets.environment.isProd()) {
				var idVar = window.location.href;
				idVar = idVar.toLowerCase();
				
				if (idVar.indexOf("latino.foxnews")>-1) {
					return cfg.siteId.latino;
				} else if (idVar.indexOf("nation.foxnews")>-1) {
					return cfg.siteId.fnation;
				} else if (idVar.indexOf("smallbusiness")>-1) {
					return cfg.siteId.sbc;
				} else if (idVar.indexOf("briansullivan.blogs")>-1) {
					return cfg.siteId.briansullivan;
				} else if (idVar.indexOf("gretawire.blogs")>-1) {
					return cfg.siteId.gretawire;
				} else if (idVar.indexOf("liveshots.blogs")>-1) {
					return cfg.siteId.liveshots;
				} else if (idVar.indexOf("politics.blogs")>-1) {
					return cfg.siteId.politicsblog;
				} else if (idVar.indexOf("foxnews")>-1) {
					return cfg.siteId.fn;
				} else if (idVar.indexOf("foxbusiness")>-1) {
					return cfg.siteId.fb;
				}
			}else{
				window.disqus_developer = 1;
			}
			
			return siteId;
		},
		setPostNum: function(callbackFn) {
			callbackFn = callbackFn || false;
			var timeout = false;
			var max = 30;
			var attempt = 0;
			var cfg = CONST_ThirdPartyConfig.disqus;
			
			function set(elm) {
				var num = 0;
				if ($.trim(elm.text()).length > 0) {
					if (!isNaN(elm.text())) {
						num = parseInt(elm.text(),10);
					}
				}
				
				if (callbackFn) { callbackFn(num); }
			}
			
			$.loadAttempt({
				maxAttempts: 30, // interval
				timeout: 500, // in ms
				callback: {
					check: function() {
						return ($(cfg.ident.postCount[1]).size()>0) ? true : false;
					},
					success: function() {
						var countElm = ($(cfg.ident.postCount[0]).size()>0) ? $(cfg.ident.postCount[0]) : $(cfg.ident.postCount[1]);
						set(countElm);
					},
					timedOut: function() {
						// timed out, exhausted attempts
					}
				}
			});
			
			
		}
	};	

/* 
	priority:
	1. meta tag
	2. title tag
*/
function getArticleTitle() {
	var metaTitle = $("meta[name='dc.title']");
	var titleStr = false;
	
	if (metaTitle.size()>0) {
		titleStr = metaTitle.attr("content");
	} else {
		titleStr = $.trim($("title:first").text());
	}
	return titleStr;
}

var configTriggered = false;
//Disqus config
function onReadyTrigger() {
	configTriggered = true;
	ThirdPartyAPI.set.postArea();
	// if commenting is already closed
	if ($(".dsq-missing-permissions p.cmt-closed").size()===0) {
		// show comments
		$("#introduction .user-interaction > li.comments").css({ display:"list-item" });
	} else {
		// hide all commenting except the alert
		$("#dsq-content").children(":not(.dsq-missing-permissions)").hide();
		$("p#lgn-disqus.login-link").hide();
		$("#commenting ul:first li > a").filter(function(){ return ($(this).text().toLowerCase()==="leave a comment") ? true : false; }).hide();
	}
	/* dsq admin tool bar if exist */
	if($('#dsq-global-toolbar .dsq-admin-settings').size() > 0){
	    $('#dsq-global-toolbar').css({display:"block"});
	}
	
}


var configFn = function() {
	var config = this, args = arguments;
	config.callbacks.onReady.push(function() {
		if (!configTriggered) { onReadyTrigger(); }
    });
};
var CONST_config = {
	domain: fox.widgets.environment.getDomainHost(true,true),
	target: "#disqus_thread",
	url: "http:\/\/${domainId}.disqus.com/embed.js",
	token: "disqus_remote_auth_s2"
};

//configuration variables
//do not declare: disqus_remote_auth_s2
CONST_config.vars = {
	"disqus_title": getArticleTitle(),
	"disqus_url": CONST_config.domain + window.location.pathname,
	"disqus_config": configFn
};

/*
var ThirdPartyAPI  = new DisqusAPI();
fox.widgets.DQIntegrationService = function(info) {
	  var DQ = this;
	  var root = this.root;
	  var cfg = CONST_config;

	  if (!info.token) { showToConsole("[api.disqus] No Disqus token found"); return false; }

	  // start integration
	  function trigger() {
	    // set up disqus window scoped variables
	    window[cfg.token] = info.token;

	    for (i in cfg.vars) {
	      if (i!==cfg.token) { window[i] = cfg.vars[i]; }
	    }

	    var disqusElm = $(cfg.target);
	    if (disqusElm.size()===0) { return false; }
	    var domainId = ThirdPartyAPI.ext.getDomainId();
	    var embedJS = cfg.url.replace("${domainId}",domainId);
	    var embedElm = $("script[src*='"+embedJS+"']");
	    if (embedElm.size()>0) { // clear
	      embedElm.remove();
	      disqusElm.html("");
	    }

	    (function() {
	    	
	      var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
	      dsq.src = embedJS;
	      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	    })();


	    $("#sect-disqus > .login-link").each(function(){
	      var item = $(this);

	      if (!info.usr) {
	        // emulate login click
	        var loginElm = $("#authentication li a").filter(function(){ return ($(this).text().toLowerCase()==="login") ? true : false; });
	        item.find("a").click(function(){ loginElm.click(); });
	        item.show();
	      } else {
	        item.hide();
	      }
	    });

	  }

	  $(document).ready(function(){ trigger(); });

	}
*/

 var ThirdPartyAPI  = new DisqusAPI();
fox.widgets.DQIntegrationService = function(info) {
	var DQ = this;
	var root = ThirdPartyAPI.root = this.root ;
	var cfg = CONST_config;

	function showToConsole(str) {
		if (typeof window.console==='object') { console.log(str); }
	}

	if (!info.token) { showToConsole("[api.disqus] No Disqus token found"); return false; }
	
	// start integration
	function trigger() {
		// set up disqus window scoped variables
		window[cfg.token] = info.token;
		// window.disqus_developer = 0; // developer mode - override for now

		for (i in cfg.vars) {
			if (i!==cfg.token) { 
				if (cfg.vars[i]) { window[i] = cfg.vars[i]; }
			}
		}
		
		var doc = $(document);
	
		if (doc.data("DQ_docHasLoaded")) { window.location.reload(); return false; } // reload again if it has already been loaded
		doc.data("DQ_docHasLoaded",true);
		
		var disqusElm = $(cfg.target);
		if (disqusElm.size()===0) { return false; }
		function setDisqusExt() {
			// set up domain ID
			var domainId = ThirdPartyAPI.ext.getDomainId();
			cfg.url = cfg.url.replace("${domainId}",domainId);
			// triggered when the service is called
			ThirdPartyAPI.ext.serviceTrigger(cfg);

			$("p#lgn-disqus.login-link").each(function(){
				var item = $(this);
				if (!info.usr) {
					// emulate login click
					item.find("a").click(function(){ 
						var loginElm = $("#authentication li a, #nav-tertiary li a, #right-head li a").filter(function(){ return ($(this).text().toLowerCase().replace(/\s+/g,"")==="login") ? true : false; });
						if (loginElm.size()>1) { loginElm = $(loginElm.get(0)); }
						loginElm.click(); 
					});
					item.show();
				} else {
					item.hide();
				}
			});
			
			// on ready trigger if needed
			$.loadAttempt({
				maxAttempts: 60, // interval
				timeout: 500, // in ms
				callback: {
					check: function() {
						return ($("#dsq-content #dsq-comments, #dsq-content .dsq-missing-permissions").size()>0) ? true : false;
					},
					success: function() {
						if (!configTriggered) { onReadyTrigger(); }
					},
					timedOut: function() {
						// timed out, exhausted attempts
					}
				}
			});
			
		}
		$.loadAttempt({
			maxAttempts: 30, // interval
			timeout: 500, // in ms
			callback: {
				check: function() {
					return (ThirdPartyAPI.ext) ? true : false;
				},
				success: function() {
					setDisqusExt();
				},
				timedOut: function() {
					// timed out, exhausted attempts
				}
			}
		});
		
	}
	
	$(document).ready(function(){ try{trigger();}catch(err){ if ( typeof window.console != "undefined"){console.log("trigger :: %o",err);}} });

};/**/

})(jQuery);
