var Remote = new Class({
	
	Implements : Options,
	
	options: {
		'lang' : ['chfr','chde','chit','en','se','es','cz','fr','de','it','befr','nl','atde'],
		'cs' : '/floor/cs',
		'server' : 'eslagency',
		'default_lang' : 'chfr',
		'sitemap_url' : '&template=sitemap&subact=sitemapnew&SitemapSrcCID=1&SitemapList=xml',
		'mask_class' : 'mask'
	},
	
	
	initialize : function(options){
		this.setOptions(options);
		this._createObj();
		this._createMenu();
	},
	
	/* Function to create the menu below the admin (backoffice) menu */
	_createMenu : function(){
		new Element('div',{'id':'IFInterfaceESLMenu','class':'IFMenu'}).inject(document.body);
		var ul = new Element('ul').inject('IFInterfaceESLMenu');
		
		//Toggler
		ul.adopt(new Element('li',{
			'class':'IFToggler IFMenuOpen',
			'events':{
				'click': function(){
					if ($('IFInterfaceESLMenu').getStyle('width') == '20px') {
						$('IFInterfaceESLMenu').setStyle('width', 278);
						Cookie.write('IFInterfaceESLMenu', '1', {duration: 30});
					}
					else {
						$('IFInterfaceESLMenu').setStyle('width', 20);
						Cookie.dispose('IFInterfaceESLMenu');
						if($('langz')) $('langz').destroy();
						if($('rm_cid').getStyle('display') == 'block') $('cid_toggler').fireEvent('click');
					}
					this.toggleClass('IFMenuOpen');
				}
			}
		}));
		
		//Remote control button
		ul.adopt(new Element('li',{
			'class':'IFOrange',
			'html':'Remote',
			'events':{
				'click': function(){
					if(remote_obj.getStyle('display') == 'none') this._show(remote_obj)
					else this._close();
				}.bind(this)
			}
		}));
		
		//Language list button
		ul.adopt(new Element('li',{
			'class':'IFOrange',
			'html':'Lang. List',
			'events': {
				'click': function(){
					if(!$('langz')) this._createLangList();
					else $('langz').destroy();
				}.bind(this)
			}
		}));
		
		//Goto button
		ul.adopt(new Element('li',{
			'id':'cid_toggler',
			'class':'IFOrange',
			'html':'Goto category',
			'events': {
				'click':function(){
					if($('rm_cid').getStyle('display') == 'block'){
						$('rm_cid').setStyle('display','none');
						$('rm_cid').getElement('input[type=text]').blur();
						$('rm_cid').getElement('input[type=text]').value = '';
					}
					else{
						if($('IFInterfaceESLMenu').getStyle('width') == '20px') $('IFInterfaceESLMenu').getElement('.IFToggler').fireEvent('click');
						$('rm_cid').setStyle('display','block');
						$('rm_cid').getElement('input[type=text]').focus();
					}
				}.bind(this)
			}
		}));
				
		if(Cookie.read('IFInterfaceESLMenu')) {
			ul.getElement('.IFToggler').fireEvent('click');
		}
	},
	
	/* Function to create the remote control object */
	_createObj: function(){
		remote_obj = new Element('div',{ 'id':'remote' }).injectInside(document.body);
		remote_obj.set('html','<h3 id="title">Remote Control</h3><div id="rm_previous"></div><div id="content" class="clearfix"></div><form action="#" id="rm_search"><input type="text" /><input type="submit" value="Search" /><input type="button" value="Reset" /></form>');
		
		//close button
		new Element('a',{
			'class':'close',
			'events':{
				'click': this._close.bind(this)
			}
		}).inject(remote_obj);
		
		//mask and spinner
		this.overlay = new Mask(document.body, {'class': this.options.mask_class, onClick: function(){ this._close() }.bind(this) });
		this.spinner = new Spinner($('content'));
		this.dataload = false;
		this.pointer = null;
		this.level = 1;
		
		remote_obj.makeDraggable({'handle':$('title')});
		this._setShortcut(remote_obj);

		// button to go back for the breadcrumb
		$('rm_previous').addEvent('click', this._goUp.bind(this));
		
		//form to go to a specific categoryID
		new Element('form',{
			'id':'rm_cid',
			'action':'#',
			'html':'<label for="cid">id:</label><input id="cid" type="text" /><label for="cid_blank">new window:</label><input id ="cid_blank" type="checkbox" />',
			'events':{
				'submit': function(event){
					event.preventDefault();
					this._gotoCID();
				}.bind(this)
			}
		}).injectInside(document.body);
		
		(eval(Cookie.read('GotoCategoryNewWindow'))) ?  $('cid_blank').set('checked','checked') : $('cid_blank').set('checked','') ;
		
		$('cid_blank').addEvent('click',function(){
			Cookie.write('GotoCategoryNewWindow', $('cid_blank').checked , {duration: 30});
		});
	},
	
	/* Function to get the size of an object */
	_getSize: function(obj){
		obj.setStyle('display','block');
		var size = obj.getSize();
		obj.setStyle('display','none');
		return size;
	},
	
	/* Function to center an object */
	_setPosition: function(obj) {
		var size = this._getSize(obj);
		var window_size = window.getSize();
		obj.setStyles({ 
			left: (window_size.x - size.x)/2,
			top: (window_size.y - size.y)/2
		});
	},
	
	/* Function to set the shortcuts */
	_setShortcut: function(obj){
		//get language information
		var lang = this.options.lang;
		var url = new URI(document.location);
		var index = (url.getData('lang')) ? lang.indexOf(url.getData('lang')) : lang.indexOf(this.options.default_lang);
		this.langIndex = index;
		
		window.onkeydown = function(e){
			var e = new Event(e);
			// CTRL + M has been pressed
			if(e.key=='m' && e.event.ctrlKey && obj.getStyle('display') == 'none'){
				this._show(obj);
			}
			
			// CTRL + N has been pressed (next language)
			if(e.key == 'n' && e.event.ctrlKey) {
				index = (index+1) % lang.length;
				this._setLanguage(lang[index]);
			}
			
			// CTRL + P has been pressed (previous language)
			if(e.key == 'p' && e.event.ctrlKey) {
				index--;
				if (index < 0) index = lang.length-1;
				this._setLanguage(lang[index]);
			}
			
			// CTRL + L has been pressed (display language menu)
			if(e.key == 'l' && e.event.ctrlKey) {
				if(!$('langz')){
					if($('IFInterfaceESLMenu').getStyle('width') == '20px') $('IFInterfaceESLMenu').getElement('.IFToggler').fireEvent('click');
					this._createLangList();	
				}
				else $('langz').destroy();
			}
			
			// CTRL + F has been pressed (show / hide the search form)
			if(e.key == 'f' && e.event.ctrlKey && obj.getStyle('display') == 'block') {
				$('rm_search').fireEvent('click');
			}
			
			// CTRL + c has been pressed (move to category)
			if(e.key == 'c' && e.event.ctrlKey) {
				$('cid_toggler').fireEvent('click');
			}
			
		}.bind(this);
	},
	
	/* Function to add a scroller if need be */	
	_addScroll : function(el) {
		if ($('slider')) {
			$('slider').setStyle('display', 'none');
		} else {
			var slider = new Element('div', {id : 'slider', styles : {display : 'none'}}).inject(remote_obj);
			new Element('div', {id : 'knob'}).inject(slider);
		}
				
		if(el.getHeight() > $('content').getHeight()) {
			
				$('slider').setStyle('display', 'block');
				var slider = new Slider('slider', 'knob', {
					mode : 'vertical',
					wheel : true,
					onChange : function(step){
						el.setStyle('marginTop', (el.getHeight() - $('content').getHeight() + 8) * -(step/100));
					}.bind(this)
				});
				
				el.addEvent('mousewheel', function(e){
					new Event(e).stop();
					slider.set(slider.step - e.wheel * 30);
				});
			
		}
	},
	
	/* Function to show the remote control 
	 * Also the MAIN function
	 */
	_show : function(obj) {
		//show the remote control with the mask
		this.overlay.toggle();
		this._setPosition(remote_obj);
		obj.setStyle('display','block');
		obj.fade('in');
		//if data haven't been loaded yet
		if (!this.dataload) {	
			this.spinner.show();
			this.sitemap_url = this.options.cs+'?server='+this.options.server+'&lang='+this.options.default_lang+this.options.sitemap_url;
			//ajax request
			new Request({
				url: this.sitemap_url,
				method: 'get',
				onSuccess: function(responseText, responseXML){
					responseText = responseText.replace(/–/gi,'-');
					responseText = responseText.replace(/&/gi,'&amp;');
					this.theTree = (new DOMParser()).parseFromString(responseText, "text/xml");
					// ajax request succeed
					this.spinner.hide();
					this.dataload = true;
					//display the first level
					this._createList(this.theTree.getElements('level1'));
					this._initSearch();
				}.bind(this)
				
			}).send();
		}
	},
	
	/* Function to close the remote control and the mask */
	_close : function(){
		remote_obj.fade('out');
		(function(){ remote_obj.setStyle('display','none') }).delay(300);
		this.overlay.toggle();
	},
	
	/* Function to create the languages list */
	_createLangList : function() {
		var lang = this.options.lang;
		var url = new URI(window.location);
		
		var langcontent = new Element('div',{ 'id':'langz', 'styles':{} }).inject(document.body);
				
		lang.each(function(el, i){
			url.setData({'server': this.options.server, 'lang':el}, true);
			new Element('a', {
				'html': el,
				'href': url,
				'class': (i == this.langIndex) ? 's' : ''
			}).inject(langcontent);
		},this);
	},
	
	/* Function to switch the site language (only used by NEXT and PREV)*/
	_setLanguage : function(lang) {
		var url = new URI(window.location);
		url.setData({'server': this.options.server, 'lang':lang}, true);
		window.location = url;
	},
	
	/* Function to initialize the search form, buttons */
	_initSearch : function(){
		//submit button
		$('rm_search').addEvent('submit',function(event){
			event.preventDefault();
			this._search(true);
		}.bind(this));
		
		//submit button and text input
		//stop the propagation of the form event
		$('rm_search').getElements('input[type=submit], input[type=text]').addEvent('click', function(event){
			event.stopPropagation();
		});
		
		//reset button
		$('rm_search').getElement('input[type=button]').addEvent('click', function(event){ 
			event.stopPropagation();
			this._resetSearch();
		}.bind(this));
		
		//form (open/close the formular by clicking on the it)
		$('rm_search').addEvent('click',function(event){
			if($('rm_search').getStyle('width') != '0px'){
				this._resetSearch();
				$('rm_search').getElement('input[type=text]').blur();
				$('rm_search').tween('width',0);
			}
			else {
				$('rm_search').tween('width',155);
				$('rm_search').getElement('input[type=text]').focus();
			} 
		}.bind(this))
	},
	
	/* Function to reset the search and show the first level */
	_resetSearch : function() {
		this.searchWord = null;
		$('rm_previous').empty().setStyle('visibility','hidden');
		$('rm_search').getElement('input[type=button]').setStyle('display','none');
		$('rm_search').getElement('input[type=text]').value = '';
		this._createList(this.theTree.getElements('level1'));
	},
	
	/* Function to search a pattern in the tree */
	_search : function(new_search) {
		if($('rm_search').getElement('input[type=text]').value != '' || this.searchWord){
			$('rm_previous').empty().setStyle('visibility','hidden');
			$('rm_search').getElement('input[type=button]').setStyle('display','block');
			
			this.searchWord = (this.searchWord && !new_search) ? this.searchWord : $('rm_search').getElement('input[type=text]').value.capitalize();

			var elements = new Array();
			var regex = new RegExp(this.searchWord.escapeRegExp(), 'i');
			this.theTree.getElements('[link]').each(function(el){
				if (regex.test(el.get('text'))) elements.push(el);
			},this);
			this._createList(elements);
		}
	},
	
	/* Function to go to a specific categoryID */
	_gotoCID : function() {
		if (new RegExp(/^[0-9]*$/).test($('rm_cid').getElement('input[type=text]').value)) {
			var url = new URI(window.location);
			var cid = $('rm_cid').getElement('input[type=text]').value;
			url.setData({'server': this.options.server,'item_categoryID':cid}, true);
			//add lang if paramater doesn't exist (after login)
			if (!url.getData('lang')) url.setData({'lang': this.options.default_lang}, true);
			($('cid_blank').checked) ? window.open(url, '_blank') : window.location = url;
		}
		else {
			alert();
			$('rm_cid').getElement('input[type=text]').value = '';
		}
		
		
	},
		
	/* Function to create and show the list */
	_createList : function(elements){
		$('content').empty();
		var list = new Element('ul');
		
		//foreach element to diplay get its level and check if it has children
		elements.each(function(el){
			var lvl = new RegExp(/level(\d)/).exec(el.get('tag'))[1].toInt();
			var children = (el.getNext() && el.getNext().get('tag') == 'subtree') ? el.getNext().getElements('level'+(lvl+1)) : [];
			
			//make a "a" tag with all information
			var copy = new Element('a',{
				'href':el.get('link'),
				'html':el.get('text'),
				'events':{
					'click': function(event){
						if (event.meta) {
							this._close();
						}else{
							event.stopPropagation();
							this.spinner.show();
						}
					}.bind(this)
				}
			});
			 
			copy.inject(list);
			
			//if it has children, show the next level on click
			if(children.length > 0){
				new Element('li',{
					'class': 'mother',
					'events':{
						'click': function(){
							$('rm_previous').setStyle('visibility','visible');
							this._makePath(el.get('text'));
							this.level = lvl+1;
							this.pointer = el;
							this._createList(children);
						}.bind(this)
					}
				}).wraps(copy)
			}
			else new Element('li').wraps(copy)
			
		},this);
		
		$('content').adopt(list);
		this._addScroll(list);
	},
	
	/* Function to make the path (breadcrumb) */
	_makePath : function(addedEl) {
		//remove the last element
		if (addedEl == '-1') {
			$('rm_previous').getLast().destroy();
			if($('rm_previous').getChildren().length == 0) $('rm_previous').setStyle('visibility','hidden');
		}
		//add the the actual level
		else {
			$('rm_previous').setStyle('visibility','visible');
			var el = new Element('span', {
				'html': addedEl,
				'class': this.level,
				'events': {
					'click': function(event) {
						event.stopPropagation();
						if(this.searchWord != null) this._search();
						else{
							for(i=this.level; i > el.get('class'); i--){
								this._goUp();
							}	
						}
					}.bind(this)
				}
				
			}).inject($('rm_previous'));
		}
	},
	
	/* Function to go up the tree */
	_goUp : function(){
		this.level--;
		this._makePath('-1');
		
		this._createList(this.pointer.getParent().getElements('level'+this.level));
		this.pointer = this.pointer.getParent().getPrevious();
	}
});
