function createPlayer(){
    var flashvars = {
        file:"",
        autostart:"false",
        volume:"50"
    };
    var params = {
        allowfullscreen:"false",
        allowscriptaccess:"always"
    };
    var attributes = {
        id:"player1",
        name:"player1"
    };
    swfobject.embedSWF("/swf/mediaplayer.swf", "placeholder1", "0", "0", "9.0.115", false, flashvars, params, attributes);
}

function createAlbumPlayer(album_id){
	var flashvars = {
			file:"http://"+window.location.host+"/playalbum."+album_id+".xml",
			resizing:"true",
			playlist:"bottom",
			repeat:"always",
			skin:"/swf/skin_2.swf",
			autostart:"true"
	};
	var params = {
	        allowscriptaccess:"always",
	        allowfullscreen:'true'
	};
	var attributes = {
	        id:"player2",
	        name:"player2"
	};
	swfobject.embedSWF("/swf/mediaplayer.swf", "albumpreviewcontainer", "282", "316", "9.0.115", "#000000", flashvars, params, attributes);
}


var playerPlay = false;
function setListenButtion()
{
    $(".listen").removeClass('pause');
    playerPlay = false;
}
function ui_attach_player(){
	if (($(".listen").length>0) && ($("#placeholder1").length>0)){
    	createPlayer();
        var plr = window.document['player1'];
    	
    	$(".listen").click(function(){
    		var plr = window.document['player1'];
    		if ((plr.getPlaylist() != null) && (playerPlay && (plr.getPlaylist()[0].file == $(this).attr('href')))){
                plr.sendEvent('STOP');
            } else {
                plr.sendEvent('LOAD', $(this).attr('href'));
                $(this).addClass('pause');
                plr.addControllerListener("STOP","setListenButtion");
                plr.sendEvent('PLAY');
                playerPlay = true;
            }
    		
    		return false;
    	});
    }
	
	if ($(".listen-album").length>0){
		$(".listen-album").click(function(){
			var id = $(this).attr('href').match(/\d+/);
			createAlbumPlayer(id);
			
			$('#albumpreview').css('display', 'block');
		});
	}
}

function duration2seconds(duration){
	//var duration_array = string(duration).split(':');
	//return duration_array[0]*60+duration_array[1]*1;
	return duration;
}
function timeListener(obj){
	var player = document['clip_viewer'];
	var position = obj.position*1.0;
	var duration = duration2seconds(player.getPlaylist()[0].duration)*1.0;
	var min_x = 10;
	var max_x = 400;
	
	var total = Math.round(position/duration*(max_x-min_x)+min_x);
	
	document.getElementById('slider').style.width = total+'px';
}
var clipPosInPlaylist = new Number(0);
var clipCurrentPlaylist = {};
var tryDownloadCounter = new Number(0);
function addClipBuyLink(step, playlist, item)
{
	if (step == 0) {
		clipCurrentPlaylist = playlist;
	} else {
		playlist = clipCurrentPlaylist;
		item = clipPosInPlaylist*1 + step*1;
		if (item == -1) { item = playlist.length - 1;}
		if (item == playlist.length) { item = 0;}
		
	}
	clipPosInPlaylist = item*1;
	
	$('.video-box .buy').attr('href', '/basket/add/'+playlist[item].id+'.json');
	$('.video-box .sms').attr('href', '/sms/'+playlist[item].id+'.json');
}
function loadPlayList(playlist, item)
{
	var player = document['clip_viewer'];
	//if (player && player.sendEvent) {
	try {
		player.sendEvent("LOAD", playlist);
		player.sendEvent("ITEM", item);
		player.sendEvent("STOP");
		player.addModelListener("TIME", "timeListener");
		addClipBuyLink(0, playlist, item);
	} catch (err) {
		tryDownloadCounter++;
		if (tryDownloadCounter < 10)
			setTimeout(function () {window.loadPlayList(playlist, item);}, 500);
	}
		
}
function createClipViewer(){
    var flashvars = {
        autostart:"false",
        volume:"50",
        controlbar: "none",
		type:"video",
		bufferlength:15,
		bandwidth:10000
    };
    var params = {
        allowfullscreen:"true",
        allowscriptaccess:"always"
    };
    var attributes = {
        id:"clip_viewer",
        name:"clip_viewer"
    };
    swfobject.embedSWF("/swf/player.swf", "clip_viewer", "449", "252", "9.0.115", false, flashvars, params, attributes);
    ;
    $(".video-control-panel li.play").click(function() { document['clip_viewer'].sendEvent("PLAY","true");});
    $(".video-control-panel li.stop").click(function() { document['clip_viewer'].sendEvent("STOP","true");});
    $(".video-control-panel li.next").click(function() { document['clip_viewer'].sendEvent("NEXT","true"); addClipBuyLink(1);});
    $(".video-control-panel li.previous").click(function() { document['clip_viewer'].sendEvent("PREV","true"); addClipBuyLink(-1);});
    
    connectVolume();
    
    $('.timeline').click(function(eventObject){
		var in_control_pos = Math.round(eventObject.clientX-$(this).parents().position().left - 5);
		var max_x = 400;
		var min_x = 10;
		var left_stop = 15;
		var right_stop = max_x + left_stop;
		if ((in_control_pos<=left_stop) || (in_control_pos>=right_stop)){
			return false;
		}
		in_control_pos-=left_stop;
		document.getElementById('slider').style.width = in_control_pos+'px';
		var player = document.getElementById('clip_viewer');
		
		var duration = duration2seconds(player.getPlaylist()[0].duration)*1.0;
		player.sendEvent('SEEK', Math.round(duration*in_control_pos/(max_x-min_x)));
		
		return false;
	});
}

