var viewport = viewportSize.getWidth();
var prev_viewport = viewport;

var global_domain = document.domain;
var site_domain = global_domain.replace("www.", "");
var com_domain = site_domain.replace(".com", "");
var domain = com_domain.replace(".org", "");
console.log("Domain: " + domain);

var site_name = '';

if( domain == "future.realcleartechnology" || domain == "realclearfuture" || domain == "dev.realclearfuture" ){
	site_name = 'Future';		
}else if( domain == "realclearpolitics" ){
	site_name = 'Politics';
}else if( domain == "realclearpolicy" ){
	site_name = 'Policy';
}else if( domain == "realclearmarkets" || domain == "dev.markets.realclearpolitics" ){
	site_name = 'Markets';
}else if( domain == "realclearworld" ){
	site_name = 'World';
}else if( domain == "realcleardefense" ){
	site_name = 'Defense';
}else if( domain == "realclearenergy" ){
	site_name = 'Energy';
}else if( domain == "realclearhealth" ){
	site_name = 'Health';
}else if( domain == "realclearscience" ){
	site_name = 'Science';
}else if( domain == "realclearreligion" ){
	site_name = 'Religion';
}else if( domain == "realcleareducation" ){
	site_name = 'Education';
}else if( domain == "realclearsports" ){
	site_name = 'Sports';
}else if( domain == "realclearhistory" ){
	site_name = 'History';
}else if( domain == "realclearbooks" ){
	site_name = 'Books';
}else if( domain == "realclearlife" ){
	site_name = 'Life';
}

$(document).ready(function(){
	//IF RCM
	if( site_name == "Markets" ){
		//IF Not IE6 Set bottom skyscraper ad on homepage to fixed when top of ad meets window scrolling down
		var msie6 = $.browser == 'msie' && $.browser.version < 7;
		  if (!msie6) {
			//get left position of left column(visible on page load/ready) 
			var top_sky_pos = $("#most-read-box").position();
			var top_sky_left = (top_sky_pos.left+45)+"px";
			var top = $('#scrollable_box').offset().top;
			
			$(window).scroll(function (event) {
			  var y = $(this).scrollTop();
			  if (y >= top) { 
			  	  $('#scrollable_box').addClass('fixed');
				  //set left position of ad to account for responsive site that is centered
				  $(".fixed").css({
						"left" : top_sky_left
					});
				   
			  }else { 
			  	  $('#scrollable_box').removeClass('fixed'); 
			  }
			});
		  }				

		//console.log("Left Pos: " + top_sky_left);
		
	}

	//MAIN MOBILE BODY SWIPER
	triggerMobileSwiper();
	$(window).resize(function(){

		var viewport = $( window ).width();
		if(viewport != prev_viewport) {
			triggerMobileSwiper();
		}
		prev_viewport = viewport;
	});
	
	// auto open second newsletter widget
	if( site_name == "Markets" || site_name == "Energy" || site_name=="Politics" || site_name == 'World' || site_name == 'Defense' || site_name == 'Science' || site_name=="Policy" || site_name=="History"){
		$(".newsletter-signup-container2").last().hide();
        $(".newsletter-widget").css({ "margin-bottom" : "20px" });
	}else{
		$(".newsletter-signup-container2").last().show();
	}
	
	//More From RC Homepage Widget
	//Hide all site related entries on the site being viewed
	$(".more-rc .site a").each(function() {
	   if( $(this).attr("data-site") == site_name ){
		   //console.log("we will hide these links");
		   $(this).parent().hide();
	   }
	});

	//pings date links and removes anchor is it's a 404
    //this is now being executed on the php side
    //2-9-2018
    
	/*setTimeout(function(){
	    $('.menu ul li a').each(function(){
	        var $this = this;
			if( site_name != "History" || site_name != "Politics" || site_name != 'policy' || site_name != 'markets' || site_name != 'world' || site_name != 'defense' || site_name !== 'science'){
				check_dates_menu_link($this); 
			}
	        
	    });
	}, 1000);*/

}); //END DOC READY

