/* ----------------------------------------------*/
/*	   Toggle Overlay (Animate it in or out)     */ 
/* --------------------------------------------- */
function toggle_overlay() 	{

	// SETTINGS
	var overlayBg  = '#overlayBg';
	var overlay    = '#overlay';
	var ease	   = 'easeOutExpo';
	var speed	   = 300;

	// FIRE
	if ($(overlayBg+':visible').length > 0)	{
		$(overlay).slideUp(speed);
		$(overlayBg).animate({'opacity' : 0}, speed, ease, function()	{
			$(overlayBg).hide();
		});

	} else {
		$(overlayBg).css({'display' : 'block', 'opacity' : 0}).animate({'opacity' : 0.7}, speed, ease);
		$(overlay).slideDown(speed);
		style_buttons_for_ie();
		
	}
	
	if ($.browser.msie && $.browser.version == "7.0" || $.browser.msie && $.browser.version == "6.0")	{
	} else { 
		return false;
	}

}


/* ----------------------------------------------*/
/*	 Center Overlay vertically + horizontally    */ 
/* --------------------------------------------- */

function overlay_position()	{
	var o 	= $('#overlay');
	var oBg = $('#overlayBg');
	o.css({'marginLeft' : o.width()/2*-1, 'marginTop' : o.height()/2*-1});
	if($.browser.msie && $.browser.version=="6.0") oBg.css('opacity', 0.75).height($('#template').height()+40);	
}




/* -------------------------------------- */
/*	Playlist actions (delete + edit)      */ 
/* -------------------------------------- */

function playlist_edit_actions(button)		{	
// DO NOT TOUCH BELOW HERE
	// FIRE
	var speed = 250;
	
	// CLICK 	
	$(button).bind('click', {self:this}, function(e) {
		$(this).fadeOut(speed);
		$(button).siblings('h3').fadeOut(speed);
		$(button).parents('form').siblings('form').fadeOut(speed);
		$(button).siblings('.textfield, .btnDefSma1').fadeIn(speed);
		$(button).siblings('.textfield').focus();
		
		return false;
	});
	
}

function playlist_delete_actions(button)		{	
// DO NOT TOUCH BELOW HERE
	// FIRE
	var speed = 250;
	
	// CLICK 	
	$(button).bind('click', {self:this}, function(e) {
		$(this).fadeOut(speed, function() {
			$(button).siblings('.btnDefSma1').fadeIn(speed);
		});
		
		return false;
	});
	
}





/* -------------------------------------- */
/*	Billboard Carousel on the homepage    */ 
/* -------------------------------------- */

function billboard_carousel()	{
// VARIABLES
	this.carouselWrapper	= $('#carousel');
	this.carousel	 		= $('#carouselUlCrop ul');
	this.panels		 		= this.carousel.children('li');
	this.panelWidth  		= this.panels.width();
	this.panelNav	 		= $('#carouselNav');
	this.panelNavItems		= this.panelNav.find('.item');
	this.panelInfoC	 		= 'info';
	this.panelInfoH	 		= 77;
	this.speed		 		= 1600;
	this.interval	 		= 5000;
	this.ease		 		= 'easeOutExpo';
	this.userClicked 		= false;
	this.activePanel 		= 0; 				// Zero indexed
	this.destinationPanel	= 0;
	this.nextBtn			= $('#carouselNext');
	this.prevBtn			= $('#carouselPrev');
	objSelf			 		= this;
	
	
// DO NOT TOUCH BELOW HERE
	// FIRE
	// Give each panel an ID
	var index = 0;
	objSelf.panels.each( function()	{
		$(this).attr('id', 'carouselPanel_'+index);
		index++;
	});
	
	// Give each nav item an ID
	index = 0;
	objSelf.panelNavItems.each( function() {
		$(this).attr('id', 'carouselNav_'+index);
		index++;
	});
	
	// Stop Default Actions
	objSelf.panelNav.find('.item').attr('onclick', 'return false;');
	objSelf.nextBtn.attr('onclick', 'return false');
	objSelf.prevBtn.attr('onclick', 'return false');
	
	// HOVER IN The UL - show the next + prev buttons
	objSelf.carousel.hover(function(){
		objSelf.nextBtn.stop().fadeIn(objSelf.speed/4);
		objSelf.prevBtn.stop().fadeIn(objSelf.speed/4);
		
	}, function() {});
	
	// HOVER OUT The Box - Hide the next + prev buttons
	objSelf.carouselWrapper.hover( function() {
	}, function() {
		objSelf.nextBtn.stop().fadeOut(objSelf.speed/4);
		objSelf.prevBtn.stop().fadeOut(objSelf.speed/4);
		
	});

	// CLICK A Number - animate to that panel.
	objSelf.panelNavItems.bind('click', {objSelf:this}, function(e) {
		objSelf.userClicked 		= true;
		objSelf.destinationPanel 	= $(this).html()-1;
		objSelf.animate_show();
		return false; 
	});
	
	// CLICK 'next' - animate to the next panel.
	objSelf.nextBtn.bind('click', {objSelf:this}, function(e) {
		objSelf.userClicked 		= true;
		objSelf.destinationPanel   += 1;
		objSelf.animate_show();	
		return false;
	});
	
	// CLICK 'Prev' - animate to the previous panel.
	objSelf.prevBtn.bind('click', {objSelf:this}, function(e) {
		objSelf.userClicked 		= true;
		objSelf.destinationPanel   -= 1;
		objSelf.animate_show();	
		return false;
	});
	
	
	
	// TIMER (Every x seconds animate the slideshow)
 	setInterval( function()	{
		if (!objSelf.userClicked)	{
			// If Destination Panel is greater than the number of panels Destination the first panel
			objSelf.destinationPanel += 1;
			objSelf.animate_show();						
			
		}	
	}, objSelf.interval );
		
	
}