/* Лента клипов */
function eventClipsColClick(){
	if ($(".prog_playClip").length>0){
		$(".prog_playClip").live("click", function() {
			/* LOAD PLAYLIST */
			loadPlayList(aClipsInfo, $(this).attr('item'));
			return false;
		}
		);
	}
}

function clipsCol() {
	var cC = $('#clipsCol');
	for (i in aClipsInfo)
	{
		cC.append("<p><a class=\"prog_playClip\" href=\"#\" item=\""+i+"\"><img src=\""+aClipsInfo[i].miniimage+"\" alt=\""+aClipsInfo[i].title+"\" /></a></p>");
	}
	eventClipsColClick();
}

var timerScrollCol;
function scrollCol() {
	 if($("#scrollColClipsUp").length>0) {
		 $("#scrollColClipsUp").live("mouseover", function(){
			 timerScrollCol = setInterval(function() {
				 document.getElementById('clipsCol').scrollTop=document.getElementById('clipsCol').scrollTop - 15;
			 },
			 100);
		 });
		 $("#scrollColClipsUp").live("mouseout", function(){
			 clearInterval(timerScrollCol);
		 });
	 }
	 
	 if($("#scrollColClipsDown").length>0) {
		 $("#scrollColClipsDown").live("mouseover", function(){
			 timerScrollCol = setInterval(function() {
				 document.getElementById('clipsCol').scrollTop = document.getElementById('clipsCol').scrollTop + 15;
			 },
			 100);
		 });
		 $("#scrollColClipsDown").live("mouseout", function(){
			 clearInterval(timerScrollCol);
		 });
	 }
}

/* Списки новых и популярных клипов */
function eventClipsTopClick(){
	if ($(".prog_playPopClip").length>0){
		$(".prog_playPopClip").live("click", function() {
			/* LOAD PLAYLIST */
			loadPlayList(aPopClipsInfo, $(this).attr('item'));
			return false;
		}
		);
	}
	if ($(".prog_playNewClip").length>0){
		$(".prog_playNewClip").live("click", function() {
			/* LOAD PLAYLIST */
			loadPlayList(aNewClipsInfo, $(this).attr('item'));
			return false;
		}
		);
	}
}

function clipsTopCol() {
		var cC = $('#popClips');
		for (i in aPopClipsInfo)
		{
			//<!--<div class="action-links"><a href="" class="add-in-cart"></a><a href="" class="buy-sms"></a></div>-->
			cC.append("<li class=\"prog_playPopClip"+((i==0)?" first":"")+"\" item=\""+i+"\"><span class=\"orange\">"+aPopClipsInfo[i].title+"</span></li>");
		}
	
	if ($('#newClips').length > 0) {
		cC = $('#newClips');
		for (i in aNewClipsInfo)
		{
			cC.append("<li class=\"prog_playNewClip"+((i==0)?" first":"")+"\" item=\""+i+"\"><span class=\"orange\">"+aNewClipsInfo[i].title+"</span></li>");
		}
		eventClipsTopClick();
	}
}
function clipsTopHeaders()
{
	if (($("#headerNewClips").length>0) && ($("#headerPopClips").length>0)){
		$("#headerNewClips").live("click", function() {
			$("#headerPopClips").attr('class', 'title');
			$("#headerNewClips").attr('class', 'title active');
			$("#popClips").hide('slow');
			$("#newClips").show('slow');
			return false;
		}
		);
		$("#headerPopClips").live("click", function() {
			$("#headerPopClips").attr('class', 'title active');
			$("#headerNewClips").attr('class', 'title');
			$("#popClips").show('slow');
			$("#newClips").hide('slow');
			return false;
		}
		);
	}
}

