//our array of valid file types.
aTypes = new Array( '.doc', '.rtf', '.txt' , '.pdf');

//return the xmlHTTP object for ajax
function getXmlHttpObject(){
	var xmlHttp;
		try {
	  	// Firefox, Opera 8.0+, Safari
	  	xmlHttp=new XMLHttpRequest();
	  	} catch (e) {
	  		// Internet Explorer
	  	try {
	    	xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    }catch (e){
	    	try{
	      		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
	      	} catch (e){
	      		alert("Your browser does not support AJAX!");
	      		return false;
	      	}
	    }
	  }
	  return xmlHttp;
}

//handle form validation
function upload(){
	//how many separate files are we uploading
	var l  = document.file_0['userFile[]'].length;
	//this flag indicates we have at least one file to upload
	var blnSomething = false;
	//if there is only one file, l will be undefined
	if (l > 1) {
		//get an array of all the files - there are more than one
		var aFiles = document.file_0['userFile[]'];
		//run through the file input fields backwards, getting rid of any that are empty
		for( var x = l - 1; x > -1; x-- ) {
			if( t = aFiles[x] ) {
				//remove the input if it is empty
				if(t.value == '') {
					removeInput( t );
				} else {
					//make sure the file extension is valid
					blnSomething = checkNewZip( t );
					//check the file name is valid characters only
					if( !checkNonValidCharacters( getFileName( t.value ) ) ){
						alert('non alpha numeric characters used in the  filename '+"\n\n"+getFileName( t.value ));
						return false;
					}
				}//end else
			}//end if
		}//end for
	} else {
		//we only have one file to upload
		if( document.file_0['userFile[]'].value=='' ){
			//do nothing 
			return false;
		}else{
			//check the file name is valid
			if( !checkNonValidCharacters( getFileName( document.file_0['userFile[]'].value ) ) ){
				m='non alpha numeric characters used in the filename'+"\n\n"
				m+=getFileName( document.file_0['userFile[]'].value );
				alert( m );
				return false;
			}
			//check the extension is valid
			blnSomething = checkNewZip( document.file_0['userFile[]'] );
		}
	}
	//finally do the upload if we have at least one file, reload otherwise
	if (blnSomething) {
		updateStatus();
		document.file_0.submit();
	}else{
		document.location = 'uploaderIndex.php';
	}
	//showDetails(l);
	
}

//prevent user uploading files with spaces and other funny stuff
function checkNonValidCharacters( strUnclean ){
	blnClean = true;
	//reg ex for non-valid characters
	if ( strUnclean.match(/[^-_a-zA-Z0-9\.]/) ) {
		blnClean = false;
	}
	return blnClean;
}

//return a filename from a file path
function getFileName( strName ){
	//get the last directory separator
	x = strName.lastIndexOf( '\\' );
	//get the filename only
	return( strName.substr( x+1 ) );
}

//return a file extension including the dot
function getExtension( n ){
 	r = n.lastIndexOf('.');
 	return( n.substr( r ) );
}

//is this used?
function showDetails(l){
	alert('in showDetails, do not delete this function');
	var xmlHttp = getXmlHttpObject();
	var obj = document.getElementById("msg");
	obj.innerHTML = "";
	var serverPage = "getDetails.php?l="+l;
	xmlHttp.open("GET", serverPage ,true);
	  xmlHttp.onreadystatechange=function(){
	    if(xmlHttp.readyState==4){
	      obj.style.display="block";
	      obj.innerHTML=xmlHttp.responseText;
	    }
	   }
	  xmlHttp.send(null);
}

//show the messages returned from the file upload
function updateStatus(){
	document.getElementById('msg').className = 'showmsg';
}

//create and add to the dom tree
function create( elem ){
	return document.createElementNS ? 
		document.createElementNS( 'http://www.w3.org/1999/xhtml', elem ) :
		document.createElement( elem );
}
var count = 0;

