$(function() {
	
	if($('.swipe').length > 0){
		swipePage();
	}

	//set tab if query string
	if($('.baseTab').length > 0){
		if(getUrlVars()["tab"] == "reg"){
			setRegTab();
		} else {
			setTabs();
		}
	}
	
	//set tab if errors
	if($('#loginRight .rf-msgs-err').length > 0){
		var myId = $('.rf-msgs-err').attr('id');
		if(myId.indexOf('webId')!=-1 || myId.indexOf('register')!=-1){
			setRegTab();
		}
	}
	
	//set tab on click
	$('.baseTab').on('click', function(){
		$('.baseTab').removeClass('activeTab');
		$(this).addClass('activeTab');
		setTabs();
	});
	
	$('.baseTab').keydown(function(ev) {
		if (ev.which ==13) {
			$(this).click()
		}
	});
	
	//temp hack for Remember Me until proper required code
	$('#loginRight #rememberMe').parent().children('label').css('backgroundColor','#ffffff');

	tooltipTrigger();
	
	var myModalTrigger;
	$('a[target="_blank"], a[target="blank"], a[target="_new"], a[target="new"]').click(function(e){
		closeMobileNav();
		myModalTrigger = this;
		
		// avoid richface modal links by removing links with onclick to popup
		if(!$(this).attr('onclick')){
			e.preventDefault();
			url = this.href;
			if(url.indexOf('compsych') != -1 || url.indexOf('hgWindow') != -1 || url.indexOf('PrinterFriendly') != -1){
				$('#iBodyLocal').show();
			} else {
				$('#iBodyExternal').show();
			}
			linkText = $(this).html();
			$('#interstitial_container').modal('show');
			$('.extLinkText').html(linkText);
			$('#continueBtn').click(function(){
				window.open(url, '_blank');
			});
		}
	});

	$('#interstitial_container').on('shown.bs.modal', function (e) {
		modalKeyTrap("interstitial");
	})
	
	$('#interstitial_container').on('hidden.bs.modal', function (e) {
		$('#continueBtn').unbind('click');
		$('#iBodyLocal').hide();
		$('#iBodyExternal').hide();		
		myModalTrigger.focus();
	})
	
	$('a[onclick*="popup"]').on('click',function(e){
		var tgt = $(this).attr('onclick');
		var clickObj = $(this);
		if(tgt.indexOf('target') != -1){
			// extract target value (e.g.) "target":["j_idt569:j_idt580:popup"]
			var start = tgt.indexOf('target') + 10;
			var end = tgt.indexOf('popup') + 5;
			var text = tgt.substring(start,end);
			tgtId = text;
		} else {
			var tgtId = tgt.split(/'/)[1];
		}
		modalKeyTrap(tgtId,clickObj);
	});

	// if no banner text, change banner cols
    if(!$.trim($(".topText").html())){
    	$('.mainLogoCol').removeClass('col-md-5').addClass('col-md-9').removeClass('col-sm-5').addClass('col-sm-9').next().removeClass('col-md-4').addClass('hidden-md').removeClass('col-sm-4').addClass('hidden-sm');
    }


	// remove any empty headings tags
	$('h1,h2,h3,h4,h5,h6,#loginRight .rf-msgs').filter(function(){return $.trim($(this).text()).length==0;}).remove();


	$('.rf-cal-btn').on('click', function(){
		$('.rf-cal-popup').css({'top':$(this).offset().bottom+'px','left':$(this).offset().left+'px'});
	});


	//skip to main content helper - scroll to content top and give focus
	$('#skip a').on('click', function(e){
		e.preventDefault();
		$("body, html").animate({ 
			scrollTop: $('#content').offset().top - 60
		},500);
		$('#content').attr('tabindex', -1).on('blur focusout', function () {
          $(this).removeAttr('tabindex');
        }).focus();
	});


	//Jquery Tabs for most viewed and locales
	$("#mostViewedTabs").tabs();
	$("#localeSelectionTabs").tabs();
	$("#healthyGuidanceTabs").tabs();
	$("#assetTabs").tabs();
	$("#groupTabs").tabs();
	
	$("#localeSelectionTabs").tabs("option", "active", $('#selectedRegion').val());
	

	//test if page has article tiles -- keep as one of first events on page
	if($('.topicList').length > 0){	
		//if only link, no abstract text, remove tile style
		$('.topicList .abstractText').each(function(){
			if($(this).is(':empty')){
				$(this).parent().parent('.topicList').removeClass();
				$(this).prev().css('fontWeight','normal');
				$(this).parent('p').css('marginBottom','0');
			}
		});
	

		//news archive, etc. -- only set of links
		$('.topicList p span').each(function(){
			if(!$(this).parent().parent().parent().parent().hasClass('archiveTopicList') &&
				!$(this).parent().parent().parent().hasClass('homeTopicList') &&
				!$(this).hasClass('abstractText')){
					$(this).parent().parent('.topicList').removeClass();
					$(this).prev().css('fontWeight','normal');
			}
		});


		//append frame to bottom of tile so text has bottom padding
		topicTileBottom();

		
		//hover style so bottom frame changes with hover state
		$('.topicList p').hover(function(){
			$(this).children('.tileBottomBuffer').removeClass('topicRevert').addClass('topicHover');
		}, function(){
			$(this).children('.tileBottomBuffer').removeClass('topicHover').addClass('topicRevert');
		});			
	}


	/* Remove all greyEight links from articles */
	$(".greyEight").each(function(index) {
		$(this).parent().remove();
	});


	/* 
	 * if the user scrolls past 300px
	 * lets show the "back to top" icon
	*/
	if ($('#backToTop').length) {
		var scrollTrigger = 300, // px
		backToTop = function () {
			var scrollTop = $(window).scrollTop();
		
			if (scrollTop > scrollTrigger) {
				$('#backToTop').fadeIn();
			} else {
				$('#backToTop').fadeOut();
			}
		};

		backToTop();

		$(window).on('scroll', function () {
			backToTop();
		});

		$('#backToTop').on('click', function (e) {
			e.preventDefault();
			$('html,body').animate({
				scrollTop: 0
			}, 300);
		});
	}
	

	/*
	 *  Lets handle HTML5 videos.  If HTML5 videos fail to load
	 * lets fall back on flash videos
	 */
	try {
		var htmlVideo = $("#htmlVideo").get(0);
		var flashVideo = $("#flashVideo").get(0);

		function showFlashVideo() {
			$("#htmlVideo").hide();
			$("#flashVideo").show();
		}

		/*
		* If HTML-5 Video errors out,
		* load the flash video player
		*/
		htmlVideo.addEventListener('error', function(e) {
			console.log("HTML-5 video failed with error code: " + htmlVideo.error.code + "\n\r");
			console.log("Loading Flash video player instead. \n\r");
			showFlashVideo();
		});

		/*
		* If HTML-5 Video is not loaded after 5 seconds,
		* load the flash video player
		*/
		setTimeout(function() {
			console.log("HTML-5 Video Ready State: " + htmlVideo.readyState + "\n\r");
			if (htmlVideo.readyState == 0) {
				showFlashVideo();
			}
		}, 5000);
	}
	catch(ex) {
		console.log(ex.message);
	}

	/*
	 * POTENTIALLY PROBLEMATIC FEATURES
	 * MOVED TO BOTTOM OF PAGE
	 */
	
	// Sticky nav for desktop
	$('#topAndBottomNav').affix({
	    offset: { top: $('#topAndBottomNav').offset().top }
	});

	// Sticky nav for mobile
	$('#mobileNav').affix({
	    offset: { top: $('#topAndBottomNav').offset().top }
	});

	//Render side menu after everything loads
	$('nav#menu').show();
	$('nav#menu').mmenu({
		   // options
	}, {
	   // config
	   offCanvas: {
	      pageSelector: "#bodyContainer"
	   }
	});
	$('.hiddenInitially').show();
});



function topicTileBottom(){
	$('.topicList p').each(function(){
		$(this).append('<div class="tileBottomBuffer"></div>');
	});
}


function swipePage(){
	$(".bottomBar").mCustomScrollbar({
		theme:"3d-thick-dark",
		scrollButtons:{ enable: true }	
	});
				
	$('.main').on('init', function () {
	    $('.articleContent').css('display', 'block');
	});
					
	if($('html').attr('dir') == 'rtl'){
		$('.main').slick({
		  rtl: true
	  });
	} else {
		$('.main').slick({
			  rtl: false
		  });
	}

	$('.main').on('afterChange',function(e,s,c,n){
		changeSwipeMenu(c);
	});

	$('.tree .rf-trn:first').addClass('active');

	$('.tree a').each(function(index){
		$(this).attr('id',index);
	});

	$('.crisisImg span').each(function(index){ 
		$(this).attr('id','img'+index);
	});

	$('.tree a').on('click',function(){
		var myId = $(this).attr('id');
		$('.main').slick('slickGoTo',myId);
		changeSwipeMenu(myId);
	});
}


function changeSwipeMenu(x){
	$('.crisisImg span').hide();
	$('.tree .rf-trn').removeClass('active');
	$('#img' + x).show();
	$('#'+x).parent().parent().parent('.rf-trn').addClass('active');	
}

//general tab setting
function setTabs(){
	$(".baseTab").each(function(){
		if(!($(this).hasClass('activeTab'))){
			var hiddenTabs = $(this).attr('id');
			hiddenTabs = hiddenTabs.slice(0,-3);
			$('#'+hiddenTabs).hide();
			$(this).attr('aria-selected','false');
		} else {
			var showTab = $(this).attr('id');
			showTab = showTab.slice(0,-3);
			$('#'+showTab).show();		
			$(this).attr('aria-selected','true');
		}
	});	
	if($('#loginRight .rf-msgs-err').length > 0){
		setTabErrors();
	}
}

//set Register tab on load
function setRegTab(){
	$('.baseTab').removeClass('activeTab');			
	$('#registerTab').addClass('activeTab');
	setTabs();
}

//if errors set correct tab
function setTabErrors(){
	var myId = $('.rf-msgs-err').attr('id');
	if(myId.indexOf('webId')!=-1 || myId.indexOf('register')!=-1){
		if($('#register').css('display') == 'none'){
			$('.rf-msgs').hide();
		} else {
			$('.rf-msgs').show();
		}
	} else {
		if($('#login').css('display') == 'none'){
			$('.rf-msgs').hide();
		} else {
			$('.rf-msgs').show();
		}
	}	
}

//get key value pairs from query string
function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}

