//******************************************************************************************************
//   ATTENTION: THIS FILE HEADER MUST REMAIN INTACT. DO NOT DELETE OR MODIFY THIS FILE HEADER.
//
//   Name: uu_file_upload.js
//   Revision: 2.1
//   Date: 25/05/2007 11:09PM
//   Link: http://uber-uploader.sourceforge.net
//   Initial Developer: Peter Schmandra  http://www.webdice.org
//
//   Licence:
//   The contents of this file are subject to the Mozilla Public
//   License Version 1.1 (the "License"); you may not use this file
//   except in compliance with the License. You may obtain a copy of
//   the License at http://www.mozilla.org/MPL/
// 
//   Software distributed under the License is distributed on an "AS 
//   IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
//   implied. See the License for the specific language governing
//   rights and limitations under the License.
//
//***************************************************************************************************************

var upload_range = 1;
var get_status_speed;
var get_status_url;
var get_data_loop = false;
var seconds = 0;
var minutes = 0;
var hours = 0;
var info_width = 0;
var info_bytes = 0;
var info_time_width = 500;
var info_time_bytes = 15;
var cedric_hold = true;
var total_upload_size = 0;
var total_Kbytes = 0;

// Check the file format before uploading
function checkFileNameFormat(fileformat,fileformat1,fileformat2){
	if(!check_file_name_format){ return false; }
	
	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements['upfile_' + i].value != ""){
			var string = document.form_upload.elements['upfile_' + i].value;
			var num_of_last_slash = string.lastIndexOf("\\");

			if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }

			var file_name = string.slice(num_of_last_slash + 1, string.length);
			var re =/^[\w][\w\.\-]{1,54}$/i;
				
			if(!re.test(file_name)){
				var spchar=false;
				for(var i=0;i<file_name.length;i++)
				 {
					 if(file_name.charAt(i)==" ")
					 spchar=true;					
				 }
				 
			   if(spchar==false)
			   {
				alert(fileformat + "\n\n" + fileformat1 + "\n\n" + fileformat2);				
				return true;
			   }			   
			}
		}
	}
	return false;
}

// Check for illegal file extentions
//function checkDisallowFileExtensions(){
//	if(!check_disallow_extensions){ return false; }
//	
//	for(var i = 0; i < upload_range; i++){
//		if(document.form_upload.elements['upfile_' + i].value != ""){
//			if(document.form_upload.elements['upfile_' + i].value.match(disallow_extensions)){
//				var string = document.form_upload.elements['upfile_' + i].value;
//				var num_of_last_slash = string.lastIndexOf("\\");
//
//				if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }
//
//				var file_name = string.slice(num_of_last_slash + 1, string.length);
//				var file_extension = file_name.slice(file_name.indexOf(".")).toLowerCase();
//				
//				//alert("Extension " + file_extension + " ");
////				if(file_extension==".html")
////				{
////					
////				   alert("Extension Not Allowed")	
////					
////				}
//				
//				alert('Sorry, uploading a file with the extension "' + file_extension + '" is not allowed.');
//				
//				
//				 
//				 
//				
//				return true;
//			}
//		}
//	}
//	return false;
//}

// Check for legal file extentions
function checkAllowFileExtensions(extnotallowed){
	if(!check_allow_extensions){ return false; }
	//alert("Checking File Name Extensions");
	
	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements['upfile_' + i].value != ""){
			if(!document.form_upload.elements['upfile_' + i].value.match(allow_extensions)){
				var string = document.form_upload.elements['upfile_' + i].value;
				var num_of_last_slash = string.lastIndexOf("\\");

				if(num_of_last_slash < 1){ num_of_last_slash = string.lastIndexOf("/"); }

				var file_name = string.slice(num_of_last_slash + 1, string.length);
				var file_extension = file_name.slice(file_name.indexOf(".")).toLowerCase();
           				
			 	
				
				//alert('Sorry, uploading a file with the extension "' + file_extension + '" is not allowed.');
				alert(extnotallowed + '(' + file_extension +').');
				return true;
			}
		}
	}
	return false;
}

// Make sure the user selected at least one file
function checkNullFileCount(chooseafile,plslogin){
	if(!check_null_file_count){ return false; }
  	
	var null_file_count = 0;
  	
	for(var i = 0; i < upload_range; i++)
	{
		if(document.form_upload.elements['upfile_' + i].value == ""){ null_file_count++; }
	}
  			

	    if(null_file_count == upload_range)
		{   
				
				alert(chooseafile);
		
			return true;
		}				
		else
		  {
			return false; 
		  }

	
    
}