//TEMP USED FOR POLICY/MARKETS KAUFFMAN FOUNDATION CLICKS
function trackclick_temp_widget(event, entry_id, atxt, site) {
	
    site = typeof site !== 'undefined' ? site : site_name; 
	site_module='center-column';
	section = site_name+'-widget';
	//Get the href value. Will use at the end to go to link target.
	event = event || window.event;
	var href = '';
	if(event.target.href.length > 2) {
		href = event.target.href;
	} else {
		href = event.target.parentNode.href;
	}
	//Build the params to go to click tracking.
	var url = window.location.protocol+'//util.realclearpolitics.com/trackclicks/trackclick.php?';
	url += 'site='+site+'&';
	if(typeof(entry_id) != 'undefined') url += 'entry_id='+entry_id+'&';
	if(typeof(atxt) != 'undefined') url += 'atxt='+atxt+'&';
	if(typeof(site_module) != 'undefined') url += 'site_module='+site_module+'&';
	url += 'entry_url='+href+'&';
	if(typeof(section) != 'undefined') url += 'section='+section+'&';

	//Wrap click tracking call to prevent premature termination of this function.
	try{
		var tclick = ajaxinclude(url);
		console.log(tclick);
	} catch(err) {}
	if(event.ctrlKey || event.metaKey) {
		return true;
	} else {
		window.setTimeout('document.location = "' + href + '"', 100);
		return false;
	}	
}

