var _POPUP_FEATURES = "location=0,statusbar=0,menubar=0,width=300,height=300,scrollbars=1";

var fader;

function raw_popup(url, target, features){
  	if(typeof features == "undefined"){
		features = _POPUP_FEATURES;
  	}

  	var theWindow = window.open(url, target, features);

 	theWindow.focus();
  	return theWindow;
}

var focused = null;
var uuid = "";
var total = 0;
var start_time = 0; // the unix timestamp of the start of upload *needs fixing*
var sid = "";
var speed = 0;	// speed of transfer in kbps
var PROGRESS = {
	uploading: false,
	STOPAJAX: false,
	timer: null,
	log: [],
	uploaded: 0,
	size: 0,
	show_tb: true
};

function debug(msg){
	if(document.getElementById("log")){
		document.getElementById("log").value += msg + "\n";
	}
}

function XHR(url, params, open){
	this.url = url;
	this.open = open || "GET";
	this.params = params || "";
	this.request = null;
	this.responseText = null;
	this.responseXML = null;
}

XHR.prototype.Ready = function(){
	try {
		if(this.request.readyState == 4 && this.request.status == 200){
			this.responseText = this.request.responseText;
			this.responseXML = this.request.responseXML;
			return true;
		}
	} catch(e) {
		
	}
	
	return false;
}

XHR.prototype.Request = function(func, nginx, uuid){
	this.request = (window.XMLHttpRequest)? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	
	if(this.request){
		this.request.onreadystatechange = func;
		this.request.open(this.open, this.url, true);
		
		if(this.open.toLowerCase() == "post"){
			this.request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.request.setRequestHeader("Content-length", this.params.length);
			this.request.setRequestHeader("Connection", "close");
		} else if(nginx && uuid){
			this.request.setRequestHeader("X-Progress-ID", uuid);
		}

		this.request.send(this.params);
	}
}

function format_size(size){
	if(size >= 1073741824){
    	size = parseFloat(size / 1073741824).toFixed(2) + ' GB';
	} else if(size >= 1048576){
    	size = parseFloat(size / 1048576).toFixed(2) + ' MB';
    } else if(size >= 1024){
		size = parseFloat(size / 1024).toFixed(0) + ' KB';
	} else {
		size = parseFloat(size).toFixed(0) + ' Bytes';
	}
	
	return size;
}

function start_progress(){
	if(PROGRESS.STOPAJAX){
		clearInterval(PROGRESS.timer);
		return;
	}
	
	var num = new Date().getTime();
	var qry = "total_size=" + total + "&start_time=" + start_time + "&sessionid=" + sid + "&num=" + num;
	var AJAX = new XHR("/ajax-progress", null, "GET");
	var pb = document.getElementById( 'progress_bar' );
	
	AJAX.Request(function(){
		if(AJAX.Ready()){
			var data = AJAX.responseText;

			if(data){
				data = eval(data);

				if(data.status && data.status == 413){
					alert("Maximum file size for the free service is 100MB.\n\nTo send bigger files, signup for a Pro account.");
					PROGRESS.STOPAJAX = true;
					PROGRESS.show_tb = false;
					location.href = "http://free.mailbigfile.com";
				}
				
				var percent = ((data.received / data.size) * 100).toFixed(0);
				
				if(isNaN(percent)){
					percent = 0;
				}
				
				if(data.received && data.size){
					PROGRESS.uploaded = data.received;
					PROGRESS.size = data.size;
					PROGRESS.log.push([data.received, data.size, percent]);
				}
				
				var current_size_fmt = format_size(data.received);
				var total_size_fmt = format_size(data.size);
				var time_remaining = remaining();
				
				if(current_size_fmt.match(/^NaN/i)){
					current_size_fmt = "0";
				}

				if(total_size_fmt.match(/^NaN/i)){
					total_size_fmt = "0";
				}
				
				var status = '<div style="width: 100%; height: 16px; border: solid 1px #fff;"><div style="width: ' + percent  + '%; background: #0b0 url(/images/progress_bg.png); height: 16px;"><\/div><\/div>';			
				status += '<span class="percentUpload">' + percent + "%<\/span><br/>";	
				status += '<span id="info">' + current_size_fmt + " / " + total_size_fmt + "</span><br/>";
				status += "Estimated Time Remaining: " + time_remaining + "<br/>";

				if(!pb.innerHTML.length){
					PROGRESS.uploading = true;
				} else if(data.size > 0){
					PROGRESS.uploading = true;
				} else {
					PROGRESS.uploading = false;
				}

				if(PROGRESS.uploading){
					pb.innerHTML = status;
				}
			}
			
			if(document.getElementById("waitmsg") && document.getElementById("waitmsg").innerHTML.length < 1){
				document.getElementById("waitmsg").innerHTML = "Please do not close this page while uploading.";
			}
		}
	}, true, uuid);
}