// FOR: trigegring an animation.
billboard_carousel.prototype.animate_show = function() 	{
	var objSelf = this;
	
	// If Destination Panel is greater than the number of panels, Destination the first panel
	if (objSelf.destinationPanel == objSelf.panels.length) objSelf.destinationPanel = 0;
	
	// If Destination Panel is less than 0, Destination is the last panel
	if (objSelf.destinationPanel < 0) objSelf.destinationPanel = objSelf.panels.length-1;
		
	// Fire
	objSelf.slide_to_panel();
	objSelf.toggle_panel_info();
	objSelf.update_nav();
	
	// Update the active panel for next time.
	objSelf.activePanel			= objSelf.destinationPanel;
	
};


// FOR: Disabling then enabling the Nav whilst animation is in progress
billboard_carousel.prototype.update_nav = function() 	{
	var objSelf = this;	
	// Remove .active from active Panel, Add .active to desitnation panel 
	objSelf.panelNav.children('#carouselNav_'+objSelf.activePanel+', #carouselNav_'+objSelf.destinationPanel).toggleClass('active');
	
};



// FOR: Slide The Billboard to the panel no that 'show_panel' stores
billboard_carousel.prototype.slide_to_panel = function()	{	
	var objSelf = this;
	// The destination margin left value (i.e: -600, -1200, -1800 etc)
	objSelf.destinationMargin = parseFloat((objSelf.destinationPanel*objSelf.panelWidth)*-1);	
	// ANIMATE!!	
	$(objSelf.carousel).stop().animate({marginLeft : objSelf.destinationMargin}, objSelf.speed, objSelf.ease);
	
};

// FOR: Hide Active Info Box.  Show Next Info Box
billboard_carousel.prototype.toggle_panel_info = function()	{	
	var objSelf = this;
	var active_panel 			= $('#carouselPanel_'+objSelf.activePanel);
	var destination_panel 		= $('#carouselPanel_'+objSelf.destinationPanel);

	// Hide The Active Panel's Info Box.
	objSelf.carousel.find('.'+objSelf.panelInfoC).stop().animate({'height' : 0}, objSelf.speed/4, objSelf.ease, function()	{

		// Show the destinations panels info box.
		destination_panel.find('.'+objSelf.panelInfoC).stop().animate({'height' : objSelf.panelInfoH}, objSelf.speed, objSelf.ease);
	});
		
};




// REPLACEMENT FOR JCAROUSEL
// USED: HORIZONTAL SLIDING VIDEO LISTS

// ------------------------------------------------------------------------------
// APPLICATION.JS
// ------------------------------------------------------------------------------

/* ----------------------------------------- */
/*	Stacked Text + Video Lists (Accordian)   */ 
/* ----------------------------------------- */

// FOR: THE  Stacked text and video lists in right column.  Basically accordians
function stacked_lists(wrap, panel, toggle, openY, closeY) 	{
// Variables
	this.wrap	 =	wrap;
	this.panel 	 =  panel;
	this.toggle  =  toggle;
	this.openY   =  openY;
	this.closeY  =  closeY;
	this.panels  =  this.wrap+' '+this.panel;
	this.toggle  =  this.wrap+' '+this.toggle;
	this.ease	 =  'easeOutQuad';
	this.openC	 =  'open';
	this.scrollC =  '.jScrollPaneContainer';
	this.dScroll =	 '.jScrollPaneTrack';


// DO NOT TOUCH BELOW HERE
	// FIRE
	this.toggle_panels($(this.panels+'.'+this.openC).attr('id'), 0, this);
	
	
	// HACK:  Remove Duplicate Scroll bar in IE.  For some reason IE adds 2 scrollbars, let it add them and then remove 1.
	// TO DO: Find out why IE is adding 2 scrollbars and stop it from doing that.
	var self = this;
	$(this.wrap+' '+this.panel).each( function() {
		if ( $(this).find(self.dScroll).length > 1) {
			$(this).find(self.dScroll+':first').remove();		
		}
	});

	$(this.toggle).bind('click', {thisObj:this}, function(e){ 
		var parent_panel_id = $(this).parents(e.data.thisObj.panel).attr('id');
		if (!($('#'+parent_panel_id).hasClass(e.data.thisObj.openC))) {
			e.data.thisObj.toggle_panels(parent_panel_id, 300, e.data.thisObj);
		}
		return false; 
	});
};


// WHAT: Provide OpenPanel, up and down speed
//			Close All Panels, Open The 'openPanel'
// WHY: 	To Toggel Panels Open/Closed					
stacked_lists.prototype.toggle_panels = function(openPanel, speedUp, thisObj) 	{
	var openPanel = '#'+openPanel;
	
	$(thisObj.panels).animate({'height' : thisObj.closeY}, speedUp, thisObj.ease);
	toggle_scroll_markup($(thisObj.wrap).find(thisObj.scrollC));
	$(thisObj.panels).removeClass(thisObj.openC);
							
	$(openPanel).animate({'height' : thisObj.openY}, thisObj.speed, thisObj.ease).addClass(thisObj.openC);
	toggle_scroll_markup($(thisObj.wrap+' '+openPanel).find(thisObj.scrollC));
};



// WHAT: Provide target jScroll Classes
//			Show target if hidden.  Hide target if visible
// WHY: 	So we dont get messy JScroll markup whilst animating the parent.
function toggle_scroll_markup(target)  	{												
	if ($(target).is(':visible')) target.css('visibility', 'hidden');
	else target.css('visibility', 'visible');
}


// CHECKBOXES
function checkboxes()	{
	$("label.checkbox").click(function() {
		var checkbox = $(this).children("input[type=checkbox]:first");
		if (checkbox.is(":checked")) checkbox.removeAttr("checked");
		else checkbox.attr("checked", "checked");
		$(this).toggleClass('cBChecked');
		return false;
	});
};


