/*
	A simple class for displaying file information and progress
	Note: This is a demonstration only and not part of SWFUpload.
	Note: Some have had problems adapting this class in IE7. It may not be suitable for your application.
*/

// Constructor
// file is a SWFUpload file object
// targetID is the HTML element id attribute that the FileProgress HTML structure will be added to.
// Instantiating a new FileProgress object with an existing file will reuse/update the existing DOM elements
function FileProgress(file, targetID) {
	this.fileProgressID = file.id;
//alert(file.post['Artist']);
	this.opacity = 100;
	this.height = 0;

	this.fileProgressWrapper = document.getElementById(this.fileProgressID);
	if (!this.fileProgressWrapper) {
		this.fileProgressWrapper = document.createElement("div");
		this.fileProgressWrapper.className = "progressWrapper";
		this.fileProgressWrapper.id = this.fileProgressID;

		this.fileProgressElement = document.createElement("div");
		this.fileProgressElement.className = "progressContainer";

		var progressCancel = document.createElement("a");
		progressCancel.className = "progressCancel";
		progressCancel.href = "#";
		progressCancel.style.visibility = "hidden";
		progressCancel.appendChild(document.createTextNode(" "));

		var progressText = document.createElement("div");
		progressText.className = "progressName";
		progressText.appendChild(document.createTextNode(file.name));
		

		var progressBar = document.createElement("div");
		progressBar.className = "progressBarInProgress";

		var progressStatus = document.createElement("div");
		progressStatus.className = "progressBarStatus";

		this.fileProgressElement.appendChild(progressCancel);
		this.fileProgressElement.appendChild(progressText);
		this.fileProgressElement.appendChild(progressStatus);
		this.fileProgressElement.appendChild(progressBar);

		this.fileProgressWrapper.appendChild(this.fileProgressElement);

		document.getElementById(targetID).appendChild(this.fileProgressWrapper);
	} else {
		this.fileProgressElement = this.fileProgressWrapper.firstChild;
	}

	this.height = this.fileProgressWrapper.offsetHeight;
}
FileProgress.prototype.setProgress = function (percentage) {
	this.fileProgressElement.className = "progressContainer green";
	this.fileProgressElement.childNodes[3].className = "progressBarInProgress";
	this.fileProgressElement.childNodes[3].style.width = percentage + "%";
};


/** функция для получения и вывода ID3 тэгов **/
FileProgress.prototype.getID3Tags = function(file){

    $.post('/track/parse/', {
        file: file.name
    }, function(xml){
		if(!document.getElementById("uploadedFilesInfo")){
			ht  = '<div class="uploadedFiles" id="uploadedFilesInfo">';
				ht += '<div class="auto-helper">'
					ht  += "Быстрое заполнение полей (выбранное поле у всех треков):<br/>";
					ht  += "<input value='' style='margin-left:0;'>";
					ht  += '<input id="chooseField" class="comboBox value0" style=""/>';
					ht  += "<a href='javascript:;' class='profileButton ok' onClick='autocompletetrack()'>Применить</a>";
					ht += '</div><br clear="All"/><br/>';
					ht += "Проверьте правильность названий треков и добавтье теги:";
			ht += '</div>';
			$('.uploaderHello').replaceWith(ht);
			
			$("#chooseField").combobox({
				data: ['Исполнитель', 'Альбом', 'Теги', 'Год'],
				arrowHTML: function() {
								return $('<a href="javascript:;" class = "ui-combobox-arrow" style="margin-top:5px;"></a>');
							}
			});
		}

		while(!this.uploadedFilesWrapper) 
			this.uploadedFilesWrapper = document.getElementById("uploadedFilesInfo");
		this.uploadedFileElement = document.createElement("div");
		this.uploadedFileElement.className = "uploadedFileForm";
		var uploadedFileText = document.createElement("div");
		uploadedFileText.className = "uploadedFileName";
		uploadedFileText.setAttribute("name", "fileForm")
		uploadedFileText.innerHTML = "<span class='formTitle' name='fileName'>" + file.name + "</span><br/>";		
		var h = "<a class='del-track' onclick='delete_uploaded(this)' href='javascript:;'></a><table><tr>";
		h += "<td class='textInfo' style='width:200px;'>Исполнитель: </td>";
		h += "<td class='textInfo'>Название: </td></tr><tr>";		
		h += "<td><input class='artistInput' id='Artist" + file.name + "' name='Artist'/></td>";
		h += "<td><input class='artistInput' id='Title" + file.name + "' name='Title'/></td></tr><tr>";
		h += "<td class='textInfo'>Альбом: </td>";
		h += "<td class='textInfo'>Теги: </td></tr><tr>";		
		h += "<td><input class='artistInput' id='Album" + file.name + "' name='Album'/></td>";
		h += "<td><input class='artistInput' id='Tags" + file.name + "' name='Tags'/></td></tr><tr>";
		h += "<td></td>";
		h += "<td></td></tr><tr>";
		h += "<td class='textInfo'>Длина трека: <span class='textInfo' style='color:#626262;' id='Length" + file.name + "' name='Length'>" + $('length', xml).text() + "</span></td>";		
		h += "<td class='textInfo' style='padding-top:3px;'>Битрейт: <span class='textInfo' id='Bitrate" + file.name + "' name='Bitrate'>" + Math.floor($('bitrate', xml).text()) + "</span> <span style='margin-left:36px;'>Год: <input value='" + $('year', xml).text() + "' class='yearInput' id='Year" + file.name + "' name='Year'/></span></td></tr></table>";

		uploadedFileText.innerHTML += h;
		this.uploadedFileElement.appendChild(uploadedFileText);
		this.uploadedFilesWrapper.appendChild(this.uploadedFileElement);
		curWrapper = this.uploadedFilesWrapper.childNodes[this.uploadedFilesWrapper.childNodes.length-1];
		inps = $(curWrapper).find('input');
		$(inps[0]).val(strFormat($('artists', xml).text()));
		
		$(inps[1]).val(strFormat($('name', xml).text()));
		$(inps[2]).val(strFormat($('album', xml).text()));
		$(inps[3]).val($('genre', xml).text());
    });
	
};

