var so = null;
var playSongId = null;
var volume = 80;
var rnd = Math.random();
var randomPlay = false;

$.fn.idle = function(time)
{
	var o = $(this);
	o.queue(function()
    {
    	setTimeout(function()
        {
        	o.dequeue();
        }, time);
	});
	return this;             
}


var ajaxReq;
var SWFObj;

function play(id) {
	$("#flashPlayer"+id).css("height", "20px");
		
	if (playSongId && playSongId != id) {
		$(".playBtn[songId='"+playSongId+"']").show();
		$(".stopBtn[songId='"+playSongId+"']").hide();	
//		$(".pauseBtn[songId='"+playSongId+"']").hide();	
		//swfobject.getObjectById("flashPlayer"+playSongId).SetVariable("message", "stop");
		$("#flashPlayer"+playSongId).flash(function() {
			this.SetVariable('/:message', "stop");
		});
		
		$("#trSongLine_"+playSongId).css("background-color", "#3d4157");
		$("#flashPlayer"+playSongId).css("height", "0px").empty();			
		
		playSongId = null;
	}
	
	$('#trSongLine_'+id).css("background-color", "#2f803a");			

	$(".playBtn[songId='"+id+"']").hide();

	

	if (playSongId) {
		//swfobject.getObjectById("flashPlayer"+playSongId).SetVariable("message", "play");
		$("#flashPlayer"+playSongId).flash(function() {
			this.SetVariable('/:message', "play");
		});
		$(".stopBtn[songId='"+playSongId+"']").show();
//		$(".pauseBtn[songId='"+playSongId+"']").show();	    
	}else{	
		playSongId = id;

		if (ajaxReq)
			ajaxReq.abort();

		ajaxReq = $.post("/?download=" + playSongId + "&t=FGV523V", {}, function(data) {
			$(".stopBtn[songId='"+playSongId+"']").show();
//			$(".pauseBtn[songId='"+playSongId+"']").show();	    

			$('#flashPlayer'+playSongId).flash({
				height: 20,
				width: 260,
				hasVersion: 6,
				wmode: 'transparent',
				swf: 'http://rusmuz.ru/flash/mp3player.swf?12345678904',
				flashvars: {
						volumepreset: volume,
					  	songId: playSongId,
					   	playlist: data
				}
			});

//			$("#flashPlayer"+playSongId).css("height", "20px");
		}, "html");
						   
//		while (!swfobject.getObjectById("flashPlayer"+id) && swfobject.getObjectById("flashPlayer"+id).PercentLoaded() != 100) {}
				   

	}
	
	return false;
} 

function stop(id, action) {  
	$('#trSongLine_'+id).css("background-color", "#3d4157");
	
	//swfobject.getObjectById("flashPlayer"+id).SetVariable("message", "stop");
	$("#flashPlayer"+playSongId).flash(function() {
//		this.SetVariable('/:message', "stop");
	}).empty();

	$("#flashPlayer"+id).css("height", "0px").empty();

	$(".playBtn[songId='"+id+"']").show();
	$(".stopBtn[songId='"+id+"']").hide();	
//	$(".pauseBtn[songId='"+id+"']").hide();	
	
	playSongId = null;
	
	if (action=="NEXT") {
		if (randomPlay) {
			rndOffset = Math.round(Math.random() * ($(".playBtn").length-2));
			tr = $(".playBtn:eq("+rndOffset+")").parents("tr").get(0);
		}else{
			tr = $(".playBtn[songId='" + id + "']").parents("tr").get(0);
		}
		nextSongId = $(tr).next().next().find(".playBtn").attr("songId");
		if (nextSongId)
			play(nextSongId);
	}
		
	return false;
}

function pause(id) {  
	//swfobject.getObjectById("flashPlayer"+id).SetVariable("message", "pause");
//	SWFObj.SetVariable("message", "pause");
	$("#flashPlayer"+playSongId).flash(function() {
		this.SetVariable('/:message', "pause");
	});

	$(".playBtn[songId='"+id+"']").show();
	$(".stopBtn[songId='"+id+"']").hide();	
	$(".pauseBtn[songId='"+id+"']").hide();	
		
	return false;
}

function setVolume(vol) {
	volume = vol;
}



