/*================================================================================= 
 XAJAX_UPLOAD.JS 
 VERSION:1.0.1
 DESCRIPTION:  THIS IS THE REQUIRED JAVASCRIPT FILE FOR  XAJAX UPLOAD:UPLOADER WITH PROGRESS BAR VERSION:1.0.1
 AUTHOR: JEREMY M. DILL
 REQUIREMENTS:  SEE UPLOAD_CONFIG_INC.PHP
================================================================================= 
* Copyright (c) 2007 JEREMY M. DILL (trydobe.com)
* This work is licensed under a Creative Commons Attribution-Share Alike 3.0  License
* http://creativecommons.org/licenses/by-sa/3.0/
* AUTHOR'S NOTE: THANKS TO THE OTHER DEVELOPERS OUT THERE WHO ESTABLISHED THE FOUNDATIONS OF THIS WORK.  
									BITS AND PIECES OF CONTRIBUTIONS FROM VARIOUS SOURCES INCLUDING THE FOLLOWING:
									http://www.raditha.com/megaupload/
									http://lists.geeklog.net/pipermail/geeklog-cvs/2005-June/000525.html
									http://labs.beffa.org/w2box/demo/
									http://tomas.epineer.se/archives/3
									http://jszen.blogspot.com/2005/05/secure-iframe-gotcha.html
									http://obokaman.obolog.com/mensaje/1596
									http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
									(sorry if any of these links become invalid)								
================================================================================= */
var count=0;
var numfiles=0;
var filecount=0;
var frameSet=false;
var frameAdv=0;
//GLOBAL DECLARATIONS
//var sid,cgiPath,maxFile,maxNumFiles,autoFirst,uploadDir,cgiDebug,uploadSpeed,extMode,blankHTMLPath,showMax;
var sid = "";
var cgiPath = "/cgi-bin/upload.cgi";
var maxFile = 1600000;
var maxNumFiles = 1;
var autoFirst = 1;
var uploadDir = "cgi-bin/uploaddir/";
var cgiDebug = 0;
var uploadSpeed = 10;
var extMode = 1;
var blankHTMLPath = "/foo.html";
var showMax = 1;
var filetypes = "jpg,gif,png,jpeg";

//RESET EVERYTHING BACK TO THE START.  SID WILL REMAIN THE SAME.
function startOver(){
	xajax_getSid();
	document.getElementById("progress_bar").style.width="0%";
	document.getElementById("load_bar").style.display="block";
	document.getElementById("uldSubmit").disabled=true;
	if (autoFirst)	document.getElementById("uldSubmit").style.display="none";	
	document.getElementById("uldCancel").style.display="none";
	if(showMax) document.getElementById("moreinfo1").style.display="block";
	count=0;
	numfiles=0;
	filecount=0;
	addfail=false;
	bastardChild(document.getElementById("file_inputs"));
	bastardChild(document.getElementById("file_list"));
	addFileInput(false);
	makeIFrame() ;
}

// SUBMIT THE FORM AND START MONITORING WITH XAJAX
function postIt()
{
	document.getElementById("file"+eval(numfiles+1)).disabled=true;
	document.getElementById("uldCancel").style.display="block";
	document.getElementById("uldSubmit").disabled=true;
	document.getElementById("moreinfo1").style.display="none";	
	document.getElementById("moreinfo2").style.display="none";	
	document.getElementById("okstatus").style.display="none";		
	document.getElementById("progress_bar").style.display="block";
	document.getElementById("loadtext").innerHTML="Upload Initiated.";
	var frmFileUpload = document.getElementById('file_upload');
	frmFileUpload.action=cgiPath+"?sid="+sid+"&amp;maxfile="+maxFile+"&amp;cgidebug="+cgiDebug+"&amp;speed="+uploadSpeed+"&amp;temp_dir="+uploadDir;
	frmFileUpload.submit();
	linksArr=getElementsByAttribute(document.getElementById("file_list"), "a","id");
	for(var i=0; i<linksArr.length; i++){
		var upmsg = document.createElement("span");
		upmsg.className="upi";
		upmsg.innerHTML="-uploading";
		linksArr[i].parentNode.appendChild(upmsg); //add upload indicator
		linksArr[i].parentNode.removeChild(linksArr[i]); //remove delete link
	}
	getProgress();
}

