/*
MMR Javascript File
AUTHOR: Jason Zajac & TJ Nicolaides
VERSION: 1.2
****************************/
if (!window.console) { 
    window.console = {
        log: function(obj){ /* define own logging function here, or leave empty */ }
    };
}

$(document).ready(function() {
						   
/* Mobile Redirect Message */

//var mobileCookie = $.getUrlVar('MMRsite');
var mobileCookie = getParameterByName(window.location.href, 'MMRsite');
var cookie = readCookie('MMRMobileCookie');
var expDate =new Date();
expDate.setDate(expDate.getDate()+1);
expDate = expDate.formatDate("D, j M Y G:i:s %U%T%C");
if(mobileCookie === "desktop") {
	document.cookie = 'MMRMobileCookie=desktop; expires=' + expDate + '; path=/';
} else {
	if (cookie === "mobile") {
		window.location.href = 'http://m.wmmr.com';
	} else if (cookie === "desktop") {
		//Do Nothing
	} else {
		if (jQuery.browser.mobile === true) {
			$("body").append("<div class=\"mobile-alert\"><div class=\"message\"><h3>MMR's Gone Mobile...</h3>Hey! You're on a mobile device. Are you sure you want to be browsing the desktop site? How about checking out the mobile version?<div class=\"user-options\"><a href=\"#\" class=\"yes\">Yes, please</a><a href=\"#\" class=\"no\">No thanks</a></div></div></div>");
			
			//Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
			var popMargTop = ($('.mobile-alert .message').height() + 80) / 2;
			var popMargLeft = ($('.mobile-alert .message').width() + 80) / 2;
			
			//Apply Margin to Popup
			$('.mobile-alert .message').css({
				'margin-top' : -popMargTop,
				'margin-left' : -popMargLeft
			});
			
			var expDate =new Date();
			expDate.setDate(expDate.getDate()+14);
			expDate = expDate.formatDate("D, j M Y G:i:s %U%T%C");
			
			$(".mobile-alert .message a").live("click", function(e) {
			e.preventDefault();
			var option = $(this).attr("class");
			if (option === "no") {
				document.cookie = 'MMRMobileCookie=desktop; expires=' + expDate + '; path=/';
				$(".mobile-alert").remove();
			} else if (option === "yes") {
				document.cookie = 'MMRMobileCookie=mobile; expires=' + expDate + '; path=/';
				window.location.href = 'http://m.wmmr.com';
				return false;
			}
			});
		}
	}
}

/* PTI */

getOnAir();
getGCal();
						   		
/** Search Input **/
$("input#q2").focus(function() { $(this).css({ "color" : "#9F0909" }); });
$("input#q2").blur(function() { $(this).css({ "color" : "#9F0909" }); });

/* AUDIO PLAYER TOOLTIPS */

if(FlashDetect.installed){
	$(function () {
	  $('div[id*="Audio"]').each(function () {
		$(this).addClass("blog-audio-player");
		$(this).parent('div').addClass("blog-audio-container");
		var blogEntryID = ($(this).attr('id')).split('_')[1].slice(0,8);
	
		$(this).after("<div class='blog-audio-tooltip'><p>To listen, <b>click the play button</b>.</p><p>Don't see it? Listen on our <a href='http://m.wmmr.com/?entry_id="+blogEntryID+"'>mobile site</a> or <a href='http://www.wmmr.com/about/podcasting/'>get help here</a>.</p></div>");
		
		// options
		var distance = 30;
		var time = 250;
		var hideDelay = 500;
		
		if ($(this).height() > 50) {
			var init_bottom = 25;
		} else {var init_bottom = 10; }
		
		var hideDelayTimer = null;
	
		// tracker
		var beingShown = false;
		var shown = false;
		
		var trigger = $(this);
		var popup = $(trigger).siblings('.blog-audio-tooltip').css('opacity', 0);
		var popupWidth = $(trigger).width();
		
		// animate when the page loads
		setTimeout(function() {      
			beingShown = true;
			popup.css({
				  bottom: init_bottom, display: 'block' // brings the popup back in to view
				  })        
				.animate({opacity:1}).animate({left:'-=5px'}).animate({left:'+=5px'}).animate({left:'-=5px'}).animate({left:'+=5px'}).animate({left:'-=5px'}).animate({left:'+=2px'}, function () {
			  // reset the timer if we get fired again - avoids double animations
			  if (hideDelayTimer) clearTimeout(hideDelayTimer);
					  beingShown = false;
					  shown = true;
			  // store the timer so that it can be cleared in the mouseover if required
			  hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.animate({
				  bottom: '-=' + distance + 'px',
				  opacity: 0
				}, time, 'swing', function () {
				  // once the animate is complete, set the tracker variables
				  shown = false;
				  // hide the popup entirely after the effect (opacity alone doesn't do the job)
				  popup.css('display', 'none');
				});
			  }, 4000);
			});
		}, 4000);
	
		// set the mouseover and mouseout on both element
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
		  // stops the hide event if we move from the trigger to the popup element
		  if (hideDelayTimer) clearTimeout(hideDelayTimer);
	
		  // don't trigger the animation again if we're being shown, or already visible
		  if (beingShown || shown) {
			return;
		  } else {
			beingShown = true;
			// reset position of popup box
			popup.css({
			  bottom: init_bottom + 30,
			  //left: -10,
			  display: 'block' // brings the popup back in to view
			})
			// (we're using chaining on the popup) now animate it's opacity and position
			.animate({
			  bottom: '-=' + distance + 'px',
			  opacity: 1
			}, time, 'swing', function() {
			  // once the animation is complete, set the tracker variables
			  beingShown = false;
			  shown = true;
			});
		  }
		}).mouseout(function () {
		  // reset the timer if we get fired again - avoids double animations
		  if (hideDelayTimer) clearTimeout(hideDelayTimer);
		  
		  // store the timer so that it can be cleared in the mouseover if required
		  hideDelayTimer = setTimeout(function () {
			hideDelayTimer = null;
			popup.animate({
			  bottom: '-=' + distance + 'px',
			  opacity: 0
			}, time, 'swing', function () {
			  // once the animate is complete, set the tracker variables
			  shown = false;
			  // hide the popup entirely after the effect (opacity alone doesn't do the job)
			  popup.css('display', 'none');
			});
		  }, hideDelay);
		});
	  });
	});
} else {
	$('div[id*="Audio"]').each(function () {
		$(this).addClass("blog-audio-player");
		$(this).parent('div').addClass("blog-audio-container");
		var blogEntryID = ($(this).attr('id')).split('_')[1].slice(0,8);
	
		$(this).html("<div class='blog-audio-tooltip'><p>Listen on our <a href='http://m.wmmr.com/?entry_id="+blogEntryID+"'>mobile site</a> or <a href='http://www.wmmr.com/about/podcasting/'>get help here</a>.</p></div>");
		
		var trigger = $(this);
		var popup = $(trigger).children('.blog-audio-tooltip').css('display', 'block').css('background-position', '100% 100%').css('position', 'relative').css('left', 0);
	});
}


