


/**
 * Format Dates
 */
var dateRe = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/;
var dateFmt = "l, F jS, Y g:i a";
 
$(function(){
	$(".dates li").each(function(){
		var date = $(this).text();
		var dt = dateRe.exec(date);

		if(dt && dt.length == 6){
			var d = new Date(dt[1],dt[2]-1,dt[3],parseInt(dt[4],10),dt[5]);
			$(this).text(" | " + d.formatDate(dateFmt));
		}
		
	});
});

$(function(){
	$(".meta-info .published").each(function(){
		var date = $(this).text();
		var dt = dateRe.exec(date);
		
		if(dt && dt.length == 6){
			var d = new Date(dt[1],dt[2]-1,dt[3],parseInt(dt[4],10),dt[5]);
			$(this).text(" | " + d.formatDate(dateFmt));
		}
		
	});
});

$(function(){
		$(".datetime").each(function(){
			var date = $(this).text();
			if(date != null && date != ""){
				var d = new Date(date);
				$(this).text(d.formatDate("F jS"));
				$(this).show();
			}
		});
});


/**
 * Article Tools 
 *
 */
var addthis_pub  = 'rogersradio';
var addthis_options = 'email, favorites, facebook, digg, delicious, myspace, google, live, more';

$(function(){
		$(".article .articleTools").each(function(){
			var html = [];
			
			// bookmark
			html.push('<a onclick="return addthis_sendto(\'favorites\');" href="./"><img src="/images/skin/articletool-bookmark.gif" alt="Bookmark" border="0"></a>');
			
			// addthis
			html.push('<a href="http://www.addthis.com/bookmark.php" onmouseover="return addthis_open(this, \'\', \'[URL]\', \'[TITLE]\')" onmouseout="addthis_close()" onclick="return addthis_sendto()">');
			html.push('<img src="/images/skin/articletool-share.gif" width="60" height="16" border="0" alt="" /></a>');
			html.push('<script type="text/javascript" src="http://s7.addthis.com/js/152/addthis_widget.js"></script>');		
																		 
			$(this).html(html.join(''));	
		});
});



				

/**
 * Google Analytics
 * Depends on jquery.ga.js and urchin.js
 */
$(function(){
	if( FLAG_GOOGLE_ANALYTICS ) {
		options = {
			domains: ANALYTICS_TRACKED_DOMAINS,
			restricted: ['ad.doubleclick.net'],
			fileTypes : ['zip','wmv','gz','mov','txt','ppt','doc','xls','mpg','mpeg','mp3','pdf','avi'],
			trackAnchors : true,
			trackFiles : true,
			trackForms : true,
			debug: FLAG_DEBUG
		};
		$(document).ga(_uacct,options);
	}
});


/**
 * Modify external links to include an icon for opening in a new window.
 */
$(function(){
					 
	$("#content .article .content .copy a,#content .article .content .copy2 a").each(function(){
		var $link = $(this);
		var href = $link.attr("href");
    if ( !isCrossDomain(href) && !isRestricted(href) ) {
			$link.after(['<a href="',href,'" target="_blank" class="ext" title="[External Link] - Click to open in a new window.">&nbsp;</a>'].join(''));
		}
  });
					 
});


function isCrossDomain(href)  {
	var href = href.toLowerCase();
	var hostDomain = document.domain.toLowerCase();
	for(var i = 0; i < ANALYTICS_TRACKED_DOMAINS.length; i++) {
		if ( href.indexOf(ANALYTICS_TRACKED_DOMAINS[i].toLowerCase()) >= 0 && 
				 href.indexOf(hostDomain) <= -1 ) {
			return true;
		}
	}
	return false;
}


var EXT_IGNORE_DOMAINS = ['ad.doubleclick.net'];

function isRestricted(href) {
	var href = href.toLowerCase();
	if(href.indexOf("javascript:") >= 0) { return true; }
	if(href.indexOf("mailto:") >= 0) { return true; }
	for(var i = 0; i < EXT_IGNORE_DOMAINS.length; i++) {
		if ( href.indexOf(EXT_IGNORE_DOMAINS[i].toLowerCase()) != -1 ) {
			return true;
		}
	}
	return false;
}

/**
 * Login input fields behaviour. 
 */
 
var loyaltyUsr = "loyaltyUsr";
var loyaltyPwd = "loyaltyPwd";
var loyaltyRem = "loyaltyRem";
var loyaltyParam = { expires: 60 };

