var interval = null;
var modal = false;
var posted = false;

$().ready(
	function()
	{
		$().replaceOn();
		
		$('#header ul li').each(
			function()
			{
				$(this).hover(
					function()
					{
						$(this).addClass('hover');
					},
					function()
					{
						$(this).removeClass('hover');
					}
				);
			}
		);
	}
);

$.fn.replaceOn = function()
{
	$("*[onclick]").each(
		function()
		{
			$(this).click(
				function()
				{
					if ( typeof( this.onclick() ) != 'undefined' )
					{
						switch ( this.onclick().action )
						{
							case 'getJSON' :
								$.getJSON( this.onclick().href );
								return false;
							break;

							case 'checkCheckbox' :
								$(this).checkCheckbox();
							break;

							case 'filterSelect' :
								$(this).filterSelect( this.onclick().href, this.onclick().data );
							break;

							case 'showModal' :
								$(this).showModal();
								return false;
							break;

							case 'showUploadForm' :
								$(this).showUploadForm( this.onclick().href );
								return false;
							break;

							case 'startProgress' :
								$(this).startProgress();
								return false;
							break;
						}
					}
				}
			);
		}
	);

	$("*[onkeyup]").each(
		function()
		{
			$(this).keyup(
				function()
				{
					if ( typeof( this.onkeyup() ) != 'undefined' )
					{
						switch ( this.onkeyup().action )
						{
							case 'disable' :
								$(this).disable( $(this).val(), this.onkeyup().check, this.onkeyup().data );
							break;
						}
					}
				}
			);
		}
	);

	$("*[onmouseover]").each(
		function()
		{
			$(this).mouseover(
				function()
				{
					if ( typeof( this.onmouseover() ) != 'undefined' )
					{
						switch ( this.onmouseover().action )
						{
							case 'shineStars' :
								$(this).shineStars( this.onmouseover().data );
							break;
						}
					}
				}
			);
		}
	);

	$("*[onsubmit]").each(
		function()
		{
			$(this).submit(
				function()
				{
					if ( typeof( this.onsubmit ) != 'undefined' )
					{
						if ( typeof( this.onsubmit().action ) != 'undefined' )
						{
							var uuid = '';

							for ( var i = 0; i < 32; i++ )
							{
								uuid += Math.floor( Math.random() * 16 ).toString( 16 );
							}

							$(this).attr( 'action', $(this).attr( 'action' ) + '?X-Progress-ID=' + uuid );

							eval( '$(this).' + this.onsubmit().action + '(\'' + uuid + '\');' );

							return true;
						}

						$('.loading').css( { height: $().height(), opacity: 0.3 } ).show();
						$('.loadingImage').show();
						scroll( 0, 0 );

						if ( posted == false )
						{
							posted = true;

							$.post(
								this.onsubmit().href,
								$(this).serializeArray(),
								function()
								{
									$('.loading,.loadingImage').hide();
									posted = false;
								},
								'json'
							);
						}

						return false;
					}
				}
			);
		}
	);
};

$.fn.startProgress = function( uuid )
{
	$('#modal_new').children().hide();
	$('#progress, #progress div').show();

	interval = window.setInterval
	(
		function ()
		{
			$(this).getProgress( uuid );
		},
		1000
	);
};

$.fn.getProgress = function( uuid )
{
	$.ajax(
		{
			async: true,
			beforeSend: function( req )
				{
					req.setRequestHeader( 'X-Progress-ID', uuid );
				},
			url: '/progress',
			complete: function( req, status )
			{
				if ( req.readyState == 4 )
				{
					if ( req.status == 200 )
					{
						var upload = eval( req.responseText );
						var state;

						if ( upload.state == 'done' || upload.state == 'uploading' )
						{
							$('#progressBar').width( Math.ceil( ( $('#progress').width() ) * upload.received / upload.size ) );
						}

						if ( upload.state == 'done' )
						{
							window.clearTimeout( interval );

							var type = $('#modal_new input[type="hidden"]').val();
							var header = document.createElement('h2');
							var input = document.createElement('input');
								input = $(input);
								input.attr( 'type', 'hidden' );
								input.attr( 'id', 'video_' + type );
								input.attr( 'name', 'video_' + type );
								input.attr( 'value', uuid );
								input.addClass( 'hidden' );

							$('.loading').hide();
							$('#modal_new').remove();
							$('#video_' + type).replaceWith( $(header).html('загружено') );
							$(header).before( input );

							modal = false;
						}
					}
				}
			}
		}
	);
};