/** Philly's Hottest Voting	**/
	$("div.votingOptions div.otherSubmission input, div.votingOptions div.otherSubmission label").remove();
	$("span.errorHeader").html("There was an error during submission. Please select one contestant.");
	$("input[id*='chkSongID']").live("click", function() {
			$("input[id*='chkSongID']").attr("checked", false);		
			$(this).attr("checked", true);
	});
					  						
// ALLOWS YOU TO SELECT ALL EXTERNAL LINKS WITH $('a:external')					
$.expr[':'].external = function(obj){
return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname) && !obj.href.match(/^javascript\:/);
};

//FORCES ALL EXTERNAL LINKS TO OPEN IN NEW WINDOW
$('a:external').attr("target","_blank");

//Remove LOGIN/REGISTER form from On-Air Contest posts
if ( $("span.header span:contains('[ON-AIR]')").length > 0 ) {
	$("span.header").parents('div:eq(0)').next("div").remove();
} else if ( $("span.header span:contains('[ONLINE*]')").length > 0 ) {
	$("div[ id *= 'UnivLoginVerify_pnlLogin' ]").remove();
}
	
//Remove LOGIN/REGISTER form from On-Air Contest posts
if ( $("span.header span:contains('[ON-AIR]')").length > 0 ) {
	$("span.header span:contains('[ON-AIR]')").each(function() {
	$("div[ id *= 'UnivLoginVerify_pnlLogin' ], div.hdiv11, div[id*='MemberAuthenticated']").remove();
	});
} else if ( $("span.header span:contains('[ONLINE*]')").length > 0 ) {
	$("span.header span:contains('[ONLINE*]')").each(function() {
	$("div[ id *= 'UnivLoginVerify_pnlLogin' ], div.hdiv11, div[id*='MemberAuthenticated']").remove();
	});
}

