var clientUploader = function(){
	
	this._self;
	this._instanceName = 'clientFileUploader';
	
	this.FORM_APPLICATION = 'files';
	this.FORM_ACTION_UPLOAD =  'upload';
	this.UPLOAD_BUTTON_PREFIX = 'upload_button_';
	this.UPLOAD_INPUT_PREFIX = 'upload_input_';
	this.UPLOAD_FILELIST_ID	= 'upload_file_list';
	this.UPLOAD_ERROR_PREFIX = 'upload_err_';
	this.ROW_LIMIT_LBL = 'row_limit_messahe';
	
	this.upload_instances = new Array();
	this.rows_count = 0;
	this.rows_count_limit = 10;
	
	
	
	this.init = function(self, row_limit) {
		this._self = self;
		this.rows_count_limit = row_limit;
	}
	
	
	this.setRows = function(i, render){
		if(typeof(render) != 'undefined' && render == true) {
			for(var j=0; j<i; j++) {
				this.addOption();
			}
		} else {
			this.rows_count = i;
		}
	}
	
	this.addOption = function() {
		
		if(this.rows_count_limit <= this.rows_count && this.rows_count_limit != 0){
			$('#' +this.ROW_LIMIT_LBL).show();
			return;
		}
		
		this.rows_count++;
		var tr = document.createElement('TR');

		var td = document.createElement('TD');
		td.className = 'moden-upload-cell';
	    td.innerHTML = '<input id="' + this.UPLOAD_INPUT_PREFIX + this.rows_count + '" type="text" style="margin-top: 1px;" />';
	    tr.appendChild(td);
	    
	    td = document.createElement('TD');
	    td.className = 'moden-upload-cell';
	    td.innerHTML = '<input id="' + this.UPLOAD_BUTTON_PREFIX + this.rows_count + '" type="button" value=\"'+ $t('button.browse', false, false) +'\"/>';
	    tr.appendChild(td);
	    
	    td = document.createElement('TD');
	    td.className = 'moden-upload-cell';
	    td.innerHTML = '<span id="' + this.UPLOAD_ERROR_PREFIX + this.rows_count + '" class="" ></span>';
	    tr.appendChild(td);
	    
	    $('#' + this.UPLOAD_FILELIST_ID).append( tr );
	    
	    this.initUpload(this.rows_count);
	}
	
	this.initUpload = function(upload_button_id, upload_params){
		
		var self = this;
		var default_params = {action : this.FORM_APPLICATION + "." + this.FORM_ACTION_UPLOAD, layout: 'ajax', operation: 'upload'};
		
		cmsAdministration.loadJS('jquery-plugins/ajaxupload.js', function() {
			var uploader = new AjaxUpload('#' + self.UPLOAD_BUTTON_PREFIX + upload_button_id, {
				id: upload_button_id,
				cmsUploader: self._self,
				interval: 0,
				// Location of the server-side upload script
				action: cmsAdministration.getURL(),
				// File upload name
				name: 'userfile',
				// Additional data to send
				data: $.extend(default_params, upload_params, self.global_upload_params),
				// Submit file after selection
				autoSubmit: false,
				// The type of data that you're expecting back from the server.
				// Html (text) and xml are detected automatically.
				// Only useful when you are using json data as a response.
				// Set to "json" in that case.
				responseType: false,
				// Fired after the file is selected
				// Useful when autoSubmit is disabled
				// You can return false to cancel upload
				// @param file basename of uploaded file
				// @param extension of that file
				onChange: function(file, extension){
					var filename = file;
					var dot = filename.lastIndexOf("."); 
					if( dot != -1 ) filename = filename.substr(0,dot); 
				
					$('#' + this._settings.cmsUploader.UPLOAD_INPUT_PREFIX + this._settings.id).val(file);
					$('#' + this._settings.cmsUploader.UPLOAD_ERROR_PREFIX + upload_button_id).text('');
				},
				// Fired before the file is uploaded
				// You can return false to cancel upload
				// @param file basename of uploaded file
				// @param extension of that file
				onSubmit: function(file, extension) {
					var cmsUploader = this._settings.cmsUploader;
					var upload_button_id = this._settings.id;				
					var value = extension[0];
					var param = this._settings.data.allowed_extension;
					param = typeof param == "string" ? param.replace(/,/g, '|') : "png|jpe?g|gif";
		
					this._settings.data.operation = 'filesUpload';
					this._settings.data.newDir = $('#newDir').val();
					this._settings.data.i_code = $('#i_code').val();
					/*
					if (! value.match( new RegExp("^(" + param + ")$", "i") ) ){
	                    // extension is not allowed
						$('#' + this._settings.cmsUploader.UPLOAD_FILE_PREFIX + this._settings.id).val('');
						$('#' + this._settings.cmsUploader.UPLOAD_FILE_PREFIX + this._settings.id).text('');
						var extensions_str = this._settings.data.allowed_extension;
						var expr = new RegExp('[|]', 'g');
						extensions_str = extensions_str.replace(expr, ', *.');
						extensions_str = '*.' + extensions_str;
						cmsAdministration.showError( $t('err_upload.file_extension', {extensions: extensions_str, filename: file}) );
	                    // cancel upload
	                    return false;
					}
					*/
					
					$('#' + cmsUploader.UPLOAD_ERROR_PREFIX + upload_button_id).html('<img width="16" height="16" src="scss/images/ajax-loader.gif" border="0" />');
					
					// If you want to allow uploading only 1 file at time,
					// you can disable upload button
					//this.disable();
					//$('#' + cmsUploader.UPLOAD_BUTTON).attr("disabled", "disabled"); 
					//$('#' + cmsUploader.UPLOAD_BUTTON).val('Uploading');
					 
					
					// Uploding -> Uploading. -> Uploading...
					this._settings.interval = window.setInterval(function(){
						$('#' + cmsUploader.UPLOAD_BUTTON).attr("disabled", "disabled");
					}, 200);
				},
				// Fired when file upload is completed
				// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
				// @param file basename of uploaded file
				// @param response server response
				onComplete: function(file, response) {
					var cmsUploader = this._settings.cmsUploader;
					var upload_button_id = this._settings.id;
					
					// enable upload button
					this.enable();
					
					var all_finished = true;
					for(var i = 0; i < cmsUploader.upload_instances.length; i++) 
						if(cmsUploader.upload_instances[i]._disabled == true) all_finished = false;
					
					if(all_finished) {
						$('#' + cmsUploader.UPLOAD_BUTTON).val($t('button.upload', '', false));
						$('#' + cmsUploader.UPLOAD_BUTTON).removeAttr("disabled");
					}
					
					window.clearInterval(this._settings.interval);
					if(response == 'msg.uploaded'){
						$('#' + cmsUploader.UPLOAD_ERROR_PREFIX + upload_button_id).addClass('success');
					}else{
						if(response == 'code.invalid'){
							$('#capcha_err').html($t(response));
							$('#' + cmsUploader.UPLOAD_INPUT_PREFIX + upload_button_id).val('');
						}
						else $('#' + cmsUploader.UPLOAD_ERROR_PREFIX + upload_button_id).removeClass('success');
					}
					
					if(response != 'code.invalid'){	
						$('#' + cmsUploader.UPLOAD_ERROR_PREFIX + upload_button_id).html($t(response));
					}else {
						$('#' + cmsUploader.UPLOAD_ERROR_PREFIX + upload_button_id).html($t(''));
					}
				}
			});
			
			self.upload_instances.push(uploader);
		});
	}
	
	this.submitUpload = function(id) {		
		for(var i = 0; i < this.upload_instances.length; i++)
		{			
			if(typeof(id) == 'undefined' || this.upload_instances[i]._settings.id == id) {
				var cmsUploader = this.upload_instances[i]._settings.cmsUploader;
				if($('#' + cmsUploader.UPLOAD_FILE_PREFIX + this.upload_instances[i]._settings.id).val() != '')
				{
					this.upload_instances[i].submit();
				}				
			}
		}
	}
	
	this.clearUpload = function() {
		for(var i = 0; i < this.upload_instances.length; i++) this.upload_instances[i].destroy();
		this.upload_instances = Array();
	}

	
	// custom user set function for different acions after file upload finished
	this.afterUpload = function(uploaderSettings) {
		
	}
	
	
}


var clientFileUploader = new clientUploader();
