/***************************************************************************
 *
 *   Uploadanh version 2
 *   Coder : Nghiem Tien Vien
 *   Email : boygiandi1@yahoo.com
 *
 ***************************************************************************/

function uploadfile() {
	var _WAITING = 0;
	var _UPLOADED = 1;
	var _DELETED = 2;
	var _UPLOADING = 3;
	var _UPLOAD_ERR = 4;

	var uploading=false;
	var ttLoaded=0;
	var current_file=-1;
	var ttSize = 0;
	var index = 0;
	
	var mode = (arguments[0])?arguments[0]:'main';

	/* file = Array ( name, size ) */
	var listfile = new Array();
	
	this.getTotalFile = function() {
		var i, c=0;
		for ( i=0; i<listfile.length; i++ ) {
			if ( listfile[i]['status'] == _WAITING ) c++;
		}
		return c;
	}

	this.hideupbutton = function(i)
	{
		string1 = "<invoke name=\"hideupbutton\" returntype=\"javascript\"><arguments><number>"+i+"</number></arguments></invoke>";
		$("#myFlashMovie").get(0).CallFunction(string1);
	}

	this.insertfile = function(data) {
		file = data.split("<!>");
		if ( data.length>3 )
			for ( i=0; i<file.length; i++ ) {
				f = file[i].split('<;>');

				var x = listfile.length;
				listfile[x] = new Array();
				listfile[x]['name'] = f[0];
				listfile[x]['size'] = f[1];
				if (f[1] > 5 * 1024 * 1024) {
					listfile[x]['status'] = _DELETED;
					//return false;
				}
				else {
					listfile[x]['status'] = _WAITING;
					ttSize += parseInt(f[1]);
				}
				
				if ( MINI_UPLOAD && ins_item.length > 1 ) {
					tmp = replace(ins_item, '%id', (index));
					tmp = replace(tmp, '%name', f[0]);
					tmp = replace(tmp, '%size', this.byte_convert(f[1]));
					$(".tableListUp").append(tmp);
				} else if ( mode=='iframe' ) {
					var files = $("#tableListUp").val() + f[0] + ', ';
					$("#tableListUp").val(files);
					$("#tableListUp").css("background", "#FFFFFF url(/templates/uploadanh/images/progress_bar.jpg) no-repeat -640px 0px");
				}
				else {
					tmp = '<tr style="background-position: -402px 0px; width:100%" id="item_' + index + '">';
					tmp +='<td width="50%" class="filename">&nbsp;' + f[0] + '</td>';
					tmp +='<td width="30%" class="filesize">' + this.byte_convert(f[1]) + '</td>';
					tmp +='<td width="20%" class="filestatus"><a href="#he" onclick="objupload.delfile('+index+'); return false;" class="delUploadFile" id="status_item_' + index + '"></a></td>';
					tmp +='</tr>';
					$(".tableListUp").append(tmp);
				}
				index++;
			}
		$("#infoLoading").html(listfile.length+" ảnh - "+ this.byte_convert(ttSize));
		$("#info_upload_div").css("display", "");
		$("#tableListUp").css("display", "");
		$("#Sign").css("display", "");
		$("#table2").css("display", "none");
		$(".guidemenu").html("<div style='height: 16px;'></div>");
		$(".guidemenu").removeClass("guidemenu");
		this.hideupbutton(1);
	}

	this.delfile = function(id)
	{
		if ( !uploading ) {
			listfile[id]['status'] = _DELETED;
			$("#item_"+id).fadeOut("slow");
		}
	}

	this.delallfile = function()
	{
		for ( var i=0; i<listfile.length; i++ )
			this.delfile(i);
	}

	this._error = function(error)
	{
		if (parseInt(error) != 505) {
			this.UploadComplete(1);
		}
		else {
			listfile[current_file]['status'] = _WAITING;
			$.facebox({
				ajax: '/pic.php?action=confirmupload'
			})
		}
	}

	this.browsefile = function()
	{
		string1 = "<invoke name=\"browsefile\" returntype=\"javascript\"><arguments></arguments></invoke>";
		$("#myFlashMovie").get(0).CallFunction(string1);
	}

	this.upload = function()
	{
		uploading=true;
		$("#uploadButton").click(function(){ return false; });
		
		for ( i=0; i<listfile.length; i++ ) {
			// Disable del button
			
			if (listfile[i]['status'] == _WAITING) {
				current_file = i;
				break;
			}
		}
		this.hideupbutton(0);
		
		split = ':-;-:';
		if ( $('#watermark').lenght > 0 )
			watermark = $('#watermark').val() +split+ $("#wtm_fonttype").val()+split+$("#wtm_color").val()+split+$("#wtm_fontsize").val();
		else watermark = '';
		
		tag = $('#tags').serialize();
		tag = tag.replace("tags=", "");
		string1 = "<invoke name=\"upload\" returntype=\"void\"><arguments>";
		string1 += "<number>"+current_file+"</number>";
		string1 += "<string>"+tag+"</string>";
		string1 += "<string>"+sessions+"</string>";
		string1 += "<string>"+$('#confirm_code').val()+"</string>";
		string1 += "<string>"+$('#confirm_id').val()+"</string>";
		string1 += "<string>"+watermark+"</string>";
		string1 += "<string>"+(($('#selectsize').val()>0)?1:0)+"</string>";
		string1 += "<number>"+$('#size').val()+"</number>";
		string1 += "<number>"+($('#private').get(0).checked?1:0)+"</number>";
		string1 += "<number>"+albumid+"</number>";
		string1 += "<string>"+usersessions+"</string>";
		string1 += "</arguments></invoke>";
		$("#myFlashMovie").get(0).CallFunction(string1);
		$("#info_Loading").css("display", "");
		$("#reg_link").css("display", "none");
		$("#delAll").css("display", "none");
		listfile[current_file]['status'] = _UPLOADING;
		uploading = false;
	}

	this.updateprogress = function(bytesLoaded)
	{
		// Set progress
		percent = bytesLoaded/listfile[current_file]['size'];
		ttpercent = Math.floor((ttLoaded+bytesLoaded)*100/ttSize);
		$("#info_Loading").html(lang['uploading']+ttpercent+"%");
		pos = ( percent*400 ) - 400;
		$("#item_"+current_file).css("backgroundPosition", pos+"px");
		if ( mode == 'iframe' ) {
			$(".tableListUp").css("backgroundPosition", (ttpercent * 2)-640 + "px");
		}
	}

	this.UploadComplete = function(m)
	{
		if ( m==0 ) { /* Upload success */
			ttLoaded += parseInt(listfile[current_file]['size']);
			$("#status_item_"+current_file).removeClass("delUploadFile");
			$("#status_item_"+current_file).addClass("okUploadFile");
			listfile[current_file]['status'] = _UPLOADED;
		} else {
			$("#status_item_"+current_file).removeClass("delUploadFile");
			$("#status_item_"+current_file).addClass("errUploadFile");
			listfile[current_file]['status'] = _UPLOAD_ERR;
			/*  Upload failure */
		}
		if (current_file+1<listfile.length) this.upload(current_file+1);
		else if ( current_file+1==listfile.length  ) {
			/* Upload All Files Complete */
			$("#info_Loading").html(lang['next_step']);
			$("#nextButton").click();
		}
		targetOffset = $("#status_item_"+current_file).offset().top-$("#status_item_0").offset().top;
		$("#tableListUp").animate({scrollTop: targetOffset}, 200);
	}

	this.byte_convert = function(bytes)
	{
		var symbol = new Array("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
		exp = 0;
		converted_value = 0;
		if( bytes > 0 )
		{
			exp = Math.floor( Math.log(bytes)/Math.log(1024) );
			converted_value = ( bytes/Math.pow(1024,Math.floor(exp)) );
		}
		return (Math.floor( converted_value*100 )/100)+' '+symbol[exp];
	}
	
	this.html_checkform = function() {
		//load confirm code
		var str = $("form").serialize();
		$("#info_Loading").css("display", "");
		$("#reg_link").css("display", "none");
		$("#uploadButton").css("disable", "true");
		return true;
	}

	
	this.add_browsefile = function(k) {
		var tpl = $('#uploadingbox').html();
		for ( i=1; i<=k; i++ ) {
			var tem = tpl.replace(' id="text_0', ' id="text_'+i);
			tem = tem.replace('browsechange(this, 0', 'browsechange(this, '+i);
			$("#uploadingbox").append(tem);
		}
	}
	
	this.status = function() {
		if ( current_file+1==listfile.length ) return 'Upload Complete';
		if ( uploading ) return 'uploading';
		else return 'wait';
	}
}
var objupload = new uploadfile();

function getFlashVersion(){ 
  // ie 
  try { 
	try { 
	  var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6'); 
	  try { axo.AllowScriptAccess = 'always'; } 
	  catch(e) { return '6,0,0'; } 
	} catch(e) { } 
	return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; 
  // other browsers 
  } catch(e) { 
	try { 
	  if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){
		return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1]; 
	  } 
	} catch(e) { } 
  } 
  return '0,0,0'; 
} 

function checkFlashVersion() {
	var playerVersion = getFlashVersion().split(',').shift();
	if ( playerVersion<8 && location.href.indexOf("?upload")==-1 ) {
		url = location.href;
		if ( url.indexOf("?flash")!=-1 ) url = url.replace("?flash", "?upload");
		else if ( url.indexOf("index.php")!=-1 ) {
			url = url.replace("index.php", "index.php?upload&");
		} else url += "?upload";
		location.href = url;
	}
}

function my_onload() {
	checkFlashVersion();
}