//makeShareButtons.init({tw:true});

	/** Facebook "Like" Button // Twitter // Google + // AddThis **/	

	var page_name = returnDocument();
	
	if(page_name == "home.aspx" || page_name == null || page_name =="index.aspx" || page_name == "") {
			var pathName = returnPath();
			
		$('table.blogs_home_link').each(function(){
			var entryLink = $(this).find("a:last").attr("href");
			var shareHTML = makeShareButtons.init({url:entryLink});
			$(this).after(shareHTML);

		});
		
		$('a.jumperlink').not($("div.contestTeaser a.jumperlink")).each(function(){
			var entryLink = pathName + $(this).attr("href");
			var shareHTML = makeShareButtons.init({url:entryLink});
			$(this).after(shareHTML);
		});
		
		FB.XFBML.parse();

	}
	else if (page_name == "blogentry.aspx") {	
		var shareHTML = makeShareButtons.init({at:true, tw:true, gp:true});
		$('table.blog_entry td.mini').append(shareHTML);
		$.addthis('jzajac');
		$.getScript("http://platform.twitter.com/widgets.js");
		$.getScript("https://apis.google.com/js/plusone.js");
		FB.XFBML.parse();
	}
	else if (page_name == "story.aspx") {
		var shareHTML = makeShareButtons.init({at:true, tw:true, gp:true});
		$('a.jumperlink[href*="TellAFriend"]').after(shareHTML).remove();	
		$.addthis('jzajac');
		$.getScript("http://platform.twitter.com/widgets.js");
		$.getScript("https://apis.google.com/js/plusone.js");
		FB.XFBML.parse();
	}
	
	$(".share-this").each(function(){
		if($(this).hasClass("all")) {
			var shareHTML = makeShareButtons.init({at:true, tw:true, gp:true});
			$(this).html(shareHTML);
			$.addthis('jzajac');
			$.getScript("http://platform.twitter.com/widgets.js");
			$.getScript("https://apis.google.com/js/plusone.js");
			FB.XFBML.parse();
		} else {
			var shareHTML = makeShareButtons.init({});
			$(this).html(shareHTML);
			FB.XFBML.parse();
		}
	});

