/*
	File: upload.js
	
	Title: upload progressbar plugin for xajax
	
*/

/*
	@package uploadProgress plugin
	@version $Id: 
	@copyright Copyright (c) 2007 by Steffen Konerow (IE)
	@license http://www.xajaxproject.org/bsd_license.txt BSD License
*/

/*
	Class: xajax.ext.uploadProgress
	
	This class contains all functions for using uploading files with xajax.
	
*/

	try 
	{
		if (undefined == xajax.ext)
			xajax.ext = {};
	} catch (e) 
	{
		alert("Could not create xajax.ext namespace");
	}

	try 
	{
		if (undefined == xajax.ext.uploadProgress)
			xajax.ext.uploadProgress = {};
	} catch (e) 
	{
		alert("Could not create xajax.ext.comet namespace");
	}

	// create Shorthand for xajax.ext.comet
	xjxUp = xajax.ext.uploadProgress;

	xjxUp.config	=	{};
	xjxUp.iframes	=	{};
	xjxUp.inputs	=	{};
	xjxUp.uploads	= 	{};
	xjxUp.StartTime	= 	null;
	
	xjxUp.configure = function(sName,mValue) 
	{
		xjxUp.config[sName]=mValue;
		
		if ( 'UploadProgressType' == sName )
		{
			xajax.js.includeScriptOnce({data:xjxUp.config.UploadScriptPath + 'xjxUp.' + xjxUp.config.UploadProgressType + '.js'});
		}
	}

	xjxUp.getConf = function(sName) 
	{
		return xjxUp.config[sName]=mValue;
	}

	
	xjxUp.processUpload = function(formID,sMethod,oParams) 
	{
		xjxUp.StartTime = new Date();
		
		eval( 'oRequest = new xjxUp.' + xjxUp.config.UploadProgressType + "();" );
		
		var oForm = xajax.$(formID);
		var pid = this.tools.getPid();
		
		var i = 0;
		for (a in xjxUp.uploads) i++;		
		
		if (1 <= i || "undefined" != typeof xjxUp.uploads[pid]) return;
		
		oRequest.prepareRequest(oForm,pid,sMethod);
		oRequest.send(pid,oParams);
		xjxUp.uploads[pid]=oRequest;
		if ("function" == typeof xjxUp.onRequest) xjxUp.onRequest();
		return false;
	}




	/* -----------------------------------------------------------------------------------
	tools & helper functions
	----------------------------------------------------------------------------------- */

	xjxUp.tools={};
	
	xjxUp.tools.manageResponse = function(pid,response) {
		
		var xx = xajax;
		var xt = xx.tools;
		var xcb = xx.callback;
		var gcb = xcb.global;
		
		var oRet = oRequest.returnValue;
		
		if (response) {
			var cmd = (new DOMParser()).parseFromString(response, "text/xml");
			var seq=0;
			var child = cmd.documentElement.firstChild;
			xt.xml.processFragment(child, seq, oRet, oRequest);
			if (null == xx.response.timeout)
				xt.queue.process(xx.response);
		
		}
		xjxUp.uploads[pid].completeRequest();
		if ("function" == typeof xjxUp.onComplete) xjxUp.onComplete();
	}
	
	xjxUp.tools.getPid = function() 
	{
		var pid_str = "";
		for (i=0;i<=3;i++) {
			var pid = 0;
			pid = Math.random();
			while( Math.ceil(pid).toString().length<8) 
			{
				pid *= 10;
			}
			pid = Math.ceil(pid).toString();		
			pid_str = pid_str+pid.toString();
		}
		return pid_str;
	}
	
	xjxUp.tools.createIframe = function(pid,oForm) 
	{

		var sTarget = xjxUp.config.UploadProgressTarget+pid;
		var iframe = document.createElement("iframe");
		iframe.setAttribute("id",sTarget);
		iframe.setAttribute("name",sTarget);
		iframe.setAttribute("width","0");
		iframe.setAttribute("height","0");
		iframe.setAttribute("border","0");
		//iframe.setAttribute("style","width: 100px; height: 100px; border: none;");
		iframe.setAttribute("style","width: 0; height: 0; border: none;display:none");
		oForm.appendChild(iframe);
		// IE fix
		window.frames[sTarget].name=sTarget; 

		return iframe;
	}
	
	xjxUp.tools.formatBytes = function(bytes) 
	{

		var ret = {};
		if (bytes / 1204  < 1024) {
		    return (Math.round(bytes / 1024 * 100)/100).toString()+ " KB";
		} else {
		    return (Math.round(bytes / 1024 / 1024 * 100)/100).toString()+ " MB";
		}
		return ret;		
	}

	xjxUp.tools.showProgress = function(upload) 
	{

		var bar = xajax.$('xjxExtUpBar');
		var barTxt = xajax.$('xjxExtUpBarTxt');
		var rateEl = xajax.$('xjxExtUpRate');

		switch (upload.state) 
		{
			case 'fake' :
							xajax.$('xjxExtUpBytes').innerHTML = 'uploading';
							bar.style.width = upload.percent + '%';
							break;
			case 'waiting' :
							break;
			
			case 'uploading':
			
							step = upload.data.bytes_uploaded / (upload.data.bytes_total / 100);
							var rate = 0;
							
							if (null != upload.data.bytes_uploaded && 0 < upload.data.bytes_uploaded) 
							{
								xajax.$('xjxExtUpBytes').innerHTML = xjxUp.tools.formatBytes(upload.data.bytes_uploaded) + "/" + xjxUp.tools.formatBytes(upload.data.bytes_total);
							}
							
							rate = xjxUp.tools.formatBytes( upload.data.speed_average ).toString() + '/s';
							
							rateEl.innerHTML = rate;
							bar.style.width = Math.round(step) + '%';
							barTxt.innerHTML = Math.round(step) + '%';
						
							break;

			case 'starting':
							bar.style.width = '1px';
							barTxt.innerHTML = '0%';
							break;			
			case 'done':
			
							bar.style.width = '100%';
							barTxt.innerHTML = '100%';
							xajax.$('xjxExtUpRate').parentNode.style.display='none';
							xajax.$('xjxExtUpBytes').parentNode.style.display='none';
							break;
			
			case '412':
							var msg = upload.msg ? upload.msg : 'This Fileformat is not supported';
							xajax.$('xjxExtUpBytes').innerHTML = msg;
							break;
			case '413':
							var msg = upload.msg ? upload.msg : 'Error, file too big';
							xajax.$('xjxExtUpBytes').innerHTML = msg;
							break;
		}
		
	}

	xjxUp.transform = function(file_target, max )
	{
	
		/*
			create markup automatically
			remove list_target 
			list_target = xajax.$('xjxExtUpFiles' ),
		
		*/
	
		/*var new_btn = document.createElement('div');
		new_btn.className = 'xjxExtUpfakefile';

		var image = document.createElement('img');
		image.src='img/browse.gif';
		
		new_btn.appendChild(image);
		var new_list = document.createElement('div');

		file_target.parentNode.appendChild(new_list);
		list_target = new_list;

		var clone = new_btn.cloneNode(true);
		file_target.parentNode.appendChild(clone);
	
		file_target.parentNode.style.position='relative';
		file_target.parentNode.style.width='300px';
		file_target.parentNode.style.height='30px';
	
		this.list_target = list_target;
		this.count = 0;
		this.name = file_target.name;
		this.id = 0;
		if( max )
		{
			this.max = max;
		} 
		else 
		{
			this.max = -1;
		};
		
		this.addElement = function( element )
		{
	
			if( element.tagName == 'INPUT' && element.type == 'file' )
			{
				if (1 != this.max) 
				{
					element.name = this.name +"[]";
					this.id++;
				} else {
					element.name = this.name;
				}
				element.multi_selector = this;
				element.className = 'file hidden';
				element.onchange = function()
				{
					var new_element = document.createElement( 'input' );
					new_element.type = 'file';
					this.parentNode.insertBefore( new_element, this );
					this.multi_selector.addElement( new_element );
					this.multi_selector.addListRow( this );
					this.style.position = 'absolute';
					this.style.left = '-1000px';
	
				};
				if( this.max != -1 && this.count >= this.max )
				{
					element.disabled = true;
				};
				this.count++;
				this.current_element = element;
			} 
			else 
			{
				alert( 'Error: not a file input element' );
			};
		};
	
		this.addListRow = function( element )
		{
			var new_row = document.createElement( 'div' );
			new_row.className="xjxExtUpRow";	
			var new_row_button = document.createElement( 'input' );
			new_row_button.type = 'button';
			new_row_button.className = 'xjxExtUpDelete';
			new_row.element = element;
			new_row_button.onclick= function()
			{
				this.parentNode.element.parentNode.removeChild( this.parentNode.element );
				this.parentNode.parentNode.removeChild( this.parentNode );
				this.parentNode.element.multi_selector.count--;
				this.parentNode.element.multi_selector.current_element.disabled = false;
				return false;
			};
			var new_row_clear = document.createElement( 'div' );
			new_row_clear.className="xjxExtUpClear";
			var new_row_txt = document.createElement( 'div' );
			new_row_txt.innerHTML = this.elipse(element.value);
			new_row_txt.className="xjxExtUpLabelFile";
			new_row.appendChild( new_row_txt );
			new_row.appendChild( new_row_button );
			new_row.appendChild( new_row_clear );
			this.list_target.appendChild( new_row );
		};
	
		this.elipse = function(str) 
		{
		 if ( 30 > str.length ) return str;
		 return '...'+str.substring(str.length-30,str.length,str);
		}
	
		this.addElement(file_target);*/
	
	};

	/*

	Function: DOMParser
	
	Prototype DomParser for IE/Opera

*/
if (typeof DOMParser == "undefined") {
   DOMParser = function () {}

   DOMParser.prototype.parseFromString = function (str, contentType) {
      if (typeof ActiveXObject != "undefined") {
         	var d = new ActiveXObject("Microsoft.XMLDOM");
         	d.loadXML(str);
         return d;
      } else if (typeof XMLHttpRequest != "undefined") {
         var req = new XMLHttpRequest;
         req.open("GET", "data:" + (contentType || "application/xml") +
                         ";charset=utf-8," + encodeURIComponent(str), false);
         if (req.overrideMimeType) {
            req.overrideMimeType(contentType);
         }
         req.send(null);
         return req.responseXML;
      }
   }
}