$(document).ready(function(){
	if (document.getElementById('searchLine').value=='')
		document.getElementById('searchLine').focus();	
		
	$(".playBtn").each(function(){
		$(this).hover(		
			function() { $("img", this).attr("src", "../img/play_over.gif"); },
			function() { $("img", this).attr("src", "../img/play.gif");	}
		);		
		$(this).click(function(){
			play($(this).attr("songId"));			
			return false;
		});
	});
	
	$(".stopBtn").each(function(){
		$(this).hover(		
			function() { $("img", this).attr("src", "../img/stop_over.gif"); },
			function() { $("img", this).attr("src", "../img/stop.gif");	}
		);		
		$(this).click(function(){
			stop($(this).attr("songId"));
			return false;			
		});
	});	
	
	$(".pauseBtn").each(function(){
		$(this).hover(		
			function() { $("img", this).attr("src", "../img/pause_over.gif"); },
			function() { $("img", this).attr("src", "../img/pause.gif");	}
		);		
		$(this).click(function(){
			pause($(this).attr("songId"));	
			return false;		
		});
	});	
	
	$(".playlistBtn").each(function(){
		/*$(this).hover(		
			function() { $("img", this).attr("src", "../img/playlist_over.gif"); },
			function() { 
				if ($(this).attr("inPlayList")==1)				
					$("img", this).attr("src", "../img/playlist_added.gif");	
				else
					$("img", this).attr("src", "../img/playlist_out.gif");	
			}
		);		*/
		$(this).click(function(){
			addToPlayList($(this), $(this).attr("songId"));	
			return false;							
		});
	});	
	
	
	$(".randomPlayBtn").hover(		
		function() { 
			$("img", this).attr("src", "../img/random_on.gif");
		},
		function() { 
			randomPlay ? $("img", this).attr("src", "../img/random_on.gif") : 
						 $("img", this).attr("src", "../img/random_off.gif");
		}
	);		
	$(".randomPlayBtn").click(function() {	
		randomPlay = !randomPlay;

		randomPlay ? $("img", this).attr("src", "../img/random_on.gif") : 
					 $("img", this).attr("src", "../img/random_off.gif");
		
		return false;							
	});	
	
		
		
	
});


function errorSong(id) {
	$('#trSongLine_'+id).css("background-color", "#96232f");
}

function addToPlayList(obj, id) {
	//$("img", obj).attr("src", "../img/playlist_loading.gif");

	
	if ($(obj).attr("inPlayList")==1) {
		$(obj).attr("inPlayList", "0");			
		$("img", obj).attr("src", "../img/playlist_out.gif");			
	}else{
		$(obj).attr("inPlayList", "1");
		$("img", obj).attr("src", "../img/playlist_added.gif");
	}


	$.post("outer.php", { act: "addToPlayList", id: id }, function(data) {
		if (data.result == "add") {
		}else{
		}
	}, "json");
}


$.preloadImages = function(preload){ 
	$(document.createElement('img')).bind('load', function(){ 
		if(preload[0]) this.src = preload.shift(); 
	}).trigger('load'); 
}

$.preloadImages(['/img/play.gif', '/img/play_over.gif', '/img/stop.gif', '/img/stop_over.gif', '/img/pause.gif', '/img/pause_over.gif', '/img/playlist_added.gif', '/img/playlist_loading.gif', '/img/playlist_out.gif', '/img/playlist_over.gif', '/img/random_on.gif', '/img/random_off.gif']);


function deletePreUploadFile(obj, id) {
	if (confirm('�������?')) {		
		var div = $(obj).parents('div').get(0);		
		
		$.post("index.php?q=upload_confirm", { upload_delete: '1', id: id }, function(data){
       		$(div).css("background", "red").hide("slow", function (){
       			$(div).remove();       			
       			setCursorAtFirstSecretCodeInput();	
       		}); 
		}, "html");	
	}
	return false;
}

function setNick(obj) {
	$(":input[name='nick']", ".confirmUpload").val( $(obj).val() );
}


function setCursorAtFirstSecretCodeInput(){
	firstForm = $(".confirmUpload:first");	
	$(":input[name='secret_code']", firstForm).focus();
}



$(document).ready(function(){
	if ($('.confirmUpload').length){
		$('.confirmUpload').each(function(){
			var self = this;
			var div = $(self).parents('div').get(0);
			
			$(this).ajaxForm({ 
	       		dataType:  'json', 
	    	   	success:   function(data) {
    	   			if (data.result==1) {    	   				
       					$(div).css("background", "green").hide("slow", function (){
       						$(div).remove();
       						setCursorAtFirstSecretCodeInput();
       					});         					
       				}else{
       					$('img', self).attr('src', $('img', self).attr('defsrc')+"&"+Math.floor( Math.random( ) * (999999+1) ));
       					$('.sout', div).html('<span style="padding: 3px; background: red; font-weight: bold;">�������� ���, ���������� �����!</span>');
		       			$(":input[name='frmsubmit']", self).attr("disabled",""); 
		       			$(":input[name='secret_code']", self).val("");
		       			setCursorAtFirstSecretCodeInput();
       				}
				},
	    	   	beforeSubmit: function(formData, jqForm, options){   
	    	   		$('.sout', div).empty();
	       			$(":input[name='frmsubmit']", self).attr("disabled","true"); 
	       			
	       			setCursorAtFirstSecretCodeInput();
    	   		}
    		});
		});
		
		setCursorAtFirstSecretCodeInput();
	}

	//adskape block	
//	if ($('#adskape_t6').length)
//		$('#adskape_t6').html('<script type="text/javascript" src="http://p66015.adskape.ru/adout.js?p=66015&t=6"></script>');
//	if ($('#adskape_t4').length)
//		$('#adskape_t4').append('<script type="text/javascript" src="http://p66015.adskape.ru/adout.js?p=66015&t=4"></script>');
//	if ($('#adskape_t5').length)
//		$('#adskape_t5').append('<script type="text/javascript" src="http://p66015.adskape.ru/adout.js?p=66015&t=5"></script>');
//	if ($('#adskape_t8').length)
//		$('#adskape_t8').append('<script type="text/javascript" src="http://p66015.adskape.ru/adout.js?p=66015&t=8&tx=3&ty=1&bgcolor=F0F0F0"></script>');
//	if ($('#adskape_t3').length)
//		$('#adskape_t3').append('<script type="text/javascript" src="http://p66015.adskape.ru/adout.js?p=66015&t=3"></script>');						
			
});