function TabbedNavigation(num_tabs, tab_handle, content_handle, classname, default_tab) {

	this.num_tabs = num_tabs;				// -> number of tabs on page
	this.tab_handle = tab_handle;			// -> name of tab IDs minus number (e.g. "tab1" would be "tab")
	this.content_handle = content_handle;	// -> name of content box IDs minus number (e.g. "content1" would be "content")
	this.classname = classname;				// -> css class to be applied to open tab
	this.default_tab = default_tab;			// -> which tab is open by default

	TabbedNavigation.prototype.hide_all_content_boxes_except = function(num, fade) {
		var css = { display:'none'};
		for(i = 1; i <= this.num_tabs; i++) {
			$(this.content_handle + i).css(css);
		}	
		if(!fade) {	
			var css = { display:'block'};
			$(this.content_handle + num).css(css);
		} else {
			$(this.content_handle + num).fadeIn(750);
		}
	};


	TabbedNavigation.prototype.set_current_tab_to = function(num) {
		for(i = 1; i <= this.num_tabs; i++) {
			$(this.tab_handle + i).removeClass(this.classname);
		}
		$(this.tab_handle + num).addClass(this.classname);
	};


	TabbedNavigation.prototype.set_tab_to = function(num) {
		this.set_current_tab_to(num);
		this.hide_all_content_boxes_except(num);
	};

	this.set_tab_to(this.default_tab);

}


function show(id) {
	$(id).show();
}

function hide(id) {
	$(id).hide();
}

function collapse(id) {
	$(id).slideUp(250, 'easeOutQuad');
}

function expand(id) {
	$(id).slideDown(250, 'easeOutQuad');
}

function collapse_and_enable(collapse, enable) {
	$(collapse).slideUp(250, 'easeOutQuad');
	$(enable).removeClass('disabled');
}

function expand_and_disable(expand, disable) {
	$(expand).slideDown(250, 'easeOutQuad');
	$(disable).addClass('disabled');
}






function style_buttons_for_ie()	{
	if($.browser.msie) {
		$('button.btn:visible').each(function() {
		
		// i X Positioning
			var spanW 		= $(this).children('span').outerWidth();
			var iW			= $(this).children('i').outerWidth();
			var XPos		= spanW+iW;
			var XPosNum		= XPos + 'px';			
		// i Y Positioning		
			var iH			= $(this).children('i').height();
			var iYPos		= '-' + iH + 'px';			
		// Button Width
			var bW			= spanW+iW + 'px';
			
			// alert('spanW: '+spanW+', iW: '+iW+', XPos: '+XPos+', XPosNum: '+XPosNum+', iH: '+iH+', iYPos: '+iYPos+', bW: '+bW);
			
			if (!(Object.prototype.toString.call(self.JSON) === "[object JSON]" || $(this).hasClass('btn-fixed')))  { 		
				// Not IE8 || Does Not Have .btn-fixed 
				$(this+ 'i').css({position : 'relative', 'left' : spanW, 'top' : iYPos});
				$(this+' *').css({'white-space' : 'nowrap'});
				$(this).css({'overflow' : 'hidden', 'width' : bW, 'height' : iH});
				$(this).addClass('btn-fixed');
			};
		});
	};
};




function style_radios()	{
	$('label.radio').click(function()	{
		$('label.radio').children('input[name='+$(this).children('input').attr('name')+']').parent().removeClass('rChecked'); //.removeClass('rChecked');
		$(this).toggleClass('rChecked');
	});
	
}



// ------------------------------------------------------------------------------
// END: APPLICATION.JS
// ------------------------------------------------------------------------------



// ------------------------------------------------------------------------------
// FROM VIEWS
// ------------------------------------------------------------------------------


// REPLACEMENT FOR JCAROUSEL
// USED: HORIZONTAL SLIDING VIDEO LISTS

function SlidingPanel(name, n, skip_jumpto_menu) {

	// -------------------------------------------------------
	//  Change to suit your markup. Note: All lists to which
	// this code applies will need to match.
	// -------------------------------------------------------

	this.controls_container 				= '#slider-controls-';
	this.sliding_list 						= '#slider-';
	this.controls_wrapper					= 'ul.navPag';
	this.controls_link_next_class			= 'next';
	this.controls_link_prev_class			= 'prev';
	this.active_class						= 'active';
	this.jump_to_link_class_prefix			= 'panel';
	this.controls_link_disabled_suffix		= 'Disabled';
	this.speed								= 500;
	this.ease								= 'easeOutExpo';

	// -------------------------------------------------------
	//  DON'T TOUCH ANYTHING BELOW THIS LINE 
	// -------------------------------------------------------

	this.n									= n;
	this.instance							= name + n;
	this.current_panel 						= 1;
    this.controls_container 				= this.controls_container + n;
	this.sliding_list 						= this.sliding_list + n;
	this.controls_link_next					= 'li.' + this.controls_link_next_class;
	this.controls_link_prev					= 'li.' + this.controls_link_prev_class;

	this.num_items 					= $(this.sliding_list).children().length;
	this.item_width 				= $(this.sliding_list).children(0).width();
	this.panel_width 				= $(this.sliding_list).parent().width();
	
	// get hidden element widths using css properties
	if (this.item_width == 0) this.item_width = parseInt($(this.sliding_list).children(0).css("width"));	
	if (this.panel_width == 0) this.panel_width = parseInt($(this.sliding_list).parent().css("width"));
	
	this.items_per_panel 			= Math.round(this.panel_width / this.item_width);
	this.num_panels 				= Math.ceil(this.num_items / this.items_per_panel);

	$(this.controls_container + ' ' + this.controls_wrapper + ' ' + this.controls_link_next + ' a').bind('click', {obj:this}, function(e){ e.data.obj.next();return false; });
	$(this.controls_container + ' ' + this.controls_wrapper + ' ' + this.controls_link_prev + ' a').bind('click', {obj:this}, function(e){ e.data.obj.previous();return false; });

	this.set_arrow_button_states();
	if (skip_jumpto_menu !== true) this.set_up_jumpto_menu();

}

SlidingPanel.prototype.next = function() {
	if(this.current_panel != this.num_panels) {
		this.current_panel += 1;
		this.slide_to_panel(this.current_panel);
	}
};

SlidingPanel.prototype.previous = function() {
	if(this.current_panel != 1) {
		this.current_panel -= 1;
		this.slide_to_panel(this.current_panel);
	}
};

