/*** scripts.js ***/
var currentIndex = 0;
var totalSlides = 0;
$(document).ready(function(){
	
	$(".single_brand .videos li.grid_3").equalHeights();
	$("#du .leftcol,#du .rightcol").equalHeights();

	$('#dashboard_blue').click(function(){
		location.href = 'http://www.sportika.com/dashboard';
	});

	$('.maingallery ul.videos li').equalHeights();

	$('a.no_preview').click(function(){ return false; });

	$("a.download_brand_file").attr('target', '_blank');

	$("dl.file_list dd ul").hide();

	// dashboard brand - downloads
	$("dl.file_list dt a").click(function(){
		var the_id = $(this).attr('itemid');
//		alert("you clicked on the category: " + the_id );
		if (!$('html').is('.ie7')) {
			$("dl.file_list dd#" + the_id + " ul" ).animate({ "height": "toggle" }, { "duration": 333 });
		} else {
			$("dl.file_list dd#" + the_id + " ul" ).animate({ "height": "toggle" }, { "duration": 0 });
		}
		return false;
	});


	$("#contact_container form").validate({
		focusInvalid: false,
		errorPlacement:function() {},
		messages:{required:''},
		highlight: function(element, errorClass) {$(element).parent().parent().addClass("error");},
		unhighlight: function(element, errorClass) {$(element).parent().parent().removeClass("error");}
 	});
	// Highlight Form Fields in Drawer when they have focus.
	$(".drawer .form input").focus(function(){$(this).parent(0).parent(0).addClass("highlight");}).blur(function(){$(this).parent(0).parent(0).removeClass("highlight");});
	$(".drawer .form textarea").focus(function(){$(this).parent(0).addClass("highlight");}).blur(function(){$(this).parent(0).removeClass("highlight");});


	// Open and close the Login Drawer (closing the contact drawer if it is open)
	// includes .ie7 visibility fix for z-index bug
	$(".login_toggle").click(function(){
		if ( !($("#login_drawer").is(':animated')) ) {
			if ($("#login_drawer").is(":hidden")) {
				if ( !($("#contact_drawer").is(":hidden")) ) {
					$(".ie7 #contact_container").css("visibility", "hidden");
					$("#contact_drawer").animate({ "height": "toggle" }, { "duration": 666 });
				}
				$(".ie7 #login_container").css("visibility", "hidden");
				$("#login_drawer").animate({ "height": "toggle" }, 666 , function(){
					$(".ie7 #login_container").css("visibility", "visible");
				});
				$(document).scrollTo(0,500);
			} else {
				$(".ie7 #login_container").css("visibility", "hidden");
				$("#login_drawer").animate({ "height": "toggle" }, { "duration": 666 });
			}
		}
	});


	// Open and close the Contact Drawer (closing the login drawer if it is open)
	$(".contact_toggle").click(function(){
		if ( !($("#contact_drawer").is(':animated')) ) {
			if ($("#contact_drawer").is(":hidden")) {
				if ( !($("#login_drawer").is(":hidden")) ) {
					$(".ie7 #login_container").css("visibility", "hidden");
					$("#login_drawer").animate({ "height": "toggle" }, { "duration": 666 });
				}
				$(".ie7 #contact_container").css("visibility", "hidden");
				$("#contact_drawer").animate({ "height": "toggle" }, 666 , function(){
					$(".ie7 #contact_container").css("visibility", "visible");
				});
				$(document).scrollTo(0,500);
			} else { 
				$(".ie7 #contact_container").css("visibility", "hidden");
				$("#contact_drawer").animate({ "height": "toggle" }, { "duration": 666 });
			}
		}
		return false;
	});

	var gSearch = $('#global_search_form'),
	gSearchVal = $('#global_search_form #q');
	gSearch.submit(function() {
		this.action = this.action.replace('term', gSearchVal.val());
		return true;
	});
	
	var gSearch_two = $('#search_search_form');
	if(gSearch_two.length) {
		gSearchVal_two = $('#search_search_form #gq');
		gSearch_two.submit(function() {
			this.action = this.action.replace('term', gSearchVal_two.val());
			return true;
		});
	}
	
	// Tabs on the homepage.
	if($(".home").length){
		var testimonials = $(".testimonial");
		var max = 0;
		testimonials.each(function(){
			if($(this).height() > max)
				max = $(this).height();
		});
		
		testimonials.hide();
		
		$(testimonials.get(0)).show();
		var currentIndex = 0;
		var totalSlides = testimonials.length;
		var test_tab = $("#testimonial_tab");
		test_tab.height(max);
		var oldIndex = false;
		
		var handleInterval = function() {
			oldIndex = currentIndex;
			currentIndex = (currentIndex + 1) % totalSlides;
			$(testimonials.get(oldIndex)).fadeOut(333,function() {$(testimonials.get(currentIndex)).fadeIn(333);});
		}
		
		var tabInterval = false;
		
		$("#testimonial_loading").remove();
		$(".testimonial").css("visibility","visible");
		
		$("body.home .tabbies").tabs({show:function(event, ui) {
			if(ui.index != 0) {window.clearInterval(tabInterval);} else {
				tabInterval = window.setInterval(handleInterval,12000);
			}
		}});
		
	}
	// Carousel on the homepage.
	$('.rotator #slide_nav_wrap').carousel('#back_slide', '#next_slide');
	$('#slide_container').cycle({
		fx: 'scrollLeft',
		after: function(currSlideElement, nextSlideElement, options, forwardFlag){
			var currentslide = $(currSlideElement).attr('itemid');
			var nextslide = $(nextSlideElement).attr('itemid');
			$("#slide_nav li[itemid='" + currentslide + "']").removeClass("ui-tabs-selected");
			$("#slide_nav li[itemid='" + nextslide + "']").addClass("ui-tabs-selected");
		},
		speed: 666
	});
	$('#slide_nav li').click(function(){
		var selected_id = $(this).attr("itemid");
		$('#slide_container').cycle(selected_id - 1);
//		$('#slide_nav li').removeClass("ui-tabs-selected");
//		$("#slide_nav li[itemid='" + selected_id + "']").addClass("ui-tabs-selected");
		return false;
	});

/*$(".ie a button").click(function() {
		var href = $($(this).parent("a")).attr("href");
		window.location.href = href;
		alert("test");
	});*/
	// Tabs on the individual Brand page.
	$("body.single_brand .tabbies").tabs();
	//$("body.single_brand .tabbies").tabs("disable",[2]);
	
	// Tabs on the dashboard Brand page.
	$("body.dashboard_brand .tabbies").tabs();
	
	if($('.ie body.dashboard_brand').length) {
		$('#download_btn_link').click(function(e) {
			window.location = this.href;
		});
	}
	
	// Tabs on contact directory.
	$("body.contact .directory").tabs();

	// Tabs on about page.
	$("body.about .directory").tabs();

	// Scroll to the top of the page
	$(".scrollToTop").click(function(){$.scrollTo({top:0,left:0},666);
		return false;
	});

	// Individual Brand mastheads
	var scroller = $('#brand_mast ul');
	if(scroller.length && $('body.single_brand').length != 0) {
		scroller.after('<div id="single_brand_nav">').cycle({
			fx:'fade',
			pager:'#single_brand_nav',
			pagerAnchorBuilder: function(){ return '<a href="#"></a>'; }
		});
	}

	// Carousel on Industry News Page
	if($('body.blog').length) {
		var tabs = $("#sx_carousel").tabs({ event: 'mouseover'});
		tabs.tabs("rotate" , 5000 , true);
	}
	
	if($('body.sportikatv').length){
	
		$(".play_btn").click(function(){
			var img = $('img.big_thumb');
			var vid = img.attr('vid');
			// These values need to be hardcoded.
			var h = 355; /*img.height()*/
			var w = 595; /*img.width()*/
			
//			if ($('html').is('.ie7')) {
//				var embed = '<embed id="mainVidEmbed" src="http://www.youtube.com/v/' + vid  + '&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' + w + '" height="' + h + '">';
//			} else {
				var embed = '<object id="mainVid" style="height: ' + h + 'px; width: ' + w + 'px"><param name="movie" value="http://www.youtube.com/v/' + vid +'&autoplay=1"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed id="mainVidEmbed" src="http://www.youtube.com/v/' + vid  + '&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' + w + '" height="' + h + '"></object>';
//			}
			
			img.parent().parent().replaceWith(embed);
			$(this).remove();
			return false;
		});
		if ($(".video_block").length > 1) {
			$('#video_slider').carousel('#video_back', '#video_next');
			$('.sportikatv .pagination').show();
		}
		
		
		// When a video thumbnail is clicked on the video page:
		$(".teevee img, .tiny_vid img").click(function(){
		
			/**** IE7 has issues with loading up new videos. Instead of replacing the DOM elements (which it seems to have trouble with) we're going to reload the page instead. ****/
			
			//alert("fn started, hash = " +  window.location.hash + "\n utitle = " + $(this).attr("utitle"));
			
			// start by updating the URL hash.
			var the_old_hash = window.location.hash;
			var the_new_url_title = $(this).attr("utitle");
			if (the_new_url_title != "" && the_new_url_title != "#") { // only change if it has a value!
				window.location.hash = the_new_url_title;
			}
			
			/**** Once the hash has been changed, tell IE7 to reload the page. ****/
			if ($('html').hasClass('ie7')) {
				// compare the old against the new to prevent infinite reloading
				//alert('old hash = "' + the_old_hash + '"' + "\n" + 'new hash = "#' + the_new_url_title + '"');
				//alert('$("#mainVid").length = "' + $("#mainVid").length + '"' + "\n" + '$("#mainVidEmbed").length = "' + $("#mainVidEmbed").length + '"');
				
				if (the_old_hash == "" || the_old_hash == "#" ) {
					if ($("#mainVid").length > 0 || $("#mainVidEmbed").length > 0){
						// video has been embedded
						location.reload();
						return false;
					} else {
						// continue.
					}
				} else {
					if (the_old_hash != "#" + the_new_url_title) {
						// hashes are different
						location.reload();
						return false;
					} else {
						// hashes are the same
						if ($("#mainVid").length > 0 || $("#mainVidEmbed").length > 0){
							// video has already been embedded; don't reload, don't reembed;
							return false;
						} else {
							// continue.
						}
					}
				}
			}
			
			// if present, remove the play button
			$(".play_btn").remove();
			
			var parent = $(this).parents(".teevee,.tiny_vid");
			var title = parent.find("figcaption a, h4").text();
			$("#gall_title").text(title);
			
			// select the <figure>
			if ($("#mainVid").length > 0 || $("#mainVidEmbed").length > 0){
				// if video already embeded
				var player_parent = $("#mainVid").parent(); 
			} else {
				// if video not yet embeded
				var player_parent = $("img.big_thumb").parent().parent().parent();
			}
			
			var vid = $(this).attr('vid');
			var desc = $(this).attr("vdesc");
			// These values need to be hardcoded.
			var h = 355; /*player.attr("height")*/
			var w = 595; /*player.attr("width")*/
			
//			if ($('html').is('.ie7')) {
//				var embed = '<embed id="mainVidEmbed" src="http://www.youtube.com/v/' + vid  + '&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' + w + '" height="' + h + '">';
//			} else {
				var embed = '<object id="mainVid" style="height: ' + h + 'px; width: ' + w + 'px"><param name="movie" value="http://www.youtube.com/v/' + vid +'&autoplay=1"><param name="allowFullScreen" value="true"><param name="allowScriptAccess" value="always"><embed id="mainVidEmbed" src="http://www.youtube.com/v/' + vid  + '&autoplay=1" type="application/x-shockwave-flash" allowfullscreen="true" allowScriptAccess="always" width="' + w + '" height="' + h + '"></object>';
//			}
			
			var str = $("#embedText").val();
			
			// Swap out the YouTube URL in the embed code
			$("#embedText").val(str.replace(/src="http:\/\/www.youtube.com\/embed\/[^"]+"/,'src="http://www.youtube.com/embed/' + vid + '"'));
			
			// remove the contents of the parent.
			player_parent.empty();
			// then add in the new video player
			player_parent.html(embed);
			
			$("#video_desc").text(desc);
			
			/*** AJAX call /[] ***/
			if (the_new_url_title != "") {
				$.ajax({
					url: "http://www.sportika.com/sportika_tv/fbtw_icons/" + the_new_url_title,
					success: function(data) {$('#fbtw_icons').html(data);}
				});
			}
			/*** call returns 3 LIs that will replace ul#fbtw_icons 's children ***/
			
			// load title in case it gets changed
			$('title').text("Sportika TV | Sportika Export");
			
			return false;
		});
		
		
		$("select.brand_select").change(function(){
			var val = $(this).val();
			window.location = tv_path + "/" + val;		
		});
		
		
		// after all the click handlers have been set, let's do some initialization
		var hash = window.location.hash;
		if(hash != "" && hash != "#"){
			hash = hash.substring(1);
			//alert("new hash set as: " + hash + " | about to trigger click on element");
			$('.teevee img[utitle="' + hash + '"]').click();
			$('title').text("Sportika TV | Sportika Export");
			//alert("click function has fired.");
		}
	}

	if($(".photos.maingallery").length){
		$("select.category_select").change(function(){
			var val = $(this).val();
			window.location = photo_path + "/" + val;		
			
		});
		if ($(".photo_block").length > 1) {
			$('#photo_slider').carousel('#video_back', '#video_next');
			$('.pagination').show();
		}
	}

	$(".special_details").each(function(){
		// Check whether the excerpt is the same as the description.
		if ($(this).find(".special_excerpt").text() != $(this).find(".special_description").text()) {
			$(this).find(".special_description").hide();
			$(this).find(".toggle_special").show();
		} else {
			$(this).find(".special_excerpt").hide();
			$(this).find(".toggle_special").hide();
			$(this).find(".special_ad_sep").hide();
		}
	});
	$(".toggle_special").click(function(){
		if ($(this).parent('p.sp_links').siblings('p.special_description').is(":hidden")) {
			$(this).parent('p.sp_links').siblings('p.special_excerpt').hide();
			$(this).parent('p.sp_links').siblings('p.special_description').show();
			$(this).siblings(".special_ad_sep").hide();
		}
		$(this).hide();
		return false;
	});

	
	// placeholder support for older browsers
	$('[placeholder]').focus(function() {
	  var input = $(this);
	  if (input.val() == input.attr('placeholder')) {
	    input.val('');
	    input.removeClass('placeholder');
	  }
	}).blur(function() {
	  var input = $(this);
	  if (input.val() == '') {
	    input.addClass('placeholder');
	    input.val(input.attr('placeholder'));
	  }
	}).blur().parents('form').submit(function() {
	  $(this).find('[placeholder]').each(function() {
	    var input = $(this);
	    if (input.val() == input.attr('placeholder')) {input.val('');}
	  })
	});
	
});
