var NetManagerFront =  new Class({
	/* 
	 * Class NetManagerFront
	 * Holds all functions for the mailcampaign interface
	 * 
	 * @Author Orestis Molopodis / Martin van der Poel
	 * @Copyright men@work / Dytech Solutions VOF
	 */
	
	
    /* 
	 * Initialize function of mailcampaign class
	 * Setting up the framework and firing the default action
	 * @Author Martin van der Poel
	 * @Copyright men@work / Dytech Solutions VOF
	 */
    
	initialize: function(options) {
		
		// Implement given options
    	this.setOptions(options);
    	
		
		// Cleanup Ajax request
		this.ajaxRequest = Class.empty;		
		
		this.formSent = false;
		
	},
	
	
	
	getAjax: function(url, onComplete, evalscripts) {
		//console.log(url + onComplete + evalscripts);
		var onCompleteAction = eval('this.' + onComplete + '.bind(this)');
		var ajaxFailure = this.ajaxFailure.bind(this);
		var ajaxOptions = {
			method: 		'get',
			evalScripts: 	evalscripts,
			onComplete: 	onCompleteAction, 
			onFailure: 		ajaxFailure
		};
		
		// Fire Ajax request
		this.ajaxRequest = new Ajax(url, ajaxOptions).request();
	},
	
	postAjax: function(url, onComplete, evalscripts) {
		//console.log(url + onComplete + evalscripts);
		var onCompleteAction = eval('this.' + onComplete + '.bind(this)');
		var ajaxFailure = this.ajaxFailure.bind(this);
		var ajaxOptions = {
			method: 		'post',
			evalScripts: 	evalscripts,
			onComplete: 	onCompleteAction, 
			onFailure: 		ajaxFailure
		};
		
		// Fire Ajax request
		this.ajaxRequest = new Ajax(url, ajaxOptions).request();
	},
	
	ajaxFailure: function() {
		this.main.setHTML('<p>Er is een probleem ontstaan bij het laden van de pagina. Probeer het nogmaals.</p>');
	},
	
	getForm: function(sFormName) {
		var fx = $('form_holder').effects({duration: 200, wait: true});
	 
		fx.start({
		}).chain(function() {
			this.start.delay(10, this, {
				'opacity': 0
			});
		});
		
		this.getAjax('/form/get/' + sFormName, 'renderForm', false);
	},
	
	renderForm: function(sResponse) {
		if (sResponse.test('<!DOCTYPE')) {
			document.location.href = '/redactie';
		}
		$('form_holder').setHTML(sResponse);
		this.initCalendarButtons();
		this.initTextAreas($('form_holder'));
		this.initFileUpload($('form_holder'));
		
		var fx = $('form_holder').effects({duration: 200, wait: true});
	 
		fx.start({
		}).chain(function() {
			this.start.delay(10, this, {
				'opacity': 1
			});
		});
		
	},
	
    initCalendarButtons: function(){
		$$('.dateTrigger').each(function ( el ) {
			Calendar.setup({
				inputField     :    el.getParent().getPrevious().id,      // id of the input field
				ifFormat       :    "%d-%m-%Y",      // format of the input field
				showsTime      :    false,           // will display a time selector
				button         :    el.id,   // trigger for the calendar (button ID)
				singleClick    :    false,           // double-click mode
				step           :    1                // show all years in drop-down boxes (instead of every other year as default)
			});
		});
	},
	
	initTextAreas: function() {
		$$('.simpleTiny textarea').each(function ( el ){
		   var sId = el.getProperty('id');
				tinyMCE.init({
				  mode : "exact",
				  elements : sId,
				  theme : "simple",
				  language : "nl",
				  height: "200px",
				  width: "483px",
				  plugins: "inlinepopups,media,style,table,advhr,advimage,insertdatetime,print,contextmenu,paste,directionality,visualchars,liststyle", 
				  cleanup_on_startup : true,
				  extended_valid_elements: "p[id|class|style],a[class|name|href|target|title],img[class|src|mce_src|border=0|alt|title|width|height|align|onmouseover|onmouseout|name|obj|param],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],div[align],hr,br,strike,sub,sup",
				  document_base_url : "/",
				  convert_urls : false,
				  force_br_newlines : true,
				  flashaudio : true,
				  flashvideo : true
			});
		});
		
		$$('.advancedTiny textarea').each(function ( el ){
		   var sId = el.getProperty('id');
		   tinyMCE.init({
				  mode : "exact",
				  elements : sId,
				  theme : "advanced",
				  language : "nl",
				  height: "400px",
				  width: "483px",
				  plugins: "inlinepopups,media,style,table,advhr,advimage,insertdatetime,print,contextmenu,paste,directionality,visualchars,liststyle", 
				  theme_advanced_buttons1: "tekstopmaak,bold,italic,underline,strikethrough,forecolor,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,bullist,numlist,liststyle,separator,outdent,indent,separator,sub,sup",
				  theme_advanced_buttons2: "interactiviteit,link,unlink,anchor,separator,invoegen,image,media,charmap,hr,insertdate,inserttime,separator,overigen,undo,redo,removeformat,pasteword,print",		
				  theme_advanced_buttons3: "tabellen,table,delete_col,delete_row,col_after,col_before,row_after,row_before,merge_cells,split_cells,delete_table",
				  theme_advanced_toolbar_location : "top",
				  theme_advanced_toolbar_align : "left",
				  cleanup_on_startup : true,
				  extended_valid_elements: "p[id|class|style],a[class|name|href|target|title],img[class|src|mce_src|border=0|alt|title|width|height|align|onmouseover|onmouseout|name|obj|param],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],div[align],hr,br,strike,sub,sup",
				  document_base_url : "/",
				  convert_urls : false,
				  force_br_newlines : true,
				  flashaudio : true,
				  flashvideo : true
				});
		});
		
	},
	
	initFileUpload: function(elm) {
		
		var inputElement = $(elm).getElement('input[type="file"]');
		if ($chk(inputElement)) {
			setTimeout(function() {
					fileUpload = null;
					fileUpload = new FancyUpload(inputElement, {
					swf: '/flash/Swiff.Uploader.swf',
					queueList: 'photoupload-queue',
					container: $('divFile'),
					form: $(elm)
				});
			}, 300);
		}
	},
	
	formatUrl: function(elm) {
		var sTitle = this.trim($(elm).value);
		$('url_segment').value = sTitle.clean().replace(/[^a-z0-9 ]/ig,'-').replace(/ /g, '-');
	},
	
	trim: function(value) {
		value = value.replace(/^\s+/,'');
		value = value.replace(/\s+$/,'');
		return value;
	},
	
	
	processForm: function(iFormId) {
		
		// Define the processed form
		this.processedForm = $(iFormId);
	
		// Show the loading animation
		this.showOverlay();
		
		// Bind the function which has to be fired after completion
		var validateForm = this.validateForm.bind(this);
		
		var ed, sText;
		$$('.tinyText textarea').each(function ( el ){
			var sId = el.getProperty('id');
			ed = tinyMCE.get(sId);
			sText = ed.getContent();
			sText = replaceImagesByMedia(sText);
			tinyMCE.execCommand('mceRemoveControl', false, sId);
			$(sId).value = sText;
		});
		
		var ed, sText;
		$$('.simpleTiny textarea').each(function ( el ){
			var sId = el.getProperty('id');
			ed = tinyMCE.get(sId);
			sText = ed.getContent();
			sText = replaceImagesByMedia(sText);
			tinyMCE.execCommand('mceRemoveControl', false, sId);
			$(sId).value = sText;
		});
		
		// Send AJAX request
		this.processedForm.send({ onComplete: validateForm });
		
		
	},
	
	validateForm: function(sResponse) {
		
		if (sResponse.test('<!DOCTYPE')) {
			document.location.href = '/auth/login';
		} else {
		
			// Evaluate server response
			var oResponse = Json.evaluate(sResponse);
			
			this.formSent = false;
			
			// Function to execute if server response is valid
			if(oResponse.valid) {
				
				// Remove error classes
				this.processedForm.getElements('input').each(function(el) {
					
					el.removeClass('iError');
					
				});
			
				// Remove previous error messages
				this.processedForm.getElements('.errormsg').each(function(el) {
					
					el.remove();
					
				});
				
				// Redirect to the defined tab
				this.switchSubTab(oResponse.redirect);
				
				// hide the loading animation
				this.hideOverlay();
			
			} else {
				
			
				// Remove error classes
				this.processedForm.getElements('input').each(function(el) {
					
					el.removeClass('iError');
					
				});
			
				// Remove previous error messages
				this.processedForm.getElements('.errormsg').each(function(el) {
					
					el.remove();
					
				});
				
				// For each error do
				$each(oResponse.errors, function(errorMessage, fieldName) {
												 
					var formElement = oNetManagerFront.processedForm.getElement('input[name^=' + fieldName + ']');
					if (fieldName == 'teaser' || fieldName == 'text') {
						
						$each(errorMessage, function(msg, key){
							// Place the error message in the dataholder
							var oError = new Element('p').addClass('errormsg').setHTML(msg).inject($(fieldName).getParent());
						});
						
					} else {
						
					
						if(formElement.getProperty('type') == 'text') {
						
							$(formElement).addClass('iError');
							
							$(formElement).value = '';
							
						} else {
							
							$(formElement).checked = false;
						
						}
						
						// Find the dataholder (dd) of the form element
						var dataHolder = $(formElement).getParent();
						
						while($(dataHolder).getTag() != 'dd') {
							
							dataHolder = $(dataHolder).getParent();
						
						}
						
						if ($type(errorMessage) == 'object') {
							$each(errorMessage, function(msg, key){
								// Place the error message in the dataholder
								var oError = new Element('p').addClass('errormsg').setHTML(msg).inject(dataHolder);
							});
						} else {
						
							// Place the error message in the dataholder
							var oError = new Element('p').addClass('errormsg').setHTML(errorMessage).inject(dataHolder);
						}
						
					}
				});
				
				// hide the loading animation
				this.hideOverlay();
				
				if(oResponse.db_error) {
					
					this.showError('Systeemfout!', oResponse.db_error);
					this.processedForm.getParent().empty();
				}
			}
		}
	},
	
	showError: function(sHeader, sContent, sFooter) {
		
		var oPopup = new Element('div').setOpacity(0).setProperty('id', 'popup').inject(document.body);
		
		var oHeader = new Element('div').setProperty('id', 'popupHeader').inject(oPopup);
		
		var oH3 = new Element('h3').setText(sHeader).inject(oHeader);
		
		var closeIcon = new Element('a').setProperties({
			'href': '#',
			'class': 'closeIcon',
			'title': 'Sluit dit venster'
		}).addEvent('click', function() {
			oNetManagerFront.closePopup();
		}).inject(oHeader);
		
		var oContent = new Element('div').setProperty('id', 'popupContent').setHTML(sContent).inject(oPopup);
		
		var oFooter = new Element('div').setProperty('id', 'popupFooter').setHTML(sFooter).inject(oPopup);
		
		$('popup').setStyles({
			'top': ((window.getHeight() / 2) - ($('popup').getSize().size.y / 2)),
			'left': ((window.getWidth() / 2) - ($('popup').getSize().size.x / 2))
		});
		
		$('popup').setOpacity(1);
	},
	
	closePopup: function() {
		if($defined($('popup'))) {
			
			// Remove the overlay from the DOM
			$ES('#popup').getLast().remove();
			
			this.hideOverlay();
		}
	},
	
	showOverlay: function(sType) {
		
		// Create the transparent overlay
		var oOverlay = new Element('div').setProperty('id', 'transOverlay');
			
		oOverlay.addClass('loadingOverlay');
		
		var oText = new Element('p').setStyle('margin-top', (window.getHeight()/2 + 30)).setText('Een ogenblik geduld a.u.b.').inject(oOverlay);
		
		// Inject the overlay into the DOM
		oOverlay.inject(document.body);
	},
	
	hideOverlay: function() {
		
		if($defined($('transOverlay'))) {
			
			// Remove the overlay from the DOM
			$ES('#transOverlay').getLast().remove();
		}
	},
	
	switchVesselTab: function(link, elm) {
		$('vessel_overview').getElements('div').each(function(elmDiv) {
			if ($(elmDiv).getProperty('id') == elm) {
				elmDiv.setStyle('display','block');
			} else {
				elmDiv.setStyle('display','none');
			}
		});
		var li = $$('#tabs li').each(function(li){
			li.removeClass('active');
		});
		$(link).getParent().addClass('active');
	}
	
	
	
	
	
		
});


NetManagerFront.implement(new Options());

window.addEvent('domready', function() {
	
	oNetManagerFront = new NetManagerFront();
	
});