// CALL THE XAJAX UPLOAD HANDLER.
function getProgress() {
	var outputId = (document.getElementById("outputId") != null) ? document.getElementById("outputId").value : "mypics";
	var user_id = (document.getElementById("user_id") != null) ? document.getElementById("user_id").value : "0";
	var poster_id = (document.getElementById("poster_id") != null) ? document.getElementById("poster_id").value : "0";
	var x = (document.getElementById("x") != null) ? document.getElementById("x").value : "0";
	var y = (document.getElementById("y") != null) ? document.getElementById("y").value : "0";
	var successorFunction = (document.getElementById("successorFunction") != null) ? document.getElementById("successorFunction").value : "loadImagesList";
	if(frameSet){
		xajax_uploadHandler(sid, count, outputId, successorFunction, user_id, poster_id, x, y);
		//xajax_uploadHandler(sid, count);
		count+=1;		
	} else {
		xajax_uploadHandler(sid, -1, outputId, successorFunction, user_id, poster_id, x, y);  // CANCELLED BY USER
		//xajax_uploadHandler(sid, -1);  // CANCELLED BY USER
	}
}

// ADD FILE TO THE LIST OF FILES TO BE UPLOADED AND DISPLAY FILENAME IN A LIST.
function addFileInput(elem) {
		if (maxNumFiles==filecount) {
			document.getElementById("okstatus").style.display="block";
			document.getElementById("okstatus").className="warning";
			document.getElementById("okstatus").innerHTML="<b>Maximum number of  files is "+maxNumFiles+".</b><br />Please remove a file using before attempting to add another."
			f=document.getElementById("file"+(numfiles+1));
			f.parentNode.removeChild(f);
		} else {
			if ( elem != false)
				{
				numfiles+=1;
					filepath = elem.value.split("\\");
					filename = filepath[filepath.length-1];
					// CHECK FOR APPROPRIATE EXTENSIONS,
					if (filetypes!=""){
						extensionpath = filename.split(".");
						extension = extensionpath[extensionpath.length-1];
						ftypes=","+filetypes.toLowerCase()+",";
						tst=ftypes.indexOf(","+extension.toLowerCase()+",");
							if ( (extMode==1&&(tst==-1)) || (extMode==0&&(tst>=0)) ){ 
								if (extMode==0){
								  document.getElementById("okstatus").innerHTML="<b>Invalid filetype for &#8220;"+filename+"&#8221;. </b>";
								} else {
								  document.getElementById("okstatus").innerHTML="<b>Invalid filetype for &#8220;"+filename+"&#8221;. </b><br />Allowed file types include only "+filetypes+".";
								}
							addfail=true;
							}
					} //CLOSE if (filetypes
					// CHECK FOR DUPE FILENAMES
						linksArr=getElementsByAttribute(document.getElementById("file_list"), "span","id");
						 for(var i=0; i<linksArr.length; i++){
							if (linksArr[i].id==filename) {
								addfail=true;
								document.getElementById("okstatus").innerHTML="<b>Cannot add file &#8220;"+filename+"&#8221;.</b><br /> A file with that name was already added to the list.";
							}
						 }
					if (addfail){
						document.getElementById("okstatus").style.display="block";
						document.getElementById("okstatus").className="warning";
						filesInList=checkForChild(document.getElementById("file_list"));
						if(filesInList<1) document.getElementById("uldSubmit").disabled = true;
						numfiles=numfiles-1;
						addfail=false;
						return false;
					} else {
						elem.style.display="none";
						var newNode = document.createElement("li");
						document.getElementById("file_list").appendChild(newNode);
						newNode.innerHTML ="<span id="+filename+">"+filename+"</span> <a id='del"+numfiles+"' name='del"+numfiles+"' href='javascript:;' onclick='delFile(this,"+numfiles+")' class='delete_link'>[x]</a>";
						document.getElementById("okstatus").style.display="none";
						if (maxNumFiles>1) document.getElementById("moreinfo2").style.display="block";	
						document.getElementById("uldSubmit").disabled = false;
						filecount+=1;
					}
				}
		}
			var newNode = document.createElement("input");
			newNode.name="file"+eval(numfiles+1);
			newNode.id="file"+eval(numfiles+1);
			newNode.size="30";
			newNode.onchange=function(){addFileInput(this);}
			newNode.type="file";
			document.getElementById("file_inputs").appendChild(newNode);
			if (autoFirst&&elem!=false) postIt();			
}

