var firstload = 0;

//If Gallery type is 'video' and there is no #title in URL
if (typeof(gallerytype) != 'undefined' && gallerytype == 'video' && !location.href.match(/^.*#/)) {
	ytAttrs = $('.ytm-img-description-list li[ytid="'+$('.items > img:first').attr('ytid')+'"]');
	$('.ytm-photo-title').html(ytAttrs.attr('title'));
	$('#img-caption').html(ytAttrs.html());
	$('#img-caption').show();
	
	var stat = 0;	
	if($('#ytm_autoplay:not(.ytm-autoplay-off)').length > 0)
		stat = 1;
	
	var params = { allowScriptAccess: "always"};
	var atts = { id: "ytmplayer" };
	swfobject.embedSWF("http://www.youtube.com/v/" + $('.items > img:first').attr('ytid') + "&enablejsapi=1&loop=0&rel=0&playerapiid=ytmplayer&autoplay=" + stat, "player_wrap", "630", "400", "8", null, null, params, atts);
}


// PageLoad function
function pageload(hash) {
  if( $('.items > img:last').hasClass('active') ){
		$('#next').addClass('end');
  } else {
		if( $('#next').hasClass('end') ) {
			$('#next').removeClass('end');
		}
  }
	 
  if( $('.items > img:first').hasClass('active') ){
		$('#prev').addClass('end');
  } else {
		if( $('#prev').hasClass('end') ) {
			$('#prev').removeClass('end');
		}
  }

	// hash doesn't contain the first # character.
	if(hash) {		
		// restore ajax loaded state
		if($.browser.msie) {
			hash = encodeURIComponent(hash);
		}

		if(hash == 'view-as-one-page') {
			$('.ytm-gallery-box').hide();
        	$('.ytm-gallery-one-page').show();
        	changeAutoPlay(0);
		} else {
			var oldhash = hash;			
			var dsc = 1;
			var loadcontent = '';
			
			switch(gallerytype){
				case 'photo':
					//dsc = $("#itemsdsc > img[title='"+hash+"']").attr("alt");
					dsc = $("#itemsdsc > img[ytid='"+hash+"']").attr("alt");
					break;
				case 'video':
					dsc = $("#itemsdsc > img[ytid='"+hash+"']").attr("alt");
					break;
			}			
			
			if(typeof(gallerytype) != 'undefined') {
				switch(gallerytype){
				case 'photo':
					loadcontent = '<img src="' + $("img[ytid='"+hash+"']").attr("alt") + '" />';
					if(firstload == 0){
						//$("img[title='"+oldhash+"']").click();
						$("img[ytid='"+oldhash+"']").click();
						firstload ++;
					}
					$("#activnum").html(dsc);
					$("#image_wrap").html(loadcontent);
					break;
				case 'video':
					if(firstload == 0){
									$("img[ytid='"+oldhash+"']").click();
									firstload ++;
							}
					var stat = 0;
					if($('#ytm_autoplay:not(.ytm-autoplay-off)').length > 0)
							stat = 1;
					$("#activnum").html(dsc);
					$('#image_wrap').html('');
					$('#image_wrap').append('<div id="player_wrap"></div>');
					var params = { allowScriptAccess: "always"};
						var atts = { id: "ytmplayer" };
						swfobject.embedSWF("http://www.youtube.com/v/" + oldhash + "&enablejsapi=1&loop=0&rel=0&playerapiid=ytmplayer&autoplay=" + stat, "player_wrap", "630", "400", "8", null, null, params, atts);

						ytAttrs = $('.ytm-img-description-list li[ytid="' + oldhash + '"]');
						$('.ytm-photo-title').html(ytAttrs.attr('title'));
						$('#img-caption').html(ytAttrs.html());
						$('#img-caption').show();
						
					break;
				}
			}
		}
	}
}

function slidshow(){
    intervalslide = setInterval('slideshowstart()', 1500);
}

function slidshowstop(){
	if(typeof(intervalslide) == 'number') {
		clearInterval(intervalslide);
	}
}
 
function slideshowstart(){
	api.next();
	var next = null;
	var curr_div = $('.items > img.active');
	if( $('.items > img:last').hasClass('active') ){
		changeAutoPlay(0);
		next = curr_div;
	} else {
		next = curr_div.next();
	}
	curr_div.toggleClass('active');
	next.toggleClass('active');
	next.click();
}
    
function getPrevImage(){
	api.prev();
	var next = null;
	var curr_div = $('.items > img.active');
	if( $('.items > img:first').hasClass('active') ){
		next = curr_div;
	} else {
		next = curr_div.prev();
	}
	curr_div.toggleClass('active');
	next.toggleClass('active');
	next.click();
}

function getNextImage(circle){
	api.next();
	var next = null;
	var curr_div = $('.items > img.active');
	if( $('.items > img:last').hasClass('active') ){
		if(circle === true) {
			api.begin();
			next = $('.items > img:first');
		} else {
			next = curr_div;
		}
	} else {
			next = curr_div.next();
	}
	curr_div.toggleClass('active');
	next.toggleClass('active');
	next.click();
}

function getFirstImage(){
	api.begin();
	var curr_div = $('.items > img.active');
	var next = $('.items > img:first');
	curr_div.toggleClass('active');
	next.toggleClass('active');
	next.click(); 
}

function getLastImage() {
	api.end();
	changeAutoPlay(0);
	var curr_div = $('.items > img.active');
	var next = $('.items > img:last');
	curr_div.toggleClass('active');
	next.toggleClass('active');
	next.click();
}

function changeAutoPlay(stat){
	if(typeof(stat) != 'number'){
		if($('#ytm_autoplay:not(.ytm-autoplay-off)').length > 0){
			stat = 0;
		} else {
			stat = 1;
		}
	}
	
	if(stat == 1) {
		if( $('#image_wrap.photo').length > 0 ){
			slidshow();
		}
		if($('#image_wrap.video').length > 0){
	        //ytplayer.playVideo();
		}
		$('#ytm_autoplay').attr('class', '');
		$('#ytm_autoplay').addClass('ytm-autoplay-on');
	} else {
		if( $('#image_wrap.photo').length > 0 ){
			slidshowstop();
		}
		if($('#image_wrap.video').length > 0){
	        //ytplayer.pauseVideo();
		}
		$('#ytm_autoplay').attr('class', '');
		$('#ytm_autoplay').addClass('ytm-autoplay-off');
	}
}

function OpenVideoTab() {
	$('.gall-tabs ul li.active').removeClass('active');
	$('.ytm-videos-tab').addClass('active');
	$('.gall-tab-body.photos').addClass('hidden');	
	$('.gall-tab-body.videos').removeClass('hidden');
}

function OpenPhotoTab() {
	$('.gall-tabs ul li.active').removeClass('active');
	$('.ytm-photos-tab').addClass('active');
	$('.gall-tab-body.videos').addClass('hidden');	
	$('.gall-tab-body.photos').removeClass('hidden');
}


function onYouTubePlayerReady(playerId) {
	ytplayer = document.getElementById('ytmplayer');
	ytplayer.addEventListener('onStateChange', 'onytplayerStateChange');
}

function onytplayerStateChange(newState) {
	switch(newState){
	case 1:
		//changeAutoPlay(1);
		break;
	case 2:
		//changeAutoPlay(0);
		break;
	case 0:
		/*
		var play = 0;
			if($('#ytm_autoplay:not(.ytm-autoplay-off)').length > 0)
				play = 1;
			
			if (play == 1)
				getNextImage(true);
			*/
		break;
	}
}


function addPhotoLayout() {
	if($('#ytm-img-layout').length > 0 && $('#ytm-img-layout').css('display') != 'none')
		$('#ytm-img-layout').hide();
	
	if(typeof(attempt) == 'undefined')
		var attempt = 0;
	
	setTimeout(function(){
		var curImg = $('#image_wrap img');
		if (curImg.length > 0 && curImg.width() > 0 && curImg.height() > 0) {
			attempt = 0;
			setPhotoOptions(curImg);	
		} else {
			attempt++;
			if(attempt >= 5) {
				attempt = 0;
			} else {
				addPhotoLayout();
			}
		}
	}, 600);
}

function setPhotoOptions(curImg) {
	$("#image_wrap").animate({ 
		height: curImg.height(),
	}, 1000, false, function(){
		$('#ytm-img-layout').show();
	});
	
	var iWidth = curImg.width();
	var iMarginLeft = '-' + ( iWidth / 2 ) + 'px';
	var htmlLayout = '<div id="ytm-img-layout">' +
		'<div class="ytm-prev-arrow" onclick="getPrevImage()"></div>' +
		'<div class="ytm-next-arrow" onclick="getNextImage(true)"></div>' +
		'<div class="ytm-clear"></div>' +
		'</div>';
	
	if(! $('#ytm-img-layout').length > 0 )
		$('#image_wrap').append(htmlLayout);
	
	var divLayout = $('#ytm-img-layout');
	
	divLayout.css({
		'width' : iWidth,
		'marginLeft' : iMarginLeft,
		'zIndex' : '100'
	});
	
	var divDescription = $('#img-caption');
	
	if($('.items img.active').length > 0) {
		var iYtid = $('.items img.active').attr('ytid');
		var iTitle = $('.items img.active').get(0).title;
		$('.ytm-photo-title').html(iTitle);
		var iDescription = $('.ytm-img-description-list li[ytid="'+iYtid+'"]').html();
		if(iDescription.length > 1) {
			divDescription.html(iDescription);
			divDescription.show();
		} else {
			divDescription.html('');
			divDescription.hide();
		}
	}
	
	if( $('.items > img:first').hasClass('active') ){
		$('#ytm-img-layout .ytm-prev-arrow').hide();
	} else {
		$('#ytm-img-layout .ytm-prev-arrow').show();
	}
}

function setActionButtons() {
	if( $('.items > img:last').hasClass('active') ){
		changeAutoPlay(0);
		$('#ytm_next').removeClass('ytm-enabled');
		$('#ytm_next').addClass('ytm-disabled');
	} else {
		$('#ytm_next').removeClass('ytm-disabled');
		$('#ytm_next').addClass('ytm-enabled');
	}
	
	if( $('.items > img:first').hasClass('active') ){
		$('#ytm_prev').removeClass('ytm-enabled');
		$('#ytm_prev').addClass('ytm-disabled');
	} else {
		$('#ytm_prev').removeClass('ytm-disabled');
		$('#ytm_prev').addClass('ytm-enabled');
	}
	
}

function initGallery() {
	var rand = function() {
		return Math.floor ( Math.random ( ) * 1000000 + 1 );
	}

	var cycleAds = function() {
		/*if($('#ad-970').length > 0) {
			var randnumber = rand();
			var iFrameAd970 = "<iframe id='a3af65ca' name='a3af65ca' src='http://openx.mashable.com/www/delivery/afr.php?resize=1&amp;zoneid=6&amp;target=_top&amp;cb=" + randnumber + "' framespacing='0' frameborder='no' scrolling='no' width='970' height='66' allowtransparency='true'>" +
				"<a href='http://openx.mashable.com/www/delivery/ck.php?n=a578f160&amp;cb=" + randnumber + "' target='_top'>" +
				"<img src='http://openx.mashable.com/www/delivery/avw.php?zoneid=6&amp;cb=" + randnumber + "&amp;n=a578f160' border='0' alt='' />" +
				"</a></iframe>";
			$('#ad-970').html(iFrameAd970);
		}
		
		if($('#ad-leaderboard').length > 0) {
			var randnumber = rand();
			var iFrameAdLeaderboard = "<iframe id='a528a934' name='a528a934' src='http://openx.mashable.com/www/delivery/afr.php?resize=1&amp;n=a528a934&amp;zoneid=2&amp;target=_blank&amp;cb=" + randnumber + "&amp;ct0=%c' framespacing='0' frameborder='no' scrolling='no' width='728' height='90' allowtransparency='true'>" +
				"<a href='http://openx.mashable.com/www/delivery/ck.php?n=a577edfd&amp;cb=" + randnumber + "' target='_blank'>" +
				"<img src='http://openx.mashable.com/www/delivery/avw.php?zoneid=2&amp;cb=" + randnumber + "&amp;n=a577edfd&amp;ct0=%c' border='0' alt='' />" +
				"</a></iframe>";
			$('#ad-leaderboard').html(iFrameAdLeaderboard);
		}
		
		if($('#ad-sidebar').length > 0) {
			var randnumber = rand();
			var iFrameAdSidebar = "<iframe id='a58f1b85' name='a58f1b85' src='http://openx.mashable.com/www/delivery/afr.php?resize=1&amp;n=a58f1b85&amp;zoneid=4&amp;cb=" + randnumber + "' framespacing='0' frameborder='no' scrolling='no' width='300' height='250' allowtransparency='true'>" +
				"<a href='http://openx.mashable.com/www/delivery/ck.php?n=acd857ce&amp;cb=" + randnumber + "' target='_blank'>" +
				"<img src='http://openx.mashable.com/www/delivery/avw.php?zoneid=4&amp;cb=" + randnumber + "&amp;n=acd857ce' border='0' alt='' />" +
				"</a></iframe>";
			$('#ad-sidebar').html(iFrameAdSidebar);
		}*/

		$.historyLoad($(this).attr('ytid'));
		var title = $(this).attr('ytid');
		var iHash = '';
		var picid = '';
		
		if (profileid != '') {
			if(typeof(gallerytype) != undefined) {
				if (matches = document.location.href.match(/^.*#(.*)/)) {
					iHash = matches[1];
				} else {
					iHash = title;
				}
				picid = $(".items img[ytid='"+iHash+"']").attr('pid');
				if (typeof(picid) == undefined) picid = '';
				
				_gaq.push( ['_trackPageview'],['_trackEvent', 'gallery', '/gallery/' + galleryid + '/type/' + gallerytype + '/post/' + postid, picid] );
			}
		}
	    
		setActionButtons();
		addPhotoLayout();
		
		return false;	
	}
	
	// initialize scrollable 
	api = $("div.scrollable").scrollable({
		size: 7,
		api: true,
		disabledClass: "end"
	});

	//Hack for disable nextPage button when gallery has 7 photos/videos
	if($('div.scrollable img').length == 7 && !$('.buttons .nextPage').hasClass('end'))
		$('.buttons .nextPage').addClass('end');
	
	// Initialize history plugin.
	// The callback is called at once by present location.hash. 
	$.historyInit(pageload, "jquery_history.html");
	
	// set onlick event for buttons
	$("img[rel='history']").click(cycleAds);
	
	if(firstload == 0){
		$('#prev').addClass('end');
		firsthash = $('.items > img:first');
		firsthash.toggleClass('active');
		firstload++;
	}
	
	setActionButtons();

	$('.ytm-set-gallery-view').click(function(){
		viewType = $(this).find('.ytm-view-type').html();
		switch(viewType){
		case 'View As One Page':
			$.historyLoad('view-as-one-page');
			break;
		case 'View As Slideshow':
			var title = $('.items img.active').attr('ytid');
			title = encodeURIComponent(title.replace(/^.*#/, ''));
			$.historyLoad(title);
			$('.ytm-gallery-one-page').hide();
			$('.ytm-gallery-box').show();
			break;
		}
		return false;
	});

	addPhotoLayout();
}

function galleryPageInit() {
	if($('#image_wrap').length > 0) {
		/*
			if(gallerytype == 'video')
				changeAutoPlay(1);
		*/
		
		initGallery();
		
		var iHash = '';
		
		if (profileid != '') {
			
			if(typeof(gallerytype) != undefined) {
				if (matches = document.location.href.match(/^.*#(.*)/)) {
					iHash = matches[1];
				} else {
					iHash = $('.items > img:first').attr('ytid');
				}
				picid = $(".items img[ytid='"+iHash+"']").attr('pid');
				if (typeof(picid) == undefined) picid = '';
				
				_gaq.push( ['_trackEvent', 'gallery', '/gallery/' + galleryid + '/type/' + gallerytype + '/post/' + postid, iHash] );
			}
		}
	}
}

function hackChromeOnHidingComments(){
	var count = 0;
	if($('#dsq-new-post').size() > 0) {
		if(Get_Cookie('comments_view') == 'true') {
			$('#ytm_view_comments').html('Hide Comments');
		} else {
			$('#dsq-content').hide();
		}
	} else {
		count++;
		if(count < 10) setTimeout(hackChromeOnHidingComments, 300);
	}
}

$(document).ready(function(){	
	/* Comments Block Hiding */
	var commentsButtonTitle = $('#ytm_view_comments').html();
	$('#disqus_thread').show();
	
	galleryPageInit();
	hackChromeOnHidingComments();		//Hack for Hiding Comments in Chrome
	
	$('#ytm_view_comments').click(function(){
		if ($('#dsq-content').css('display') == 'none') {
			$(this).html('Hide Comments');
			Set_Cookie( 'comments_view', 'true', 1);
		} else {
			$(this).html(commentsButtonTitle);
			Set_Cookie( 'comments_view', 'false', 1);
		}
		$('#dsq-content').slideToggle();
		$('a.dsq-brlink').toggle();
		return false;
	});
	/* End Comments Block */
	
	//Temp (Remove)
	$('a.ytm-button-link').click(function(){
		return false;
	});	
});

