
$(document).ready(function() {


	// background images/captions/gallery
	
	var heroIdx = 0;
	$(function() {

		$('#heroPrev').click(function() {
			heroIdx--;
			if (heroIdx < 0) {
			    heroIdx = heroImgsJSON.heroes.length - 1;
			}
			updateHero();
		});
		$('#heroNext').click(function() {
			heroIdx++;
			if (heroIdx > heroImgsJSON.heroes.length - 1) {
				heroIdx = 0;
			}
			updateHero();
		});
		function updateHero() {
			var oldBgImage = $('.bgImage');
			var newBgImage = $(oldBgImage).clone();
			$(newBgImage).css('z-index', 5);
			var img = $(newBgImage).find('img.hero');
			$(img).remove();
			var newImg = $('<img></img>');
			$(newImg).addClass('hero');
			$(newImg).load(function() {
				$(oldBgImage).fadeOut(700, function() {
					$(this).remove();
					$(newBgImage).css('z-index', 10);
					$('#infoBubble .caption').text(heroImgsJSON.heroes[heroIdx].graphic.Caption);
				});
			});
			$(newBgImage).append($(newImg));
			$('.bgWrap').append($(newBgImage));
			$(newImg).attr('src', heroImgsJSON.heroes[heroIdx].graphic.ImageUrl);
		}
		$('.showHideContent').click(function() {
			if ($('#infoIcon').hasClass('minimized')) {
				$('#infoIcon').removeClass('minimized');
			}
			else {
				$('#infoIcon').addClass('minimized');
			}
			showHideContentArea(500);
		});
		/*
		moved into a tooltip to better support mouse hover
		$('#infoIcon').click(function() {
		if ($('#infoBubble').hasClass('visible')) {
		$('#infoBubble').removeClass('visible');
		$('#infoBubble').fadeOut('fast');
		}
		else {
		$('#infoBubble').addClass('visible');
		$('#infoBubble').fadeIn('fast');
		}
		});
		*/
		function showHideContentArea(duration) {

			var revealText = "View Full Image";

			if ($('#infoIcon').hasClass('minimized')) {
				revealText = "Return to content";
				$('#containerMain').fadeOut(duration);
				$('#boxDate').fadeOut(duration, function() {
					$('.showHideContent').text(revealText);
				});
			}
			else {
				$('#containerMain').fadeIn(duration);
				$('#boxDate').fadeIn(duration, function() {
					$('.showHideContent').text(revealText);
				});
			}
		}
		$(window).bind('resize', function() {
			if ($('#infoIcon').hasClass('minimized')) {
				showHideContentArea(0);
			}
		});
	});


	// navigation
	var navDelay;
	var isIe7OrLess = false;
	if ($.browser.msie) {
		var version = parseFloat($.browser.version);
		if (version <= 7) {
			isIe7OrLess = true;
		}
	}

	$('.btnNav').mouseover(function() {
		var btn = $(this);
		$('.btnNav').removeClass('active');
		$(this).addClass('active');
		clearInterval(navDelay);
		$('.navbox').hide();
		var btnNav = $(this);
		var navbox = $(this).siblings('.navbox');
		var navboxTable = $(navbox).find('.navboxTable');

		if (isIe7OrLess) {
			$(navbox).css('top', '-10000px');
			$(navbox).css('overflow', 'visible');
			$(navbox).show();
		}

		// how wide is the navbox?
		var w = $(navbox).width();
		// how tall is the navbox?
		var nh = $(navbox).height();
		// how tall is the calling button?
		var h = $(this).height();

		if (isIe7OrLess) {
			$(navbox).hide();
			$(navbox).css('top', '0px');
			$(navbox).css('right', '219px');
			$(navbox).css('overflow', 'hidden');
		}

		// make sure everything else has removed itself
		$('.navbox').not($(this)).hide();

		setTimeout(function() {
			if ($(btn).hasClass('active')) {
				// hide the menu itself
				$(navboxTable).hide();
				$(navbox).css('width', '0px');
				$(navbox).css('height', h + 'px');
				$(navbox).show();
				$(navbox).animate({
					width: w
				}, 120, function() {
					// done animating left
					$(navboxTable).fadeIn('fast');
					$(this).animate({
						height: nh
					}, 120, function() {
						// done animating down
						// now turn on mouseovers
						$(this).unbind('mouseover');
						$(this).unbind('mouseout');

						$(this).mouseover(function() {
							if (!$(btnNav).hasClass('active')) {
								$(btnNav).addClass('active');
							}
							clearInterval(navDelay);

						});

						$(this).mouseout(function() {
							var nb = $(this);
							navDelay = setInterval(function() {
								$(nb).fadeOut('fast', function() {
									$(btnNav).removeClass('active');
								});
							}, 200);
						});

						// and do this again
						$('.navbox').not($(this)).hide();
					});
				});
			}
		}, 300);
	});

	$('.btnNav').mouseout(function() {
		var nb = $(this).siblings('.navbox');
		var btn = $(this);
		navDelay = setInterval(function() {
			$(nb).fadeOut('fast', function() {
				$(btn).removeClass('active');
			});
		}, 200);
	});


	// create custom tooltip effect for jQuery Tooltip 
	$.tools.tooltip.addEffect("blind",
	// opening animation 
	    function(done) {
	    	this.getTip().show("blind", {}, 200);
	    },
	// closing animation 
	    function(done) {
	    	this.getTip().fadeOut();
	    	done.call();
	    }
	);
	// tooltip for background image gallery controls
	$('#infoIcon').tooltip({
		relative: true,
		position: 'bottom right',
		offset: [-24, 3],
		effect: 'blind',
		predelay: 300,
		delay: 800,
		onBeforeShow: function() {
			this.getTrigger().addClass('visible');
		},
		onHide: function() {
			this.getTrigger().removeClass('visible');
		}
	});
	// add event card back ground image
	//$("#containerEventCardBG").css("background", "url('" + $('[id$=hdnFlipCardBackground]').val() + "') left top no-repeat");

	// setup jScrollPane custom scrollbars
	$('.scroll-pane').jScrollPane(
		{
			verticalDragMinHeight: 50,
			verticalDragMaxHeight: 50,
			hideFocus: true
		}
	);
	// hide the containerEventCard div after the custom scroller is loaded
	$('#containerEventCard').hide();

	// setup jQuery tools tabs/panes
	$("ul.tabsRightColEvents").tabs("div.panesRightColEvents > div", { effect: 'fade' });
	$("ul.tabsRightColSocial").tabs("div.panesRightColSocial > div", { effect: 'fade' });
	$("ul.tabsContentSub").tabs("div.panesContentSub > div", { effect: 'fade' });


	// toggle event card
	$('#containerEventCardBG').hover(function() {
		$("#containerEventCard").fadeToggle("slow", "linear");
	});

	// iOS specific stuff
	if (navigator.platform == 'iPad' || navigator.platform == 'iPhone' || navigator.platform == 'iPod') {
		$("#containerEvents").css("background", "#ffffff");

		$('#containerEventCardBG').click(function() {
			$("#containerEventCard").fadeToggle("slow", "linear");
		});

	};

	$('div.pagination div.arrow').hover(function() {
		$(this).toggleClass('active');
	});
	$('a.tabFacebook').click(function() {
		initFacebook();
	});
	$('a.tabTwitter').click(function() {
		$('div.twFeedTabs a:first').trigger('click');
	});

    //setup selectmenu custom dropdowns
	$('.ddlSets').selectmenu({
	    style: 'dropdown',
	    width: 240
	});
	$('.ddlPlaylists').selectmenu({
	    style: 'dropdown',
	    width: 140
	});

});
function parseDate(str) {
	var v = str.split(' ');
	return new Date(Date.parse(v[1] + " " + v[2] + ", " + v[5] + " " + v[3] + " UTC"));
}
function cleanFbLinks(t) {
	return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
		return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
	});
}
window.ify = function() {
	var entities = {
		'"': '&quot;',
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;'
	};

	return {
		"link": function(t) {
			return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
				return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
			});
		},
		"at": function(t) {
			return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function(m, m1, m2) {
				return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
			});
		},
		"hash": function(t) {
			return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
				return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
			});
		},
		"clean": function(tweet) {
			if (tweet != undefined && tweet != '') {
				return this.hash(this.at(this.link(tweet))).replace('\n', '<br />');
			}
			else {
				return "";
			}
		}
	};
} ();


