(function($){
	
	// $tartup documentation: https://github.com/mitzerh/Startup.js/blob/master/Documentation.md
	var FOX = window.FOX = $tartup;
	
	var Add = FOX.site.Add,
		DOC_Ready = FOX.site.OnDocReady,
		PAGE_Ready = FOX.site.OnPageReady;
	
	/*** General document.ready ***/
	DOC_Ready(function(){
		if ($.ad) { $.ad.init(); } // ads initialize
		
	});
	
	/*** General pageReady ***/
	PAGE_Ready(function(){
		var priNav = 'Politics';
		var secNav = 'Elections';
		$('div#nav-primary ul:first').find('li').each(function(){
		    var el = $(this);
		    if($.trim(el.text()) == priNav){
		       el.addClass('active');
		    }
		});
		$('div#nav-sub ul.first').find('li').each(function(){
		   var el = $(this);
		    if($.trim(el.text()) == secNav){
		       el.addClass('active');
		    }
		});
	});
	PAGE_Ready(function(){
		if ($.ad) { $.ad.pre(); } // ads preload
		$('div.social a').each(function(){
				var atag = $(this);
				atag.bind('click',function(){
					 window.open (atag.attr('href'), "electionsSharePop","location=1,status=1,scrollbars=1, width=750,height=400");return false;
			});
		});
		$('div.social span.t-count').bind('click',function(){
			var stl = $(this);
			var elm = stl.find('a');
			window.open (elm.attr('href'), "electionsSharePop","location=1,status=1,scrollbars=1, width=750,height=400");return false;
		});
		setUpMorebutton();
	});

	/*** Star Voting ***/
	PAGE_Ready("starVoting",{
		init: function() {
			var root = this;
			root.cookieIssueObj = false;
			root.setStarsDefault();
			root.setEvents();
		},
		voteFor: function(issueNum){
			var root = this;
			var c = $.cookie("hotIssues");			
						
			if(c){
				$.cookie("hotIssues" , c + "_" + issueNum);
			}else{$.cookie( 'hotIssues', issueNum );}
		},
		setEvents: function(){
			var root = this;
			$('#issues ul li .vote').click(function(){
				var thisElm = $(this);
				if(!thisElm.find('a').hasClass("selected")){
					var rel = thisElm.attr("rel");
					root.voteFor(rel);
					thisElm.find('a').addClass("selected");
					$.ajax({
						type: "POST",
						url: "http://"+location.host+"/politics/elections/topic_vote/"+rel,
					  	success: function(x){
					    	thisElm.prev().text(x).addClass("voted");
							$("#tid-"+rel).find('.bar p').text(x);
					  	}
					});
				}
				return false;
			})
			
		},
		setStarsDefault: function(){
			var root = this;
			var iString = $.cookie('hotIssues')? $.cookie('hotIssues') : false;	
			if(iString){iArr = iString.split("_");

				//turn array into object to use "in" check below.
				function oc(a){
					var o = {};
				  	for(var i=0;i<a.length;i++){o[a[i]]='';}
				  	return o;
				}
				root.cookieIssueObj = oc(iArr);
			}

			if(iString){
				$('#issues ul li .vote').each(function(){
					var thisElm = $(this);
					var issueNum = thisElm.attr("rel");
					
					//in check
					if(issueNum in root.cookieIssueObj){
						thisElm.find('a').addClass("selected");
						thisElm.prev('p').addClass("voted");
					}
				})				
			}
		}
	});	
	
	/*** Candidate slider carousel top ***/
	PAGE_Ready("candidateCarousel",{
		init: function() {
			var self = this;
			$("#section-content .ct-mod.slider:first").each(function(){
				self.set($(this));
			});
		},
		set: function(elm) {
			var target = elm.find(".content"), cntrl = elm.find(".content > .controls");
				
			var config = {
				auto: { set:false, speed:0, resume:true }, // auto scroll
				slide: "horizontal", // horizontal or vertical
				scroll: 1, // number of items to scroll per event
				show: 7, // items shown
				speed: "slow", // scroll speed
				rotate: false, // rotate back to star if end
				eventCallback: function(obj) { // callback function for all carousel events
					var start = obj.start, end = obj.end,
						 isFirst = (obj.batch.current===1) ? true : false,
						 isLast = (obj.batch.current===obj.batch.max) ? true : false;
				 
				 cntrl.find(".prev").toggleClass("inactive-prev",isFirst);
				 cntrl.find(".next").toggleClass("inactive-next",isLast);
				},
				controlsCallback: function(control) { // callback to set up controls
					cntrl.find(".prev").click(function(){ // previous link
						control.stopAutoScroll();
						control.slide("prev");
						return false;
					});

					cntrl.find(".next").click(function(){ // next link
						control.stopAutoScroll();
						control.slide("next");
						return false;
					});
				}
			};
			
			target.jACarousel(config);
		}
	});
/* ============== Widget Twitter ====================*/
	PAGE_Ready("twitterSearchWidget",{
		config : {
				max_id: 0,
				twtstoShownumber:3,
				initialized: false,
				dftAccount : "FoxNewsPolitics",
				widget_type : "search_from_users",
				tweets_queue:[],
				isready : true,
				refresh_url:'',
				tweet_count : 0,
				widget_vars : {
					search_from_users: "", //comma separated values of account to search from 
					search_term: ""
				},
				URL: {
					url: "http:\/\/search.twitter.com/search.json",
					type: "jsonp",
					interval: 3e4
				},
				text: {
					more: " more tweets have been posted"
				},
				containers: {
					cntnr_id : "div#twtr-widget",
					twr_tlne : "ul#twtr-widget-list", // TimeLine must be a UL
					twr_rfsh : "div#twtr-widget-rfsh" // refresh button
				}
		}
		, init : function (){//
			var self = this;
			var cnt =self.config.containers;
			if($(cnt.cntnr_id).size() && $(cnt.twr_tlne).size() ){
				
				self.set();
			}
		}
		, set: function(){
			var self = this;
			var wdgcnf = self.config ;
			var cnt = wdgcnf.containers;
			//var type =
			try{
			if(wdgcnf.widget_type === "search_from_users"){
				wdgcnf.widget_vars.search_from_users = window.candidates_twitter_accounts;
				wdgcnf.twtstoShownumber = window.numberOfTweetstoShow;
				$.loadAttempt({
					maxAttempts: 1e3, // interval attempts
					timeout: wdgcnf.URL.interval, // in milliseconds
					callback: { 
					check: function() { // what the load attempt pooler must check on. must return a boolean
						if(wdgcnf.isready){self.getFeed();}
						return false;
					},
					success: function() { },// what to do on success
						timedOut: function() {}// timed out, exhausted attempts
					}
				});
			}
			}catch(e){if(typeof window.console != undefined){console.log(e);}}
		}
		, getFeed : function(){
			var slf = this;
			var conf = slf.config;
			var searchquery = slf.setQuery(conf);
			var getMaxIdQuery = slf.getMaxIdQuery(),refreshurl='',refresh_url = conf.refresh_url;
			if (refresh_url.length > 1){
				refreshurl = refresh_url ; 
			}
			else{
				refreshurl = "?"+searchquery+getMaxIdQuery;
			}				
			$.ajax({
				url: conf.URL.url+refreshurl+'&callback=twitter_widget_setup&rpp='+conf.twtstoShownumber,
				dataType:'jsonp',
				jsonp: 'twitter_widget_setup'
			});
			window.twitter_widget_setup = function(data){
				var selfobj = window.FOX.site.twitterSearchWidget;
				var cnfg 	= selfobj.config;
				selfobj.config.refresh_url = data.refresh_url;
				selfobj.config.max_id = parseInt(data.max_id_str,10);
				var rcount = data.results.length;
				if(rcount > 0 && !cnfg.initialized){
					for(var i =rcount; i > 0; i--){
						selfobj.insertLiTweet(data.results[i-1]);
					}
					cnfg.initialized = true;
				}else if( rcount > 0 && cnfg.initialized){
					for(var i =0; i < rcount; i++){
						cnfg.tweets_queue.push(data.results[i]);
					}
					selfobj.setTweetsAfterLoad();
				}
			};
		}
		, insertLiTweet : function(tweet){
			var selfobj = window.FOX.site.twitterSearchWidget,countr = 0;
			var cnfg =selfobj.config;
			var ultweetsCont = $(cnfg.containers.twr_tlne+' li.twtr-reference-tweet.first')
			,numbrTwts = cnfg.twtstoShownumber , tweet_id= 'tweet-id-' + cnfg.tweet_count++;
			$(cnfg.containers.twr_tlne).find('li').each(function(){
				if(countr >= numbrTwts){
					$(this).css({'display':'none'});
				}
				countr++;
			});
			$(selfobj.getTweetHtml(tweet,tweet_id)).insertAfter(ultweetsCont);
			$('#'+tweet_id).animate({
				opacity:1.0
				}, 600, 'linear', function() { });
		}
		, setTweetsAfterLoad : function(){
			var selfobj = window.FOX.site.twitterSearchWidget;
			var cnfg = selfobj.config;
			var cnttwts = cnfg.tweets_queue.length;
			if(cnttwts > 0){
				var elem = $(cnfg.containers.twr_rfsh);
				elem.html('<p>'+cnttwts+' '+cnfg.text.more+'</p><p class="refresh"><a href="#"><img alt="" src="/politics/elections/sites/foxnews.com.politics.elections/themes/politics_elections/assets/img/refresh.png"></a></p>').show();
				elem.unbind('click').bind('click',function(){
					var selfobj = window.FOX.site.twitterSearchWidget;
					var cnttwts = selfobj.config.tweets_queue.length;
					for(var i =0; i < cnttwts; i++){
						selfobj.insertLiTweet(selfobj.config.tweets_queue[i]);
					}
					selfobj.config.tweets_queue = [];
					$(this).hide();
					return false;
				});
			}
		}
		, setTweetText :function(text) {
		
			var matches = {
				links: text.match(/\http:\/\/\S+/gi),
				users: text.match(/@[a-z-_]+/gi),
				terms: text.match(/#[a-z-_]+/gi)
			};
			
			var replace = {
				links: '<a target="_blank" href="${item}" target="_blank" class="hyper-word">${item}</a>',
				users: '<a target="_blank" href="http://twitter.com/${link}">${item}</a>',
				terms: '<a target="_blank" href="http://twitter.com/${link}">${item}</a>'
			};
			for (var i in matches) {
				var match = matches[i];
				if (match) {
					for (var x = 0; x < match.length; x++) {
						var item = match[x];
						if (i==="users") {
							text = text.replace(item,replace[i].replace(/(\$\{item\})/g,item).replace(/(\$\{link\})/g,item.slice(1)));
						} else if (i==="terms") {
							text = text.replace(item,replace[i].replace(/(\$\{item\})/g,item).replace(/(\$\{link\})/g,"search?q="+item.slice(1)));
						}
						else {
							text = text.replace(item,replace[i].replace(/(\$\{item\})/g,item));
						}
					}
				}
			}
			
			return text;
		}
		, getTweetHtml : function(tweet,tweet_id){
			var selfobj = window.FOX.site.twitterSearchWidget;
			function showPopular(tweet) {
				if (tweet.metadata && tweet.metadata.result_type && tweet.metadata.result_type == 'popular') {
					return '<span class="twtr-popular">' + tweet.metadata.recent_retweets + '+ recent retweets</span>';
				} else {
					return '';
				}
				}
			function date_format(dateString){
				var newdate = new Date(dateString);
				return newdate.toLocaleDateString() + ' ' +newdate.toLocaleTimeString();
			}
			
			var html = Array();
				html.push('<li id="'+tweet_id+'" class="twtr-tweet" style="height:0px,opacity:0.0;overflow:hidden;"><div class="twtr-tweet-wrap" >');
				html.push('<div class="twtr-avatar m m-l"> ');
				html.push('<div class="twtr-img"><a target="_blank" href="http://twitter.com/intent/user?screen_name=' + tweet.from_user + '"><img alt="' + tweet.from_user + ' profile" src="' + tweet.profile_image_url + '"></a></div> ');
				html.push('</div>	<div class="twtr-tweet-text"> ');
				html.push('<p> <a target="_blank" href="http://twitter.com/intent/user?screen_name=' + tweet.from_user + '" class="twtr-user">@' + tweet.from_user + '</a> ' + selfobj.setTweetText( tweet.text )+ '');
				html.push('<br/><em><span class="twtr-timestamp" time="' + tweet.timestamp + '" >' + date_format(tweet.created_at) + '</span> ');
				html.push('<span class="retweet"><a href="http://twitter.com/intent/retweet?tweet_id=' + tweet.id_str + '"><img alt="" src="/politics/elections/sites/foxnews.com.politics.elections/themes/politics_elections/assets/img/icon-retweet.jpg"> Retweet</a></span>');
				html.push('</em> ' + showPopular(tweet) );
				html.push('</p> </div> </div></li>');
			return html.join('');
		}
		, setQuery : function(vars){
			if(vars.widget_type === "search_from_users"){
				var useraccounts = vars.widget_vars.search_from_users, rslt = Array();
				var count = useraccounts.length;
				for(var i = 0;	i< count; i++ ){
					var useraccnt = useraccounts[i];
					if(useraccnt.length > 1){
					rslt.push('from:'+useraccnt);}
				}
				return 'q='+rslt.join('+OR+');
			}else if(vars.widget_type === "search_term"){
				return 'q='+ vars.widget_vars.search_term;
			}
		}
		, getMaxIdQuery : function(){
			var slf = this.config;
			if(slf.max_id!=0){
				return '&since_id='+ slf.max_id;
			}else return "";			
		}
	});
/* ============== Widget Twitter END ================*/
	function setUpMorebutton(){
	window.req_pending = false;
	$('.show-more a.btn-smll').data('doffset',1);
	$('.show-more a.btn-smll').click(function(){
	$('.show-more a.btn-smll').data('doffset');
		var datatype='json',call_back='';
		window.offset = $('.show-more a.btn-smll').data('doffset');
		
	//http://beta-drupal7.foxnews.com/politics/elections/loadpage/article/1/type/callback
		$.ajax({
		beforeSend:function(request) {
			if(req_pending) {return false;} else {req_pending = true;}
			$('.show-more a.btn-smll').hide();
			$('div.show-more img.m-2').show();
		},
		cache: false,
		url: '/politics/elections/loadpage/article/'+offset+'/'+datatype,
		contentType:'text/html',
		data: 'html',
		type: 'GET',
		success: function(data) {
			 var evldata =	eval('(' + data + ')');
			 if(evldata.more){
				$('.show-more a.btn-smll').data('doffset',evldata.next_offset).show();
				req_pending=false;
			 }
			 $('#block-fox-elections-fox-elections-feed-content ul.list').append(""+evldata.content);
			 $('div.show-more img.m-2').hide();
			window.setopenWindow = function(){
				$('ul.list li.loaded-content').each(function(){
					var ali = $(this);
					var atag = ali.find('div.social a');
					atag.each(function(){
						var alik = $(this);
						alik.bind('click',function(){
							window.open (alik.attr('href'), "electionsSharePop","location=1,status=1,scrollbars=1, width=750,height=400");return false;
						});
					});
					ali.find('span.t-count').bind('click',function(){
						var stl = $(this);
						var elm = stl.find('a');
						window.open (elm.attr('href'), "electionsSharePop","location=1,status=1,scrollbars=1, width=750,height=400");return false;
					});
					ali.removeClass('loaded-content');
				});
			};
			 setTimeout("setopenWindow()",3000);
		},
		error: function(data,e){
			req_pending=false;
			$('.show-more a.btn-smll').show();
			$('div.show-more img.m-2').hide();
		}
		});
		return false;
	});
	}

}(jQuery));
