// scripts-mp.js for EES

cat_name = 'video';

var video_cat_act = 'video-new';
var video_cat_page = 1;
var video_channel_act = '';
var videos_info = [];
var videos_info_i = 0;
var video_strip_ani = 333;
var video_strip_item_ani = 300;
var video_strip_item_ani_delay = 150;
var video_strip = '';

var flashvars = {};
var params = {};
var attributes = {};
var an_imgs = {};

// GET VIDEO STRIP BY CHANGING CAT

var get_vstrip_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {
		// Hide waiting
		$( '#video_container_wait' ).addClass( 'dn' );

		// Close player
		close_player();

		// Set page to 1
		video_cat_page = 1;

		// Set active cat &/or channel
		//$( '#' + video_cat_act + ', #ch' + video_channel_act ).removeClass( 'act' );
		//if( obj.tagName.toLowerCase() == 'span' ) {
		//	obj.className = 'act';
		//	obj.parentNode.parentNode.className = 'act';
		//	video_cat_act = obj.parentNode.parentNode.id;
		//	video_channel_act = obj.id.substr( 2 )
		//}
		//else {
		//	obj.className = 'act';
		//	video_cat_act = obj.id;
		//	video_channel_act = ''
		//}

		// Update strip content
		update_video_strip( r, 'to-right' )
	}
	// Failure
	else {$( '#video_container_wait' ).addClass( 'dn' )}
}
var get_vstrip_error = function( msg, obj ) {
	alert( msg );
	$( '#video_container_wait' ).addClass( 'dn' )
}

// GET VIDEO STRIP BY CHANGING CAT'S PAGE

var get_vpage_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {
		// Hide waiting
		$( '#video_container_wait' ).addClass( 'dn' );

		// Set active page number & update strip content
		if( obj.id == 'mp-videostrip-next' ) {
			video_cat_page--;
			update_video_strip( r, 'to-left' );
		}
		else {
			video_cat_page++;
			update_video_strip( r, 'to-right' );
		}
	}
	// Failure
	else {$( '#video_container_wait' ).addClass( 'dn' )}
}
var get_vpage_error = function( msg, obj ) {
	alert( msg );
	$( '#video_container_wait' ).addClass( 'dn' )
}

// UPDATE VIDEO STRIP CONTENT