SlidingPanel.prototype.slide_to_panel = function(panel_num) {
	var move_to = 0 - ((panel_num - 1) * this.panel_width);
	$(this.sliding_list).animate( { left: move_to }, { queue: false, duration: this.speed, ease: this.ease } );
	this.set_arrow_button_states();
	this.set_jumpto_button_states(panel_num);
};

SlidingPanel.prototype.disable_btn = function(id) {
	var new_class = id + this.controls_link_disabled_suffix;
	$(this.controls_container + ' ' + this.controls_wrapper + ' li.' + id).addClass(new_class);
};

SlidingPanel.prototype.enable_btn = function(id) {
	var class_to_remove = id + this.controls_link_disabled_suffix;
	$(this.controls_container + ' ' + this.controls_wrapper + ' li.' + id).removeClass(class_to_remove);
};

SlidingPanel.prototype.set_jumpto_button_states = function(num) {
	$(this.controls_container + ' ' + this.controls_wrapper + ' li.' + this.active_class).removeClass(this.active_class);
	$(this.controls_container + ' ' + this.controls_wrapper + ' li.' + this.jump_to_link_class_prefix + num).addClass(this.active_class);
};

SlidingPanel.prototype.set_arrow_button_states = function() {
	if(this.num_panels <= 1) {
		this.disable_btn(this.controls_link_next_class);
		this.disable_btn(this.controls_link_prev_class);
	} else if (this.current_panel == 1) {
		this.disable_btn(this.controls_link_prev_class);
		if(this.num_panels > 1) this.enable_btn(this.controls_link_next_class);
	} else if(this.current_panel == this.num_panels) {
		this.disable_btn(this.controls_link_next_class);
		if(this.num_panels > 1) this.enable_btn(this.controls_link_prev_class);
	} else {
		this.enable_btn(this.controls_link_next_class);
		this.enable_btn(this.controls_link_prev_class);
	}
};

SlidingPanel.prototype.jump_to_panel = function(num) {
	this.current_panel = num;
	this.slide_to_panel(this.current_panel);
};

SlidingPanel.prototype.set_up_jumpto_menu = function() {
	var slider = this;
	if(slider.num_panels > 1) {
		for(var i = slider.num_panels; i >= 1; i--) {
			var link = $(
				'<li class="' + slider.jump_to_link_class_prefix + i + '">' +
					'<a href="#" title="Jump to panel ' + i + '" >' + i + '</a>' +
				'</li>'
			).bind('click', { panel: i }, function(event) {
				slider.jump_to_panel(event.data.panel);
				return false;
			});
			
			$(slider.controls_container + ' ' + slider.controls_wrapper).prepend(link);
		}
		slider.set_jumpto_button_states(1);
	}
};


/**
 * Ajax Gird List Filtering/pagination
 */
function init_grid_videos_filter() {

	$("form.js-grid-filter").submit(function() {
		apply_form_filter($(this));
		return false;
	});

	$("select.js-grid-order").change(function() {
		apply_form_filter($(this).parents("form:first"));
		return false;
	});

	$("div.sort_vids button").hide();
	
	$("a.js-filter-reset").click(function() {
		filter_form = $("#frmTagList");
		reset_grid_filter(filter_form);
		return false;
	});
}

function init_grid_videos_results() {
	
	$(".vVLActions ul.navPag a").click(function() {
		filter_form = $("#frmTagList");
		var href = $(this).attr("href");
		var query_string = href.substring(href.indexOf("?")) + '&' + filter_form.serialize();
		
		// Find the channel id if it is in the url
		var channel_id;
		var pattern = "channel-([0-9]*)-";
		var regex = new RegExp(pattern);
		var match = regex.exec(window.location);
		
		if (match != null) {
			channel_id = match[1];
		}
		apply_link_filter(query_string, channel_id);
		return false;
	});
	
	$("form.frmVVLA").submit(function(){
		href = $(this).attr("action");
		method = $(this).attr("method");
		
		data_array = $(this).serialize();
		$.ajax({
			url: href,
			type: method,
			data: data_array,
			success: function(json) {
				$("#overlayBg").remove();
				$("#overlay").remove();
				$("body").prepend(json["overlay"]);
			},
			dataType: "json"
		});

		return false;
	});
}



function apply_form_filter(form) {
	var data_string = $(form).serialize();
	filter_form = $(form);
	$.get(MOKO_WEB_AREA_ROOT + "videolist/grid", data_string, update_grid_results, 'html');
}


function apply_link_filter(query_string, channel_id) {
	var url = MOKO_WEB_AREA_ROOT + "videolist/grid";
	if (channel_id != undefined) url += "/" + channel_id;
	
	$.get(url, query_string, update_grid_results, 'html');
}


function update_grid_results(html) {
	$(filter_form).siblings(".vVLResults").replaceWith(html);
}


function reset_grid_filter(form) {
	$(form).find("input[type=checkbox]:checked").each(function() {
		$(this).removeAttr("checked");
		$(this).parent().removeClass("cBChecked");
	});
	apply_form_filter(form);
}


function animate_stacked_text_lists() 	{
// SETTINGS
	wrap	  = '#navStackText';
	panels  = '.stackPanel';
	ease	  = 'easeOutQuad';
	openC	  = 'open';
	openY	  = 248;
	closeY  = 21;
	speed	  = 400;
	scrollC = '.jScrollPaneContainer';
	
// DO NOT TOUCH BELOW HERE
	// FIRE
	toggle_panels($('.stackPanel.open').attr('id'), 0, speed);
	$(wrap).find('.sPToggle').click( function() {
		parent_panel_id = $(this).parents(panels).attr('id');
		if (!($('#'+parent_panel_id).hasClass(openC))) toggle_panels(parent_panel_id, speed, speed);
		return false;
	});
	
// METHODS	
	// WHAT: Provide OpenPanel, up and down speed
	//			Close All Panels, Open The 'openPanel'
	// WHY: 	To Toggel Panels Open/Closed					
	function toggle_panels(openPanel, speedUp, speedDown) 	{
		
		$(panels).animate({'height' : closeY}, speedUp, ease, function() {
			toggle_scroll_markup($(wrap).find(scrollC));
			$(panels).removeClass(openC);
			$('#'+openPanel).animate({'height' : openY}, speedDown, ease).addClass(openC);
			toggle_scroll_markup($('#'+openPanel).find(scrollC));
			
		});
	}
	
	// WHAT: Provide target jScroll Classes
	//			Show target if hidden.  Hide target if visible
	// WHY: 	So we dont get messy JScroll markup whilst animating the parent.
	function toggle_scroll_markup(target) 	{
		if ($(target).is(':visible')) target.hide();
		else target.show();
	}
	
};




