
var Bitrockers_ajaxLayer = new Class({
	
	isUpload:	false,
	attachments: {},
	countAttachments: 0,
	attachmentCounter: 0,
	inProgress: false,
	
	initialize: 		function(formID, submitID, layerID, options)	{
		this.formID = formID;
		this.submitID = submitID;
		this.layerID = layerID;
		this.options = Object.extend({}, options);
		
		
		
		// file uploads? 
		if (this.options.upload)	this.isUpload = true;
		
		// default values
		if (!this.options.maxAttachments)		this.options.maxAttachments = 2;
		
		Window.onDomReady(this.onReady.bind(this));
	},

	stopEvent:			function(event)	{
		if (event.preventDefault)	{
			event.preventDefault();
		} else {
			var ev = new Event(event);
			ev.stop();	
		}
		
	},
	
	onReady:			function()	{
		
		// file upload? create frame
		if(this.isUpload)	{
			// this.uploadCreateFrame.bind(this)();
			this.uploadCreateFrame();
			if(this.options.attachments && $(this.formID+'_attachment_0'))	this.attachmentAddHandler(0);
		};
		
		// add context links
		$(this.formID).addEvent('submit', this.doCall.bindAsEventListener(this));
		if (this.submitID)	$(this.submitID).onclick = this.doCall.bindAsEventListener(this);
	},
	
	doCall:				function(e)	{
		this.stopEvent(e);	// iframe must be submitted
		if (this.inProgress)	return;	// only allow one click
		this.inProgress = true;


		// hide message bar if exist
		if ($(this.layerID + '_message'))	{
			$(this.layerID + '_message').setStyle('display','none');
		}

		// display progress bar if exist
		if ($(this.layerID + '_progress'))	{
			$(this.layerID + '_progress').setStyle('display','block');
		}
		
		// start ajax call or iframe
		if (!this.isUpload)	{
			this.options['method'] = 'post';
			this.options['onComplete'] = this.onComplete.bind(this);
			this.ajax = $(this.formID).send(this.options);		
		} else {
			this.uploadStart();
		}
		
		
		if (!this.isUpload)		return false;		// only return false if not iframe
	},
	
	onComplete:			function(request)	{
		
	
		// is there JSON result or simple html to output? 
		var response = parseJson(request);
		
		// hide progress and content
		if ($(this.layerID + '_progress'))		$(this.layerID+'_progress').setStyle('display','none');
		if (!this.options.preventClose && $(this.layerID + '_content'))		$(this.layerID + '_content').setStyle('display','none');
		
		// show html
		var messageLayer = $(this.layerID + '_message');
		if (response.html && messageLayer)	{
			messageLayer.innerHTML = response.html;
			messageLayer.setStyle('display','block');
		}
		
		// only html? call onlyHtml function
		if (response.onlyHtml && this.options.onHtml)	{
			this.options.onHtml();
		}
		
		// any actions?
		if (response.actions)	{
			for (var i=0; i < response.actions.length; i++)	{
				try{
					var actionToCall = eval(response.actions[i]);
					actionToCall(response.data);
				} catch (err)	{
					
				}
			}
		}
		this.inProgress = false;
	},
	
	uploadCreateFrame:		function()	{
		// create the for file uploads necessary iframe
		this.frameID = this.formID + '_upload_iframe';

		// ie9?
		var ie9=false;
		var ie = false;
		if (window.ActiveXObject)	{
			ie = true;
			var version = parseFloat(navigator.appVersion.split('MSIE')[1]);
			if (version >= 9.0)	ie9 = true;
		}

		if(ie && !ie9){
			var iframe = document.createElement('<IFRAME id="' + this.frameID + '" name="' + this.frameID + '">');
			iframe.src = 'javascript:false';
		}else{
			var iframe = document.createElement('IFRAME');
			iframe.id = this.frameID;
			iframe.name = this.frameID;
		};		
		
		// set style to 'hidden'
		iframe.style.position = 'absolute';
		iframe.style.left = '-1000px';
		iframe.style.top = '-1000px';
		document.body.appendChild(iframe);
	
	},
	
	uploadStart:			function()	{
		// override some parameters in form to use iframe as target
		var form = $(this.formID);
		form.enctype = 'multipart/form-data';
		form.method = 'POST';
		form.target = this.frameID;
		form.submit();
		
		// attach callback function to onload
		this.bound = {uploadComplete: this.uploadComplete.bind(this)};
		$(this.frameID).addEvent('load', this.bound.uploadComplete);
	},
	
	uploadComplete:			function()	{
		
		// read content of iframe
		var request = $(this.frameID).contentWindow.document.body.innerHTML;

		// remove onload event (e.g. backbutton etc)
		$(this.frameID).removeEvent('load', this.bound.uploadComplete);
		
		// call original onCompleteHandler
		this.onComplete(request);
	},
	
	attachmentAddHandler:		function(attachmentID)	{
		// add onchange handler
		var attachment = $(this.formID + '_attachment_' + attachmentID);
		attachment.onchange = this.attachmentOnChange.pass(attachmentID, this);
	},
	
	attachmentOnChange:			function(attachmentID)	{

		// preventing overlap, set height to auto
		$(this.layerID).setStyle('height', 'auto');
		// read desired informations from input file
		var attachment = $(this.formID + '_attachment_' + attachmentID);
		var file = attachment.value.split("\\");
		var fileName = file[file.length-1];
		var extensionArray = fileName.split(".");
		var extension = extensionArray[extensionArray.length-1];
		
		// create new info div
		var fileInfo = new Element('div');
		fileInfo.setOpacity(0);
		fileInfo.setStyle('display','block');
		fileInfo.id = this.formID + '_attachmentFileInfo_' + attachmentID;
		var deleteLink = fileInfo.id + '_delete';
		fileInfo.innerHTML = '<span id="'+ deleteLink + '">[ - ]</span> ' + fileName;
		
		
		// show if hidden
		$(this.formID+'_attachments').setStyle('display','block');
		
		// inject 
		fileInfo.injectInside($(this.formID+'_attachments'));
		
		// add ondelete handler for delete link
		$(deleteLink).onclick = this.attachmentDelete.pass(attachmentID, this);
		
		// fade into effect
		var targetBGColor = $(this.layerID).getStyle('background-color'); 
		// this.fx2 = new fx.Color(fileInfo.id, 'background-color');
		// this.fx1 = new fx.Style(fileInfo.id, 'opacity', {onComplete: this.fx2.custom.pass(['fc0', targetBGColor], this.fx2)});
		this.fx1 = new Fx.Style(fileInfo.id, 'opacity', {duration: 1000});
		this.fx1.custom(0,1);
		
		
		// hide original attachment input
		attachment.setStyle('display','none');
		
		// check if we should add more attachment options
		this.countAttachments++;
		var attachmentNewID = attachmentID + 1;
		if (this.options.maxAttachments > this.countAttachments)	{
			this.attachmentCreateNewInput();
		} else {
			if ($(this.formID+'_attachmentLink'))	$(this.formID+'_attachmentLink').setStyle('display','none');
		}
	},
	
	attachmentCreateNewInput:		function()	{
			this.attachmentCounter++;
			var attachmentNewID = this.attachmentCounter;
			var attachmentNew = new Element('input');
			attachmentNew.type = 'file';
			attachmentNew.name = 'attachment_' + attachmentNewID;
			attachmentNew.id = this.formID + '_attachment_' + attachmentNewID;
			attachmentNew.injectInside($(this.formID + '_attachmentLinkContainer'));
			//attachmentNew.setStyle('display','block');
			this.attachmentAddHandler(attachmentNewID);			
	},
	
	attachmentDelete:		function(attachmentID)	{
		// remove attachments
		$(this.formID + '_attachment_' + attachmentID).remove();
		$(this.formID + '_attachmentFileInfo_' + attachmentID).remove();
		
		// we must redisplay attachmentLink
		if($(this.formID + '_attachmentLink').getStyle('display') == 'none')	{
			$(this.formID + '_attachmentLink').setStyle('display','block');	
			this.attachmentCreateNewInput();
		};
		
		this.countAttachments--;
		
	}
	
	
});