function utf8_encode ( argString ) {
    // Encodes an ISO-8859-1 string to UTF-8  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/utf8_encode
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // +   bugfixed by: Ulrich
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'
    var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if (c1 > 127 && c1 < 2048) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}

function serialize (mixed_value) {
    // Returns a string representation of variable (which can later be unserialized)  
    // 
    // version: 910.813
    // discuss at: http://phpjs.org/functions/serialize
    // +   original by: Arpad Ray (mailto:arpad@php.net)
    // +   improved by: Dino
    // +   bugfixed by: Andrej Pavlovic
    // +   bugfixed by: Garagoth
    // +      input by: DtTvB (http://dt.in.th/2008-09-16.string-length-in-bytes.html)
    // +   bugfixed by: Russell Walker (http://www.nbill.co.uk/)
    // +   bugfixed by: Jamie Beck (http://www.terabit.ca/)
    // +      input by: Martin (http://www.erlenwiese.de/)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // -    depends on: utf8_encode
    // %          note: We feel the main purpose of this function should be to ease the transport of data between php & js
    // %          note: Aiming for PHP-compatibility, we have to translate objects to arrays
    // *     example 1: serialize(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: 'a:3:{i:0;s:5:"Kevin";i:1;s:3:"van";i:2;s:9:"Zonneveld";}'
    // *     example 2: serialize({firstName: 'Kevin', midName: 'van', surName: 'Zonneveld'});
    // *     returns 2: 'a:3:{s:9:"firstName";s:5:"Kevin";s:7:"midName";s:3:"van";s:7:"surName";s:9:"Zonneveld";}'
    var _getType = function (inp) {
        var type = typeof inp, match;
        var key;
        if (type == 'object' && !inp) {
            return 'null';
        }
        if (type == "object") {
            if (!inp.constructor) {
                return 'object';
            }
            var cons = inp.constructor.toString();
            match = cons.match(/(\w+)\(/);
            if (match) {
                cons = match[1].toLowerCase();
            }
            var types = ["boolean", "number", "string", "array"];
            for (key in types) {
                if (cons == types[key]) {
                    type = types[key];
                    break;
                }
            }
        }
        return type;
    };
    var type = _getType(mixed_value);
    var val, ktype = '';
    
    switch (type) {
        case "function": 
            val = ""; 
            break;
        case "boolean":
            val = "b:" + (mixed_value ? "1" : "0");
            break;
        case "number":
            val = (Math.round(mixed_value) == mixed_value ? "i" : "d") + ":" + mixed_value;
            break;
        case "string":
            mixed_value = this.utf8_encode(mixed_value);
            val = "s:" + encodeURIComponent(mixed_value).replace(/%../g, 'x').length + ":\"" + mixed_value + "\"";
            break;
        case "array":
        case "object":
            val = "a";
            /*
            if (type == "object") {
                var objname = mixed_value.constructor.toString().match(/(\w+)\(\)/);
                if (objname == undefined) {
                    return;
                }
                objname[1] = this.serialize(objname[1]);
                val = "O" + objname[1].substring(1, objname[1].length - 1);
            }
            */
            var count = 0;
            var vals = "";
            var okey;
            var key;
            for (key in mixed_value) {
                ktype = _getType(mixed_value[key]);
                if (ktype == "function") { 
                    continue; 
                }
                
                okey = (key.match(/^[0-9]+$/) ? parseInt(key, 10) : key);
                vals += this.serialize(okey) +
                        this.serialize(mixed_value[key]);
                count++;
            }
            val += ":" + count + ":{" + vals + "}";
            break;
        case "undefined": // Fall-through
        default: // if the JS object has a property which contains a null value, the string cannot be unserialized by PHP
            val = "N";
            break;
    }
    if (type != "object" && type != "array") {
        val += ";";
    }
    return val;
}


