$(document).ready(function() {

	// Slide swapper
	$(function () {
	    var tabContainers = $('div#panelSwapper > div');
	    
	    $('div#panelSwapper ul#panelCtrl a').click(function () {
	        tabContainers.hide().filter(this.hash).show();
	        
	        $('div#panelSwapper ul#panelCtrl a').removeClass('switchActive');
	        $(this).addClass('switchActive');
	        
	        return false;
	    }).filter(':first').click();
	    
	    $('div#panelSwapper ul#panelCtrl a').hover(
	    	function () {
	    		tabContainers.addClass('panelHover');
	    	},	    
	    	function () {
	    		tabContainers.removeClass('panelHover');
	    	}
	    );
	});
	

	if ( $('.panel_animate').length > 0 ) { 
		
		$('#panelSwapper .imgSwapPane:first').addClass('active');
		setInterval(function(){ChangeHPSlide();}, 5000);
	} 
		                     
	function ChangeHPSlide() {

		var $hpTabContainers = $('#panelSwapper div.imgSwapPane');
		var $active = $('#panelSwapper .imgSwapPane.active');
		
	    if ( $active.length == 0 ) $active = $('#panelSwapper .imgSwapPane li:last');
	
	    // use this to pull the images in the order they appear in the markup
	    var $next =  $active.next().length ? $active.next() : $('#panelSwapper .imgSwapPane:first');

	    $hpTabContainers.hide();
	    $next.addClass('active').fadeIn(function() {
			$active.removeClass('active');
		});
		
		// Link highlighting
		var $activeHref = $next.attr('id');
		var $tabNumber = parseInt($activeHref.substring(9,10));
		var $activeLink = $('div#panelSwapper ul#panelCtrl a[href="#homePanel'+$tabNumber+'"]');
		
		// Remove link active class
		$('div#panelSwapper ul#panelCtrl a').removeClass('switchActive');
		// Add link active class
		$activeLink.addClass('switchActive');
	}
	
	
	
	// Homepage feature swapper
	$('.home_feature_slider_ctrl a').click(function() {
		var $hp_features = $(this).parents('.home_feature_slider').children();
		var $active_feature = $hp_features.children('li.active');
		
		if ( $active_feature.length == 0 ) $active_feature = $hp_features.children('li:last');
		
	    // use this to pull the images in the order they appear in the markup
		var $next_feature =  $active_feature.next().length ? $active_feature.next() : $hp_features.children('li:first');
		var $prev_feature =  $active_feature.prev().length ? $active_feature.prev() : $hp_features.children('li:last');
		
		if($(this).hasClass('next_feature')) {
			$active_feature.removeClass('active').hide();	
			$next_feature.addClass('active').fadeIn();
		}
		
		if($(this).hasClass('prev_feature')) {
			$active_feature.removeClass('active').hide();	
			$prev_feature.addClass('active').fadeIn();
		}
		return false;
	});
	// Show the first pane of all homepage features	
	$('.home_feature_slider li').filter(':first').show();
	
	// Homepage gallery
	if ( $('.homeGal').length > 0 ) { 
		setInterval(function(){ChangeSlide();}, 5000);
	} 
		                     
	function ChangeSlide() {
		var $active = $('.homeGal li.active');
		
	    if ( $active.length == 0 ) $active = $('.homeGal li:last');
	
	    // use this to pull the images in the order they appear in the markup
	    var $next =  $active.next().length ? $active.next() : $('.homeGal li:first');

	    $active.addClass('last-active');
	
	    $next.css({opacity: 0.0})
	        .addClass('active')
	        .animate({opacity: 1.0}, 1000, function() {
	            $active.removeClass('active last-active');
		});
	}
	
	// Print this page link
	$(".backToTop").after("&nbsp;|&nbsp;<a href=\"#\" onclick=\"window.print();\">Print this page</a>");
	
	// Remove search term onfocus
	$.fn.search = function() {
		return this.focus(function() {
			if( this.value == this.defaultValue ) {
				this.value = "";
			}
		}).blur(function() {
			if( !this.value.length ) {
				this.value = this.defaultValue;
			}
		});
	};
	$("#siteSearch input").search();
	
	//Info box reveal
	$(".swapPaneQM").hover(
		function () {
			$(this).siblings(".swapPaneDesc").show();
		},
		function () {
			$(this).siblings(".swapPaneDesc").hide();
		}
	);

	// If the 'categories_list' cookie is set to 'closed', hide the categories list
	if($.cookies.get('categories_list') == 'closed')
	{
		$("#catList").css('display','none');
		$("#catListCtrl").html("Show categories").addClass("closed");
	}
	
	//Cat list toggle
	$("#catListCtrl").click(
		function () {
			if ($(this).hasClass('closed')) 
			{
				$(this).removeClass("closed");
				$("#catList").slideDown(750, function(){ 
					$("#catListCtrl").html("Hide categories");
				});
				$.cookies.set('categories_list','open');
			}
			else
			{
				$("#catList").slideUp(750, function() { 
					$("#catListCtrl").addClass("closed").html("Show categories");
				});
				$.cookies.set('categories_list','closed');
			}
		}
	);
	
	
	// V-Zone popup
	if ( $('#v_item_holder').length > 0 && isIOS == 'false') { 
		
		
		var focused_item = null;
		
		$(".v_item a").click(function(event) {
			
			var self = $(this);
			var rel = self.attr('rel');
			var ajax_data = '';
			
			focused_item = self;
			
			if($(this).hasClass('is_youtube'))
			{
				ajax_data = 'youtube_id=' + $(this).attr('id');	
			}
			
			$.ajax({
			  url: "/ajax/vzone/"+rel,
			  data: ajax_data,
			  context: document.body,
			  success: function(html){
			    $("#vzone_ajax_holder").empty();
			    $("#vzone_ajax_holder").append(html);
			    self.blur();
			    setTimeout(function(){focusModal()}, 100);
			  }
			});
			
			event.preventDefault();
		});
		
		/* Custom funcs for popup */
		var showPop = function(hash)
		{ 
			hash.w.fadeIn('1000').show();
		}; 
		
		var clearPop = function(hash) { 
			if(focused_item != null)
			{
				focused_item.focus();
				focused_item = null;
			}
			hash.w.fadeOut('2000',function()
			{ 
				$("#vzone_ajax_holder").empty(); 
			}); 
		};
		
		var focusModal = function()
		{
			$("#vzone_popup #close_pop").focus();
		}
		
		$('#vzone_popup').jqm({
			trigger: '.v_item a',
			onShow: showPop,
			onHide: clearPop,
			overlay: 0
		});
		
	} 
	
	//V-Zone submit form conditionals
	if ( $('#vzone_form_typeselect').length > 0 ) { 
		
		// Toggle dropdown input show/hide
		function contentToggle(obj) {
			if (obj.val() == 'video') {
				$('#vzone_video_holder').show();
				$('#vzone_file_holder').hide();
			}
			else 
			{
			  $('#vzone_video_holder').hide();
			  $('#vzone_file_holder').show();
			}
		};
		
		contentToggle($('form#vzone_submit #vzone_form_typeselect select'));
		
		// Custom dropdown
		createDropDown();
		            
        $(".dropdown dt a").click(function() {
            $(".dropdown dd ul").toggle();
            return false;
        });

        $(document).bind('click', function(e) {
            var $clicked = $(e.target);
            if (! $clicked.parents().hasClass("dropdown"))
                $(".dropdown dd ul").hide();
        });
                    
        $(".dropdown dd ul li a").click(function() {
            var text = $(this).html();
            var sel_class = $(this).attr('class');
            $(".dropdown dt a").html(text).attr('class', sel_class);
            $(".dropdown dd ul").hide();

            var source = $("#vzone_form_typeselect select");
            source.val($(this).find("span.value").html());
            contentToggle($('form#vzone_submit #vzone_form_typeselect select'));
			return false;
        });
	  
	};
	
	
});