function user_box_images() {
	// SETTINGS
	var next     = '#uBNext';
	var prev     = '#uBPrev';
	var wrap     = '#uBImages';
	var activeC	 = 'active';
	
	// FIRE
	$(next).click( function() {
		show_image('next');
		return false;
	});
	$(prev).click( function() {
		show_image('prev');
		return false;
	});
	
	
	// METHODS
	function show_image(direction)	{
		// SETTINGS
		var activeLi = $(wrap+' .'+activeC);
		var nextLi	 = $(activeLi).next();
		var prevLi	 = $(activeLi).prev();
								
		//FIRE						
		if (direction == 'next' && nextLi.length > 0) {
			activeLi.removeClass(activeC);
			nextLi.addClass(activeC);

		} else if (direction == 'prev' && prevLi.length > 0) {
			activeLi.removeClass(activeC);
			prevLi.addClass(activeC);
			
		}													
	}	
	
	function set_arrow_states() 	{
		// PREDICTING THE FUTURE OOOWWWOOOOWWWWOOOO
	}		
}


/*
function trail()	{
	// REUSABLE VARIABLES
	speed		=	150;
	all_ul	=	$("#navTrail ul ul");
	trigger  =  $("#navTrail strong a");

	// ACTIONS
	trigger.focus(
		function() 	{
			open_drop_down(this);
			return false;
		}
	);
	
	trigger.click(
		function() 	{
			open_drop_down(this);
			return false;
		}
	);

	// HOVER
	all_ul.mouseover( 
		function()	{
			ul		= $("#navTrail ul ul:visible");
			w 		= $(ul).width()+100+'px';
			css	= 'width:'+w+'; height:600px; position:absolute; top:-32px; left:-57px; z-index:999;';
			out	= '#navTrail_out';


			// Create The out borders if they dont exist
			if ($(out).length == 0)	$(ul).before('<div id="navTrail_out" style="'+css+'"></div>');

			// User mouses over the out borders, close the ul.				  				
			$(out).mouseover(
				function()	{
					$(out).remove();
					close_everything();
				}
			);	
		}
	);

	// METHODS
	// Reset all classes						
	resetAll_a	=	function()	{$("#navTrail a").not("#navTrail li li a").removeClass('open');};

	// Close all Drop downs
	function close_everything()	{
		$(all_ul).slideUp(speed);
		resetAll_a();	
	}
	
	// Open a drop down
	function open_drop_down(clicked) 	{
		child			=	$(clicked).parent().siblings('ul');

		// Cicks the trail
		if	($(clicked).hasClass('open'))	{
			close_everything();													

		}	else	{
			$(all_ul).not(child).slideUp(speed);
			resetAll_a();
			$(child).slideDown(speed, 
				function()	{
					$(this).siblings("strong").children('a').toggleClass('open');								
				}
			);
		}
	
	}

};
*/


function init_overlay_forms() {
	$("form.overlay").submit(function() {
		
		href = $(this).attr("action");
		method = $(this).attr("method");
		data_array = $(this).serialize();
		var form = $(this);
		$.ajax({
			url: href,
			type: method,
			data: data_array,
			success: function(json) {
				$("#overlayBg").remove();
				$("#overlay").remove();
				$(".communityOverlay").remove();
				$("body").prepend(json["overlay"]);
				switch(form.attr('id')){
				  case 'fav-article-remove':
				   $('#article-' + form.attr('data-article-id')).remove();
				   break;
				}
			},
			dataType: "json"
		});

		return false;
	});
}


function init_overlay_links() {
	$("a.overlay").click(function() {
	
		href = $(this).attr("href");
		method = 'GET';
		
		$.ajax({
			url: href,
			type: method,
			success: function(json) {
				$("#overlayBg").remove();
				$("#overlay").remove();
				$(".communityOverlay").remove();
				$("body").prepend(json["overlay"]);
			},
			dataType: "json"
		});

		return false;
	});
}



// About:
// This adds/removes the .labelOn.
// You need to make sure that if the view sets input[checked=checked] then you also set label.labelOn
// Then everything will smell like roses!


function community_overlay_select_actions() {
	// Document Loads
	$('#selectFriends input[checked]').each( function() {
		$(this).parent('label').addClass('labelOn');

	});
	$('#clearAll').attr('onclick', 'return false;');
	$('#selectAll').attr('onclick', 'return false;');

	// User clicks a label
	$('#selectFriends label').mousedown( function() {
		$(this).toggleClass('labelOn').css('background' , '#E0DED8');

	});
	$('#selectFriends label').mouseup( function() {
		if ($(this).hasClass('labelOn'))
				$(this).css('background' , '#EFECE6');
		else
				$(this).css('background' , '#fff');

	});

	// User Clicks 'clear all'
	$('#clearAll').mousedown( function() {
		$('#selectFriends label').removeClass('labelOn').css('background' , '#fff');
		$('#selectFriends input').removeAttr('checked');	

	});

	// User clicks 'select all'
	$('#selectAll').mousedown( function() {
		$('#selectFriends label').addClass('labelOn').css('background' , '#EFECE6');
		$('#selectFriends input').attr('checked', 'checked');	

	});

	// IE: Remove duplicate scroll
	if ($('#selectFriendsWrapper .jScrollPaneTrack').length > 1) {
		$('#selectFriendsWrapper .jScrollPaneTrack:first').remove();

	}
	
}