// Make sure the user is not uploading duplicate files
function checkDuplicateFileCount(dupfile,dupfile1,dupfile2){
	if(!check_duplicate_file_count){ return false; } 	 
   
	var duplicate_flag = false;
	var file_count = 0;
	var duplicate_msg = "\n" + dupfile + "\n\n" ;
	var file_name_array = new Array();  
	upload_range = document.getElementById('selectslots').value;
	for(var i = 0; i < upload_range; i++)
	{		
		if(document.form_upload.elements['upfile_' + i].value != "")
		{
			
			
			var string = document.form_upload.elements['upfile_' + i].value;
			var num_of_last_slash = string.lastIndexOf("\\");

             
			 
			if(num_of_last_slash < 1)
			{ 
			num_of_last_slash = string.lastIndexOf("/");
		    }

			var file_name = string.slice(num_of_last_slash + 1, string.length);
			            
			file_name_array[i] = file_name;
		}
	}
  	
	var num_files = file_name_array.length;
       
	for(var i = 0; i < num_files; i++)
	{
	  	
		
		for(var j = 0; j < num_files; j++)
		{
			if(file_name_array[i] == file_name_array[j] && file_name_array[i] != null)
			
			{ 
			
			file_count++;
			
			}
		}
		if(file_count > 1)
		{
				
			duplicate_msg += dupfile1 + ' "' + file_name_array[i] + '" ' + dupfile2 + (i + 1) + ".\n";
			duplicate_flag = true;
		           
		
		}
		file_count = 0;
	}
       
	   
	if(duplicate_flag){ 
		
		alert(duplicate_msg);
		return true; 
	}
	else
	{
	return false;
	}
}

// Handle user pressing 'Enter' in the upload slots
function handleKey(event){
        if(document.all){ if(window.event.keyCode == 13){ return false; } }
        else{ if(event && event.which == 13){ return false; } }
}

// Submit the upload form
function uploadFiles(chooseafile,extnotallowed,fileformat,fileformat1,fileformat2,dupfile,dupfile1,dupfile2,uplinprog,initprog,errajax,err){
	if(checkFileNameFormat(fileformat,fileformat1,fileformat2)){ return false; }
	//if(checkDisallowFileExtensions()){ return false; }
	if(checkAllowFileExtensions(extnotallowed)){		
	
		return false;
		
		}
	if(checkNullFileCount(chooseafile)){ return false; }
	if(checkDuplicateFileCount(dupfile,dupfile1,dupfile2)){ return false; }
	
	var total_uploads = 0;
	
	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements['upfile_' + i].value != ""){ total_uploads++; }
	}
	
	//document.getElementById('total_uploads').innerHTML = total_uploads;
	document.form_upload.submit();
	//document.getElementById('upload_button').disabled = true;
	document.getElementById('upload_button').style.display = "none";
	document.getElementById('reset_button').style.display = "block";
	
	iniProgressRequest(uplinprog,initprog,errajax,err);
	
	for(var i = 0; i < upload_range; i++){ document.form_upload.elements['upfile_' + i].disabled = true; }	
}
function uploadFiles1(chooseafile,plslogin,extnotallowed,fileformat,fileformat1,fileformat2){
	
	if(checkFileNameFormat(fileformat,fileformat1,fileformat2)){ return false; }
	//if(checkDisallowFileExtensions()){ return false; }
	if(checkAllowFileExtensions(extnotallowed)){ return false; }
	if(checkNullFileCount(chooseafile,plslogin)){ return false; }
	if(checkDuplicateFileCount()){ return false; }
	
	var total_uploads = 0;
	
	for(var i = 0; i < upload_range; i++){
		if(document.form_upload.elements['upfile_' + i].value != ""){ total_uploads++; }
	}
	
	//document.getElementById('total_uploads').innerHTML = total_uploads;
	document.form_upload.submit();
	//document.getElementById('upload_button').disabled = true;
	document.getElementById('upload_button').style.display = "none";
	document.getElementById('reset_button').style.display = "block";
	
	iniProgressRequest();
	
	for(var i = 0; i < upload_range; i++){ document.form_upload.elements['upfile_' + i].disabled = true; }	
}

// Reset the file upload page 
function resetForm(){ location.href = self.location; }

// Hide the progress bar
function hideProgressBar(){ document.getElementById('progress_bar').style.display = "none"; }

