$(document).ready(function() {
	$('#slogan_home').css('display', 'none');
	enable_lazy_load();
	
	openid.init('openid_url');

	$('#VideoSearchSubmit').click(function() {
		$('#VideoSearchForm').submit();
	});
	
	$('#logo_home').hover(function() {
		$('#slogan_home').fadeIn('slow');
		
	});
	
	// table striping
	$('table tr:odd').addClass('altrow');

	$('#signin').live('click', function() {
		$('#UserLoginForm').slideToggle(200);
		return false;
	});

	var total=$('#NumVideos').val();
	var keywords=$('#VideoTitle').val();
	if (total>0) {
		$('#num_results').html((total>0?'<b>'+total+'</b>':'No')+' '+(total<2?'video has':'videos have')+' been found');
		if (keywords) set_related_tag(keywords);
		$('#results_stat').delay(300).slideDown('medium');
	}	
	// auto-focus on first form element
	$('form :input:visible:enabled:first').focus();
	
	// notice styling
	$('#flashMessageWrapper').animate({opacity: 1.0}, 3000).fadeOut();
	
	// hide all second level submenu
	$('ul.menu ul').hide();
	$('ul.menu li.active').children().show();

	var movepad=10;
	var timeout=250;
	var originalpadding=5;

	// menu animation on hover
	$('ul.menu li.parent a').hover(
		function() { // in 
			$(this).animate({paddingLeft: originalpadding+movepad}, {queue: false, duration: timeout});
		},
		function() { // out
			$(this).animate({paddingLeft: originalpadding}, {queue: false, duration: timeout});
		}
	);	

	// menu animation on click (dropdown)
	$('ul.menu li a').click(function() {
		var nextNode = $(this).next();
		var parent = $(this).parent().parent();

		if((nextNode.is('ul')) && (!nextNode.is(':visible'))) {
			parent.children('ul:visible').slideUp('normal');
			nextNode.slideDown('normal');
			return false;
		}

	});


});

String.prototype.replaceAll = function(pcFrom, pcTo){
	var i = this.indexOf(pcFrom);
	var c = this;

	while (i > -1){
		c = c.replace(pcFrom, pcTo); 
		i = c.indexOf(pcFrom);
	}
	return c;
}

function set_related_tag(keywords) {
	$.get(server_url+'tags/related/'+keywords+'.json', {}, function(datatag) {
		var related=new Array();
		for(id in datatag) related.push('<a href="'+server_url+'videos/tag/'+id+'/'+datatag[id]+'">'+datatag[id]+'</a>');
		$('#num_results').append(related.length?' / related tag'+(related.length>1?'s':'')+': '+related.join(', '):'');
	}, 'json');
}

function enable_lazy_load() {
	
	if($.browser.msie==undefined) { // lazyload not supported on IE
		$('img.videothumb').lazyload({ 
			'effect': 'fadeIn',
			'placeholder': server_url+'img/placeholder.gif'
		});
	}
}
