// This function removes non-numeric characters
function stripNonNumeric(str){
	str += ''; var rgx = /^\d|\.|-$/; var out = ''; for( var i = 0; i < str.length; i++ ) { if( rgx.test( str.charAt(i) ) ){ if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||(str.charAt(i) == '-' && out.length != 0 ) ) ){ out += str.charAt(i); }}}return out;
}

function incrementStoryCount(id){
	$.ajax({
	url: site_root+"/wp-content/themes/ceo/lib/StoryIncrement.php",
	type: 'POST',
	data: "id=" + stripNonNumeric(id),
	success: function(){
			//console.log("incremented post with id: "+id);
  	}
	});
}

function showModal(){
	$.fn.colorbox({
		width:"900px",
		height:"290px",
		inline:true,
		href:"#Subscription",
		open: true,
		onOpen:function(){
			$("#colorbox").addClass("subscribebox");
			$("#colorbox").append('<a href="#" id="dontaskbtn" >Don\'t Show Again</a>');
			$("#dontaskbtn").click(function(){
				$.cookie('subscribe', "stop", {expires: 1, path:"/"});
				$.fn.colorbox.close();
			});
		},
		onLoad:function(){
			$('#cboxClose').html('No Thank You');
		},
		onClosed:function(){
			$.cookie('numtilshow', 10, {path:"/"});
			$("#colorbox").removeClass("subscribebox");
			$("#Subscription").css({"display":"none"});
			$("#dontaskbtn").remove();
		}
	});
	$.cookie('subscribe', 1, {path:"/"});
}

// Need a var outside of scope of functions below to track if the modal close
// button was clicked. We want to be sure it does not go back to showing the
// tab if the user has tried to close the modal window.
var userReqClose = false;

function hideNLModal(){
	$('#NLSubMod').animate({
		'bottom': '-1500px'
		}, 2000, function(){		
			//console.log('done');
	});
}

function showBottomModalTab(){
	if(!userReqClose){
		nltogstat = 0;
		$("#NLToggle").css('background-position','50% -90px');
		$('#NLSubMod').animate({
			'bottom': '-340px'
			}, 500, function(){		
				//console.log('done');
		});
	}
}

function showBottomModal(dotimeout){
	nltogstat = 1;
	$("#NLToggle").css('background-position','50% 0%');
	$('#NLSubMod').animate({
		'bottom': '-80px'
		}, 800, function(){
			 // Wait and then move to tab only
			if(dotimeout){
				window.setTimeout( "showBottomModalTab()", 4000 );
			}
	});
}