// Initialize the file upload page
function iniFilePage(){
	resetProgressBar();
	
	for(var i = 0; i < upload_range; i++){
		document.form_upload.elements['upfile_' + i].disabled = false;
		document.form_upload.elements['upfile_' + i].value = "";
	}
	
	document.getElementById('progress_info').innerHTML = "";
	document.getElementById('upload_button').disabled = false;
	document.getElementById('progress_bar').style.display = "none";	
	document.form_upload.reset();
}

// Reset the progress bar
function resetProgressBar(){
	get_status_url = "";
	get_data_loop = false;
	seconds = 0;
	minutes = 0;
	hours = 0;
	info_width = 0;
	info_bytes = 0;
	cedric_hold = true;
	total_upload_size = 0;
	total_Kbytes = 0;
	
	document.getElementById('upload_status').style.width = '0px';
	document.getElementById('percent').innerHTML = '0%';
	//document.getElementById('uploaded_files').innerHTML = 0;
	//document.getElementById('total_uploads').innerHTML = '';
	document.getElementById('current').innerHTML = 0;
	document.getElementById('total_kbytes').innerHTML = '';
	//document.getElementById('time').innerHTML = 0;
	//document.getElementById('remain').innerHTML = 0;
	//document.getElementById('speed').innerHTML = 0;
}

// Stop the upload
function stopUpload(){
	try{ window.stop(); }
	catch(e){
		try{ document.execCommand('Stop'); }
		catch(e){} 
	}
}

// Add one upload slot
function addUploadSlot(num){
	if(upload_range < max_upload_slots){
		if(num == upload_range){
			var up = document.getElementById('upload_slots');
			var dv = document.createElement("div");
			
			dv.innerHTML = '<input type="file" name="upfile_' + upload_range + '" size="90" onChange="addUploadSlot('+(upload_range + 1)+')" onKeypress="return handleKey(event)">';
			up.appendChild(dv);
			upload_range++;
		}
	}
}

// Make the progress bar smooth
function smoothCedricStatus(){
	if(info_width < progress_bar_width && !cedric_hold){
		info_width++;
		document.getElementById('upload_status').style.width = info_width + 'px';
	}
	
	if(get_data_loop){ self.setTimeout("smoothCedricStatus()", info_time_width); }
}

// Make the bytes uploaded smooth
function smoothCedricBytes(){
	if(info_bytes < total_Kbytes && !cedric_hold){
		info_bytes++;
		document.getElementById('current').innerHTML = info_bytes;
	}
	
	if(get_data_loop){ self.setTimeout("smoothCedricBytes()", info_time_bytes); }
}

// Get the progress of the upload
function getProgressStatus(){
	var jsel = document.createElement('SCRIPT');
	
	jsel.type = 'text/javascript';
	jsel.src = get_status_url + "&rnd_id=" + Math.random();
	
	document.body.appendChild(jsel);
	
	if(get_data_loop){ self.setTimeout("getProgressStatus()", get_status_speed); }
}

// Calculate and display upload stats
function setProgressStatus(bytes_read, lapsed_time, uploaded_files){
	var byte_speed = 0;
	var time_remaining = 0;
	
	if(lapsed_time > 0){ byte_speed = bytes_read / lapsed_time; }
	if(byte_speed > 0){ time_remaining = Math.round((total_upload_size - bytes_read) / byte_speed); }
	
	if(cedric_progress_bar == 1){
		if(byte_speed != 0){
			info_time_width = Math.round(total_upload_size * 1000 / (byte_speed * progress_bar_width));
			info_time_bytes = Math.round(1024000 / byte_speed);
		}
		else{
			info_time_width = 200;
			info_time_bytes = 15;
		}
	}
	
	// Calculate percent finished
	var percent_float = bytes_read / total_upload_size;
	var percent = Math.round(percent_float * 100);
	var progress_bar_status = Math.round(percent_float * progress_bar_width);
	
	// Calculate time remaining
	var remaining_sec = (time_remaining % 60); 
	var remaining_min = (((time_remaining - remaining_sec) % 3600) / 60);
	var remaining_hours = ((((time_remaining - remaining_sec) - (remaining_min * 60)) % 86400) / 3600);

	if(remaining_sec < 10){ remaining_sec = '0' + remaining_sec; }
	if(remaining_min < 10){ remaining_min = '0' + remaining_min; }
	if(remaining_hours < 10){ remaining_hours = '0' + remaining_hours; }

	var time_remaining_f = remaining_hours + ':' + remaining_min + ':' + remaining_sec; 
	var Kbyte_speed = Math.round(byte_speed / 1024);
	var Kbytes_read = Math.round(bytes_read / 1024);
	
	if(cedric_progress_bar == 1){
		cedric_hold = false;

   		//if(progress_bar_status > info_width && Kbytes_read > info_bytes){ 
   		//	info_width = progress_bar_status;
   		//	info_bytes = Kbytes_read; 
   		//}
   		//else{ cedric_hold = true; }
   		
		info_width = progress_bar_status;
		info_bytes = Kbytes_read;
	}
	else{
		document.getElementById('upload_status').style.width = progress_bar_status + 'px';
		document.getElementById('current').innerHTML = Kbytes_read;
	}
	
	document.getElementById('percent').innerHTML = percent + '%';
	top.document.title =percent + '% -Completed';
	//document.getElementById('uploaded_files').innerHTML = uploaded_files;
	//document.getElementById('remain').innerHTML = time_remaining_f;
	//document.getElementById('speed').innerHTML = Kbyte_speed;
}