function community_overlay_actions() {
	var confirm_locked = false;
	
	$('.communityOverlay .cOClose').click(function(){
		$('.communityOverlay').remove();
		//return false;
	});
	
	if ($('.communityOverlay form.overlay').length > 0) {
		$(".communityOverlay form.overlay").submit(function() {
			
			href = $(this).attr("action");
			method = $(this).attr("method");
			
			data_array = $(this).serialize();
			$.ajax({
				url: href,
				type: method,
				data: data_array,
				success: function(json) {
					$("#overlayBg").remove();
					$("#overlay").remove();
					$(".communityOverlay").remove();
					$("body").prepend(json["overlay"]);
				},
				dataType: "json"
			});

			return false;
		});
	}
	
	if ("#oInviteFriends form".length > 0) {
		$("#oInviteFriends form").submit(function() {
			
			var current_form = $(this);
			
			href = $(this).attr("action");
			method = $(this).attr("method");
			
			data_array = $(this).serialize();
			$.ajax({
				url: href,
				type: method,
				data: data_array,
				success: function(json) {
					
					var total_items = 0;
					if (json["item_ids"] != undefined) total_items = json["item_ids"].length;
					
					if (total_items > 0) {
						
						var last_item = total_items - 1;
						
						var items = $("li#overlay-item-"+json['item_ids'][last_item]);
						for (var i = last_item; i--;) {
							items = items.add("li#overlay-item-"+json['item_ids'][i]);
						}
						
						items.animate({opacity: 'hide'}, 400, "easeOutQuad", function() {
							items.remove();
							if ($("#selectFriends li").length == 0) {
								//$('.communityOverlay').remove();
								window.location.href=window.location.href;
							}
						});
						
						$('.communityOverlay .cOClose').unbind("click").click(function(){
							window.location.href=window.location.href;
							return false;
						});
					}
					else {
						$("#overlayBg").remove();
						$("#overlay").remove();
						$(".communityOverlay").remove();
						$("body").prepend(json["overlay"]);
					}
				},
				dataType: "json"
			});

			return false;
		});
	}
	
	if ("#oFriendRequest form".length > 0) {
		$("#oFriendRequest form").submit(function() {
			
			if (!confirm_locked) {
				confirm_locked = true; // lock out user clicks to prevent button mashing while confirm is taking place
				
				var current_form = $(this);
				
				href = $(this).attr("action");
				method = $(this).attr("method");
				
				data_array = $(this).serialize();
				$.ajax({
					url: href,
					type: method,
					data: data_array,
					success: function(json) {
						confirm_locked = false;
						var total_items = 0;
						if (json["item_ids"] != undefined) total_items = json["item_ids"].length;
						
						if (total_items > 0) {
							
							var last_item = total_items - 1;
							
							var items = $("li#overlay-item-"+json['item_ids'][last_item]);
							for (var i = last_item; i--;) {
								items = items.add("li#overlay-item-"+json['item_ids'][i]);
							}
							
							items.animate({opacity: 'hide'}, 400, "easeOutQuad", function() {
								items.remove();
								if ($("#friendRequest li").length == 0) {
									//$('.communityOverlay').remove();
									window.location.href=window.location.href;
								}
							});
							
							$('.communityOverlay .cOClose').unbind("click").click(function(){
								window.location.href=window.location.href;
								return false;
							});
						}
						else {
							var parent = current_form.parent();
							parent.find("span.message").remove();
							
							if (json["message"] != '' && json["message"] != null) {
								parent.find("form").remove();
								parent.append(json["message"]);
							}
							else {
								parent.append("<span class='message'>" + json["error"] + "</span>");
							}
						}
					},
					error: function(json) {
						// if there is a serverside error unlock the form to allow submission
						confirm_lock = false;
					}, 
					dataType: "json"
				});
			} // confirm lock is in place
			return false;
		});
	}
}