$(document).ready(function(){
		var $scrollingDiv = $("#ShareThisCustom"),
				$contDiv = $(".lClm"),
				sdpos = $scrollingDiv.position(),
				sdstart = (sdpos) ? sdpos.top : 0 ,
				botmodaltimeout = 5000,
				$inp = $("#NLEmail"),
				$nltog = $("#NLToggle"),
				inpbgimg = $inp.css('background-image')
				nltogstat = 1;
		
		// Stuff for modal that pops up from bottom
		var dt = true,
				botck = $.cookie('subscribe');
		if(newsletter_modal_bottom!=1 && botck!="stop" && !isiPad()){
			// Uncomment the next line of you want the modal to show just the whole window first
			//window.setTimeout( function(){ showBottomModal(dt); }, botmodaltimeout );
			// Use the following line to show just the tab first
			showBottomModalTab();
		}
		$inp.click(function(){
			var $inp = $(this);
			if($inp.val()==""){
				$inp.css({'background-image':'none','background-color':'#ffffff'});
			}
		}).blur(function(){
			if($inp.val()==""){
				$inp.css({'background-image':inpbgimg});
			}
		});
		
		$nltog.click(function(e){
			e.preventDefault();
			$('#NLSubMod').stop();
			if(nltogstat==0){
				showBottomModal();
			} else {
				var skiptimeout = true;
				showBottomModalTab();
			}
		});
		
		$("#NLClose, #NLClose2").click(function(e){
			e.preventDefault();
			hideNLModal();
			$.cookie('subscribe', "stop", {expires: 1, path:"/"});
			userReqClose = true;
		});
		
		// ENd stuff for modal that pops up from bottom
		
		
		$(window).scroll(function(){
			var wintop = $(window).scrollTop(),
					$sharepad = $("#sharepad"),
					$modalw = $('#colorbox'),
					sharepadh = parseInt($sharepad.css('height')),
					contdivp = $contDiv.position(),
					contdivb = contdivp.top + parseInt($contDiv.css('height')),
					winh = $(window).height(),
					disfromtop = (winh - $modalw.height()) / 2,
					stopscroll = contdivb - sharepadh - 294;
			if(typeof $modalw!="undefined"){
				$modalw.stop().animate({'top': wintop + disfromtop}, 250);
			}
			if(wintop > sdstart){
				if(wintop <= stopscroll){
					$scrollingDiv
						.stop()
						//.animate({"marginTop": (wintop - sdstart + 10) + "px"}, "fast" );
						//.css({"marginTop": (wintop - sdstart + 10) + "px"});
						.css({"position":"fixed","top":"10px"});
				} else {
					$scrollingDiv
						.stop()
						.css({"position":"absolute", "top":stopscroll + "px"});
				}
			} else {
				$scrollingDiv
					.stop()
					//.animate({"marginTop": -1 + "px"}, "fast" );
					//.css({"marginTop": -1 + "px"});
					.css({"position":"absolute","top": sdstart + "px"});
			}
		});
	
	// For modals
	var modaltimeout = 10000;
	if(window.open_subscribe_modal==1 && $.cookie('subscribe')!="stop"){
		window.setTimeout( "showModal()", modaltimeout );
	}	
	
	$('#NwsLtrEmail').focus(function() {
  	$(this).keyup(function() {
			if ($(this).val() != "") {
				$(this).addClass("roll");
			} else {
				$(this).removeClass("roll");
			}
		});
	});
	
	$('#NwsLtrEmail').blur(function() {
		if ($(this).val() == "") {
			$(this).removeClass("roll");
		}
	});

	$('.ceoIntrvw a.tab').click(function() {
		var s=s_gi(s_account);
		if(typeof s!="undefined"){
			s.events="event13";
			s.linkTrackEvents = 'event13';
			s.t();
		}
	});
	
	$(".cboxElement").each(function(key, value) {
		$(this).colorbox({
			width:"90%",
			height:"90%",
			opacity: 0.5,
			iframe:true,
			href: $(this).attr('href'),
			title: "Showing: " + $(this).attr('href'),
			current: "showing story {current} of {total}",
			close: "Return to CEO.com",
			onComplete: function() {
				if(typeof s!="undefined"){
					s.pageName="Iframe Article: " + $(this).text();
					s.channel="Article";
					s.eVar1 = "";
					s.eVar2 = "";
					s.eVar6 = $(this).text();
					s.prop4 = $(this).text();
					s.prop8 = "";
					s.prop9 = "";
					s.prop10 = "";
					s.prop25 = "";
					s.events="event7";
					s.t();
				}
			}
		});
	});
	
	$(".ttlink").each(function(t){
		var ttpos = ($("#"+this.id).hasClass("dirLeft")) ? "left" : "right";
		var ttoff = ($("#"+this.id).hasClass("ttlinkleft")) ? -600 : -20;
		var ttoff = ($("#"+this.id).hasClass("guideCbox")) ? -365 : ttoff;
		var tt = $("#"+this.id);
		var thistip = '#tip'+this.id;
		var thisgplus = 'gplus'+this.id;
		var thistbutt = 'tbuttholder'+this.id;
		var thistbutta = 'tbutta'+this.id;
		var thisfblike = 'fblikeholder'+this.id;
		var thisfblikea = 'fblikea'+this.id;
		var thislishare = 'liholder'+this.id;
		var thislisharea = 'lisharea'+this.id;
		$(this).click(function() {
			incrementStoryCount(this.id);
			trackHeadlineStackClicks(this);											 
		});
		if($.isFunction(tt.tooltip)){
			tt.tooltip({
				tip: thistip,
				direction: ttpos,
				effect: 'slide',
				slideOffset: 20,
				slideInSpeed: 200,
				fadeOutSpeed: 300,
				predelay: 400,
				position: ttpos,
				offset: [150, ttoff],
			});
		}
		$(this).mouseenter(function() {
			userHeadlineHover = setTimeout($.proxy(function(){
				trackHeadlineHovers(this)
			}, this), 2000);
			renderTweetButton(thistbutt,thistbutta);
			renderFBLikeButton(thisfblike,thisfblikea);
			renderLIButton(thislishare,thislisharea);
			renderPlusone(thisgplus,$("#gpluslink"+this.id).attr("href"));
		});
		$(this).mouseout(function() {
			clearTimeout(userHeadlineHover);
		});	
	});
		
	$(".tooltip a.viewfull").each(function(t){
		$(this).click(function() {
			trackHeadlineClicks(this);							 
		});
	});
							
	$('.blur').click(function() {
		if (this.value == this.defaultValue) {
		this.value = '';
		$(this).removeClass("blur");
		$(this).addClass("focus");
	}});
	
	$('.blur').blur(function() {
		if (this.value == '') {
		this.value = this.defaultValue;
		$(this).removeClass("focus");
		$(this).addClass("blur");
	}});
	
	// ANALYTICS
	$(".home_featured_content_slider .wrapper a").each(function(){
		$(this).click(function() {
			s.prop11 = "Headline Click";
			s.prop12 = "Featured Content";
			s.events='event14';
			s.linkTrackEvents = 'event14';
			s.eVar6 = $(this).find('.fctitle').text();
			s.linkTrackVars = 'prop11,prop12,eVar6';
			s.tl(this, 'o');					 
		});
	});
	$(".home_ceo_guides_slider .wrapper a").each(function(){
		$(this).click(function() {
			s.prop11 = "Headline Click";
			s.prop12 = "CEO Guides";
			s.events='event14';
			s.eVar6 = $(this).parent().attr('data-title');
			s.linkTrackEvents = 'event14';
			s.linkTrackVars = 'prop11,prop12,eVar6';
			s.tl(this, 'o');	
		});
	});
	
		$(".featcon").click(function(e) {
			var fcid = $(this).attr('data-fcid');
			incrementStoryCount(fcid);
		});

});