// Calculate the time spent uploading
function getElapsedTime(){
	seconds++;
    	
	if(seconds == 60){
		seconds = 0;
		minutes++;
	}
    	
	if(minutes == 60){
		minutes = 0;
		hours++;
	}
    	
	var hr = "" + ((hours < 10) ? "0" : "") + hours;
	var min = "" + ((minutes < 10) ? "0" : "") + minutes;
	var sec = "" + ((seconds < 10) ? "0" : "") + seconds;
    	
	//document.getElementById('time').innerHTML = hr + ":" + min + ":" + sec;
    	
	if(get_data_loop){ self.setTimeout("getElapsedTime()", 1000); }
}

// Create the AJAX request
function createRequestObject(errajax){
	var req = false;
  	
	if(window.XMLHttpRequest){
		req = new XMLHttpRequest();
		
		if(req.overrideMimeType){ req.overrideMimeType('text/xml'); }
	}
	else if(window.ActiveXObject){
		try{ req = new ActiveXObject("Msxml2.XMLHTTP"); }
		catch(e){
			try{ req = new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(e){}
		}
	}
	
	if(!req){
		document.getElementById('progress_info').innerHTML = errajax + " ";
		return false;
	}
	else{ return req; }
}

// Initialize the progress bar
function iniProgressRequest(uplinprog,initprog,errajax,err){
	var req = false;
	req = createRequestObject(errajax);
	
	if(req){
		document.getElementById('progress_info').innerHTML = initprog + " ";
		req.open("GET", path_to_ini_status_script + "&rnd_id=" + Math.random(), true);
		req.onreadystatechange = function(){ iniProgressResponse(req,uplinprog,err); };
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send(null);
	}
}

// Initialize the progress bar
function iniProgressResponse(req,uplinprog,err){
	if(req.readyState == 4){
		if(req.status == 200){
			var xml = req.responseXML;
			
			if(xml.getElementsByTagName('error_status').item(0).firstChild.nodeValue == 1){
				document.getElementById('progress_info').innerHTML = xml.getElementsByTagName('error_msg').item(0).firstChild.nodeValue;
				
				if(xml.getElementsByTagName('stop_upload').item(0).firstChild.nodeValue == 1){ stopUpload(); }
			}
			else{
				get_status_speed = xml.getElementsByTagName('get_data_speed').item(0).firstChild.nodeValue;
				total_upload_size = xml.getElementsByTagName('total_bytes').item(0).firstChild.nodeValue;
				total_Kbytes = Math.round(total_upload_size / 1024);
				get_status_url = "uu_get_status.php?temp_dir_sid=" + xml.getElementsByTagName('temp_dir_sid').item(0).firstChild.nodeValue + "&start_time=" + xml.getElementsByTagName('start_time').item(0).firstChild.nodeValue + "&total_upload_size=" + xml.getElementsByTagName('total_bytes').item(0).firstChild.nodeValue;
				get_data_loop = true;
				
				if(document.form_upload.embedded_upload_results && document.form_upload.embedded_upload_results.value == 1){
					document.getElementById('upload_div').style.display = "none";
				}
				
				document.getElementById('progress_bar').style.display = "";
				document.getElementById('total_kbytes').innerHTML = total_Kbytes + " ";
				document.getElementById('progress_info').innerHTML = uplinprog + " ";
				
				getElapsedTime();
				getProgressStatus();
				
				if(cedric_progress_bar == 1){
					smoothCedricBytes();
					smoothCedricStatus();
				}
			}
		}
		else{
			document.getElementById('progress_info').innerHTML = err + " " + req.status + " " + req.statusText;
			//stopUpload();
		}
	}
}