/**
 * This js file contains almost all the site media detail methods. 
 * 
 * @author Basit (i@Basit.me || http://Basit.me)
 */
var media = {
		
	getID: function()
	{
		var media_id = $j('h2').attr('id');
			
		if (!media_id)
			return 0;
			
		media_id = media_id.replace(/^m{1}/ig, '');
		return media_id;
	},
	
	renameTitle: function (media_id, name)
	{
		api.mediaModify(media_id, {title: name}, function(response)
		{
			if (response.status_valid == 1) 
			{
				api.ajax_response(response, 'renamed Successfully.');
				$j('#title').text(response.title).next('a').show();
				$j('title').text(response.title+' - '+$site_name); // changing header title
			}
		});
	},
	
	modifyDescription: function (media_id, description)
	{
		api.mediaModify(media_id, {description: description}, function(response)
		{
			if (response.status_valid == 1) 
			{
				api.ajax_response(response, 'description changed Successfully.');
				$j('#description').text(response.description).next('a').show();
			}
		});
	},
	
	band: function(media_id, band)
	{
		api.mediaModify(media_id, {band: band}, function(response)
		{
			if (response.status_valid == 1) 
			{
				api.ajax_response(response, 'status changed Successfully.');
				var text = (band == 'yes') ? 'unBan' : 'Ban';
				$j('#band a').html(text);
			}
		});
	},
	
	delete_media: function(media_id)
	{
		api.mediaDelete(media_id, function(response)
		{
			if (response.status_valid == 1) 
			{
				api.ajax_response(response, 'deleted Successfully.');
				$j('#content_large').css('background-color', '#ffe6e6');
				$j('#content_small').css('background-color', '#ffe6e6');				
			}
		});
	},
	
	length_duration: function (seconds)
	{
		var hours = '', mins = '', sec = '';
		
		//for seconds
		if(seconds > 0)
			sec = (seconds % 60 < 10) ? "0"+(seconds%60) : ""+(seconds%60);
		
		//for mins
		if(seconds >= 60)
			mins  = ~~(((seconds/60)%60)<10) ? "0"+~~((seconds/60)%60)+":" : ""+~~((seconds/60)%60)+":";
		
		//for hours
		if(seconds/60 >= 60)
			hours = ~~(((seconds/60)/60) < 10) ? "0"+~~((seconds/60)/60)+":" : ""+~~((seconds/60)/60)+":";
		
		return hours+mins+sec;
	}	
};
	