//PLACE ADS
$("div#bottom-banner").html("<iframe id='a50223c2' name='a50223c2' src='http://banners.andomedia.com/openx_gm/www/delivery/afr.php?n=a50223c2&amp;zoneid=329&amp;cb=INSERT_RANDOM_NUMBER_HERE' framespacing='0' frameborder='no' scrolling='no' width='468' height='60'><a href='http://banners.andomedia.com/openx_gm/www/delivery/ck.php?n=a9c5e759&amp;cb=INSERT_RANDOM_NUMBER_HERE' target='_blank'><img src='http://banners.andomedia.com/openx_gm/www/delivery/avw.php?zoneid=329&amp;cb=INSERT_RANDOM_NUMBER_HERE&amp;n=a9c5e759' border='0' alt='' /></a></iframe><script type='text/javascript' src='http://banners.andomedia.com/openx_gm/www/delivery/ag.php'></script>");
$("div#ll_ad").html("<iframe id='ac9a0f7f' name='ac9a0f7f' src='http://banners.andomedia.com/openx_gm/www/delivery/afr.php?n=ac9a0f7f&amp;zoneid=331&amp;cb=INSERT_RANDOM_NUMBER_HERE' framespacing='0' frameborder='no' scrolling='no' width='120' height='60'><a href='http://banners.andomedia.com/openx_gm/www/delivery/ck.php?n=a8721a67&amp;cb=INSERT_RANDOM_NUMBER_HERE' target='_blank'><img src='http://banners.andomedia.com/openx_gm/www/delivery/avw.php?zoneid=331&amp;cb=INSERT_RANDOM_NUMBER_HERE&amp;n=a8721a67' border='0' alt='' /></a></iframe><script type='text/javascript' src='http://banners.andomedia.com/openx_gm/www/delivery/ag.php'></script>");
	
	/** Random Masthead Image **/
	var mh = ["masthead-v1-foo-fighters.png", "masthead-v1-green-day.png", "masthead-v1-pearl-jam.png", "masthead-v2-nirvana.png", "masthead-v2-metallica.png", "masthead-v2-u2.png", "masthead-v2-guns-n-roses.png"];
	var mhpath = "http://www.wmmr.com/Pics/Global/masthead/";
	var randomNumber = 0;
	$('img#mmr-masthead').attr('src', mhpath + mh[Math.round(Math.random()*(mh.length-1))] );

	/**POP-UP WINDOWS **/
	/*AV PLAYER*/ $(".av-popup").popup({width: 675, height: 320});
	/*Listen Live HD1*/ $(".stream-popup-lc").popup({width: 680,height: 511});
	/*Listen Live HD2*/ $(".stream-popup-lc-hd2").popup({width: 680,height: 380});
	/*Listen Live STW*/ $(".stream-popup-stw, a[target='stream']").popup({width: 742,height: 388,resizeable: false,scrollbars: false,titlebar:false,status:false,toolbar:false,menubar:false});
	/*Webcam*/ $(".webcam-popup").popup({width: 980,height: 620,resizeable: true,scrollbars: true	});

	
	$("div.memberStatus span.lnkLogin a").append(" - VIP");
	$("div.memberStatus span").css("display", "inline-block");
	$('ul.sf-menu').superfish({
		autoArrows:  false,  
		dropShadows: false, 
		delay: 1000, 
		onBeforeShow:  function() {
			$("div.memberStatus").fadeTo(10, 0);
		}, 
		onHide: function() {
			if($('ul.sf-menu li.sfHover').length == 0) {	
				$("div.memberStatus").fadeTo(1000, 1);
			}
		} 
	});

// GOOGLE ANALYTICS TRACKING FOR PHOTO GALLERIES AND AV PLAYERS
	
	
if(pageTracker != null && typeof(pageTracker) != 'undefined') {
	
	$("div[ id *= 'AVPlayerFlash' ] > *").bind("click", function() {
		trackThis("AV Player", this);
	});
	
	$("div[ id *= 'Images_' ] > *").bind("click", function() {
		trackThis("Photo Gallery", this);
	});
	
	$("div[ id *= 'Audio_' ] > *").one("click", function() {
		trackThis("Audio Embed", this);	
	});
	
	$("a[href *='.mp3']").bind("click", function() {
		pageTracker._trackEvent('MP3 Download', $(this).context.hostname, $(this).attr('href'));
	});
	
	$('a:external').bind("click", function() {
		 pageTracker._trackEvent('Outbound Traffic', $(this).context.hostname, $(this).attr('href'));
	});
	
}
	
});