//add an extra file input field to the form, together with a remove button
function addFile(){
	count++;
	//create a div to hold the to-be-created input in
	var NewDiv = create( "div" );
	NewDiv.id='input_'+count;
	//create a new input and assign id, name, class and type
	var fInput = create( "input" );
	fInput.id="userFile[]";
	fInput.name="userFile[]";
	fInput.type="file";
	fInput.className = "butClass";
	
	//add the new input to the new div
	NewDiv.appendChild(fInput);
	//create a link to remove this input field if required.
	sLink = create('a');
	sLink.setAttribute('href', 'javascript:remove("input_'+count+'");');
	sLinkText = document.createTextNode('(remove)');
	sLink.appendChild( sLinkText );
	sLink.className = 'tiny';
	//add the newly created link to the newly created div
	NewDiv.appendChild( sLink );
	//this is the form
	var par = document.file_0;
	var but = document.file_0.send;
	//insert the new div at the end of the file before the button
	par.insertBefore( NewDiv, but );
	
	//add an onchange event listener
	if( fInput.addEventListener ){
		//ff
		fInput.addEventListener('change', eventHandler, false);
	} else if( fInput.attachEvent ){
		//ie
		fInput.attachEvent('onchange', eventHandler);
	}
	
}

//called onchange - validates the value in the file input field 
//and adds it's textual value onscreen for a visual aid.
function eventHandler( elem ){
	//find out what fired this event, changes in ie and ff
	var theTarget = elem.currentTarget;
	if(!theTarget){
		theTarget = elem.srcElement;
	}
	//3 is a textnode and 4 is CDATA_SECTION_NODE
	if( theTarget && ( theTarget.nodeType == 3 || theTarget.nodeType == 4 ) ) {
  		theTarget = theTarget.parentNode;
	}
	//as this function can be called from the hard-coded first input element
	//on index.php, target won't be anything but the elem, so if it's still not set by the 
	//time we have checked for IE and FF differences we should assign theTarget to elem
	if( !theTarget ){
		theTarget = elem;
	}
	var valid = checkNewZip( theTarget );
	if( !valid ){
		return;
	}
	var txt = theTarget.value;
	var inputVal =  theTarget.parentNode.id ;
	var y = inputVal.lastIndexOf('_');
	var countToUse = inputVal.substr( y+1 );
	//show the chosen filename devoid of path information for visual aid
	//create a div to hold the new filename in 
	var displayDiv = document.getElementById('file'+countToUse);
	if (!displayDiv) {
		var displayDiv = create("div");
		displayDiv.id = "file" + countToUse;
	}
	var p = document.file_0;
	//isolate the filename from the filepath
	usethis = getFileName( txt );
	displayDiv.innerHTML = ' filename added:<strong> '+usethis+'</strong>';
	var hidden = document.getElementById("fileName");	
	hidden.value = usethis;
	//stop id displaying an empty filename
	if( usethis.length>1 ){
		theTarget.parentNode.appendChild( displayDiv );
		//p.insertBefore(displayDiv, document.file_0.send);
	}
}

//validate the format of the file extension
//deprecated use checkNewZip
function checkZip( elem ){
	bValid = false;
 	var n = elem.value;
 	r = n.lastIndexOf('.');
 	fileType = n.substr( r );
 	for( var i=0; i<aTypes.length; i++ ){
 		if( aTypes[i] == fileType ){
			bValid = true;
		}
 	}
 	if( !bValid ){
 		elem.value='';
 		alert('doc, rtf, txt, pdf files only'+"\n"+'thank you ');
		elem.focus();
 }
 return bValid;
}

//validate file extension against list of accepted extensions
function checkNewZip(elem){
	bValid = false;
	fileType = getExtension( elem.value );
 	for( var i=0; i<aTypes.length; i++ ){
 		if( aTypes[i] == fileType ){
			bValid = true;
		}
 	}
	
 	if( !bValid ){
 		elem.value='';
 		alert('doc, rtf, txt, pdf files only'+"\n"+'thank you ');
		elem.focus();
	 }
	 return bValid;
}

//used to remove one input element at a time based on use clicking remove link
function remove( c ){
	counter = c.lastIndexOf('_');
	num = c.substr( counter+1 );
	elem = document.getElementById( c );
	//elem.innerHTML='';
	if( elem ) elem.parentNode.removeChild( elem );
	textElem = document.getElementById( 'file'+num);
	if( textElem )textElem.parentNode.removeChild( textElem );
}

//remove all empty input fields and their remove links in one go
//upon uploading
function removeInput( elem ){
	if( elem ){
		par = elem.parentNode;
		while( par.firstChild ){
			par.removeChild( par.firstChild );
		}
	}
}

var selected = false;

