preload_images( new Array(
	'arrow_properties1.gif',
	'prop_tab_tl.gif',
	'prop_tab_tr.gif',
	'arrow_properties.gif',
	'prop_bottom.gif',
	'prop_top.gif',
	'button_cancel_upload.gif',
	'progress_bgr.gif',
	'progress.gif'
));

var wikiObj = {
	fid: 0,
	indexURL: "/",
	downloadURL: "/download/",
	dispatchPath : "upload/_dispatch.php",
	detailsLoc : "upload/_details.php",
	errorURL : "/error/",
	isFinished : 0,
	errorCount : 0,
	lastUplodedVal : 0,
	maxAjaxTimeout : 5000,
	activeRequests : 0,
	progressBarMaxWidth : 450
};

$(function() {
	$.ajaxSetup({
		dataType: 'json',
		cache: false,
		type: 'POST'
	});
	$("#switch").toggle(
		function () {
			$("#proper").attr('class', 'proper');
			$("#block").slideToggle(800, function (){
				$("#ffname").focus();
			});
		},
		function () {
			$("#block").slideToggle(500, function (){
				$("#proper").attr('class', 'noproper');
				$("#switch").blur();
			});
		}
	);

	$("#upload_but").bind("click", function(e) {
		dispatchUpload();
	});
	$("#sendmail, label[for=sendmail]").bind("click", function(e) {
		if( $('#sendmail').is(":checked") ) {
			$("#email").attr("class","inputfield").attr("readonly", "").trigger('focus');
			$("label[for=email]").attr("class","");
		} else {
			$("#email").attr("class","disabledfield").attr("readonly", "readonly");
			$("label[for=email]").attr("class","passive");
		}
	});
	$("#protected, label[for=protected]").bind("click", function() {
		if( $('#protected').is(":checked") ) {
			$("#confpassw, #passw").attr("class","inputfield").attr("readonly", "").trigger('focus');
			$("label[for=passw],label[for=confpassw], ").attr("class", "");
		} else {
			$("#passw, #confpassw").attr("class","disabledfield").attr("readonly", "readonly");
			$("label[for=passw],label[for=confpassw]").attr("class", "passive");
		}
	});
});

function dispatchUpload() {
	
	var params = processFormData();
	if( !params )
		return false;
	$("#upload_but").unbind();
	$.ajax({
		url: wikiObj.dispatchPath,
		data: params,
		success: function(json) {
			$("#uploadForm").attr("action", json.nodeUpldAdress);
			$("#fid").val(json.fileId);
			$("#fileName").val(json.fileName);
			try {
				$("#uploadForm").submit();
			} catch (e) {
				// IE throws exception if we try to upload rubbish
				alert("Please, use the browse button to attach a file!");
				window.location = '/';
				return;
			}
			wikiObj.fid = json.fileId;
			var date = new Date();
			wikiObj.ts = date.getTime();
			$("#theme").html(json.html);
			$("#cancel").bind("click", function () {
				cancelUpload();
				window.location = wikiObj.indexURL;
				return false;
			});
			wikiObj.setIntervalId = window.setInterval( "updateProgress()", 1000 );
			updateProgress();
		},
		error: function(XMLHttpRequest, textStatus, errorThrown){
			window.clearInterval(wikiObj.setIntervalId);
			window.location = wikiObj.errorURL;
		}
	});	
	return false;
}

function processFormData() {
	var params = new Object();
	var filename = $.trim( $('#uploadfield').val() );
	if ( filename == '' ) {
		alert('Please, attach the file!');
		return false;
	}
	params.fileName = string2Unicode(filename);
	params.ffName = $('#ffname').val();
	params.storageDays = $('#lifetime').val();
	params.fileDesc = $('#filedescr').val();
	
	if( $('#sendmail').is(":checked") ) {	
		var email = $.trim($('#email').val());
		if( !email ) {
			alert('You should specify your email if you want to get the resulting link!');
			$('#email').trigger("focus");
			return false;
		}	
		
		if( !is_valid_email(email) ) {
			alert("Invalid email adress!");
			$('#email').trigger("focus");
			return false;
		}
		params.email = email;
	}

	if( $('#protected').is(":checked") ) {	
		if( $.trim($('#passw').val()) == '' ) {
			alert('You should specify the password if you want to protect the file!');
			$('#passw').trigger("focus");
			return false;
		}
		if( !is_valid_password($('#passw').val()) ) {
			alert("The following characters are allowed in your password: a-z, A-Z, 0-9, _ and common punctuation characters.");
			$('#passw').val('').trigger("focus");
			$('#confpassw').val('');
			return false;
		}
		if( $('#passw').val() != $('#confpassw').val() ) {
			alert('The password and the retyped passwords do not match! Please, retype the password once again!');
			$('#confpassw').val('').trigger("focus");
			return false;
		}
		params.pwd = $('#passw').val();
	}
	params.t =  new Date().getTime();
	return params;
}

function cancelUpload() {	
	wikiObj.isFinished = 1;
	window.clearInterval(wikiObj.setIntervalId);
	$.ajax({
		url: wikiObj.detailsLoc,
		async: false,
		data: "cancelUpload=1&fid=" + wikiObj.fid
	});
}

