var t;
var limit = 0;
var speed = 5000;
		
$(document).ready(function(){
	var compReveal = getUrlVars();
	if(compReveal.ford == 'enter'){
		$('#compReveal').show();
	}
	
	$(".thumbWrap").each(function(el){
		this.ontouchstart = function() { 
		    var href = $(this).attr('href');
			window.location = href;
		}
	});
	$("#products label").each(function(el){
		this.ontouchstart = function() { 
			var toCheck =$(this).children('input');
			check(toCheck);
		}
	});
	$(".nominate label").each(function(el){
		this.ontouchstart = function() {
			$(this).children('input').attr('checked','checked');
			$('.nominate').addClass('selected'); 
			$('form#products #voteBlock li').removeClass('selected'); 
			var myCheckbox = $(this).children('input');
			if ($(myCheckbox).is(':checked')) {
				$('#nominate_product').removeAttr('disabled');
				$('#save_vote').attr('disabled', false);
			}	
		}
	});	
	/*
	$('#products label').tap(function(){
		$(this).children('input').attr('checked',true);
	});
	*/
	count();
	$('select:not(.ignoreMe)').selectBox();
	limit = $('#carousel li').length-1;
	autoSwitchCarousel();
	$('#carouselY').text(limit+1);
	$('.manualControl').click(function(){
		var newDirection = $(this).attr('id');
		shiftCarousel(newDirection)
		return false;
	});	
	/*
	$('#carousel_container').live('swipeleft swiperight',function(event){
		clearInterval(t);
		if (event.type == "swiperight") {
			var newDirection = 'leftBtn';
			shiftCarousel(newDirection);
			console.log(this.nodeName);
		}
		if (event.type == "swipeleft") {
			var newDirection = 'rightBtn';
			shiftCarousel(newDirection);
		}
		autoSwitchCarousel();
		event.preventDefault();
	});
	*/
	$('#carousel_container').hover(function(){
		clearInterval(t);
	}, function(){
		autoSwitchCarousel();
	});
	var liWidth = parseInt($('#galleryMask ul li').first().width())+1;
	var ulWidth = parseInt(liWidth*$('#galleryMask ul li').length);
	var gallerylimit = ulWidth - parseInt($('#galleryMask').width());
	$('#galleryMask ul').width(ulWidth);
	var indexThumb = $('#selectedThumb').index('#galleryMask ul li');
	var startPos = (liWidth*(indexThumb-1))-10;
	if (startPos > gallerylimit){
		startPos = gallerylimit;
	}
	setDisable(-startPos,gallerylimit);
	$('#galleryMask ul').css('left','-'+startPos+'px');
	$('#galleryMask .control').click(function(){
		if($('#galleryMask ul:not(:animated)').length){
			var direction = $(this).attr('id');
			var pos = parseInt($('#galleryMask ul').css('left')); 
			if(direction == 'left'){
				if (pos >= 0){
					return false;
				} else{
					direction = 1;	
				}	
			} else {
				if (pos <= -gallerylimit){
					return false;
				} else {
					direction = -1;	
				}
			}
			pos = pos+(liWidth*direction);
			$('#galleryMask ul').animate({
			   	left: pos
			}, 180);
			setDisable(pos,gallerylimit);
		}
		return false;
	});
	$('#videoPlaceHolder').show();
	$('#youTube').remove();
	$('#videoPlaceHolder a').click(function(){
		$('#videoPlaceHolder').replaceWith('<embed src="http://www.youtube.com/v/tbYSdI0PSFY&autoplay=1&hd=1" type="application/x-shockwave-flash" wmode="transparent" width="624" height="385"></embed>')
		return false;
	});
	
	$("#carousel_container").touchwipe({
		wipeLeft: function() { 
			clearInterval(t);
			shiftCarousel('rightBtn');
			autoSwitchCarousel(); 
		},
		wipeRight: function() { 
			clearInterval(t);
			shiftCarousel('leftBtn');
			autoSwitchCarousel(); 
		}
	});
	
	var params = {allowScriptAccess: "always"}, atts = {id: "videoPlayer"};
	
	var firstVideo = 'vTwZPXi_Rho';
	//Load chromeless player SWF.
	swfobject.embedSWF('http://www.youtube.com/e/'+firstVideo+'?version=3&enablejsapi=1', "videoContainer", "624", "351", "8", null, null, params, atts);
	//getDescription(firstVideo);
	
	//Load thumbnail images for video playlist and set click method. 
	$('ul#videoPlaylist li.video').each(function(index){
		var $this = $(this);
		var $thumbnail = $this.find('img.thumbnail');
		var video_id = $this.children('a').attr('href').split('v=')[1];
		if(index==0) first_video_id = video_id;
		var thumbnail_url = "http://img.youtube.com/vi/"+video_id+"/default.jpg";
		$thumbnail.attr('src', thumbnail_url);
		$this.each(function(el){
			this.ontouchstart = function() { 
			    var href = $(this).children('a').attr('href');
				window.location = href;
				return false;
			}
		});
		$this.click(function(e){
			$('ul#videoPlaylist li').removeClass('selected');
			$this.addClass('selected');
			video_player.loadVideoById(video_id);
			getDescription(video_id);
			$('.videoControls a').removeClass('disabled');
			if($this.hasClass('last')){
				$('#nextBtn').addClass('disabled');
			} else if($this.hasClass('first')){
				$('#previousBtn').addClass('disabled');
			}
			return false;
		});
	});
	
	$('.videoControls a').click(function(){
		var $this = $(this);
		if(!$this.hasClass('disabled')){
			var	modifier = 1,
				$controls = $('.videoControls a'),
				$playlist = $('#videoPlaylist'),
				selectedVideoIndex = $playlist.children('li.selected').index();
			if($this.attr('id') == 'previousBtn')
				modifier = -1;
			var newselectedVideoIndex = selectedVideoIndex + modifier,
				$newselectedVideo = $playlist.children('li:eq('+newselectedVideoIndex+')'),
				video_id = $newselectedVideo.children('a').attr('href').split('v=')[1];
			$playlist.children('li').removeClass('selected');
			$controls.removeClass('disabled');
			if($newselectedVideo.hasClass('last')){
				$('#nextBtn').addClass('disabled');
			} else if(newselectedVideoIndex == 0){
				$('#previousBtn').addClass('disabled');
			}
			$newselectedVideo.addClass('selected');
			video_player.loadVideoById(video_id);
			getDescription(video_id);
		}
		return false;
	});
	
});