var update_video_strip = function( r, dir ) {

	// Update videos item's array & html item's string
	videos_info = [];
	video_strip = '';
	for( var i in r['data'] ) {
		video_strip += '<a class="item" href="/video/' + ( r['data'][i]['url'] == '*' ? r['data'][i]['id'] : r['data'][i]['url'] ) + '"><img src="' + r['data'][i]['photo_name_0'] + '" alt="' + r['data'][i]['name'] + '" /></a>';
		videos_info[i] = [r['data'][i]['id'],r['data'][i]['name'],r['data'][i]['title_b'],r['data'][i]['photo_name_0'],r['data'][i]['qc'],r['data'][i]['date_add'],r['data'][i]['duration'],r['data'][i]['votes_p'],r['data'][i]['url'],r['data'][i]['photo_name_1'],r['data'][i]['video_name_1']];
	}	
	
	// Hide, renew content & show video strip. Also bind mover & click on <a>
	if( jQuery.browser.msie ) {
		$( '#mp-videostrip' ).children('.item').remove()
		$( '#mp-videostrip' ).append( video_strip );
		$( 'a.item' ).click( open_player ).mouseover( function() {
		
        // Event is fired on video item
        if ($(this).hasClass('item') ) {
            // Obtain index
            var index = $(this.parentNode).children('.item').index(this);
            // Already active
            if ($('#mp-videoprev-icon').attr('src') == videos_info[index][3]) {
                return;
            }
			videos_info_i = index
            // Update video prev data
            $('#mp-videoprev-icon').attr('src', videos_info[index][3]);
            $('#mp-videoprev-name').html(videos_info[index][1]);
            $('#mp-videoprev-brief').html(videos_info[index][2]);
            $('#mp-videoprev-date').text(videos_info[index][5]);
            $('#mp-videoprev-comments').text(videos_info[index][4]);
            $('#mp-videoprev-votes').text(videos_info[index][7]);
            $('#mp-videoprev-duration').text(videos_info[index][6]);
            // Move video prev block
            var total_moveable_lenght = $('div.mp-videoprev-wr').width() - $('#mp-videoprev').width();
            $('#mp-videoprev').stop().animate(
                {left:Math.ceil(total_moveable_lenght * index / 6) + 'px'},
                {duration: vp_ani_t, easing: 'easeInOutQuad'}
            );
        }	
    })
	}
	else {
		if( dir == 'to-left' ) {
			$( '#mp-videostrip' ).children('.item').remove()
			$( '#mp-videostrip' ).animate( {opacity:0}, {duration:video_strip_ani, complete:function() {
				$( this ).css( {opacity:1} ).append( video_strip ).children().reverse().css({opacity:0}).each( function( index ){
					$( this ).delay( index * video_strip_item_ani_delay ).animate( {opacity:1}, {duration:video_strip_item_ani} );
				} );
				$( 'a.item' ).click( open_player ).mouseover( function() {
		
        // Event is fired on video item
        if ($(this).hasClass('item') ) {
            // Obtain index
            var index = $(this.parentNode).children('.item').index(this);
            // Already active
            if ($('#mp-videoprev-icon').attr('src') == videos_info[index][3]) {
                return;
            }
			videos_info_i = index
            // Update video prev data
            $('#mp-videoprev-icon').attr('src', videos_info[index][3]);
            $('#mp-videoprev-name').html(videos_info[index][1]);
            $('#mp-videoprev-brief').html(videos_info[index][2]);
            $('#mp-videoprev-date').text(videos_info[index][5]);
            $('#mp-videoprev-comments').text(videos_info[index][4]);
            $('#mp-videoprev-votes').text(videos_info[index][7]);
            $('#mp-videoprev-duration').text(videos_info[index][6]);
            // Move video prev block
            var total_moveable_lenght = $('div.mp-videoprev-wr').width() - $('#mp-videoprev').width();
            $('#mp-videoprev').stop().animate(
                {left:Math.ceil(total_moveable_lenght * index / 6) + 'px'},
                {duration: vp_ani_t, easing: 'easeInOutQuad'}
            );
        }	
    })
			}} );
		}
		else {
			$( '#mp-videostrip' ).children('.item').remove()
			$( '#mp-videostrip' ).animate( {opacity:0}, {duration:video_strip_ani, complete:function() {
				$( this ).css( {opacity:1} ).append( video_strip ).children().css({opacity:0}).each( function( index ){
					$( this ).delay( index * video_strip_item_ani_delay ).animate( {opacity:1}, {duration:video_strip_item_ani} );
				} );
				$( 'a.item' ).click( open_player ).mouseover( function() {
		
        // Event is fired on video item
        if ($(this).hasClass('item') ) {
            // Obtain index
            var index = $(this.parentNode).children('.item').index(this);
            // Already active
            if ($('#mp-videoprev-icon').attr('src') == videos_info[index][3]) {
                return;
            }
			videos_info_i = index
            // Update video prev data
            $('#mp-videoprev-icon').attr('src', videos_info[index][3]);
            $('#mp-videoprev-name').html(videos_info[index][1]);
            $('#mp-videoprev-brief').html(videos_info[index][2]);
            $('#mp-videoprev-date').text(videos_info[index][5]);
            $('#mp-videoprev-comments').text(videos_info[index][4]);
            $('#mp-videoprev-votes').text(videos_info[index][7]);
            $('#mp-videoprev-duration').text(videos_info[index][6]);
            // Move video prev block
            var total_moveable_lenght = $('div.mp-videoprev-wr').width() - $('#mp-videoprev').width();
            $('#mp-videoprev').stop().animate(
                {left:Math.ceil(total_moveable_lenght * index / 6) + 'px'},
                {duration: vp_ani_t, easing: 'easeInOutQuad'}
            );
        }	
    })
			}} );
		}
	}
	

	// Set <- & -> visibility
	if( r['strip_l'] ) {$( '#mp-videostrip-next' ).removeClass( 'dn' )}
	else {$( '#mp-videostrip-next' ).addClass( 'dn' )}
	if( r['strip_r'] ) {$( '#mp-videostrip-prev' ).removeClass( 'dn' )}
	else {$( '#mp-videostrip-prev' ).addClass( 'dn' )}
}


// PLAYER : OPEN / CLOSE

var open_player = function( event ) {
	event.preventDefault();
	$( "#player_container" ).removeClass('dn');
	// Show video profile block
            $('#mp-videoprofile').removeClass('vh9999');
            // Adjust top of video prev block
            $('#mp-videoprev').addClass('videoprev-top');
            // Adjust top of video strip block
            $('#mp-videostrip').addClass('videostrip-top');
	
	// Request information about selected video
	sendXHR( '/video/' + videos_info[videos_info_i][0], 'a=a', set_video_ready, set_video_error, {} );
}
var close_player = function() {

	$('#mp-videoprofile-x').click();

	// Remove player
	$( "#videoplayer" ).empty();
}

// *****************************************************************************
// REQUEST NEW VIDEO & PLAY IT
// *****************************************************************************