function updateProgress() {
	if ( wikiObj.isFinished || wikiObj.activeRequests >= 2 )
		return;
	wikiObj.activeRequests++;
	$.ajax({
		url: wikiObj.detailsLoc,
		data: "watch=1&fid=" + wikiObj.fid,
		success: function(json) {
			if ( wikiObj.isFinished )
				return;
			if ( json.finishStatus == "approved" ) {
				wikiObj.isFinished = 1;
				window.clearInterval(wikiObj.setIntervalId);
				showProgress (json);
				window.location = wikiObj.downloadURL + wikiObj.fid + "/";
			} else if ( json.startStatus == "removed" ) {
				var date = new Date();
				var curTs = date.getTime();
				var past = Math.ceil( (curTs - wikiObj.ts) / 1000 );
				if( past > 15) {
					errorFinalize ();
				}
			} else if ( json.startStatus == "started" ) {
				wikiObj.errorCount = 0;
				showProgress (json);
				return
			} else {
				if ( wikiObj.isFinished )
					return;
				wikiObj.errorCount++;
				if ( wikiObj.errorCount > 10 ) {
					errorFinalize ();
				}
			}
		},
		error: function(XMLHttpRequest, textStatus, errorThrown) {
			if ( wikiObj.isFinished )
				return;
			wikiObj.errorCount++;
			if ( wikiObj.errorCount > 10 ) {
				errorFinalize ();
			}
		},
		complete: function () {
			wikiObj.activeRequests--;
		}
	});
};

function errorFinalize () {
	wikiObj.isFinished = 1;
	window.clearInterval(wikiObj.setIntervalId);
	window.location = wikiObj.errorURL + wikiObj.fid + "/";
}

function showProgress (json) {
	if ( wikiObj.lastUplodedVal >= json.uploaded )
		return;
	wikiObj.lastUplodedVal = json.uploaded;
	if ( !json.uploaded || !json.total )
		return;
	var persents = calcPersents(json.uploaded, json.total);
	var width = calcPixels(json.uploaded, json.total);
	var status = getStatusStr(json.uploaded, json.total);
	var estimate = getEstimateTimeStr(json.uploaded, json.total);
	$("#progressbar").width(width);
	$("#percents").html(persents + "%");
	$("#status").html(status);
	$("#estimate").html(estimate);
}
function calcPersents(a,z) {
	var cur = Math.floor(100*a/z);
	return ( cur > 100 ) ? 100 : cur;
}

function calcPixels (a,z) {
	var cur = Math.floor(wikiObj.progressBarMaxWidth * a/z);
	return ( cur > wikiObj.progressBarMaxWidth ) ? wikiObj.progressMaxWidth : cur;
}

function getStatusStr(a,z) {
	if( a < 1024) {
		a = a.toString() + 'B';
	} else {
		a = a / 1024; //Kb
		if ( a < 1024 ) { //<Mb
			if ( a<10 ) {
				a = a.toString().substring(0,1) + 'Kb';
			} else if ( a<100 ) {
				a = a.toString().substring(0,2) + 'Kb';
			} else if ( a<1000 ) {
				a = a.toString().substring(0,3) + 'Kb';
			} else {
				a = a.toString().substring(0,4) + 'Kb';
			}
		} else {
			a = (a/1024).toString().substring(0,4) + 'Mb';
		}
	}
	if( z < 1024 ) {
		z = z.toString() + 'B';
	} else {
		z = z / 1024; //Kb
		z = ( z < 1024 ) ? Math.floor(z).toString() + 'Kb' : (z/1024).toString().substring(0,4) + 'Mb';
	}
	return a + ' of ' + z;
}

function getEstimateTimeStr(a,z) {
	var date = new Date();
	var curTs = date.getTime();
	var speed = a / (curTs - wikiObj.ts);
	//var est = (z-a) / speed / 1000
	var seconds = Math.ceil( (z-a) / speed / 1000 );
	var minutes = Math.floor( seconds / 60 );
	if( minutes ){
		seconds -= minutes*60;
		min = (minutes>1) ? ' Minutes ' : ' Minute ';
		sec = (seconds>1) ? ' Seconds' : ' Second';
		return minutes.toString() + min + ( seconds ? seconds.toString()  + sec : '' ); 
	}
	return seconds.toString()  + " Seconds";
}

function string2Unicode(s) {
    var uniString = '';
    for (var i = 0; i < s.length; i++) {
        var hexVal = Number(s.charCodeAt(i)).toString(16);
        var uniChar = "\\u" + ("000" + hexVal).match(/.{4}$/)[0];
        uniString += uniChar;
    }
    return uniString;
}

function is_valid_password(str) {
	return ( str.match(/[^a-zA-Z0-9_.?:;!,'"]/) ) ? false : true;
}

function is_valid_email(str) { 
	return str.match(/^(\w|-|\d|_)+(\.(\w|-|\d|_)+)*@(\w|-|\d)+(\.(\w|-|\d)+)+$/);
}