var CommentsManager = (function() {
	
	var form_id = "#frmComment";
	
	var prepare = function(new_comments) {
		
		if ($(".listComments .commentsNo").length == 0) {
			$(".listComments div.clear:first").after("<small class=\"commentsNo\"></small>");
		}
		
		if ($(".listComments ul.navPag").length == 0) {
			$(".listComments .commentsNo").after("<ul class=\"navPag\"></ul>");
		}
		
		if ($(".listComments .comments").length == 0) {
			$(".listComments ul.navPag").after("<ol class=\"comments clearfix\"></ol>");
		}
		
		var total = new_comments.length;
		if (total > 0) {
			for (var i = 0; i < total; i++) {
				$(".listComments .comments").prepend(new_comments[i].hide());
			}
		}
		
		return new_comments;
	};
	
	var update = function(new_comments, commentsNo_html, pagination_html, last_comment_id, update_all_comments) {
		
		var old_comments = $(".listComments .comments li");
		var new_comments = prepare(new_comments);
		var all_comments = $(".listComments .comments li");
		
		$(".listComments .commentsNo").replaceWith(commentsNo_html);
		$(".listComments ul.navPag").replaceWith(pagination_html);

		var total = all_comments.length;
		var max_items = $("#frmComment input[name=limit]").val();

		$("#last_comment_id").val(last_comment_id);

		if (total > max_items || (old_comments.length > 0 && update_all_comments === true)) {

			var comments_to_hide = (update_all_comments === true) ? old_comments : getLastItems(all_comments, (total - max_items));

			comments_to_hide.animate({opacity: 'hide'}, 400, "easeOutQuad", function() {
				comments_to_hide.remove();
				showItems(new_comments);
			});
		}
		else {
			showItems(new_comments);
		}
		
		addPageNavigationEventHandlers();
		enableButtons();
	};
	
	var showItems = function(items) {
	
		var total = items.length;
	
		if (total > 0) {
		
			var jq_items = $(items[0]);
			for (var i = (total - 1); i >= 0; i--) {
				jq_items = jq_items.add(items[i]);
			}
		
			jq_items.animate({opacity: 'show'}, 400, "easeInQuad");
		}
	};

	var getLastItems = function(collection, amount) {
	
		if (amount == undefined) amount = 1;
		
		var items = collection.filter(":last");
		for (var i = amount-1; i > 0; i--) {
			items = items.prev().andSelf();
		}
	
		return items;
	};
	
	var enableButtons = function(on_complete) {
		var submit_button = $(form_id + " button.btn[type=submit]");
		submit_button.removeAttr('onclick').css('cursor', 'pointer').animate({opacity: 1}, 0, "easeInQuad", on_complete);
	};

	var disableButtons = function(on_complete) {
		var submit_button = $(form_id + " button.btn[type=submit]");
		submit_button.attr('onclick', 'return false').css('cursor', 'default').animate({opacity: 0.5}, 0, "easeOutQuad", on_complete);
	};
	
	var addEventHandlers = function() {
		
		addFormEventHandlers();
		addPageNavigationEventHandlers();
		addCommentEventHandlers();
	};
	
	var addFormEventHandlers = function() {
		
		$(form_id).submit(function() {
			disableButtons(function() {
				
				var href = $(form_id).attr("action");
				var method = $(form_id).attr("method");
				var data_array = $(form_id).serialize();
				
				$.ajax({
					url: href,
					type: method,
					data: data_array,
					success: function(json) {
						// get the comment region id
						var region_id = $('#comment-region-id').val();
						
						$("#overlayBg").remove();
						$("#overlay").remove();
						$("body").prepend(json["overlay"]);
						
						// if the message has posted then reset the input field
						if (json['posted'] == 'true') $('#comment-textarea-' + region_id).val('Type your message...');
					},
					dataType: "json"
				});

				return false;
			});
			
			return false;
		});
	};
	
	var addPageNavigationEventHandlers = function() {
		
		$("#commentsList ul.navPag a").click(function(){

			var href = MOKO_WEB_AREA_ROOT + "comment/page" + $(this).attr("href").substring($(this).attr("href").indexOf("?"));
			var method = "POST";
			var data_array = $(form_id).serialize();
			
			$.ajax({
				url: href,
				type: method,
				data: data_array,
				success: function(json) {
					$("#overlayBg").remove();
					$("#overlay").remove();
					$("body").prepend(json["overlay"]);
				},
				dataType: "json"
			});

			return false;
		});
	};
	
	var addCommentEventHandlers = function() {
		
		$(".comments li a.overlay").unbind("click").click(function() {
			
			href = $(this).attr("href");
			method = 'GET';
			
			$.ajax({
				url: href,
				type: method,
				success: function(json) {
					$("#overlayBg").remove();
					$("#overlay").remove();
					$(".communityOverlay").remove();
					$("body").prepend(json["overlay"]);
				},
				dataType: "json"
			});

			return false;
		});
	};
	
	return {
		// declare public properties and methods
		update: update,
		addEventHandlers: addEventHandlers,
		enableButtons: enableButtons,
		disableButtons: disableButtons
	};
	
}());

// TABBED BLOCK
// Handles the image show/hide for news + blog tabs
function tab_txt_hover(wrapper) {
	var $wrapper 	= $(wrapper);
	var $items		= $wrapper.find('li');
	var $anchors	= $items.find('a');
	
	$anchors.hover( function () {
	   $items.removeClass('active');
		$(this).parent().addClass('active');
	
	}, 
	function () {
		// Has No Hover Out effect
	});					
}

// Handles the Tabs Show/Hide
function imama_tabs(wrapper, heading, tab) {
	var $wrapper 		= $(wrapper);
	var $tabHeading	= $wrapper.find(heading);
	var $tabs 			= $wrapper.find('.tab');
	
	$tabHeading.click( function() {
		$tabs.removeClass('active');
		$tabHeading.removeClass('active');
		$(this).addClass('active').next(tab).addClass('active');
		
	});
	
}
// END: TABBED BLOCK

/** From the community/index view **/
function horizontally_center(target) {
	$(target).css('margin-left' , ($(target).parent().width()/2)-($(target).width()/2));
}			

// ------------------------------------------------------------------------------
// END: FROM VIEWS
// ------------------------------------------------------------------------------


/* ----------------------------------------- */
/*           Show / Hide Sub Nav             */ 
/* ----------------------------------------- */
function sub_nav() {
	
	// Methods
	// 1. Move Sub Nav to bottom of markup
	function move_to_bottom_of_markup() {
		var position 	= $('#navMain').offset();
		if(typeof position != 'undefined'){
		  var positionT	= position.top;

		  $('body').append($('#navMain'));
		  $('#navMain').css({'position' : 'absolute', 'top' : positionT, 'left' : '50%', 'marginLeft' : (($('#navMain').width()/2)-10)*-1});
	  }
	}
	
	
	// 2. Handle All the users interactions 
	function sub_nav_interactions() {	
		var $allDropDowns		= $('#navMain .navSub');	
		var currentHref			= window.location.href;
		
		function show_nav_sub($anchor) {
			var $thisDropDown 		= $anchor.parents('li').children('.navSub');
			
			if ($thisDropDown.length) {
				dropDownPosition	= parseInt($thisDropDown.css('left').split('p')[0]);
			}

			if(!($thisDropDown.length)) {			
			} else if (!dropDownPosition)  {
				$anchor.attr('onclick', 'return false;');
				$allDropDowns.css({'left' : -9999});	

			} else {
				$anchor.attr('onclick', 'return false;');
				$allDropDowns.css({'left' : -9999});
				$thisDropDown.css({'left' : 0});

			}
		}

		// EVENTS
		$('#navMain a').click( function() {
			$allDropDowns.css({'left' : -9999});
			if (!($(this).hasClass('overlay')))
				// It doesnt open an overlay, so go to the URL
				window.location.href = $(this).attr('href');
			
		});
		
		$('#navMain > li > a').hover( function() {
			show_nav_sub($(this));
			return false;

		}, function() {	
		});
		
		$('#navMain > li > strong > a').hover( function() {
			show_nav_sub($(this));
			return false;
		}, function() {
		});

		$('.navSub').hover( function(){
		}, function() {
			$('.navSub').css('left' , -9999);

		});
		
		
		$('#navBar').hover(function(){}, function() {
			$('.navSub').css('left' , -9999);
		});
		
		
	}
	
	// 3. Fix height for ie6
	function fix_nav_height() {
		$('.navSub').each( function() {
			$(this).css('height', $(this).height());
		});
		
	}
	
	// FIRE
	sub_nav_interactions();
	if (typeof ie6 != 'undefined' || typeof ie7 != 'undefined')
		move_to_bottom_of_markup();
		
	if (typeof ie6 != 'undefined')
		fix_nav_height();
	
	
	
}