//TEMP USED FOR POLICY/MARKETS KAUFFMAN FOUNDATION CLICKS
function trackclick_cross_domain(event, entry_id, atxt, site, permanent, partner_title) {

    site = typeof site !== 'undefined' ? site : 'politics';
	site_module='center-column';
	section = 'More From RC Widget';
	//Get the href value. Will use at the end to go to link target.
	event = event || window.event;
	var href = '';
	if(event.target.href.length > 2) {
		href = event.target.href;
	} else {
		href = event.target.parentNode.href;
	}
	
	var atxt_str = atxt.replace(/'/g, "\\'");
	
	//Build the params to go to click tracking.
	var url = 'http://util.realclearpolitics.com/trackclicks/trackclick.php?';
	url += 'site='+site+'&';
	if(typeof(entry_id) != 'undefined') url += 'entry_id='+entry_id+'&';
	if(typeof(atxt) != 'undefined') url += 'atxt='+atxt+'&';
	if(typeof(site_module) != 'undefined') url += 'site_module='+site_module+'&';
	url += 'entry_url='+href+'&';
	if(typeof(section) != 'undefined') url += 'section='+section+'&';
	if(parseInt(permanent) == 1) url += 'perm='+'1'+'&position=1&partner_title='+partner_title+'&';

	//Wrap click tracking call to prevent premature termination of this function.
	try{
		var tclick = ajaxinclude(url);
		console.log(tclick);
	} catch(err) {}
	if(event.ctrlKey || event.metaKey) {
		return true;
	} else {
		window.setTimeout('document.location = "' + href + '"', 100);
		return false;
	}	
}

function ajaxinclude(url) {
	var page_request = false;
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
		page_request = new XMLHttpRequest();
	else if (window.ActiveXObject){ // if IE	
		try { page_request = new ActiveXObject("Msxml2.XMLHTTP"); } 	
		catch (e){
			try{ page_request = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch (e){  }
		}
	}else
		return false;
		page_request.open('GET', url, false); //get page synchronously 
		page_request.send(null);
		//handle = getpagecontent(page_request);
		//processReturnData(handle); //this functions outputs everything on the page
}



var alpha_cached = '';
var footer_cached = '';
var first_hp_slide_load = true;
var prev_slide = 1;

function triggerMobileSwiper(){

	//alert(viewport);
	//console.log(viewport);
	//console.log('Site Name: '+site_name);
	if(viewport<768){

		//INIT FLEXSLIDER IF NON-EXISTENT
		var flexslider_instance = $('#container').data('flexslider');
		if(flexslider_instance==undefined){

			//alert('init flexslider');

			//SORT COLUMNS FOR FLEXSLIDER POSITIONS
			//alpha_cached = $('.alpha-container').html();
			//$('#container .gamma').after(alpha_cached);

			//MOVE LATEST POLLS UP ON MOBILE ONLY
			mobile_polls_interval = setInterval(move_polls_widget_when_visible, 2000);

			$('.alpha-container').insertAfter('#container .gamma');

			var starting_slide = 1; // middle col
			// get breaking news hash if exists
			if(window.location.hash) {
				var hash = window.location.hash.substring(1); //Puts hash in variable, and removes the # character
				if(hash == 'breaking_news') {
					starting_slide = 0; // left col
				}
			}

			$('#container').flexslider({
				container_exists: first_hp_slide_load, // Assumes flex-viewport is there already
				selector: ".mobile-slider > .tab",
				slideshow: false,
				slideshowSpeed: 0,
				animation: "slide",
				controlNav: false,
				startAt:starting_slide,
				smoothHeight:false,
				slideshowSpeed:500,
				prevText: "<img src='/asset/img/icon-arrow-left-white.png' />",
				nextText: "<img src='/asset/img/icon-arrow-right-white.png' />",
				start: function(slider){

					//$('.clone .RC-AD > div').attr('id', '');

					console.log('main slider started');
					//move foter wrapper down
					footer_cached = $('.footer-wrapper').html();
					//$('.flex-control-nav').after(footer_cached);
					//$('.footer-wrapper').show();
					$('.footer-wrapper').insertAfter( $('#container > ul.flex-direction-nav') ).show();

					//mobile nav arrows
					$( ".mobile-nav-wrapper a.arrows" ).on('click', function(e){
						e.preventDefault();
						if($(this).attr("rel")=="prev"){
							$('#container > ul.flex-direction-nav > li > .flex-prev').trigger('click');
						}else if($(this).attr("rel")=="next"){
							$('#container > ul.flex-direction-nav > li > .flex-next').trigger('click');
						}
					});


					//HOMEPAGE MOBILE NAV MENU ITEMS
					$( ".mobile-nav-wrapper a" ).click(function(e){

						// Prevent a page reload when a link is pressedv
				        e.preventDefault();

				        if($(this).hasClass("arrows")==false){

							//remove class from all then add active class back to active link - controls border bottom visual
							$(".mobile-nav-wrapper a").removeClass('active');
							$( this ).addClass('active');

				        	// Call the scroll function
				       		// alert($(this).attr("rel"));


				       		//var slider = $('#container').data('flexslider');
				       		//alert( $(this).attr("rel") );
				       		var gotoslide = parseInt($(this).attr("rel"));
				       		//alert(gotoslide);
				     		slider.flexAnimate(gotoslide);
				     	}


					});

					//ELECTION CENTRAL WIDGET CONTAINER CLICK -> GOTO LATEST POLLS COLUMN
					$("#election_central_hp_widget").click(function(e){
						e.preventDefault();
						slider.flexAnimate(2);
					});


				},
				after: function(slider){
					//update mobile menu to hightlight current slide
					currentslide = slider.currentSlide;
					$('.mobile-nav-wrapper a').each(function(index){
						$(this).removeClass("active");
						if( $(this).attr('rel')==currentslide ){
							$(this).addClass("active");
						}
					});
					//console.log('slider.currentSlide: '+slider.currentSlide);
					//console.log(slider);
					// Send GA Event
					var slide_name = '';
					if(currentslide == 0) {
						slide_name = 'gamma';
					} else if(currentslide == 1) {
						slide_name = 'alpha';
					} else if(currentslide == 2) {
						slide_name = 'beta';
					}
					var prev_slide_name = '';
					if(prev_slide == 0) {
						prev_slide_name = 'gamma';
					} else if(prev_slide == 1) {
						prev_slide_name = 'alpha';
					} else if(prev_slide == 2) {
						prev_slide_name = 'beta';
					}
					if(slide_name != prev_slide_name) {

						var event_data = {
							'ge_action' : 'Slide',
							'ge_category' : 'HP Mobile Pane Switcher',
							'ge_label' : 'from '+prev_slide_name+' to '+slide_name
						};
						send_ga_event(event_data);
					}

					prev_slide = currentslide;
					//loadAds();
				},
				before: function(slider){
					//EVERYTIME YOU SWITCH SLIDES THIS WILL TAKE YOU AUTOMATICALLY TO THE TOP OF THE ONE YOU SLID TO
					$("html, body").animate({ scrollTop: 0 }, "slow");
				}

				//RE-TRIGGER GA DIV CONTAINER AND AD-SLOT PUSH 
				//loadAds();				

			});

			first_hp_slide_load = false;


			// Reset battle widget slider
			var bw_flex = $('.beta-container:not(.clone) #small_rectangles_election_wrapper').data('flexslider');
			if(typeof bw_flex !== 'undefined') {

				console.log('destroy flex for battle widget');
				bw_flex.destroy();
				gmur_interval = setInterval(init_slider_when_visible, 1000);
			}

		}

	}else{

		//MOVE LATEST POLLS BACK TO ORIGINAL POSITION
		$('.beta-container:not(.clone) .widget_slot[data-widget-type="latest_polls"]').insertAfter('#container .beta-container .beta .RC-AD-BOX-MIDDLE');

		//DESTROY FLEXSLIDER IF EXISTS
		var flexslider = $('#container').data('flexslider');
		if(typeof flexslider !== 'undefined'){

			console.log('destroy flex');

			flexslider.destroy();
			//SORT COLUMNS FOR FLEXSLIDER POSITIONS
			$('.alpha-container').insertBefore('#container .gamma');

		}
		
		$('.alpha-container').attr('style', ''); 
		$('.mobile-slider .gamma').attr('style', '');

	}

}


function move_polls_widget_when_visible()
{

	//console.log('not visible');
	//console.log($('.beta-container:not(.clone) .widget_slot[data-widget-type="latest_polls"] .rec-widget-header').is(":visible"));

	if( $('.beta-container:not(.clone) .widget_slot[data-widget-type="latest_polls"]').is(":visible") ){
		//console.log('is visible');

		//MOVE LATEST POLLS UP
		$('.beta-container:not(.clone) .widget_slot[data-widget-type="latest_polls"]').prependTo('#container .beta-container .beta');

		clearInterval(mobile_polls_interval);
	}
}


/*Function to check homepage dates links
  receives anchor element, ajax get to it
  and if error remove the anchor element
  with text  and update class on li element
*/
function check_dates_menu_link(element){
    var link = $(element).attr('href');
    $.ajax({
        url:link,
        method: 'GET',
        success: function(response){
        },
        error: function( jqXHR, textStatus, errorThrown){
            if(jqXHR.status == 404 || jqXHR.status == 403){
                var text = $(element).text();
                $(element).parent().html(text).addClass("no_link");
            }
        }
    });
}


/** sets up the skyscrapers on the left and right on homepage, enable after function */
function hp_floating_skyscrapers(){
	//Homepage - Floating SkyScraper Ads...
	if( $("body.home").length > 0 ){

		var winWidth = $(window).width();

		var adMarkup = '<ul><li class="RC-AD RC-AD-SKY-TOP"></li><li class="RC-AD RC-AD-SKY-BOTTOM"></li></ul>';
		var adMarkUpAbsolute = '<li class="top-left RC-AD RC-AD-SKY-TOP"></li><li class="top-right RC-AD RC-AD-SKY-BOTTOM"></li>';

		if( winWidth >= 1520 ){
			//console.log("SCREEN WIDTH: You Meet Scrn Wid. Show Ads on Sides....");
			//console.log("Soups On.... Pre-Appending SkyScrapers to Container....");
			$("#container").prepend(adMarkUpAbsolute);
		}else{
			//console.log("SCRN WID: No Soup For You.... Going Hulk...");
			$(".gamma").append(adMarkup);
		}

		//var top_sky_pos = $("#most-read-box").position();
		//var top_sky_left = (top_sky_pos.left+45)+"px";
		var top = $('#container').offset().top;
		var offset_left = ($("#container").offset().left) + 'px';
		var offset_full = ($("#container").offset().left + 1360) + 'px';

		$(window).on('resize', function(){
		    //console.log('RESIZING THE SOUP BOWL');

		    winWidth = $(window).width();
		    top = $('#container').offset().top;
			offset_left = ($("#container").offset().left) + 'px';
			offset_full = ($("#container").offset().left + 1360) + 'px';
			$(window).scroll();

		}).resize();

		if( winWidth >= 1520 ){
			$(window).scroll(function (event) {
			  var y = $(this).scrollTop();
			  if (y > top) {

				  $(".top-left, .top-right").css({
					  "position" : "fixed"
				  });

				  $(".top-left").css({
					  "left" : offset_left
				  });

				  $(".top-right").css({
					  "left" : offset_full
				  });

			  }else { 
				  $(".top-left, .top-right").css({
					  "position" : "absolute",
					  "top" : "5px"
				  }); 

				  $(".top-left").css({
					  "left" : 0
				  });

				  $(".top-right").css({
					  "left" : "1360px"
				  });

			  }
			}); //end window .scroll
		}
		
	}
}

//enable skyscrapers for specific sites
$(document).ready(function(){

	var skyscrapers_allowed_sites = [
		"politics",
		"defense",
		"world",
		"policy"
	];

	if( $.inArray(siteName, skyscrapers_allowed_sites) > -1 ){

		if( !$('body').hasClass('with-distroscale') ){
			hp_floating_skyscrapers();
		}
	}

	videoWidgetGaEvents();

	// Distroscale JS DST
	if($('body').hasClass('with-distroscale') && window.innerWidth >= 1025){

        $dstro = $('div.distro_spot');
        $dstro.append("<div id=\'ds_default_anchor\' style=\'margin-left:15px;\'></div>");

        var distroscale = document.createElement('script');
        distroscale.type = 'text/javascript'; distroscale.async = true; 
        distroscale.src = (document.location.protocol == "https:" ? "https:" : "http:") + '//c.jsrdn.com/s/cs.js?p=22663';
        var dstrox = document.getElementsByTagName('script')[0];
        dstrox.parentNode.insertBefore(distroscale, dstrox);     

        var videoWrapper = $('.pop-wrapper');

        var isOverrideCSS = ''; 
        if ($('.pop-wrapper').hasClass("override_1") == true){ //checks if override order set
        	var isOverrideCSS = 'noHeading'; //hide heading and top-border  
        }


        var videoHtml = '<div id="popular" class="section-header video-heading dynamic '+isOverrideCSS+'">\
                            <h2><a href="/video">Videos</a></h2>\
                        </div>\
                        <div class="pop-wrapper dynamic">\
                            '+videoWrapper[0].innerHTML+'\
                        </div>';

        $('#mc_rclife').before(videoHtml);

        window.closeDstEvent = function(){

        	var body = $('body');
        	var bodyClassList = "";
        	if(body[0]){
        		bodyClassList = body[0].classList.value;
        	}

        	var data = {
	          'ge_action' : 'Click',
	          'ge_category' : 'DST Events',
	          'ge_label' : bodyClassList+' fixed-player close btn'
	        };

	        send_ga_event(data);
        }
    }
    // End Distroscale JS DST
	
}); //end doc ready

function videoWidgetGaEvents(){

	//set the positon for list view video widget
	$('.list-view div.pop-wrapper .pop-item').each(function(index, el){
        $('a',el).attr('click-index', (parseInt(index)+1) );
    });

	//set the positon for grid view video widget
    $('.grid-view div.pop-wrapper .pop-item').each(function(index, el){
        $('a',el).attr('click-index', (parseInt(index)+1) );
    });

    //set the click handler to send ga event if anchor is clicked
    $('div.pop-wrapper').on('click', 'a', function(e){

        triggerVideoGaEvent($(this).attr('click-index'));
    });

    $('#popular').on('click', 'a[href="/video"]', function(e){
    	
    	triggerVideoGaEvent(0);
    });

    var triggerVideoGaEvent = function(pos){

    	var data = {
          'ge_action' : 'Click',
          'ge_category' : 'HP MC Video Section',
          'ge_label' : 'position: '+pos
        };

        send_ga_event(data);
    }
}