function remaining(){
	var remain = "Calculating...";
	
	if(PROGRESS.log.length){		
		if(PROGRESS.log.length >= 6){
			var log = PROGRESS.log;
			
			log.reverse();
			
			var avgs = [
				log[0][0] - log[1][0],
			    log[1][0] - log[2][0],
			    log[2][0] - log[3][0],
			    log[3][0] - log[4][0],
			    log[4][0] - log[5][0]
			];
							
			log.reverse();
			
			var total = 0;
			
			for(var i = 0, l = avgs.length; i < l; i ++){
				total += avgs[i];
			}
			
			var avg = (total / PROGRESS.log.length);
			
			remain = Math.round(((PROGRESS.size - PROGRESS.uploaded) / avg));
			
			var hours = Math.floor(remain / 3600);
			var minutes = (Math.floor(remain / 60) - (hours * 60));
			var seconds = ((remain - (hours * 3600)) - (minutes * 60));
			var hs = " hour";
			var ms = " minute";
			var ss = " second";
			
			hours = (isNaN(hours))? 0 : hours;
			minutes = (isNaN(minutes))? 0 : minutes;
			seconds = (isNaN(seconds))? 0 : seconds;
			
			if(hours != 1){
				hs += "s"
			}
			
			if(minutes != 1){
				ms += "s"
			}
			
			if(seconds != 1){
				ss += "s"
			}
			
			remain = hours + hs + ", " + minutes + ms + ", " + seconds + ss;			
		}
				
		if(PROGRESS.log.length > 6){
			PROGRESS.log.shift();
		}
	}
	
	return remain;
}

function doIt(theForm){
	if(theForm.recipient){
		if(theForm.recipient.value == ""){
			alert("Please enter the recipient's e-mail address.");
			theForm.recipient.focus();
			return false;
		} else {
			if(!isValidEmail(theForm.recipient.value)){
				alert("The recipient e-mail address does not appear to be valid.  Please make sure you have entered only one address.  e.g. user@domain.com");
				theForm.recipient.focus();
				return false;
			}
		}
	}
	
	if(theForm.fileInput.value == ""){
		alert("Please select a file.");
		theForm.fileInput.focus();
		return false;
	}
	
	if(theForm.from){
		if(theForm.from.value != ""){
			if(!isValidEmail(theForm.from.value)){
				alert("Your e-mail address does not appear to be valid.");
				theForm.from.focus();
				return false;
			}
		}
	}
	
	if(theForm.repro_id){
		if(theForm.from.value == ""){
			alert("You must enter your e-mail address");
			theForm.from.focus();
			return false;
		}
	}
	
	
	// stop the fader on the homepage as error checking has been done: reducing overhead during upload.
	clearInterval( fader );
	
	
	if(theForm.submitButton){
	//	theForm.submitButton.value = "Please Wait...";
		theForm.submitButton.disabled = true;
	}
	
	if(theForm.submitImage){
		//theForm.submitImage.style.display = "none";
	}
	
	for(i = 0; i < 32; i ++){
		uuid += Math.floor(Math.random() * 16).toString(16);
    }

	document.getElementById("fileForm").action ="/processUpload.php?X-Progress-ID=" + uuid;

	if((navigator.userAgent.match(/webkit/i) && navigator.userAgent.match(/safari/i) && (navigator.userAgent.match(/version\/(3|4|5|6)\./i) || navigator.userAgent.match(/chrome/i))) || navigator.userAgent.match(/opera/i)){
		setTimeout(function(){
			if(document.getElementById("progressframe")){
				document.getElementById("progressframe").src = "/progress/index.php?sid=" + uuid + "&X-Progress-ID=" + uuid;
				setTimeout(function(){
					document.getElementById("progressframe").style.display = "block";
				}, 1000);
			}
		}, 250);
	} else {
		start_progress();
		setTimeout("start_progress()", 50);
		PROGRESS.timer = setInterval("start_progress()", 1000);
	}
	
	// show tired of waiting message, encourage upgarde to pro account.
	//document.getElementById("tired_of_waiting").style.display = "block";
	
	setTimeout(function(){
		var _h = (_pro)? 105 : 125
		
		if(PROGRESS.show_tb){
			tb_show("", "TB_inline?height=" + _h + "&width=530&inlineId=myprogdata&modal=true");
		}
	}, 900);
	
	return true;
}