/* Лента Видео Артистов */
function clipPopUpFixerMain(){
	$('.to_basket').click(function()
	{ 
		$('#clip_viewer').css('visibility', 'hidden');
		//$('#clip_viewer_blank').show();
		
	});
	
	$('.sms').click(function()
	{ 
		$('#clip_viewer').css('visibility', 'hidden');
		//$('#clip_viewer_blank').show();
	});
	
	$('.add-basket-close').click(function()
	{
		//$('#clip_viewer_blank').hide();
		$('#clip_viewer').css('visibility', 'visible');
	});
	$('#sms-windows-closer').click(function()
	{
		//$('#clip_viewer_blank').hide();
		$('#clip_viewer').css('visibility', 'visible');
	});
	$('#sms-windows-closer2').click(function()
	{
		$('#clip_viewer').css('visibility', 'visible');
	});
	
}
var varClipPopUpFixerPopUp = false;
function clipPopUpFixerPopUp(){
	$('.to_basket').click(function()
	{ 
		$('#video-player').css('display','none');
	});
	$('.sms').click(function()
	{ 
		$('#video-player').css('display','none');
	});
	$('.add-basket-close').click(function()
	{
		if (varClipPopUpFixerPopUp) 
		{
			$('.background-frame').show();
			$('#video-player').css('display','block');
		}
	});
	$('#sms-windows-closer').click(function()
	{
		if (varClipPopUpFixerPopUp) 
		{
			$('.background-frame').show();
			$('#video-player').css('display','block');
		}
	});
	$('#sms-windows-closer2').click(function()
	{
		if (varClipPopUpFixerPopUp) 
		{
			$('.background-frame').show();
			$('#video-player').css('display','block');
		}
	});
}
function closePopUpClipViewer()
{
	if ($(".video-player .top small").length>0){
		$(".video-player .top small").live("click", function() {
			document['clip_viewer'].sendEvent("STOP","true");	
			$('#video-player').css('display','none');
			$('.background-frame').hide();
			varClipPopUpFixerPopUp = false;
			return false;
		});
	}
}

//&this
var openClipWindow = function(item) {
	/* LOAD PLAYLIST */
	var index;
	if (!item) {
		index = $(this).attr('item').valueOf();
	} else {
		index = 0;
		for(i in aRowInfo) {
			if (aRowInfo[i].id == item) {
				index = i;
				break;
			}
		}
	}
	
	$('#popupPlayerClipTitle').html(aRowInfo[index].title);
	$('#popupPlayerClipAuthor').html(aRowInfo[index].author);
	$('#add-basket-image').attr('src', aRowInfo[index].miniimage);
	$('#popupPlayerClipURI').html('http://music.golden.ru'+aRowInfo[index].link+'#'+aRowInfo[index].id);
	$('.background-frame').show();
	$('#video-player').show();
	varClipPopUpFixerPopUp = true;
	loadPlayList(aRowInfo, index);
	
	return false;
};
function eventArtistsClips()
{
	if ($(".prog_playArtClip").length>0){
		$(".prog_playArtClip").live("click", function () {this.play = openClipWindow; this.play(false);});
	}
}
//this
function artistsClips()
{
	cC = $('#videoRow');
	cC.empty();
	for (i in aRowInfo)
	{
		cC.append('<li style="height: auto;" class="prog_playArtClip" url="http://music.golden.ru'+aRowInfo[i].link+'#'+aRowInfo[i].id+'" item="'+i+'"><img src="'+aRowInfo[i].miniimage+'" alt="'+aRowInfo[i].title+'" /><div class="orange">'+aRowInfo[i].title+'</div></li>');
	}
	eventArtistsClips();		
}