function relative_time(time_value) {
	// Tue Feb 01 12:44:15 +0000 2011
	var values = time_value.split(" ");
	var parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]);
	var date = new Date(parsed_date);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	var r = '';

	function formatTime(date) {
		var hour = date.getHours(),
                min = date.getMinutes() + "",
                ampm = 'AM';

		if (hour == 0) {
			hour = 12;
		} else if (hour == 12) {
			ampm = 'PM';
		} else if (hour > 12) {
			hour -= 12;
			ampm = 'PM';
		}

		if (min.length == 1) {
			min = '0' + min;
		}

		return hour + ':' + min + ' ' + ampm;
	}

	function formatDate(date) {
		var ds = date.toDateString().split(/ /),
                mon = months[date.getMonth()],
                day = date.getDate() + '',
                dayi = parseInt(day),
                year = date.getFullYear(),
                thisyear = (new Date()).getFullYear(),
                th = 'th';

		// anti-'th' - but don't do the 11th, 12th or 13th
		if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
			th = 'st';
		} else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
			th = 'nd';
		} else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
			th = 'rd';
		}

		if (day.substr(0, 1) == '0') {
			day = day.substr(1);
		}

		return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
	}

	delta = delta + (relative_to.getTimezoneOffset() * 60);
	
	if (delta < 5) {
		r = 'less than 5 seconds ago';
	} else if (delta < 30) {
		r = 'half a minute ago';
	} else if (delta < 60) {
		r = 'less than a minute ago';
	} else if (delta < 120) {
		r = '1 minute ago';
	} else if (delta < (45 * 60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (2 * 90 * 60)) { // 2* because sometimes read 1 hours ago
		r = 'about 1 hour ago';
	} else if (delta < (24 * 60 * 60)) {
		r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else {
		if (delta < (48 * 60 * 60)) {
			r = formatTime(date) + ' yesterday';
		} else {
			r = formatTime(date) + ' ' + formatDate(date);
		}
	}

	return r;
}

function formatFBTime(fbDate) {
	var arrDateTime = fbDate.split("T");
	var strTimeCode = arrDateTime[1].substring(0, arrDateTime[1].indexOf("+"));

	var arrDateParts = arrDateTime[0].split("-");
	var year = arrDateParts[0];
	var month = parseInt(arrDateParts[1] - 1);
	var day = arrDateParts[2];

	var valid_date = new Date();
	valid_date.setUTCFullYear(year);
	valid_date.setUTCMonth(month);
	valid_date.setUTCDate(day);

	var arrTimeCode = strTimeCode.split(":");
	valid_date.setUTCHours(arrTimeCode[0]);
	valid_date.setUTCMinutes(arrTimeCode[1]);
	valid_date.setUTCSeconds(arrTimeCode[2]);
	return valid_date;
}
Date.prototype.toRelativeTime = function(now_threshold) {
	var delta = new Date() - this;

	now_threshold = parseInt(now_threshold, 10);

	if (isNaN(now_threshold)) {
		now_threshold = 0;
	}

	if (delta <= now_threshold) {
		return 'Just now';
	}

	var units = null;
	var conversions = {
		millisecond: 1, // ms    -> ms
		second: 1000,   // ms    -> sec
		minute: 60,     // sec   -> min
		hour: 60,     // min   -> hour
		day: 24,     // hour  -> day
		month: 30,     // day   -> month (roughly)
		year: 12      // month -> year
	};
	var conversions = { millisecond: 1 }

	delta = delta / 1000;
	var r = "";

	if (delta < 5) {
		r = 'less than 5 seconds ago';
	} else if (delta < 30) {
		r = 'half a minute ago';
	} else if (delta < 60) {
		r = 'less than a minute ago';
	} else if (delta < 120) {
		r = '1 minute ago';
	} else if (delta < (45 * 60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (2 * 90 * 60)) { // 2* because sometimes read 1 hours ago
		r = 'about 1 hour ago';
	} else if (delta < (24 * 60 * 60)) {
		r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else {
		if (delta < (48 * 60 * 60)) {
			r = dateFormat(this, "h:MM TT") + ' yesterday';
		} else {
			r = dateFormat(this, "h:MM TT") + ' ' + dateFormat(this, "mmm d");
		}
	}

	return r;
};

Date.fromString = function(str) {
	return new Date(Date.parse(str));
};

function setContainerHeight(container, parent) {
	$(container).fadeIn('fast', function() {
		var newHeight = $(this).height();
		$(parent).animate({
			height: newHeight
		}, 'fast');
	});
}

function LoadTabbedElement(instanceName) {
    $("ul#tabsRightCol" + instanceName).tabs("div#panesRightCol" + instanceName + "> div", { effect: 'fade' });
}

function LoadPromotionCarouselPaging(promotionCarouselId) {
var promoIdx = 0;
var promotionCarousel = $('#' + promotionCarouselId);
var totalPromos = parseInt(promotionCarousel.find('#promoCount').html()); ;
promotionCarousel.find('.prev').click(function() {
changePromotion('prev');
});
promotionCarousel.find('.next').click(function() {
changePromotion('next');
});

function changePromotion(direction) {
    var currentPromo = promotionCarousel.find('#promoItems').find('.promoItem').eq(promoIdx);
    switch (direction) {
        case 'prev':
            promoIdx--;
            if (promoIdx < 0) {
                promoIdx = totalPromos - 1;
                currentPromo.parent().find('.promoItem').last().fadeToggle("slow", "linear");
            }
            else {
                currentPromo.prev('.promoItem').fadeToggle("slow", "linear");
            }


            break;
        case 'next':
            promoIdx++;
            if (promoIdx > totalPromos - 1) {
                promoIdx = 0;
                currentPromo.parent().find('.promoItem').first().fadeToggle("slow", "linear");
            }
            else {
                currentPromo.next('.promoItem').fadeToggle("slow", "linear");
            }

            break;
    }
    currentPromo.hide();
    promotionCarousel.find('#promoIndex').html(promoIdx + 1);
}
}