//WHAT: Toggle classes for tags
//WHY:  To provide feedback to the user when they click a tag
function click_tag_event(tag)	{
	var checkbox = $(tag).children("input[type=checkbox]:first");
	
	if (checkbox.is(":checked")) {
		checkbox.removeAttr("checked");
		$(tag).removeClass('tagOn').addClass('tagOff');
	
	} else {
		checkbox.attr("checked", "checked");
		$(tag).removeClass('tagOff').addClass('tagOn');
	
	}
	return false;
	
};

//WHAT: Document ready: fade inactive tags out.  User clicks tags: fade active tags in, inactive tags out. (Themes TED)
//WHY:  It allows the user to hide/show videos by their tag
function filter_boutique_list() {
	// Selectors
	wrapTags		=	'#fBFCategories';
	wrapBoutiques	=	'#filteredBoutiques';
	boutiqueItems	=	'#filteredBoutiques li';
	offTagClass		=	'tagOff';
	onTagClass		=	'tagOn';
	greyOut			=	'greyOut';
	
	// SETTINGS
	ease			=	'easeOutExpo';
	speed			=	500;
	
	// --------------
	// Document Ready
	// --------------
	
	$('.'+greyOut).css('opacity', 0).hide();
	//toggle_items();
	
	// --------------
	// INTERACTION
	// --------------
	// Tag
	$(wrapTags+' .tagCheckbox').click( function()	{
		click_tag_event(this);
		toggle_items();
		return false;
	});
	
	
	
	// --------------
	// METHODS
	// --------------
	
	
	// 1. Return an array of every disabled tag
	function get_enabled_tags() {
		tags = [];
		$(wrapTags+' .'+onTagClass).each( function() {
			tags.push($(this).attr('rel'));	
		});
		return tags;
	}
	
	
	// 2. Return an array of every list item that should be disabled.
	function toggle_items()	{
		
		var enabled_tags = get_enabled_tags();
		
		// Each List item
		$(boutiqueItems).each( function() {
			thisTags = $(this).attr('rel').split(',');
			thisId	 = $(this).attr('id');

			var has_all = true;

			// Each disabled tag (from the get_disabled_tags) array
			for (b in enabled_tags)	{
				
				var has_tag = false;
				
				// Each Tag
				for (tag in thisTags) {
					
					// If This list item has tags that should be disabled
					if (thisTags[tag] == enabled_tags[b]) {
						has_tag = true;
					}
					
					if (has_tag == true) break;
				}
				
				if (has_tag == false) has_all = false;
			}
			
			// If We Havent Disabled the video: Enable it
			if (enabled_tags.length == 0) fade_greyout(thisId, 'out');
			else if (has_all == false) fade_greyout(thisId, 'in');
			else fade_greyout(thisId, 'out');
		
		});
		
	}
	
	
	// 3. Fade A List item (in or out)
	function fade_greyout(item, direction) {
		greyOutItem	= $('#'+item).find('.'+greyOut);
		
		if (direction == 'in')	greyOutItem.show().animate({'opacity' : 0.7}, speed, ease);
		else greyOutItem.animate({'opacity' : 'hide'}, speed, ease);
	}
	
}

//WHAT: Set the outbound link title
//WHY:  So that when users mouse-over the outbound link it's more clear what will happen
function setOutboundLinkTitle() {
  $(this).attr('title', 'Open ' + $(this).attr('hostname') + ' in a new window');
}

//WHAT: Tracks outbound link clicks
//WHY:  Allows stats to be compiled about where we are sending traffic
function trackOutboundLinkClick(event) {
	try {
		_gaq.push(['_trackEvent', 'Outbound Link', event.type.toLowerCase(), $(this).attr('hostname')]);
	}catch(err){}
}
ready = false;
$(document).ready(function() {
  if(ready == true) return;
	ready = true;
	$("body").addClass("has-js");	
	if ($.browser.msie) style_buttons_for_ie();
	
	if ($('#uBImages').length > 0) user_box_images();
	
	if ($('.checkbox').length > 0) checkboxes();
	
	if ($('.toggle_overlay').length > 0) {
		$('.toggle_overlay').click( function() {
			return toggle_overlay();
		});
		overlay_position();
	}
	
	if ($('#selectFriends').length) {
		//community_overlay_select_actions();
		//$('#selectFriends').jScrollPane();
	}
	
	if ($('label.radio')) style_radios();
	//trail();
	sub_nav();
	
	if ($('form.overlay').length > 0) init_overlay_forms();
	if ($('a.overlay').length > 0) init_overlay_links();
	if($('#frmComment').length > 0) CommentsManager.addEventHandlers();
	if ($('#tabTextNews')) tab_txt_hover('#tabTextNews');
	if ($('#tabTextBlog')) tab_txt_hover('#tabTextBlog');
	if ($('#tabTextTubes')) tab_txt_hover('#tabTextTubes');
	if ($('#navTabs')) imama_tabs('#navTabs', '.tabHeading', '.tab');
	if ($('#commentsList')) {
		$("#ScrollToComments").click( function() {
			$.scrollTo( $('#commentsList'), 400 );
		});
	}
	
	// open all outbound links in a new window
	$('a[href^="http"]:not([href*="://' + location.host + '"])')
	   .attr('target', '_blank')
	   .click(trackOutboundLinkClick)
	   .each(setOutboundLinkTitle);
	   
	   
	ZeroClipboard.setMoviePath('/site/swf/ZeroClipboard10.swf');
});