if ( $('#vzone_form_typeselect').length > 0 ) { 
// Custom dropdown for V-Zone
function createDropDown(){
    var source = $("#vzone_form_typeselect select");
    var selected = $("#vzone_form_typeselect select option:selected");
    var options = $("option", source);
    
    $("#vzone_form_typeselect").append('<dl id="vzone_form_fancytypeselect" class="dropdown"></dl>')
    $("#vzone_form_fancytypeselect").append('<dt><a href="#" class="'+ selected.attr('class') +' vzone_button"><span>' + selected.text() + 
        '</span><span class="value">' + selected.val() + 
        '</span></a></dt>')
    $("#vzone_form_fancytypeselect").append('<dd><ul></ul></dd>')

    options.each(function(){
        $("#vzone_form_fancytypeselect dd ul").append('<li><a href="#" class="'+$(this).attr('class')+' vzone_button"><span>' + 
            $(this).text() + '</span><span class="value">' + 
            $(this).val() + '</span></a></li>');
    });
}

// Tooltips for V-Zone        
	/*!
	 * jQuery Tools v1.2.6 - The missing UI library for the Web
	 * 
	 * tooltip/tooltip.js
	 * 
	 * NO COPYRIGHTS OR LICENSES. DO WHAT YOU LIKE.
	 * 
	 * http://flowplayer.org/tools/
	 * 
	 */
	(function(a){a.tools=a.tools||{version:"v1.2.6"},a.tools.tooltip={conf:{effect:"toggle",fadeOutSpeed:"fast",predelay:0,delay:30,opacity:1,tip:0,fadeIE:!1,position:["top","center"],offset:[0,0],relative:!1,cancelDefault:!0,events:{def:"mouseenter,mouseleave",input:"focus,blur",widget:"focus mouseenter,blur mouseleave",tooltip:"mouseenter,mouseleave"},layout:"<div/>",tipClass:"tooltip"},addEffect:function(a,c,d){b[a]=[c,d]}};var b={toggle:[function(a){var b=this.getConf(),c=this.getTip(),d=b.opacity;d<1&&c.css({opacity:d}),c.show(),a.call()},function(a){this.getTip().hide(),a.call()}],fade:[function(b){var c=this.getConf();!a.browser.msie||c.fadeIE?this.getTip().fadeTo(c.fadeInSpeed,c.opacity,b):(this.getTip().show(),b())},function(b){var c=this.getConf();!a.browser.msie||c.fadeIE?this.getTip().fadeOut(c.fadeOutSpeed,b):(this.getTip().hide(),b())}]};function c(b,c,d){var e=d.relative?b.position().top:b.offset().top,f=d.relative?b.position().left:b.offset().left,g=d.position[0];e-=c.outerHeight()-d.offset[0],f+=b.outerWidth()+d.offset[1],/iPad/i.test(navigator.userAgent)&&(e-=a(window).scrollTop());var h=c.outerHeight()+b.outerHeight();g=="center"&&(e+=h/2),g=="bottom"&&(e+=h),g=d.position[1];var i=c.outerWidth()+b.outerWidth();g=="center"&&(f-=i/2),g=="left"&&(f-=i);return{top:e,left:f}}function d(d,e){var f=this,g=d.add(f),h,i=0,j=0,k=d.attr("title"),l=d.attr("data-tooltip"),m=b[e.effect],n,o=d.is(":input"),p=o&&d.is(":checkbox, :radio, select, :button, :submit"),q=d.attr("type"),r=e.events[q]||e.events[o?p?"widget":"input":"def"];if(!m)throw"Nonexistent effect \""+e.effect+"\"";r=r.split(/,\s*/);if(r.length!=2)throw"Tooltip: bad events configuration for "+q;d.bind(r[0],function(a){clearTimeout(i),e.predelay?j=setTimeout(function(){f.show(a)},e.predelay):f.show(a)}).bind(r[1],function(a){clearTimeout(j),e.delay?i=setTimeout(function(){f.hide(a)},e.delay):f.hide(a)}),k&&e.cancelDefault&&(d.removeAttr("title"),d.data("title",k)),a.extend(f,{show:function(b){if(!h){l?h=a(l):e.tip?h=a(e.tip).eq(0):k?h=a(e.layout).addClass(e.tipClass).appendTo(document.body).hide().append(k):(h=d.next(),h.length||(h=d.parent().next()));if(!h.length)throw"Cannot find tooltip for "+d}if(f.isShown())return f;h.stop(!0,!0);var o=c(d,h,e);e.tip&&h.html(d.data("title")),b=a.Event(),b.type="onBeforeShow",g.trigger(b,[o]);if(b.isDefaultPrevented())return f;o=c(d,h,e),h.css({position:"absolute",top:o.top,left:o.left}),n=!0,m[0].call(f,function(){b.type="onShow",n="full",g.trigger(b)});var p=e.events.tooltip.split(/,\s*/);h.data("__set")||(h.unbind(p[0]).bind(p[0],function(){clearTimeout(i),clearTimeout(j)}),p[1]&&!d.is("input:not(:checkbox, :radio), textarea")&&h.unbind(p[1]).bind(p[1],function(a){a.relatedTarget!=d[0]&&d.trigger(r[1].split(" ")[0])}),e.tip||h.data("__set",!0));return f},hide:function(c){if(!h||!f.isShown())return f;c=a.Event(),c.type="onBeforeHide",g.trigger(c);if(!c.isDefaultPrevented()){n=!1,b[e.effect][1].call(f,function(){c.type="onHide",g.trigger(c)});return f}},isShown:function(a){return a?n=="full":n},getConf:function(){return e},getTip:function(){return h},getTrigger:function(){return d}}),a.each("onHide,onBeforeShow,onShow,onBeforeHide".split(","),function(b,c){a.isFunction(e[c])&&a(f).bind(c,e[c]),f[c]=function(b){b&&a(f).bind(c,b);return f}})}a.fn.tooltip=function(b){var c=this.data("tooltip");if(c)return c;b=a.extend(!0,{},a.tools.tooltip.conf,b),typeof b.position=="string"&&(b.position=b.position.split(/,?\s/)),this.each(function(){c=new d(a(this),b),a(this).data("tooltip",c)});return b.api?c:this}})(jQuery);
	
	$(function() {
		$("#vzone_submit :input[title]").tooltip({
			position: "center right",
			offset: [-2, 10],
			effect: "fade"	
		});
	});
	
};