function initLoyaltyForm() {
		
	$("#username-field").click(function(){ hideFieldLabel("username",true); });
	$("#username").focus(function(){ hideFieldLabel("username",false); });
	$("#username").blur(function(){	checkFieldLabel("username");});
	
	$("#password-field").click(function(){ hideFieldLabel("password",true); });
	$("#password").focus(function(){ hideFieldLabel("password",false); });
	$("#password").blur(function(){	checkFieldLabel("password");});
	
	/*
	if($.cookie(loyaltyRem)) {
		$("#rememberme").attr('checked','checked');	
		$("#username").val($.cookie(loyaltyUsr));
		$("#password").val($.cookie(loyaltyPwd));
	}*/
	
	$("#loyalty").submit(function(){
		
		var usr = $("#username").val();
		var pwd = $("#password").val();
		var empty = usr == "" || pwd == "";
		
		if(!empty) {
			
			/*
			if($("#rememberme").attr('checked')) {
				$.cookie(loyaltyUsr,usr,loyaltyParam);
				$.cookie(loyaltyPwd,pwd,loyaltyParam);
				$.cookie(loyaltyRem,"true",loyaltyParam);
			} else {
				$.cookie(loyaltyUsr,null);
				$.cookie(loyaltyPwd,null);
				$.cookie(loyaltyRem,null);
			}*/
			
			return true;
			
		// Display an error message prompting for username and password
		} else {
			
			if(usr == "") { flashFieldLabel("username"); }
			if(pwd == "") { flashFieldLabel("password"); }
			$("#loyalty p#login-message").html('Please enter your username and password (or <a href="http://www.m2omedia.com/cftr/">sign-up</a>).');
			
			return false;
		}
		
	});

	setTimeout("checkFieldLabels()", 5000);

}

function flashFieldLabel(field) {
	$("#"+field+"-field").addClass("flash");
	setTimeout("$('#"+field+"-field').removeClass('flash')",100);
	setTimeout("$('#"+field+"-field').addClass('flash')",200);
}

function hideFieldLabel(field, setfocus) {
		$("#"+field+"-field label").hide();
		if(setfocus) {
			$("#"+field+"").focus();
			$("#"+field+"").select();	
		}
}

function checkFieldLabel(field) {
		if($("#"+field+"").val() == "") {
			$("#"+field+"-field label").show();
		} else {
			$("#"+field+"-field").removeClass("flash");
			hideFieldLabel(field);
		}
}
function checkFieldLabels() {
	checkFieldLabel("password");
	checkFieldLabel("username");
}


/**
 * Look for media - convert to tabs and appropriate display
 */
$(function(){
	var tabinst = 0;
	$('ul.media').each(function(){
		
		$links = $(this).find('li a');
		if($links.length == 0) return;
		
		var count = 0;
		var mediatabs = $('<ul id="#mediatabs-'+tabinst+'"></ul>');
		tabinst++;
		
		if($links.length > 1) {
			$links.each(function(){
				count++;
				var tabid = 'tab-'+tabinst+'-'+count;
				$(this).parent().attr("id",tabid);
				$(this).media();
				mediatabs.append('<li><a href="#'+tabid+'" title="'+this.text+'">&nbsp;'+count+'&nbsp;</a></li>');
			});
			$(this).before(mediatabs);
			mediatabs.tabs({ fxFade: true });
		} else {
			var src = $links.attr("href");
			$links.media();
			
			// add a download link except for FLV & SWFs
			if(src.indexOf("flv") == -1 && src.indexOf("swf") == -1) {
				$('ul.media').append("<p class='download'><a href='"+src+"' title='Having problems? Click here to download to your computer.'>[download]</a> <small>(To download: Right click-&gt;Save as..)</small></p>");
			}
		}
	});
});

$(function(){
	
	$('#content .tabify-media .record').each(function(){									
		tabify_media(this);									
  });
					 
});

/**
 * tabify_media
 *
 * @param rec The record to 'tabify'
 */
function tabify_media(rec)
{
	if ($(".media",rec).length) {
	
		$(rec).addClass("article-tab");
		
		$(".media",rec).hide();
		
		var tabs = [];
		tabs.push("<div class='articleTabs'>");
		tabs.push("<a id='tab-article'>Article</a>");
		tabs.push("<a id='tab-media'>Multimedia</a>");
		tabs.push("</div>");
		
		$(".articleTools",rec).after(tabs.join(''));
		
		$('#tab-article',rec).click(function(){
			$(rec).removeClass("media-tab"); $(rec).addClass("article-tab");
			$(".media",rec).hide();
			$(".image",rec).show();
			$(".related",rec).show();
			$(".copy",rec).show();
			$(".copy2",rec).show();
		});
		
		$('#tab-media',rec).click(function(){
			$(rec).removeClass("article-tab"); $(rec).addClass("media-tab");
			$(".image",rec).hide();
			$(".related",rec).hide();
			$(".copy",rec).hide();
			$(".copy2",rec).hide();
			$(".media",rec).show();
		});
	
	}
	
}



/**
 * Related Links. Finds all related links in the page 
 * and adds appropriate behaviour.
 */