//DELETES A FILE ELEMENT FROM VIEW, AND ITS HIDDEN FORM COUNTERPART.
function delFile (node,filenum)
{
	f=document.getElementById("file"+filenum);
	node.parentNode.parentNode.removeChild(node.parentNode);
	if(f.parentNode.removeChild(f)) {
		filecount=filecount-1;
	}
	document.getElementById("okstatus").style.display="none";
	filesInList=checkForChild(document.getElementById("file_list"));
	if(filesInList<1) document.getElementById("uldSubmit").disabled = true;
}

//REMOVES ALL CHILDREN FROM A NODE
function bastardChild(node)
    {
        while (node.childNodes.length)
        {
            node.removeChild(node.childNodes[0]);
        }
    }

//CHECK FOR EXISTENSE OF IMMEDIATE (1ST LEVEL) CHILD NODES AND RETURN NUMBER OF FOUND
function checkForChild(node)
    {
		var numnodes=0;
        while (numnodes<node.childNodes.length)
        {
            numnodes+=1;
        }
		return numnodes;
    }
	

// BUILD THE IFRAME TO SUBMIT INTO
function makeIFrame() {
if(cgiDebug!=1){ 
        d_nested = document.getElementById("destination"+frameAdv);
        if (d_nested) throwaway_node = document.forms['file_upload'].removeChild(d_nested);
 } 
frameAdv+=1;
var iframe = document.createElement("iframe");
iframe.setAttribute("src", blankHTMLPath);
iframe.setAttribute("id","destination"+frameAdv);
iframe.setAttribute("name","destination"+frameAdv);
 if(cgiDebug==1) { 
	iframe.setAttribute("height", "150px");
	iframe.setAttribute("width", "100%");
	iframe.setAttribute("frameBorder", "1");
} else { 
	iframe.setAttribute("height", "0");
	iframe.setAttribute("width", "0");
	iframe.setAttribute("frameBorder", "0");
 } 
if(document.forms['file_upload'].appendChild(iframe)) frameSet=true;
document.forms['file_upload'].target="destination"+frameAdv;

// FIX FOR IE.  ATTRIBUTES FOR NAME AND ID ARE NOT SET USING DOM.
if (window.frames[window.frames.length-3] != null) {
	window.frames[window.frames.length-3].id=iframe.id;
	window.frames[window.frames.length-3].name=iframe.name;
} else if (window.frames[window.frames.length-2] != null) {
	window.frames[window.frames.length-2].id=iframe.id;
	window.frames[window.frames.length-2].name=iframe.name;
} else {
	window.frames[window.frames.length-1].id=iframe.id;
	window.frames[window.frames.length-1].name=iframe.name;
}
// END FIX
} 

// CANCEL BUTTON ACTION
function cancel() {
	if(frameSet){
			frameSet=false;
	}
	return false;
}

/*
    Copyright Robert Nyman, http://www.robertnyman.com
    Free to use if this text is included
*/
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
    var oCurrent;
    var oAttribute;
    for(var i=0; i<arrElements.length; i++){
        oCurrent = arrElements[i];
        oAttribute = oCurrent.getAttribute(strAttributeName);
        if(typeof oAttribute == "string" && oAttribute.length > 0){
            if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
                arrReturnElements.push(oCurrent);
            }
        }
    }
    return arrReturnElements;
}
