var upld = Class.create({
	initialize:function(c){
		this.action=typeof(c.action)=='undefined' ? "/reg/cgi-bin/jsupload.cgi.pl" : c.action;
		this.finalize=typeof(c.finalize)=='undefined' ? "/reg/forms/forms_lib/upld_finalize.asp" : c.finalize;
		this.finalize_cancel=typeof(c.finalize_cancel)=='undefined' ? "/reg/forms/forms_lib/upld_finalize_cancel.asp" : c.finalize_cancel;
		this.containerId=typeof(c.containerId)=='undefined' ? "upload_area" : c.containerId;;
		this.extra_vars=Object.isUndefined(c.extra_vars) ? {} : c.extra_vars; //includes: reg_id, clogin_id, group_id, reg_table, form_id
		this.file_info=Object.isUndefined(c.file_info) ? [] : c.file_info; //includes: type, title, remark, header, link, name (if there is a link and a name then this is a file that was already uploaded and it is presented)
		this.multi_text=typeof(c.multi_text)=='undefined' ? "Add another file" : c.multi_text;
		this.file_msg=typeof(c.file_msg)=='undefined' ? ["Preparing...", "Starting Upload", "Finalizing", "Uploaded", "Canceling"] : c.file_msg;
		this.errors=typeof(c.errors)=='undefined' ? ["The file you are trying to upload is too big.<br>Please upload a different file", "The file type you are trying to load is not allowed.<br>Please upload a file with one of the following following extensions:"] : c.errors;
		this.user_info=typeof(c.user_info)=='undefined' ? this.get_userinfo(): c.user_info;
		
		this.max_size=typeof(c.max_size)=='undefined' ? 2000000: c.max_size;
		this.validext=typeof(c.validext)=='undefined' ? "jpg|jpeg|gif|png|pdf|doc|odt" : c.validext;
		this.num_files=typeof(c.num_files)=='undefined' ? this.file_info.size() : c.num_files;
		this.max_num_files=typeof(c.max_num_files)=='undefined' ? 30 : c.max_num_files;
		this.multiple=typeof(c.multiple)=='undefined' ? false : c.multiple;
		this.css=typeof(c.css)=='undefined' ? '/reg/js/upld.css' : c.css;
		
		//
		this.can_upload=true;  
		this.file_list=[];
		
		
		
		Lightbox.init();
		this.load_css();
	},
	
	is_finished:function(){
		var t=""
		for (var i=0; i<this.file_list.size(); i++){
			if ($('file_' + this.file_list[i])){
				t+=$F('file_' + this.file_list[i]);
			}
		}
		//t= t=="" ? true: false 
		return t=="";
	},
	
	init: function(){
		//creating the units and binding them
		for (var i=0; i<this.num_files; i++){
			this.frame(i);
		}
		
		//bind the units
		this._bind_frame();
		
		//if this is an existing file we present it as such
		for (var i=0; i<this.file_info.size(); i++){
			if (this.file_info[i]["link"] && this.file_info[i]["name"] && this.file_info[i]["panelid"] && this.file_info[i]["file_uploaded_id"]){
				this.upload_complete(this.file_info[i]["panelid"],this.file_info[i]["link"], this.file_info[i]["file_uploaded_id"]);
			}
		}
	},
	
	load_css: function(){
		//load the css for the first time
		if (!$('css-done')){
			//create it
			var str="<div id='css-done'></div>";
			$(document.body).insert({'top':str});
			//if after we create it, it is not none, then we need to upload the css, otherwise the css has been loaded already
			if ($('css-done').getStyle('display') != 'none') {
				LazyLoad.css(this.css);
			}
			
			//after we have loaded the css for the first time we do a loop to check that it has been loaded already
			//check that the css has loaded
			poll = function () {
				if ($('css-done').getStyle('display') === 'none') {
					// Once the element's display property changes, we know the CSS has
					// finished loading.
					$('css-done').remove();
					this.init();
				} else {
					// The element's display property hasn't changed yet, so call this
					// function again in 50ms.
					setTimeout(poll, 50);
				}
			}.bind(this);	
			poll();
			
        }
	},
	
	
	get_userinfo: function(){
		alert("no user info");	
	},
	
	frame: function(n) {
		var panelid='f' + Math.floor(Math.random() * 999999999);
		
		//we check if we have a filelink and file name for this file
		if (this.file_info[n]["link"] && this.file_info[n]["name"] && this.file_info[n]["panelid"]){
			//this means that this file is an existing file and we want to present it as such
			//set the panelid
			panelid=this.file_info[n]["panelid"]
		}
		this.file_info[n]["panelid"]=panelid;
		
			
		var r=Math.floor(Math.random() * 99999);
		var con= "<div class='upld_multi' id='upld_multi'></div>"
		if (!$('upld_multi')){
			$(this.containerId).insert({'bottom':con});
		}
		
		var d="<form target='formpanel_" +  panelid + "' method='post' action='" + this.action + "' id='form_" + panelid + "' enctype='multipart/form-data'>";
			//init
			file_info=this.file_info[n];
			if (typeof(file_info["type"])=='undefined'){
				file_info["type"]='file_' + r 
				file_info["extra_file"]=1
			}
			file_info["extra_file"]=typeof(file_info["extra_file"])=='undefined' ? 1 : file_info["extra_file"];
			file_info["file_uploaded_id"]=typeof(file_info["file_uploaded_id"])=='undefined' || file_info["file_uploaded_id"]==null ? '' : file_info["file_uploaded_id"];
			file_info["locked"]=typeof(file_info["locked"])=='undefined'? 0  : file_info["locked"];
			
			file_info["title"]=typeof(file_info["title"])=='undefined' ? '' : file_info["title"];
			file_info["remark"]=typeof(file_info["remark"])=='undefined' || file_info["remark"]==null ? '' : file_info["remark"];
			file_info["header"]=typeof(file_info["header"])=='undefined' || file_info["header"]==null ? '' : file_info["header"];
			
			//add the vars to a div (if we add to the form it creates problems) with a unique id
			
			d+="<div id='upld_type" + panelid + "' style=\"display: none;\">" + file_info["type"] + "</div>"
			d+="<div id='upld_title" + panelid + "' style=\"display: none;\">" + file_info["title"] + "</div>"
			d+="<div id='extra_file_" + panelid + "' style=\"display: none;\">" + file_info["extra_file"] + "</div>";
			d+="<div id='file_uploaded_id_" + panelid + "' style=\"display: none;\">" + file_info["file_uploaded_id"] + "</div>";
			
			
			if (file_info["header"]!=''){
				d+="<div class='upld_header'>" + file_info["header"] + "</div>";
			}
			d+="<div class='upld_title'>" + file_info["title"] + "<div class='clear' style='height: 1px;'></div></div>";
			
			d+="<div class='upld_input'>";
				d+="<input id='file_" + panelid + "' class='upld_fileupload' type='file' name='" + panelid + "'>";
				
				//upload info
				d+="<div class='upld_info' id='upld_info_" + panelid + "' style='display: none;'>";
					if (file_info["locked"]==0){ //we enable to delete the file only if the file is not locked
						d+="<div class='upld_del_file_div' rel='" + panelid + "' id='upld_del_file_div_" + panelid + "'>"
						d+="<a href='#' class='upld_del_file' id='upld_a_del_file_" + panelid + "' rel='" + panelid + "'>X</a></div>";
					}
					
						d+="<div id='upld_file_name_" + panelid + "' class='upld_file_name'>" 
							if (file_info["name"]){
								d+=this.file_name_fix(file_info["name"]) 
							}
						d+="</div>";
					d+="<div class='upld_progressbar' id='upld_progressbar_" + panelid + "'></div>";
					d+="<div class='upld_info_area' id='upld_info_area_" + panelid + "'></div>";
				d+="</div>";
			d+="</div>";
			if (file_info["remark"]!=''){
				d+="<div class='upld_remark'>" + file_info["remark"] + "</div>";
			}
		d+="</form>"
		
		$('upld_multi').insert({'bottom':d});
		
		//adding the panelid to the list
		this.file_list.push(panelid);
		this.file_list=this.file_list.compact().uniq();	
		
		
		if (this.multiple && n==(this.num_files-1) && this.num_files<=(this.max_num_files-1)){
			var a="<div class='upld_add'><a href='#' id='upldadd' class='upld_add_a'>" + this.multi_text + "</a></div>"
			$(this.containerId).insert({'bottom':a});
			this._bind_multi();
		}
		
		
		
		var s ="<iframe class=\"upld_iframe\" id=\"iframe_" +  panelid + "\" style=\"display:none; border 0pt none; position: absolute; width: 0pt; height: 0pt\" name=\"formpanel_" +  panelid + "\" src=\"javascript:''\">"
		s+="<html><head></head><body></body></html></iframe>";
		$(document.body).insert({'bottom':s});
		
		return panelid;
	},
	
	
	_bind_frame: function(n){
		if (!n){n=0;}
		for (var i=n; i<this.file_list.size();i++){
			$('file_' + this.file_list[i]).stopObserving();
			$('file_' + this.file_list[i]).observe('change',function(event){this.upload_file(false,event);}.bind(this));
		}
		
		var arr_cancel=$$('div.upld_del_file_div');
		for (var i=n; i<arr_cancel.size();i++){
			if ($('upld_del_file_div_' + this.file_list[i])){
				$('upld_del_file_div_' + this.file_list[i]).stopObserving();
				$('upld_del_file_div_' + this.file_list[i]).observe('click',function(event){this.upload_cancel(event)}.bind(this));
			}
		}
		
	},
	
	_bind_multi: function (){
		if ($('upldadd')){
			$('upldadd').stopObserving();
			$('upldadd').observe('click', this.a_handler.bindAsEventListener(this));
		}
	},
	
	a_handler: function(event){
		Event.stop(event);
		if (this.num_files<=this.max_num_files){
			this.file_info.push([]);
			
			this.frame(this.num_files);
			
			this.num_files++
			if (this.num_files>this.max_num_files-1){
				$$('div.upld_add').invoke('hide');
			}
			this._bind_frame(this.file_list.size()-1);
		}else{
			$$('div.upld_add').invoke('hide');
		}		
	},
	
	
	
	//-----------------------Upload file functionality----------------------
	
	upload_file: function(input_item,event){
		var panelid=false;
		if (!(input_item)){
			input_item=Event.element(event);
			panelid=$(input_item).name;
			
			var objRE = new RegExp(/([^\/\\]+)$/);
			var file_name = objRE.exec($F(input_item));
			file_name  = (file_name == null) ? null : file_name[0];
			
			var ext=new RegExp('^.*\.(' + this.validext + ')$', 'i');
			
			if (!ext.test(file_name)){
				msg="<div class='upld_error'>" + this.errors[1] + "<br><br>" + this.validext.replace(/\|/gi," | ") + "<Br><br></div>"
				msg+="<div class='upld_errorOK'><a href='#' onclick='Event.stop(event);Lightbox.hideBox()'>OK</a></div>";
				Lightbox.showBoxString(msg);
				if (typeof(progressbar)!='undefined'){
					progressbar.setPercentage('0');
				}
				$(input_item).value='';
				return false;
			}
			
			
			//CSS clean up
			this.css_cleanup;
			$('upld_info_' + panelid).show();
			$('upld_file_name_' + panelid).update(this.file_name_fix(file_name));
			
			$('upld_file_name_' + panelid).update(this.file_name_fix(file_name));
			$('upld_info_area_' + panelid).update(this.file_msg[0]);
			
			$(input_item).hide();
			
		}
		
		
	
		if (!panelid){
			panelid=input_item;
			input_item=$('file_' + panelid);
		}
		if (this.can_upload && !$(input_item).visible()){
			progressbar= new JS_BRAMUS.jsProgressBar($('upld_progressbar_' + panelid), 0, {animate: true, width: 120, height: 12, barImage: '/reg/imgs/progressbar/percentImage_back.png'});
			this.post_file(panelid);
			
		}
	},
	
	file_name_fix: function(file_name){
		var exn=file_name.substr(file_name.lastIndexOf('.') + 1);
		var fn=file_name.split("."+exn).first();
		if (fn.length>10){
			fn=fn.substr(0,7) + "..." + fn.substr(fn.length-3);
		}
		fn+="." + exn;
		return fn
	},
	
	post_file: function(panelid){
		this.can_upload=false;
		var form_id="form_" + panelid;
		var random=Math.floor(Math.random() * 999999999);
		
		//check that the file ext is right
		$(form_id).submit();
		
		var cgi_cookie=getCookie('CGISESSID');
		if (cgi_cookie=""){
			var url=this.action;
			//if we do not have a cookie we create one
			new Ajax.Request(url, {
				parameters : {new_session: true, random: random},
				method: 'get',
				onSuccess: function(transport) {
					var xml = transport.responseXML.documentElement;
					var s = xml.getElementsByTagName('session')[0].firstChild.data;
					if (s=='ok'){
						//alert(s);
						this.progress_check(panelid);			
					}
					
				}.bind(this)
			});
		}else{
			this.progress_check(panelid);
		}
	},
	
	
	progress_check: function(panelid){
		var url=this.action;
		var random=Math.floor(Math.random() * 999999999);
		var c=0;
		new Ajax.Request(url, {
			parameters : {filename: panelid, c: c, random: random},
			method: 'get',
			onSuccess: function(transport) {
				var xml = transport.responseXML.documentElement;
				
				var canceled = xml.getElementsByTagName('canceled')[0];
				var finished = xml.getElementsByTagName('finished')[0];
				
				if (typeof(finished)=='undefined' || finished==null){
					this.progress_update(panelid, xml);
				}else{
					if (typeof(canceled)=='undefined' || canceled==null){
						//we timeout the finalize since there are sometimes problems
						window.setTimeout(function(){this.upload_finalize(panelid)}.bind(this), 1500);;
					}else{
						this.upload_canceled(panelid);
					}
				}
			}.bind(this)
		});
	},
	
	progress_update: function(panelid, xml){
		var percent=0
		//CSS clean up
		this.css_cleanup;
		
		//make sure we can see the progressbar
		$('upld_progressbar_' + panelid).show();
		
		percent=xml.getElementsByTagName('percent')[0].firstChild.data;
		percent=parseInt(percent);
		totalBytes=xml.getElementsByTagName('totalBytes')[0].firstChild.data;
		
		if (totalBytes>this.max_size){
			//cancel the process
			msg="<div class='upld_error'>" + this.errors[0] + "</div>";
			msg+="<div class='upld_errorOK'><a href='#' onclick='Event.stop(event);Lightbox.hideBox()'>OK</a></div>";
			Lightbox.showBoxString(msg);
			this.upload_cancel(false,panelid);
		}
		
		if (percent>0){
			progressbar.setPercentage(percent);
			currentBytes=xml.getElementsByTagName('currentBytes')[0].firstChild.data;
			var str=parseInt(currentBytes/1024) + "/" + parseInt(totalBytes/1024) + " KB.";
			$('upld_info_area_' + panelid).update(str);
		}
		window.setTimeout(function(){this.progress_check(panelid)}.bind(this), 1000);
		
	},
	
	upload_loop: function (panelid){
		this.progress_check(panelid);
	},
	
	upload_finalize: function(panelid, action_type){
		if (typeof(progressbar)!='undefined'){
			progressbar.setPercentage('98');
		}
		
		$('upld_info_area_' + panelid).update(this.file_msg[2]);
		//finalizing the upload
		var url=this.finalize;
		if (action_type=='cancel'){
			 url=this.finalize_cancel;
		}
		
		var param = new Hash();
		param.set('filename', panelid);
		param.set('file_type', $('upld_type' + panelid).innerHTML);
		param.set('file_title', $('upld_title' + panelid).innerHTML);
		param.set('extra_file', $('extra_file_' + panelid).innerHTML);
		param.set('file_uploaded_id', $('file_uploaded_id_' + panelid).innerHTML);
		
		param.set('clogin_id', this.user_info["clogin_id"]);
		param.set('group_id', this.user_info["group_id"]);
		param.set('reg_id', this.user_info["reg_id"]);
		param.set('reg_table', this.user_info["reg_table"]);
		param.set('file_form_id', this.user_info["form_id"]);
		
		var param_all=param.merge(this.extra_vars);
		
		new Ajax.Request(url, {
			parameters : param_all.toQueryString(),
			method: 'post',
			onFailure: function(){
				//alert("there is a problem");
				this.upload_finalize(panelid);
			},
			onSuccess: function(transport) {
				var filelink=transport.responseText
				var json=transport.responseText.evalJSON(true);
				var fr_path=json[0]["path"];
				var fr_id=json[0]["id"];
				var fr_error=json[0]["error"];
				
				if (fr_error){
					lightbox_error(fr_error)
				}
				
				if (fr_path && fr_id){ //this means everything worked
					progressbar.setPercentage('100');
					this.upload_complete(panelid, fr_path, fr_id);
				}
				
				//this is for the delete
				if (fr_path=='deleteOK' && fr_id==''){ //this means that the delete worked
					//we clear up the file file_uploaded_id
					$('file_uploaded_id_' + panelid).update("");
				}
			}.bind(this)
		});
	},
	
	upload_complete: function(panelid, fr_path, fr_id){
		
		//var f=$(document.body).getElementsByTagName(iframe);
		//we make sure the info area is shown and the input area is hidden - this is done for the file already exist option
		$('upld_info_' + panelid).show();
		
		$('file_' + panelid).hide();
		
		//updating the id
		$('file_uploaded_id_' + panelid).update(fr_id);
		
		//updating visual
		$('upld_info_area_' + panelid).update(this.file_msg[3]);
		$('upld_info_area_' + panelid).addClassName("done");
		
		//creating the link to the file
		var file_name=$('upld_file_name_' + panelid).innerHTML;
		var t="<a href='" + fr_path + "' target=_blank>" + file_name + "</a>"
		$('upld_file_name_' + panelid).update(t);
		$('upld_file_name_' + panelid).addClassName("done_file_name");
		
		if ($('upld_progressbar_' + panelid)){
			$('upld_progressbar_' + panelid).hide();
		}
		this.can_upload=true;
		//take the file off the filelist
		panelid_index=this.file_list.indexOf(panelid);
		this.file_list.splice(panelid_index,1);
		this.file_list=this.file_list.compact().uniq();	
		
		
		//after the file has been uploaded we need to change the action of the cancel
		if ($('upld_del_file_div_' + panelid)){
			$('upld_del_file_div_' + panelid).stopObserving();
			$('upld_del_file_div_' + panelid).observe('click',function(event){this.cancel_after_complete(panelid)}.bind(this));
		}
		
		//do we have another one to upload?
		for (var i=0; i<=this.file_list.size();i++){
			if (this.file_list[i]){
				this.upload_file(this.file_list[i]);
				break;
			}
		}
	},
	
	cancel_after_complete: function(panelid){
		this.upload_finalize(panelid, "cancel");
		this.upload_cancel(false, panelid);
		this.css_cleanup(panelid);
	},
	
	css_cleanup: function(panelid){
		$('upld_info_area_' + panelid).removeClassName("cancel");
		$('upld_info_area_' + panelid).removeClassName("done");
		$('upld_file_name_' + panelid).removeClassName("done_file_name");
	},
	
	//------------- Cancel upload ------------------
	upload_cancel: function(event,panelid){
		if(event){
			Event.stop(event);
			//remove or delete?
			var item=Event.element(event);
			panelid=$(item).readAttribute('rel');
		}
		
		//CSS clean up
		this.css_cleanup;
			
		$('upld_info_area_' + panelid).update(this.file_msg[4]);
		
		var random=Math.floor(Math.random() * 999999999);
		var url=this.action;
		
		if ($('upld_info_area_' + panelid).hasClassName('done')){
			//if the file is already loaded we delete it
			new Ajax.Request(url, {
				parameters : {remove: panelid, random: random},
				method: 'get',
				onSuccess: function(transport) {
					$('upld_info_' + panelid).hide();
					$('file_' + panelid).value='';
					$('file_' + panelid).show();
					
					this.file_list.push(panelid);
					this.file_list=this.file_list.compact().uniq();	
					
					//delete the iframe and create a new one
					$('iframe_' + panelid).remove();
					var s ="<iframe id=\"iframe_" +  panelid + "\" style=\"display:none; border 0pt none; position: absolute; width: 0pt; height: 0pt\" name=\"formpanel_" +  panelid + "\" src=\"javascript:''\">"
					s+="<html><head></head><body></body></html></iframe>";
					$(document.body).insert({'bottom':s});
		
				}.bind(this)
			});
		}else{
			
			//if the file is loading we cancel it
			if (typeof(progressbar)!='undefined'){
				progressbar.setPercentage('0');
				new Ajax.Request(url, {
					parameters : {cancel: true, random: random},
					method: 'get'
				});
			}
		}
	
	},
	
	upload_canceled: function(panelid){
		$('upld_info_area_' + panelid).update(this.file_msg[4]);
		$('upld_info_area_' + panelid).addClassName("cancel");
		
		$('upld_info_' + panelid).hide();
		//$('upld_progressbar_' + panelid).hide();
		$('file_' + panelid).value='';
		$('file_' + panelid).show();
		
		
		
		this.can_upload=true;
		//take the file off the filelist
		panelid_index=this.file_list.indexOf(panelid);
		this.file_list.splice(panelid_index,1);
		this.file_list=this.file_list.compact().uniq();	
		
		//do we have another one to upload?
		for (var i=0; i<=this.file_list.size();i++){
			if (this.file_list[i]){
				this.upload_file(this.file_list[i]);
			}
		}
	}
	
}); //end of upld class
 
/*
	
 
 */