jQuery(function($)
{	
	$(window).load(function () {
		// shrink image, if its image
    	$('.related-media').find('img').imageShrink(120, 90);
    });
	

	
	$('.related-media').find('img').imageShrink(120, 90);
	
	// zoom
	$('#zoom').toggle(function() {
		$('#content_small').hide();
		$('#media-main-image').attr('style', '').css('z-index', 1000);
		$('#media-main').css('width', '100%').css('overflow', 'visible');
		return false;	
	},
	function() {
		$('#media-main-image').imageShrink(630, 400);
		$('#media-main').css('width', '630px').css('overflow', 'hidden');
		$('#content_small').show();
		return false;
	});
	
	// band/unband
	$('#band').click(function() {
		var band = ($(this).text() == 'Ban') ? 'yes' : 'no';
		media.band(media.getID(), band);
		return false;		
	});
	
	// delete
	$('#delete').click(function() {
		media.delete_media(media.getID());
		return false;
	});

	// comments
	feed.set_media_id = media.getID();
	feed.callback_success_list = function  (response) {
		$j('#rows').empty();
	};
	
	// comments paginator
	$('#paginator').find('a').live('click', function() {
		var href = $(this).attr('href');
		var after = href.replace(/\?after=/ig, '');
		
		feed.get_list('media', media.getID(), after);
		
		var comment_offset = $('#comments').offset();
		$('html, body').animate({scrollTop: comment_offset.top}, 500);
		
		return false;
	});
	
	$('#slideshow').jcarousel({
		size:   ($('#slideshow').find('.total_rows').text() - 1),
		start:  ($('#slideshow').find('.total_rows').text() == $('#slideshow').find('.current_position').text()) ?  ($('#slideshow').find('.current_position').text() - 2) : ($('#slideshow').find('.current_position').text() - 1),
		offset: ($('#slideshow').find('.total_rows').text() == $('#slideshow').find('.current_position').text()) ?  ($('#slideshow').find('.current_position').text() - 2) : ($('#slideshow').find('.current_position').text() - 1),
		scroll: 1,
		visible: 2,
		animation: 'fast',
		itemLoadCallback: mycarousel_itemLoadCallback
    });

	function mycarousel_itemLoadCallback (carousel, state)
	{	
		/* debugging use
		console.log('first: '+carousel.first);
		console.log('last: '+carousel.last);
		console.log(carousel.options.size);
		console.log(carousel.options.start);
		console.log(state);		
		*/
		
		// Check if the requested items already exist
	    if (state == 'init')
			return false;
		else if (carousel.has(carousel.first, carousel.last))
	        return false;
				
		var after = 0;
		
		if (state == 'prev')
		{			
			after = (carousel.first - 7);
			if (after < 0)
				after = 0;
		}
		else if (state == 'next')
		{
			after = (carousel.last - 1);
		}
		
		// Lock carousel until request has been made
	    carousel.lock();

		api.GET('/album/'+$('#album_id').val(), {show: 7, after: after, media_not: media.getID()}, function(response)
		{			
			 if (response.status_valid == 1 && response.items)
			 {
			 	$.each(response.items, function(i, item) {
					
					if ($('#slideshow').find('.current_position').text() == 1 && carousel.first == 2 && i == 0)
						after; // dont do anything, cause it skips one, if we increment, cause first position is selected
					else
						++after;
								
					var li = '<a id="m'+item.media_id+'" href="http://'+profile_username+'.'+$domain_only+'/'+item.media_id+'"><img src="http://'+profile_username+'.'+$domain_only+'/thumbnail/'+item.media_id+'.jpg" alt="'+item.title+'" /></a>';
					if (item.media_type == 'video')
						li += '<span class="videothumb_play">Play video</span><span class="media_length">'+media.length_duration(item.length)+'</span>';
					
					if (!carousel.has(after) && !$('#m'+item.media_id).attr('id')) // dont add current showing media in the list
					{
						carousel.add(after, li);
					}
					else
						--after;					
				});
			 }
			 
			// Unlock
    		carousel.unlock();
		});
	}

	// adds the x icon class for the editable places
	$.editable.types.text.plugin = function (form, settings)
	{
		$(this).find('button:contains(X)').addClass('edit-cancel');	
		$(this).parent().next('a').hide(); // hide edit link
	};

	if (login_username == profile_username)
	{
		$("#title, #description").editable(function(name, settings) {
			var media_id = media.getID();
			var old_name = this.revert;
			var modify = $(this).attr('id');
			
			api.ajax_options.error = function ()
			{
				$j('#'+modify).text(old_name);
			};
			
			if (modify == 'title')
				media.renameTitle(media_id, name);
			else
				media.modifyDescription(media_id, name);
				
			api.ajax_options.error = false;
			return 'saving...';
			
		}, {
			cancel: 'X',
			submit: ' ',
			width: '65%',
			onreset: function ()
			{
				$(this).parent().next('a').show(); // show edit link
			}
		})
		.next('a').click(function() {
			$(this).prev('span').trigger('click');
			return false;
		});
		
		
		$("#addtag").click(function(event) {
			event.preventDefault();
			$("#tags-add").slideToggle("normal");	
		});
		
		$('#word_tags_form').submit(function() {
			var word_tags = $("#word_tags").val();
			
			if (!word_tags)
				return false;
				
			api.mediaModify(media.getID(), {add_word_tags: word_tags}, function(response)
			{
				if (response.status_valid == 1) 
				{
					api.ajax_response(response, 'tags added Successfully.');
					$("#word_tags").val('');
					$("#tags-add").hide();
					
					$(".tag").remove();
					$.each(response.word_tags, function(i, tag) {
						$('#addtag').before('<li class="tag"><a href="#">'+tag+'</a></li>');
					});
				}
			});
			
			return false;
		});
		
		$('.tag').live('click', function() {
					
			var word_tags = $(this).text();
			
			if (!word_tags)
				return false;
				
			api.mediaModify(media.getID(), {remove_word_tags: word_tags}, function(response)
			{
				if (response.status_valid == 1)
				{
					api.ajax_response(response, 'tag removed Successfully.');
					$("#tags-content ul li:contains('"+word_tags+"')").remove();
				}
			});
			
			return false;
		});
	}
	else
	{
		$("#addtag").hide();
	}
		
		// copying share input boxs
	$("#share").find('label').each(function() {
		
		clip = new ZeroClipboard.Client();
		clip.setHandCursor(true);
		clip.setText($(this).next('input').val());
		
		var width = $(this).parent('.form-row').width();
		var height =  $(this).parent('.form-row').height();
		var flash_movie = '<div>'+clip.getHTML(width, height)+'</div>';
	
		flash_movie = $(flash_movie).css({
			position: 'absolute',
			//backgroundColor: 'red',
			marginBottom: -height,
			width: width,
			height: height,
			zIndex: 101
		})
		.click(function() {
			$(this).siblings('input').indicator({className: 'copied', wrapTag: 'div', text: 'Copied!', fadeOut: 2000, display: 'after'});
		})
		.insertBefore(this);
	});
	
	$("#hiddenshare").hide();	
	$("#shareall").toggle(function(event) {
		event.preventDefault();
		$("#hiddenshare").slideDown("normal");
		$("#shareall").text("hide");
	}, 
	function(event) {
		event.preventDefault();
		$("#hiddenshare").slideUp("normal");
		$("#shareall").text("show all");
	});
	
	
	// z-index the youtube player with wmode, so gigya shows fine on top of the player
	if ($('#media-main-video').find('object').html())
	{
		$('#media-main-video').find('object').prepend('<param name="wmode" value="opaque" />');
	}
	
	/**
	 * single share - add gigya popup link on share button
	 */ 
	$("#share-to-networks a").live('click', function() {
				
		if ($('#share_gigya').attr('id'))
			$('#share_gigya').remove();

		$('body').append('<div id="share_gigya" style="display:none;"></div>');
		
		var pconf = { widgetTitle: $('#title').html()+' - '+$domain_only, 
					  bookmarkURL: $("[name='emaillink']").val(), 
					 // defaultPreviewURL: ' ', 
					  advancedTracking: 'true', 
					  useFacebookMystuff: 'false', 
					  defaultContent: $("[name='htmlcode']").val(), 
					  UIConfig: '<config baseTheme="v2"><display showDesktop="true" showEmail="true" showBookmark="true" showCodeBox="false" showCloseButton="false"></display><body><controls><snbuttons iconsOnly="true"></snbuttons></controls></body></config>'
					};
		Wildfire.initPost('74041', 'share_gigya', 400, 150, pconf);
		
		$("#share_gigya").dialog({ 
	    	title: 'Share with everyone!',
			modal: true,
			autoResize: true,
			resizable: false,
			draggable: false,
			height: 220,
			minHeight: 220,
			width: 440,
			minWidth: 440,		    
			overlay: { 
		        opacity: 0.5, 
		        background: "black" 
		    }			
		});
		
		return false;
	});
	
		
	/* for the main media rating system */
	$('.rating-media #thumbsup, .rating-media #thumbsdown').live("mouseover", highliteMediaThumb);
	$('.rating-media #thumbsup-over, .rating-media #thumbsdown-over').live("mouseout", normalizeMediaThumb);
	$('.rating-media #thumbsup-over, .rating-media #thumbsdown-over').live("click", selectMediaThumb);
	
	function highliteMediaThumb() {
		var idName = $(this).attr('id');
		$(this).attr('id', idName + "-over");
	}
	
	
	function normalizeMediaThumb() {
		var idName = $(this).attr('id');
		var na = idName.split("-");
		$(this).attr('id', na[0]);
	}
	
	function selectMediaThumb() {
		var idName = $(this).attr('id');
		var na = idName.split("-");
		$(this).attr('id', na[0] + "-selected");

		if (na[0] == "thumbsup") 
		{			
			$(this).parent().find('#thumbsdown').attr('id', 'thumbsdown-static');
		}
		else if (na[0] == "thumbsdown") 
		{
			$(this).parent().find('#thumbsup').attr('id', 'thumbsup-static');
		}
		
		api.mediaVote(media.getID(), (na[0] == "thumbsup") ? 'up' : 'down', function(response) {
			if (response.status_valid == 1) 
			{
				api.ajax_response(response, 'voted Successfully.');
			}
		});
	}
	
	/* media preview link */
	$("#media-preview").hide();
	$("#media-main").mouseover(function() {
		$("#media-preview").fadeIn("fast");
	}).mouseleave(function() {
		$("#media-preview").fadeOut("fast");
	});
	
	var selected_option = $('#related_options').val();
	$('#'+selected_option).find('.related-media').jScrollPane({
		showArrows: true,
		scrollbarWidth: 20,
		arrowSize: 15,
		reinitialiseOnImageLoad: true,
		wheelSpeed: 28
	});
	
	$('#related_options').change(function() {
		var show = $(this).val();
		$("#related_options option").each(function() {
			var hide = $(this).attr('value');
			$('#'+hide).hide();
		});
		
		$('#'+show).css('display', 'inline');
/*		
		$('#'+show).find('.related-media').jScrollPane({
			showArrows: true,
			scrollbarWidth: 20,
			arrowSize: 15,
			reinitialiseOnImageLoad: true,
			wheelSpeed: 28
		});
*/		
		$('.related-media').find('img').imageShrink(120, 90);
	}).trigger('change');
});