//select all files for deletion in file manager
function selectAll(){
	var f = document.deleteFileForm['files[]'];
	txt = selected ? 0 : 1;
	var buttonText = !selected ?'unselect all' : 'select all';
    for( z=0; z<f.length; z++ ){	
		h=f[z];	
		if (h.disabled == false && h.checked !=txt){ 
			h.checked=txt;
		}
	}
	selected = txt;
	document.getElementById( 'toggler' ).value=buttonText;
}

//confirm they want to delete
function checkDeletion( theForm ){
	if( confirm( 'are you sure?  This is irreversible.' ) ){
		theForm.submit();
	}else{
		var f = theForm['files[]'];
		for( var z = 0; z<f.length; z++ ){
			f[z].checked = 0;
		}
	}
	return false;
}

//make the table holding deleted file names visible.
function showDeletedFiles(){
	var delTable = document.getElementById('deletedTable');
	if( ! delTable.style.display ){
		delTable.style.display='block';
		return;
	}
	if( delTable.style.display=='block' ){
		delTable.style.display='none';
		return;
	}
	delTable.style.display='block';
}

//display the help message 
function showMsg(){
	var msg = 'Use this button to add'+"\n";
	msg +='another file upload box'+"\n\n";
	msg +='it will appear beneath the first'+"\n";
	msg +='and can be removed';
	alert( msg );
}


function close(){
	document.getElementById('msg').className = 'msg';
}

function overrideExistingFiles(){
	var e = document.existingFileForm.elements;
	var strParam = '';
	var aFiles = document.existingFileForm['remove[]'];
	//this won't be an array if there is only one file
	var l = aFiles.length;
	if( !l ){
		if( aFiles.checked){
			strParam+='f_'+aFiles.value+'=ow&';
		}else{
			strParam+='f_'+aFiles.value+'=del&';
		}
	}else{
		for( var x=0; x<l; x++ ){
			if(aFiles[x].checked){
				strParam+='f_'+aFiles[x].value+'=ow&';
			}else{
				strParam+='f_'+aFiles[x].value+'=del&';
			}
		}	
	}
	var u = document.getElementById('user_id');
	strParam+='user_id='+u.value;
	var output = parent.document.getElementById('msg');
	output.innerHTML = '';
	var url = "manageFileDuplicates.php";
	http = getXmlHttpObject();
	http.open("POST", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", strParam.length);
	http.setRequestHeader("Connection", "close");
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			output.innerHTML = http.responseText;
		}
	}
	http.send(strParam);
	var h = document.getElementById('msg').clientHeight;
	if( h ){
		var lh = document.getElementById('layout').style.height;
		document.getElementById('layout').style.height=lh+h+2+'px';	
	}
	
	
	//alert( strParam );
	
}

function setCookie(cookieName, cookieValue ) {
	//double check
	//if( cookieValue = '--area--' ) alert('here');
	if( !cookieValue || cookieValue == 'undefined' ){
		var s = document.getElementById( 'cookieSetter' );
		var so = s.selectedIndex;
		cookieValue = s.options[so].text;
	}
	var theCookie = readCookie( cookieName );
	if( theCookie == cookieValue ){
		//reload
		window.parent.location.href = 'uploaderIndex.php';
	}
 	var today = new Date();
 	var expire = new Date();
	endDate = 1825*24*60*60*1000;
 	expire.setTime(today.getTime()+ endDate);
 	document.cookie = cookieName+"="+escape(cookieValue)+ ";expires="+expire.toGMTString();
	//reload
	window.parent.location.href = 'uploaderIndex.php';
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function showConfiguration(task){
	var f = document.getElementById('uploadFrame');
	if( !f ){
		f = parent.document.getElementById( 'uploadFrame' );
	}
	var l = document.getElementById('configurator_link');
	var lt = document.getElementById('layout');
	var md = document.getElementById( 'mainDiv' );
	//there are some height issues with divs I'd like to resolve
	if( !lt ){
		lt = parent.document.getElementById( 'layout' );
		md = parent.document.getElementById( 'mainDiv' );
	}
	
	f.className =task;
	if( task =='showMsg' ){
		var hlt = lt.clientHeight;
		var mdh = md.clientHeight;
		hlt = hlt+205;
		mdh = mdh+190;
		lt.style.height = hlt+'px';
		md.style.height = mdh+'px';	
		f.src='setArea.html';
		l.href='#'
	}else{
		lt.style.height='auto';
		md.style.height='auto';
		f.src='upload.php';
	}
	return false;
}