function countPlusOne()
{
	var s=s_gi(s_account);
	if(typeof s!="undefined"){
		s.events="event5";
		s.linkTrackEvents = 'event5';
		s.t();
	}
}

function countFacebookLike()
{
	var s=s_gi(s_account);
	if(typeof s!="undefined"){
		s.events="event4";
		s.linkTrackEvents = 'event4';
		s.t();
	}
}

function countTwitterTweet()
{
	alert("here")
	var s=s_gi(s_account);
	if(typeof s!="undefined"){
		s.events="event3";
		s.linkTrackEvents = 'event3';
		s.t();
	}
}

function countLinkedinShare()
{
	var s=s_gi(s_account);
	if(typeof s!="undefined"){
		s.events="event6";
		s.linkTrackEvents = 'event6';
		s.t();
	}
}

var renderedids = new Array();

function renderPlusone(elid,href) {
	var inarr = jQuery.inArray(elid,renderedids);
	if(inarr == -1){
		gapi.plusone.render(elid, {"callback":"countPlusOne","size":"tall","count":"true","href":href});
		renderedids.push(elid);
	}
}

function renderTweetButton(elid,linkel){
	var href = $("#"+linkel).attr('href'),
			$target = $("#"+elid),
			qstring = $.param({ url: href, count: "vertical" }),
			toinsert = '<iframe allowtransparency="true" frameborder="0" scrolling="no" src="http://platform.twitter.com/widgets/tweet_button.html?'+qstring+'" style="width:57px; height:70px;"></iframe>';
	$target.html(toinsert);
}

function renderFBLikeButton(elid,linkel){
	var href = $("#"+linkel).attr('href'),
			$target = $("#"+elid),
			toinsert = '<fb:like href="'+href+'" send="false" layout="box_count" width="90" show_faces="false" font=""></fb:like>';
	$target.html(toinsert);
	FB.XFBML.parse(document.getElementById(elid));
}

function renderLIButton(elid,linkel){
	var href = $("#"+linkel).attr('href'),
			$target = $("#"+elid),
			toinsert = '<script type="IN/Share" data-onsuccess="countLinkedinShare" data-url="'+href+'" data-counter="top"></script>';
	$target.html(toinsert);
	IN.parse(document.getElementById(elid));
}


$(window).load(function(){
	// Render the Google+ button for left side sharing
	var lsurl = $("#gpluslink-side").attr("href");
	if (typeof(lsurl)!="undefined"){
		//console.log("sharebar is there");
		renderPlusone("gplus-side",lsurl);
	}
});