function strFormat(str){
	var fstr = '';
	str = str.toLowerCase().split(' ');
	for(i=0;i<str.length;i++){
		fstr += str[i].substr(0, 1).toUpperCase() + str[i].substr(1, str[i].length);
		if(i!=str.length-1)
			fstr += ' ';
	}
	return fstr;
}

FileProgress.prototype.setComplete = function () {
	this.fileProgressElement.className = "progressContainer blue";
	this.fileProgressElement.childNodes[3].className = "progressBarComplete";
	this.fileProgressElement.childNodes[3].style.width = "";


	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 10000);
};
FileProgress.prototype.setError = function () {
	this.fileProgressElement.className = "progressContainer red";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 5000);
};
FileProgress.prototype.setCancelled = function () {
	this.fileProgressElement.className = "progressContainer";
	this.fileProgressElement.childNodes[3].className = "progressBarError";
	this.fileProgressElement.childNodes[3].style.width = "";

	var oSelf = this;
	setTimeout(function () {
		oSelf.disappear();
	}, 2000);
};
FileProgress.prototype.setStatus = function (status) {
//	this.fileProgressElement.childNodes[2].innerHTML = status;
};

// Show/Hide the cancel button
FileProgress.prototype.toggleCancel = function (show, swfUploadInstance) {
	this.fileProgressElement.childNodes[0].style.visibility = show ? "visible" : "hidden";
	if (swfUploadInstance) {
		var fileID = this.fileProgressID;
		this.fileProgressElement.childNodes[0].onclick = function () {
			swfUploadInstance.cancelUpload(fileID);
			return false;
		};
	}
};

// Fades out and clips away the FileProgress box.
FileProgress.prototype.disappear = function () {

	var reduceOpacityBy = 15;
	var reduceHeightBy = 4;
	var rate = 30;	// 15 fps

	if (this.opacity > 0) {
		this.opacity -= reduceOpacityBy;
		if (this.opacity < 0) {
			this.opacity = 0;
		}

		if (this.fileProgressWrapper.filters) {
			try {
				this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity;
			} catch (e) {
				// If it is not set initially, the browser will throw an error.  This will set it if it is not set yet.
				this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")";
			}
		} else {
			this.fileProgressWrapper.style.opacity = this.opacity / 100;
		}
	}

	if (this.height > 0) {
		this.height -= reduceHeightBy;
		if (this.height < 0) {
			this.height = 0;
		}

		this.fileProgressWrapper.style.height = this.height + "px";
	}

	if (this.height > 0 || this.opacity > 0) {
		var oSelf = this;
		setTimeout(function () {
			oSelf.disappear();
		}, rate);
	} else {
		this.fileProgressWrapper.style.display = "none";
	}
};