function getDescription(myId){
	var URI = 'https://gdata.youtube.com/feeds/api/videos/'+myId+'?alt=json&v=2&callback=?';
	$.ajax({
	  url: URI,
	  dataType: 'JSON',
	  success: function(data){
	    var description = linkFormat(data.entry.media$group.media$description.$t);
		var title =  data.entry.title.$t;
		$('#videoTitle').text(title);
		$('#videoDescription').html(description);
	  }
	});
}

function linkFormat(text) {
	var string = text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
		var wrap = document.createElement('div');
		var anch = document.createElement('a');
		anch.href = url;
		anch.target = "_blank";
		anch.innerHTML = url;
		wrap.appendChild(anch);
		return wrap.innerHTML;
	});
	return string;
}

function shiftCarousel(direction){
	var elements = $("#carouselControl li a");
	if(direction == 'leftBtn'){
		direction = -1;
	} else {
		direction = 1;
	}
	var nextIndex = getActiveIndex(elements) + direction;
	switchCarousel(nextIndex,elements);	
}
function setDisable(n,l){
	if (n >= 0 ){
		$('#galleryMask .control').removeClass('disable');
		$('#galleryMask #left').addClass('disable');
	} else if (n <= -l){
		$('#galleryMask .control').removeClass('disable');
		$('#galleryMask #right').addClass('disable');
	} else {
		$('#galleryMask .control').removeClass('disable');
	}
}
function autoSwitchCarousel(){
	var elements = $("#carouselControl li a");
	var nextIndex = getActiveIndex(elements) + 1;
	t = self.setInterval(function(){
		if(nextIndex > limit){
			nextIndex = 0;
		} 
		switchCarousel(nextIndex++,elements);
	},speed);	
}
function switchCarousel(btnIndex,set){
	if(btnIndex > limit){
		btnIndex = 0;
	} else if (btnIndex == -1){
		btnIndex = limit;
	}
	var oldIndex = getActiveIndex(set);
	var sTarget = btnIndex*624;
	var difference = Math.abs(btnIndex-oldIndex);
	var animationSpeed = difference*100;
	$('#carousel').stop(true);
	set.removeClass('active').eq(btnIndex).addClass('active');
	$('#carousel').animate({
	   	left: -sTarget
	}, animationSpeed);	
	$('#carouselX').text(btnIndex+1);
}

function getActiveIndex(indexSet){
	var getIndex = -1;
	for(var i =0; i < indexSet.length; i ++) {
		if($(indexSet[i]).hasClass('active')) {
			getIndex = i;
			break;
		}			
	}
	return getIndex;
}
//social networking
function count(){
	//count facebook
	if ($('#fbCount').length){
		var fbURI = 'https://api.facebook.com/method/fql.query?query=SELECT%20like_count%20FROM%20link_stat%20WHERE%20url%3D%22http%3A%2F%2Ffacebook.com%2Ft3mag%22&format=json&callback=?'
		$.getJSON(fbURI, function(d){	
			$('#fbCount').html(d[0].like_count);
		});	
	}
	//count twitter
	if ($('#twitterCount').length){
		var twitterURI = 'http://urls.api.twitter.com/1/urls/count.json?url=http%3A%2F%2Fawards.t3.com%2F&callback=?';
		$.getJSON(twitterURI, function(d){	
			$('#twitterCount').html(d.count);
		});
	}
}

function jumpTo(elem){
	var target = elem.attr('href');
	var destination = $(target).offset().top;
	var fixDestination = Math.floor(destination);
	$("html:not(:animated),body:not(:animated)").animate({ scrollTop: fixDestination}, 500);
	return false;
}

function onYouTubePlayerReady(playerId){
  video_player = document.getElementById('videoPlayer');
  video_player.cueVideoById(first_video_id);
  video_player.playVideo();
  getDescription(first_video_id);
  $('#videoContainer').removeClass('loading');
}
function getUrlVars(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
