$(document).ready(function()
{
	var selected_rating=0;
	var orig_header_search='';

	$('.header .menu a').mouseover(function()
	{
		$(this).addClass('hover');
	});
	$('.header .menu a').mouseout(function()
	{
		$(this).removeClass('hover');
	});

	// start autocomplete plugin
	StartAutocomplete();
	
	
	
	if ( document.location.toString().match(/\#comment\-add/) )
	{
		$('#comment-add-form').show();
		document.location='#comment-add';
	}
	
	if ( $('#message-ok').hasClass('message-show') )
	{
		$('#message-ok').show();
		document.location='#comments';
	}
	
	if ( $('#comment-add-form').hasClass('comment-form-show') )
	{
		$('#message-ok').hide();
		$('#comment-add-form').show();
		document.location='#comment-add';
	}
	
	/**
	 * click on 'explorer.exe' from search panel
	 */
	$('#search-example').click(function()
	{
		t=$(this).html();
		$('#search-input').val( t );
		return false;
	});

	/**
	 * click on 'Add you comment'
	 */
	$('a.comment-add').click(function()
	{
		$('#comment-add-form').show();
		document.location='#comment-add';
		return false;
	});
	
	/**
	 * captcha refresh
	 */
	$('a.captcha-refresh').click(function()
	{
		s=$('img#captcha').attr('src').replace(/\?.*?$/,"");
		s+='?r='+Math.floor(Math.random()*1000);
		$('img#captcha').attr('src', s);
		return false;
	});
	
	/**
	 * onfocus()  on input field from site header
	 */
	$('#header-search').focus(function()
	{
		if (!orig_header_search)
		{
			orig_header_search=$('#header-search').val();
		}
		if ( $('#header-search').val()==orig_header_search )
		{
			$('#header-search').val('');
			$('#header-search').removeClass('example');
		}
	});
	/**
	 * onclick() on submit "mini-search" (pages: /files/, /fileinfo/..., etc)
	 */
	$('div.header input[type=submit]').click(function()
	{
		if ( $('#header-search').val()=='Type in a process name')
		{
			$('#header-search').val('');
		}
	});
	
	/**
	 * blur input field from site header
	 */
	$('#header-search').blur(function()
	{
		if ( $('#header-search').val()=='' )
		{
			$('#header-search').val( orig_header_search );
			$('#header-search').addClass('example');
		};
	});

	$('#search-input').focused({text:'lsass.exe'});


	StartRatings( $('.content .rating a') );

	// on click on the rating starts of the top of page
	// move screen to comment form
	$('.content .rating a').click(function()
	{
		$('#comment-add-form').show();
		document.location='#comment-add';
		return false;
	});
	
	// @TODO ajax send form
	$('#comment-add-form form').submit(function()
	{
		//return false;
	});
	
	$('a#blog-this').click(function()
	{
		$('div.into-blog').show();
		$(this).hide();
		$('.panel').css('height','100%');
		return false;
	});
	
	$('a#blog-how-look').click(function()
	{
		$('div.blog-how-look').toggle();
		$('.panel').css('height','100%');
		return false;
	});
	
	$('a#blog-copy').click(function()
	{
		if ($.browser.msie)
		{
			range=$('#blog-copy-text').get(0).createTextRange();
			range.execCommand('Copy');
			return false;
		}
	});
	
	if (!$.browser.msie)
	{
		$('a#blog-copy').hide();
		$('label#blog-label').show();
	}
	else
	{
		$('label#blog-label').hide();
		$('a#blog-copy').show();
	}
	
	VotesEvent();
	
});


/**
 * Setups and processes handle file ratings behaviour
 *
 *
 */
function StartRatings( $source )
{
	var $rating_div = $('div.rating');
	var $source     = $('a',$rating_div);
	// possible ratings
	var ratings = {
		0 : {
			'css'   : 'rating-grey',
			'title' : 'unrated file'
		},
		1 : {
			'css'   : 'rating-green',
			'title' : 'safe file'
		},
		2 : {
			'css'   : 'rating-yellow',
			'title' : 'unsafe file'
		},
		3 : {
			'css'   : 'rating-red',
			'title' : 'dangerous file'
		}
	};
	//
	var GetRating   = function( string )
	{
		rating = 0;
		rating = string.replace(/[^0-9]+/,"");
		rating = parseInt( rating );
		return rating;
	}
	//
	var GetCurrentRating = function( $rating )
	{
		rating = 0;
		css    = $rating.attr('class');
		rating = css.replace(/^.*?current-rating-(\d).*?$/,'$1');
		rating = parseInt( rating );
		return rating;
	}
	// 
	var ClearRating  = function( $object )
	{
		$object.each(function(){
			$this = $(this);
			for ( i in ratings )
				$this.removeClass( ratings[i].css );
			$('.title',$this).html('');
		});
	}
	//
	var SetRating    = function( $object, rating )
	{
		$object.each(function(){
			$this = $(this);
			oRating = ratings[ rating ];
			$this.addClass( oRating.css );
			$('.title',$this).html( oRating.title );
		});
	}

    //
	var onMouseOver  = function( $ahref )
	{
		$rating    = $ahref.parent();
		new_rating = GetRating( $ahref.attr('href') );
		ClearRating( $rating );
		SetRating( $rating, new_rating );
	}
	// 
	var onMouseOut   = function( $ahref )
	{
		$rating    = $ahref.parent();
		old_rating = GetCurrentRating( $rating );
		ClearRating( $rating );
		SetRating( $rating, old_rating );
	}
	//
	var onMouseClick = function( $ahref )
	{
		$rating    = $('div.rating');
		$c_block   = $ahref.parent();
		new_rating = GetRating( $ahref.attr('href') );
		old_rating = GetCurrentRating( $c_block );
		ClearRating( $rating );
		if ( old_rating == new_rating && !$c_block.parent().hasClass('content') )
		{
			new_rating = 0;
		}
		SetRating( $rating, new_rating );
		$rating.removeClass( 'current-rating-'+old_rating );
		$rating.addClass( 'current-rating-'+new_rating );
		// set rating for the comment field
		$('#rating-field').val( rating );
		return false;
	}

	$source.mouseover( function(){ onMouseOver($(this)) } );
	$source.mouseout(  function(){ onMouseOut($(this)) } );
	$source.click(     function(){ return onMouseClick($(this)) } );

}

/**
 * Returns rating of file from string
 *
 * @example GetRating( $('a').attr('href') );
 *
 * @param string 
 * @return int
 */
function GetRating( string )
{
	rating = 0;

	rating = string.replace(/[^0-9]+/,"");
	rating = new Number( rating );

	return rating;
}

/**
 * Setup and start jQuery autocoplete plugin
 *
 * @see http://plugins.jquery.com/project/jq-autocomplete
 *
 * @return void
 */
function StartAutocomplete()
{
	var formatItem = function(row)
	{
		if (row[1])
		{
			return row[0] + " - " + row[1];
		}
		else
		{
			return false;
		}
	}
	var formatResult = function(row)
	{
		str = row[0];
		return str;
	}
	
	var selectResult = function(data)
	{
		if (data.extra && data.extra[1])
		{
			document.location=data.extra[1];
		}
	}
	// подключаем suggest (автозаполнение) для поиска похожих файлов
	// @see http://plugins.jquery.com/project/jq-autocomplete
	$('.search-input').autocomplete(
		'/api/search.php?o=suggest', {
		width			: 300,
		multiple		: false,
		matchContains	: true,
		maxItemsToShow	: 10,
		minChars		: 3,
		formatItem		: formatItem,
		formatResult	: formatResult,
		onItemSelect	: selectResult
	});
}

/**
 * Processes clicks on comments votes
 *
 * @return void
 */
function VotesEvent()
{
	$('.comment .votes a').click(function()
	{
		obj=$(this);
		href       = $(this).attr('href');
		// parts of href
		hrefp      = href.split('-');
		comment_id = hrefp[1];
		vote       = hrefp[0].substr(1);
		url='/fileinfo/vote.php?cid='+comment_id+'&vote='+vote;
		$.ajax({
			type:'GET',
			url:url,
			dataType:'json',
			success:function(data)
			{
				if (data.msg)
				{
					$( 'em', obj.parent() ).html(data.msg);
					$( 'em', obj.parent() ).css('display','inline');
					$( 'em', obj.parent() ).fadeOut(2500);					
				}
				obj.html(data.new_value);
			}
		});
		return false;
	});
}

/**
 * Плагин обрабатывает строку поиска,
 * строка по умолчанию содержит серый текст "lsass.exe"
 * когда пользователь на неё нажимает - текст пропадает, и пользователь может ввести свой текст
 * Plugin for jQuery
 *
 * @see http://www.codenet.ru/webmast/js/jquery-plugin.php
 */
(function($){
$.fn.focused = function( options ){
	
	var def_options = {
		'cls'	: 'focused',
		'text'	: 'Type text to search'
	}

	options = $.extend(def_options, options)


	// если поле ввода пустое - показываем options.text
	if ( $(this).val() == '' )
	{
		$(this).val( options.text );
	}
	else if ( $(this).val() != options.text )
	{
		$(this).addClass( options.cls );
	}


	$(this).bind('focus',function(){
		if ( $(this).val() == options.text )
		{
			$(this).val('');
			$(this).addClass( options.cls );
		}
	});

	$(this).bind('blur',function(){
		if ( $(this).val() == '' )
		{
			$(this).val( options.text );
			$(this).removeClass( options.cls );
		}
	});
};

})(jQuery);