$(function(){
	
	$('.related ul li a.audio').each(function(){
		var html = [];
		var href = $(this).attr("href");
		
		html.push('<div class="relatedAudioTools"><object type="application/x-shockwave-flash" width="17" height="17"');
		html.push('data="/images/skin/related-audio.swf?song_url=');
		html.push(href);
		html.push('&b_bgcolor=FFFFFF">');
		html.push('<param name="movie" value="/images/skin/related-audio.swf?song_url=');
		html.push(href);
		html.push('<param name="bgcolor" value="d0e6ef"/></object>');
		
		html.push(' <a href="');
		html.push(href);
		html.push('" class="dl" title="Right click-&lt;Save As to download this file to your computer.">[download]</a>');
		html.push('</div>');

		$(this).after(html.join(''));
		return false;
  });
	
	$('.related ul li a.video').each(function(){	
		$(this).mediabox();
		debugLog("Related Video: ", $(this).attr("href"));
  });	
	
	
});


/**
* Fancify pagination
*/
function fancifyPagination(id) {
	
	$(id+" .archivePagination").each(function(){
	
		var $pages = $(this).find('li');
		var $curr = $(this).find('.current');
		var $next = $curr.next().clone();
		var $prev = $curr.prev().clone();
		
		// Reduce the navigation if there are more than 5 pages.
		if($pages.length > 5) {
			$nextAll = $curr.nextAll();
			$prevAll = $curr.prevAll();
			
			if($nextAll.length > 3) {
				$nextAll.slice(3).hide();
			}
			
			if($prevAll.length > 3) {
				$prevAll.slice(3).hide();
			}
		}
		
		// Add Next page navigation
		if($next.length) {
			$('a',$next).html("Next &raquo;");
			$next.addClass("last");
			$(this).append($next);
		}
		
		// Add Previous page navigation
		if($prev.length) {
			$('a',$prev).html("&laquo; Prev");
			$prev.addClass("first");
			$(this).prepend($prev);
		}
		
		
		debugLog($curr,$next, $prev, $pages);
																								 
  });
	
	
}


 
/**
* Utility for adding hover behaviours to elements in ie6
* since it does not fully support the :hover selector
*/
$.fn.hoverClass = function(c) {
	return this.each(function(){
		$(this).hover( 
			function() { $(this).addClass(c);  },
			function() { $(this).removeClass(c); }
		);
	});
};


/**
* Greybox links (aka Lightbox)
*
*/
var GB_ANIMATION = true;
$(function(){
	$("a.greybox").click(function(){
		var t = this.title || $(this).text() || this.href;
		var meta = $.metadata.get(this);
    var h = meta.h || 470;
    var w = meta.w || 600;
		GB_show(t,this.href,h,w);
		return false;
	});
});


function openListenLive(file) {
	var location = "";
	if(file != null && file.length > 0) {
		location = MEDIAPLAYER_URL + "?file=" + file;
	} else {
		location = MEDIAPLAYER_URL;
	}
	var win = window.open(location,'ListenLiveWindow','width='+MEDIAPLAYER_WIDTH+',height='+MEDIAPLAYER_HEIGHT+',status=0,scrollbars=0,resizable=0');
	win.focus();
	return false;
}

function latestTraffic() {
	openListenLive(LATEST_TRAFFIC_MP3);
}
function latestBusiness() {
	openListenLive(LATEST_BUSINESS_MP3);
}
function latestWeather() {
	openListenLive(LATEST_WEATHER_MP3);
}



/* Scroll to named anchors with the class="scroll" */
$(document).ready(function() {
  $('a.scroll').each(function() {
	  var $target = $(this.hash);
	  if ($target) {
			var targetOffset = $target.offset().top;
			$(this).click(function() {
		  	$('html, body').animate({scrollTop: targetOffset}, 400);
		  	return false;
			});
	  }
  });
});

/* Tools for debugging */
var FLAG_DEBUG = isURLParamDefined("debug");
function debugLog() {
	if(FLAG_DEBUG) {
		if(window.console) {
			console.debug.apply( console, arguments );
		} else {

			var out = [];
			for(var i=0; i<arguments.length; i++) {
				out.push(arguments[i].toString());
				out.push(", ");
			}
			out.push("\n\n");
			alert(out.join(''));
			
/*			if(!$("#DebugLog").length) {
				$("<div id='DebugLog'></div>").appendTo('body');
			}
			
			var out = [];
			out.push("<p>");
			for(var i=0; i<arguments.length; i++) {
				out.push(arguments[i].toString());
				out.push(", ");
			}
			out.push("</p>");
			$("#DebugLog").prepend(out.join(''));*/
			
		}
	}
}

function isURLParamDefined( name ) {
	return getURLParam(name).length > 0;
}

// Utility function that pulls a URL parameter value from the query string.
// Example:
// www.site.com?paramname1=paramvalue1&paramname2=paramvalue2...
// var value = getURLParam("paramname1");
function getURLParam( name )
{
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var tmpURL = window.location.href;
  var results = regex.exec( tmpURL );
  if( results == null )
    return "";
  else
    return results[1];
}