$.fn.showUploadForm = function( href )
{
	if ( modal == false )
	{
		modal = true;

		$('.loading').css( { height: $().height(), opacity: 0.3 } ).show();
		$('#modal').hide();
		$('#modal').clone(true).insertAfter('#modal').attr('id', 'modal_new').show();

		$('#modal_new').show(
			'fast',
			function()
			{
				var div = document.createElement( 'div' );
					div.id = 'modal_new_inner';

				$('#modal_new').empty().html($(div));

				$.getJSON( href );

				var offset = $('#modal_new').offset();

				$().click(
					function(e)
					{
						if ( e.pageX < offset.left || e.pageX > ( offset.left + $('#modal_new').width() ) || e.pageY < offset.top || e.pageY > ( offset.top + $('#modal_new').height() ) )
						{
							$('.loading').hide();
							$('#modal_new').remove();

							modal = false;
						}
					}
				);
			}
		);
	}
};

$.fn.shineStars = function( shineThis )
{
	for ( var i = 0; i <= shineThis; i++ )
	{
		$( '#vote_' + i ).addClass('hover').mouseout(
			function()
			{
				for ( var z = 1; z <= 5; z++ )
				{
					$( '#vote_' + z ).removeClass('hover');
				}
			}
		);
	}
};

$.fn.showModal = function()
{
	$('.loading').css( { height: $().height(), opacity: 0.3 } ).show();

	$('#modal').fadeIn(
		'slow',
		function()
		{
			var offset = $('#modal').offset();

			$().click(
				function(e)
				{
					if ( e.pageX < offset.left || e.pageX > ( offset.left + $('#modal').width() ) || e.pageY < offset.top || e.pageY > ( offset.top + $('#modal').height() ) )
					{
						$('.loading,#modal').hide();
					}
				}
			);
		}
	);
};

$.fn.checkCheckbox = function()
{
	if ( typeof( $(this).attr('checked') ) == 'undefined' )
	{
		$(this).parent().parent().children('td').removeClass('checked');
	} else {
		$(this).parent().parent().children('td').addClass('checked');
	}
};

$.fn.filterSelect = function( select, values )
{
	if ( $(this).attr('checked') == true )
	{
		$('#' + select + '_filtered').remove();
		$('#' + select).hide();
		$('#' + select).clone(true).insertAfter('#' + select).attr('id', select + '_filtered').show();

		$('#' + select + '_filtered option').each(
			function( i, option )
			{
				if ( $.inArray( $(option).val(), values ) > -1 )
				{
					$(option).remove();
				}
			}
		);
		
		if ( select == 'video_section' && values != '1,2,3,4,5,6' ) {
			$('#' + select + '_filtered optgroup').remove();
		}
	}
};

$.fn.disable = function( value, check, data )
{
	$(data).each(
		function( i, el )
		{
			if ( $.trim( value ) == '' )
			{
				if ( typeof( check ) != 'undefined' )
				{
					var k = 0;

					$(check).each(
						function ( z, ch )
						{
							if ( $.trim( $('#' + ch).val() ) != '' )
							{
								k++;
							}
						}
					);

					if ( k == 0 )
					{
						$('#' + el).attr( { disabled: '' } ).removeClass('disabled');
					}
				} else {
					$('#' + el).attr( { disabled: '' } ).removeClass('disabled');
				}
			} else {
				$('#' + el).attr( { disabled: 'disabled' } ).addClass('disabled');
			}
		}
	);
};

$().ajaxSuccess(
	function( e, request, options )
	{
		eval( 'var response = ' + request.responseText + ';' );

		if ( typeof response.html != 'undefined' )
		{
			$('#' + response.html[0]).replaceWith( response.html[1] );
		}

		$().replaceOn();
	}
);