//for locale picker - pull id from onclick
function modalFocus(e){
	var cString = $(e.target).attr('onclick');
	var myValue = cString.split(/'/)[1];
	modalKeyTrap(myValue);
}

//accessibility - modals must not lose focus to background until "close" or esc key
//pass id of main modal container
function modalKeyTrap(id,clickObj){			
	
	// escape : and . from jsf ids
	var who = "#"+id.replace( /(:|\.|\[|\]|,)/g, "\\$1" )+"_container";
	
	// find all tabbable elements in modal + first & last
	var inputs = $(who).find('select, input, textarea, button, a').filter(':visible');
	var firstInput = inputs.first();
	var lastInput = inputs.last();
	
	// hide modal on escape key
	$(document).keydown(function(e) { 
    	if (e.keyCode == 27) { 
    		if(typeof RichFaces.$(id) === "undefined"){
    			$(id).hide(); 
    		} else {
    			RichFaces.$(id).hide();
    		}
    		// return focus to original link clicked
    		if(typeof clickObj !== "undefined"){
    			clickObj.focus();
    		}
		} 
	});
	
	/*set focus on first input*/
	firstInput.focus();

	/*redirect last tab to first input*/
	lastInput.on('keydown', function (e) {
	   if ((e.which === 9 && !e.shiftKey)) {
	       e.preventDefault();
	       firstInput.focus();
	   }
	});

	/*redirect first shift+tab to last input*/
	firstInput.on('keydown', function (e) {
	    if ((e.which === 9 && e.shiftKey)) {
	        e.preventDefault();
	        lastInput.focus();
	    }
	});
	
	closeMobileNav();
}

function closeMobileNav(){
	var mnu = $('#menu').data("mmenu");
	mnu.close();	
}


function tooltipTrigger() {
	var isiOS = /iPad|iPhone|iPod/.test(navigator.platform); // Is this device an iOS device
	var isAndroid = /(android)/i.test(navigator.userAgent); // Is this device an Android device
	var options = {
		trigger:'manual', // We'll be manually handling bootstrap tooltips
		html: true, // Render basic html
		container: 'body'
	};

	$('[data-toggle="tooltip"]').tooltip(options).click(function(e) {
		e.preventDefault(); // Prevent browser from jumping when tooltip link is clicked
	});

	// If device is ios, change cursor to a pointer (safari bug fix)
	if (isiOS)
		$('[data-toggle="tooltip"]').css( 'cursor', 'pointer' );
	
	$('[data-toggle="tooltip"]').on('click', function(e) {
		var tip = $(this); // Store clicked tip for later
		var tipId = tip.attr('aria-describedby'); // Get and store clicked tip id for later
		var hidden, sameTip = false;
		var altTipId = null;
		console.log("Tip Id: " + tipId);

		// For each tooltip currently shown, lets hide them
		// There should only be one .tooltip class shown at a time though
		$('.tooltip').each(function (e){ 
			altTipId = $(this).attr('id'); // Store the tip id of the tip we're hiding for later
			console.log("New tooltip id: " + altTipId);
			console.log("Hiding all tooltips!");
			hidden = true;
			sameTip = tipId === altTipId;
			$(this).tooltip('hide'); // Hide currently shown tip
		}).promise().done(function(e) { // Make sure this runs when the previous block is finished
			if (!hidden || !sameTip) {
				console.log("Showing tooltip with id: " + tipId);
				tip.tooltip('show'); // Show newly clicked tooltip
			}
		});
	});

	// This will run after the tooltip is shown
	$('[data-toggle="tooltip"]').on('shown.bs.tooltip', function(e) {
		var tip = $(this); // Store the clicked tip in a variable for later

		// Bind tooltip to click
		$('.tooltip').on('click', function(e) {
			console.log("Hiding current tooltip");
			tip.tooltip('hide');
		});

		if (isiOS) {
			// Bind body to touchstart
			$('body').on('touchstart', function(e) {
				console.log("Hiding current tooltip from touch");
				tip.tooltip('hide');
			});
		}
		else {
			// Bind body to click
			$('body').on('click', function(e) {
				console.log("Hiding current tooltip from click");
				tip.tooltip('hide');
			});
		}
	});

	// This will run after the tooltip is hidden
	// Unbind click and touchstart from body
	$('[data-toggle="tooltip"]').on('hide.bs.tooltip', function(e) {
		console.log("Removing document 'click' bind");
		if (isiOS)
			$('body').off('touchstart');
		else
			$('body').off('click');
	});
}

function progressBar(){
	
	var elem = document.getElementById("myBar"); 
	var width = 0;
	var id = setInterval(frame, 10);
	var earned = $("#earnP input").length > 0 ? $("#earnP input").val() : 0;
	var total = $("#maxP input").length > 0 ? $("#maxP input").val() : 0;
	var completed = $("#completed input").length > 0 ? $("#completed input").val() : "";	
	var earnText =  $("#earnT input").val().toLowerCase();
	var rewardText = $("#rewardT input").val().toLowerCase();
	var type = $("#symbols input").length > 0 ? $("#symbols input").val().toLowerCase() : "rewards";
	var actText = $("#activityT input").val() == "Actividad" ? "Actividades" : "Activities";
	var compText = $("#activityT input").val() == "Actividad" ? "Completadas" : "Completed";
	var labelText = $("#rewardLabel input").val().toLowerCase();
	
	if(rewardText.indexOf('premios')!==-1){
		rewardText = " hay " + rewardText;
	} else {
		rewardText = rewardText + "s";
	}
	var percent, pre, post, longP, userPts, userMessage;
	
	if($("#prefix input").length > 0){
		pre = type;
		post = "";
	} else {
		pre = "";
		post = type;	
	}
	
	userMessage = pre + earned + " " + post + " " + earnText;

	if(completed == ""){
		if(earned == 0){
			percent = 0;
			if(total == 0){
				$('#label0').html("");
				$('#label4').html("");
			}
		} else if(earned > 0 && total == 0){
			percent = 100;
			$('#label0').html("");
			$('#label4').html("");
		} else {
			percent = Math.round((earned/total) * 100);
		}
		if(total != 0){
			$('#label0').html(pre + "0 " + post);	
			$('#label4').html(pre + total + " " + post);
		}	
	} else if(completed != ""){
		if(earned > 0 && total != 0){
			$('#label0').html(pre + "0 " + post);	
			$('#label4').html(pre + total + " " + post);	
			percent = Math.round((earned/total) * 100);
		} else if(earned == 0 && total != 0){
			percent = 0;
			$('#label0').html(pre + "0 " + post);	
			$('#label4').html(pre + total + " " + post);
		} else if(earned > 0 && total == 0){
			percent = 100;
			$('#label0').html("");	
			$('#label4').html("");
		} else {
			percent = 100;
			$('#label0').html("");	
			$('#label4').html("");
		}
	}
	
	$('#myProgress').attr("data-amount",percent);

	function frame() {
		if (width >= percent) {
			clearInterval(id);
			$('.user').fadeIn();
		} else {
			width++; 
			elem.style.width = 100 - width + '%'; 
			//document.getElementById("label").innerHTML = width * 1 + '%';
			$('.user').html(userMessage);
			if (percent < 93) {
				$('.user').css({"left":userPts+"%"}).hide();
			} else {
				$('.user').css({"left":"auto","right":0}).hide();
			}
		}
		if(completed == ""){
			if(earned == 0){
				if(total != 0){
					$('.user').html("No " + labelText + " " + earnText);
					$('.user').fadeIn();
				} else {
					$('.user').html("No " + actText + " " + compText);
					$('.user').fadeIn();
				}
			}
		} else if(completed != "") {
			if(earned == 0){
				if(total != 0){
					$('.user').html("No " + rewardText + " " + earnText);
					$('.user').fadeIn();
				} else {
					$('.user').html(actText + " " + compText);
					$('.user').fadeIn();
				}
			}			
		}
		
		if (width <= 25) {
			userPts = width;
		} else if (width <= 50 ){
			userPts = width - 7;
		} else if (width <= 75) {
			userPts = width - 10;
		} else {
			userPts = width - 15;
		}
	}
}