//var uppodInit = function( playerID ) { document.getElementById( playerID ).sendToUppod( 'play', '' ) }
var set_video_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {
		item_id = videos_info[videos_info_i][0];

		// Show "ADD A COMMENT" form
		$( 'td.add_comm' ).animate( {opacity:1}, {duration:444} );

		flashvars = {};
		flashvars = {st: host + '/video/' + videos_info[videos_info_i][0] + '/styleclip', file: host + r['data']['video_name_1'], autostart: false, uid:"videoplayer", addreftofile:1};
		if( r['data']['video_name_2'] != '*' ) {flashvars.filehd = host + r['data']['video_name_2']}
		if( r['data']['photo_name_1'] != '*' ) {flashvars.poster = host + r['data']['photo_name_1']}
		flashvars.pl = host + '/video/' + videos_info[videos_info_i][0] + '/playlist';
		
		swfobject.embedSWF( host + "/swf/uppod.swf", "videoplayer", "720", "405", "9.0.115", host + "/swf/expressInstall.swf", flashvars, params, attributes );

		// Update video's info
		$( '#player_name' ).text( r['data']['name'] );
		$( '#player_title_f' ).html( r['data']['title_f'] );
		$( '#player_vlink' ).text( (r['data']['url'] == '*' || !r['data']['url']) ? r['data']['id'] : r['data']['url'] );
		$( '#player_qc' ).text( r['data']['q_r'] );
		$( '#player_votes_p' ).text( r['data']['votes_p'] );
		$( '#comm_bl' ).text( '' );
		$( '#comm_res_t' ).html( r['data']['as'] );
		
		$('#player_title_f').append('<iframe src="//www.facebook.com/plugins/like.php?locale=ru_RU&amp;href='
			+ escape('http://www.warmuptv.ru/video/' + $('#player_vlink').text())
			+ '&amp;send=false&amp;layout=button_count&amp;width=250&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:250px; height:21px;" allowTransparency="true"></iframe>');

		// Add "add a comment" handler
		$( '#comm_btn_send' ).click( add_comm );

		if( r['data']['rand_c']['ctext'] ) {$( '#rand_c' ).html( print_comment( r['data']['rand_c'], false ) )}
		else {$( '#rand_c' ).text( '' )}

		if( r['data']['is_voted'] ) {$( '#player_plus, div.player_b2_title' ).fadeOut( 555 )}
		else {$( '#player_plus, div.player_b2_title' ).fadeIn( 555 )}
	}
	// Failure
	else {}
}
var set_video_error = function( msg, obj ) {alert( msg )}

// *****************************************************************************
// VOTE FOR VIDEO
// *****************************************************************************

var vvote_ready = function( r, obj ) {
	// Success
	if( !r['error'] ) {$( '#player_votes_p' ).text( r['data']['votes_p'] )}
	// Failure
	else {}
}
var vvote_error = function( msg, obj ) {alert( msg )}

// *****************************************************************************
// ON READY
// *****************************************************************************

$( document ).ready( function() {

	// HOVER & CLICK ON HEADER VIDEO HORIZONTAL MENU


	// REWIND VIDEO STRIP
	
	$( '#mp-videostrip-next, #mp-videostrip-prev' ).click( function() {
		$( '#video_container_wait' ).removeClass( 'dn' );

		if( this.id == 'mp-videostrip-next' ) {var page = video_cat_page - 1}
		else {var page = video_cat_page + 1}
		
		if( video_cat_act == 'video-channel' ) {sendXHR( '/video-channel/' + video_channel_act + '/' + page, null, get_vpage_ready, get_vpage_error, this )}
		else {sendXHR( '/' + video_cat_act + '/' + page, null, get_vpage_ready, get_vpage_error, this )}
	} );

	// HOVER & CLICK ON VIDEO STRIP ITEMS

	$( 'a.item' ).click( open_player );

	// CLOSE PLAYER

	$( '#player_close' ).click( close_player );

	// VOTE FOR VIDEO

	$( '#player_plus' ).click( function() {
		$( this ).fadeOut( 555 );
		$( ' div.player_b2_title' ).fadeOut( 555 );
		sendXHR( '/video/' + videos_info[videos_info_i][0] + '/plus', 'a=a', vvote_ready, vvote_error, this )
	} )

	
} );

// *****************************************************************************
// ON LOAD
// *****************************************************************************

$( window ).load( function() {
	if( jQuery.browser.msie ) { }
	else {$( '#video_strip > div' ).animate( {opacity: 1}, {duration:video_strip_ani} )}
	
    $('span.email').click(function() {
        sendEmail(this);
    } )
} )