function isValidEmail(str){
	if(str.match(/[\/\;\,\s]+/)){
		return false;
	}
	
	return (str.indexOf(".") > 0) && (str.indexOf("@") > 0);
}

var messageDiv;
var xmlhttp;

function onchangeRecipient(){
	var repro = 0;

	if(document.forms.item(0).elements["repro_id"] && !location.href.match(/\-send/i)){
		repro = document.forms.item(0).elements["repro_id"].value;
	}
	
	xmlhttp = new XHR("/ajax/verifyEmail.php?recipient=" + this.value + "&repro=" + repro, null, "GET");
	
	xmlhttp.Request(function(){
		if(xmlhttp.Ready()){
			writeDetails(xmlhttp.responseText); 
		}
	});
		
	return true;
}
	
function writeDetails(r) {
	var recipient = document.getElementById( 'recipient' );
	var existingClass = recipient.className;
	
	if(r.charAt( 0 ) == '0'){
		if (!messageDiv){
			messageDiv = message( recipient, 'errorMessage', 'Please enter a valid e-mail address' );
				
			recipient.className = existingClass + ' formError';
		}
	} else {
		if ( messageDiv ) {
			messageDiv.parentNode.removeChild( messageDiv );
			
			messageDiv = null;
			
			var filterClass = recipient.className.split(" ");
			recipient.className = filterClass[0];
		}
	}
	
	xmlhttp = null;
}
	
function message( element, classString, errorMessage ) { 
	var messageDiv = document.createElement( 'div' ); 
	
	element.parentNode.insertBefore( messageDiv, element ); 
	messageDiv.className = classString; 
	messageDiv.appendChild( document.createTextNode( errorMessage ) ); 
	
	return messageDiv; 
}

function event_popup(e) {
  link_popup(e.currentTarget);
  e.preventDefault();
}

function init() {

	var recipientField = document.getElementById( "recipient" );
		
	// CC focus
	
	var r2 = document.getElementById("recipient2");
	var r3 = document.getElementById("recipient3");
	var r4 = document.getElementById("recipient4");
	var r5 = document.getElementById("recipient5");
	
	if(r2 && r3 && r4 && r5){
		r2.onfocus = r3.onfocus = r4.onfocus = r5.onfocus = recipientField.onfocus = function(){
			focused = this.name;
		}
	}

	if ( recipientField != null ) {
		recipientField.focus();
		
		if(recipientField.nodeName.toLowerCase() == "input" && recipientField.value.length > 0){
			recipientField.onblur = onchangeRecipient
		}
		
		recipientField.onchange = onchangeRecipient;
	}

	return true;
}