function connectVolume() {
	$(".volume a.vol3").click(function() { 
    	document['clip_viewer'].sendEvent("VOLUME",100);
    	$(".volume a.vol3-off").removeClass("vol3-off").addClass("vol3");
    	$(".volume a.vol2-off").removeClass("vol2-off").addClass("vol2");
    	$(".volume a.vol1-off").removeClass("vol1-off").addClass("vol1");
    	$(".volume a.vol0-off").removeClass("vol0-off").addClass("vol0");
    	return false;
    });
    $(".volume a.vol2").click(function() { 
    	document['clip_viewer'].sendEvent("VOLUME",75);
    	$(".volume a.vol3").removeClass("vol3").addClass("vol3-off");
    	$(".volume a.vol2-off").removeClass("vol2-off").addClass("vol2");
    	$(".volume a.vol1-off").removeClass("vol1-off").addClass("vol1");
    	$(".volume a.vol0-off").removeClass("vol0-off").addClass("vol0");
    	return false;
    });
    $(".volume a.vol1").click(function() { 
    	document['clip_viewer'].sendEvent("VOLUME",50);
    	$(".volume a.vol3").removeClass("vol3").addClass("vol3-off");
    	$(".volume a.vol2").removeClass("vol2").addClass("vol2-off");
    	$(".volume a.vol1-off").removeClass("vol1-off").addClass("vol1");
    	$(".volume a.vol0-off").removeClass("vol0-off").addClass("vol0");
    	return false;
    });
    $(".volume a.vol0").click(function() { 
    	document['clip_viewer'].sendEvent("VOLUME",25);
    	$(".volume a.vol3").removeClass("vol3").addClass("vol3-off");
    	$(".volume a.vol2").removeClass("vol2").addClass("vol2-off");
    	$(".volume a.vol1").removeClass("vol1").addClass("vol1-off");
    	$(".volume a.vol0-off").removeClass("vol0-off").addClass("vol0");
    	return false;
    });
}
function createPopUpClipViewer(){
    var flashvars = {
        autostart:"false",
        volume:"50",
        controlbar: "none",
		type:"video",
		bufferlength:15,
		bandwidth:1000
    };
    var params = {
        allowfullscreen:"true",
        allowscriptaccess:"always"
    };
    var attributes = {
        id:"clip_viewer",
        name:"clip_viewer"
    };
    
    swfobject.embedSWF("/swf/player.swf", "popupClipViewer", "449", "252", "9.0.115", false, flashvars, params, attributes);
    
    $(".video-control-panel li.play").click(function() { document['clip_viewer'].sendEvent("PLAY","true");});
    $(".video-control-panel li.stop").click(function() { document['clip_viewer'].sendEvent("STOP","true");});
    $(".video-control-panel li.next").click(function() { document['clip_viewer'].sendEvent("NEXT","true"); addClipBuyLink(1);});
    $(".video-control-panel li.previous").click(function() { document['clip_viewer'].sendEvent("PREV","true"); addClipBuyLink(-1);});
    
    connectVolume();
    
    $('.timeline').click(function(eventObject){
    	var margin = new String($('#video-player').css('margin-left'));
    	if (!jQuery.browser.msie) {
    		margin = margin.substr(1, margin.length - 3)*1 + 28;}
    	else {
    		margin = 28; }
    	
    	if (jQuery.browser.mozilla) {
    		margin = margin - 35;}
    	
    	var in_control_pos = Math.round(
				eventObject.clientX 
				- $('#video-player').position().left 
				+ margin 
				- 5);
		var max_x = 400;
		var min_x = 10;
		var left_stop = 15;
		var right_stop = max_x + left_stop;
		if ((in_control_pos<=left_stop) || (in_control_pos>=right_stop)){
			return false;
		}
		in_control_pos-=left_stop;
		document.getElementById('slider').style.width = in_control_pos+'px';
		var player = document.getElementById('clip_viewer');
		
		var duration = duration2seconds(player.getPlaylist()[0].duration)*1.0;
		player.sendEvent('SEEK', Math.round(duration*in_control_pos/(max_x-min_x)));
		
		return false;
	});
}

function clipsLister() {
	$('.prog_Lister li').live('click', function() {
        var fields = {
            param:paramRowInfo,
            type:paramRowType
            };
        
        var setActiveClass = function (obj) {
        	$('.prog_Lister li').removeClass("active");
        	$($('.prog_Lister li').get(obj)).addClass("active");
        };
        
        var me = $(this).children('A');
        var page = me.text()*1-1;
		$.post(me.attr('href'), fields, function (obj) {
			aRowInfo = obj;
			setActiveClass(page);
			artistsClips();
			clipsLister();
		}
		, 'json');
		return false;
	});
}

function clipViewer() {
	if ($("#clip_viewer").length>0){
		createClipViewer();
		clipPopUpFixerMain();
	}
	
	if ($('#clipsCol').length > 0) {
		clipsCol();
		scrollCol();
		loadPlayList(aClipsInfo, '0');
	}
	
	if ($('#popClips').length > 0) {
		clipsTopCol();
		clipsTopHeaders();
	}
	
	
	if (($("#clip_viewer").length==0) && ($("#popupClipViewer").length>0)){
		createPopUpClipViewer();
		closePopUpClipViewer();
		clipPopUpFixerPopUp();
	}
	
	if ($("#videoRow").length>0) {
		artistsClips();
		clipsLister();
	}
	
}

function get_hash() {
	var hash = window.location.hash;
	var len = hash.length;
	if (len > 1) {
		return hash.substr(1, len-1);
	}
	return false;
}
function open_clip() {
	var hash = get_hash(); 
	/*	if (hash) {
		$.post('/get_clip_page.json', {hash: hash}, function (obj) {
			if ((val = parseInt(obj)) != NaN) {
				window.location = '/catalog/artist/'+val+'.html#'+hash;
			}
		});
	} */
	if (hash) {
		openClipWindow(hash);
	}
}

$(document).ready(function(){
	clipViewer();
	ui_attach_player();
	open_clip();
});