var Finder = new Class({
	
	Implements : Options,
	
	options: {
		lang : 'chfr',
		lang_categoryID_adult: 23,
		lang_categoryID_junior: 630,
		lang_categoryID : {
			2496 : 23,
			7782 : 1003,
			7781 : 24,
			7793 : 22,
			7784 : 160			
		},
		selector : '#open_finder',
		
		underlay : true,
		autostart: false,
		
		server : 'eslagency',
		
		mode : 'default', // default or formular_id??
		
		schoolImage : true,
		schoolDetail : true,
		bypassSingleResult : false,
		
		category : 'adult',

		CS3 : 'cs3/app',
		CS2 : 'floor/cs',
		year : '2010',
		server_ID : '1',

		build : {
			container : 'wrapper',
			width : 326
		},
		boxes : [
			'flanguages',
			'fcountries',
			'ftowns',
			'fschools',
			'fschooldetail'
		],
		stepsParams : {	
			1 : 'orderby=desc&m=Finder&sct=lang&lstonly=1&valid=1',
			2 : 'noschool=1&order=name&m=Finder&lstonly=1&valid=1&sct=',
			3 : 'noschool=1&order=name&m=Finder&lstonly=1&valid=1&sct=',
			4 : 'noschool=1&order=name&m=Finder&lstonly=1&valid=1&sct='
		},
		language : {
			schoolfinder	: 'SchoolFinder',
			schooldetail 	: 'Détails de l\'école',
			select			: 'Sélectionner...',
			change			: 'Modifier...',
			quickquote		: 'Your quickquote',
			steps : [
				'Langues',
				'Pays',
				'Villes',
				'Ecoles',
				'Détail'
			]
		}
	},
	
	initialize: function(options){
		this.setOptions(options);
		this.loader = new Loader();						// Init the loader
		if (typeof(defaultLanguage) != 'undefined')
			this.options.lang = defaultLanguage;		// Init current lang
		
		if (typeof(finderLanguage) != 'undefined')
			this.options.language = $merge(this.options.language, finderLanguage);		// Load localisation
			
		if (typeof(options.language) != 'undefined')
			this.options.language = $merge(this.options.language, options.language);
		
		$$(this.options.selector).each(function(el){
			el.addEvent('click', function(e){
				new Event(e).stop();
				this.start(e.target.getProperty('rel'));
			}.bind(this));
		}, this);
			
		this.pos = 0;
		this.step = 0;
		this.path = [];
		this.labels = [];
		this.fxRunning = false;
		
		if(this.options.autostart) this.start();
	},
	
	start : function(target){
		target = target ? eval(target) : false;
		if (this.finder) {						
				this.step = 0;
				this.getChild({ID: this._GetCategoryID(), first: true, box:this.options.boxes[0]});	// start finder	
							
			
			$('finder').setStyles({
				'display': 'block',
				top : window.getScroll().y + 100
			});
			if ($('underlay')) {
				$('underlay').setStyle('display', 'block');
				this.underfx.start('opacity', 0.3);
			}
			if(Browser.Engine.trident && Browser.Engine.version == 4) $('underlay_ie').setStyle('display', 'block');
			if (target) $('flanguages').getElement(".cid_" + target[0]).fireEvent('click');
		} else { 
			this._build(); 						// Create the finder
			this.getChild({ID: this._GetCategoryID(), first: true, box:this.options.boxes[0]});	// start finder			
		}
		
		//slide to target
		this.target = target;
		
		if (this.target) this.slider.start('left', this.options.build.width * -this.target.length);
	},
	
	
	/*
	Function: _GetCategoryID
		Get the right list according the product type
	*/
	_GetCategoryID : function() {
		if (typeof(defaultLanguage) != 'undefined') this.options.lang = defaultLanguage;
		
		// Check if is adult or junior
		var cid = (this.options.category == 'adult') ? this.options.lang_categoryID_adult : this.options.lang_categoryID_junior;
		
		// Check if is adult, gap or cadres (in the same formular)
		if (this.options.category == 'adult' && $('forms_categoryID')) { cid = this.options.lang_categoryID[$('forms_categoryID').get('value')]; }
		
		// Check speciality for Gap Year
		if (cid == '1003') {
			if (this.options.lang == 'fr' || this.options.lang == 'de' || this.options.lang == 'it') { this.options.lang = 'ch' + this.options.lang; }
			else if (this.options.lang == 'en') { this.options.lang = 'chfr'; }				
		} 
		
		if (cid == '24') {
			if (this.options.lang == 'fr' || this.options.lang == 'de' || this.options.lang == 'it') { this.options.lang = 'ch' + this.options.lang; }
			else if (this.options.lang == 'cz') { this.options.lang = 'en'; }				
		}
		
		return cid;
	},
	
	/*
	Function: getChild
		
		Parameters:
			-
	*/
	getChild :function(opt){
		if(!opt.first) this.hideBox(opt.parent.getProperty('class'));		
		var param = "lng="+this.options.lang+"&cid=" + opt.ID;
		
		this.getList({
			'param' : param,
			'box' : opt.box,
			'cid' : opt.ID,
			'txt' : opt.txt,
			'first' : opt.first || false
		});
	},
	
	/*
	Function: addLink
		check in the current box all li to add an Event
		
		Parameters:
			box - to check
	*/
	addLink :function(box){
		$(box).getElements('*[class*=cid]').each(function(el){	
			var regex = /cid_(\w+)/;
			if (el.getProperty('class').match(regex)) {
				var cid = el.getProperty('class').match(regex)[1];
				var nextBox = this.options.boxes[this.options.boxes.indexOf(box)+1];
				el.addEvent('click', function(e){
					if(this.fxRunning && !this.options.bypassSingleResult) return;
					this.fxRunning = true;
					if (box == 'ftowns') { this.cid = cid; } 
					if (nextBox == 'fschooldetail') {
						this.getSchoolDetail(cid,'fschooldetail');	
					} else if(nextBox == 'fschoolslist') {
						this.getSchoolsList({
							'ID' : cid, 
							'box' : nextBox, 
							'parent' : el.getParent(),
							'txt' : el.get('text').trim()
						});
					} else {
						this.getChild({
							'ID' : cid, 
							'box' : nextBox, 
							'parent' : el.getParent(),
							'txt' : el.get('text').trim()
						});	
					}
				}.bind(this));
				
				//target ?
				if (this.target.length > this.step && this.target[this.step] == cid) {
					el.fireEvent('click');
				} else if (this.target.length == this.step) {
					this.target = false;
				}
			}
		}, this);
		
		//bypass slide
		if(this.options.bypassSingleResult && $(box).getElements('*[class*=cid]').length == 1) {
			var el = $(box).getElement('*[class*=cid]');
			el.fireEvent.delay(50, el, 'click');
		}
	},
	
	/*
	Function: getList
		get the category list by Ajax
		
		Parameters:
			param - of the ajax url
			box - current box 
			cid - current categoryID
	*/
	getList :function(opt){	
		this.loader.load('mfinder', 'center');	
		var myAjax = new Request({
			url : window.location.protocol + "//" + window.location.hostname + "/" + this.options.CS3 + '?' + this.options.stepsParams[this.step+1] + '&' + opt.param,
			method: 'get',
			onComplete: function(req) {
				if (req) {
					var el = $(opt.box).set('html', req);
					this.addLink(opt.box);
					if (!opt.first && !this.target) this.slide_next();
					this.addScroll(el);
					this.makePath(opt);
				} else if (this.options.mode != 'formular_id') {
					var param = "?server="+this.options.server+"&lang="+this.options.lang+"&item_categoryID=" + opt.cid;
					window.location = window.location.protocol + "//" + window.location.hostname + "/" + this.options.CS2 + param;
				}
				this.loader.load('mfinder');	
			}.bind(this)
		}).send();
	},
	
	addScroll : function(el){
		if ($('slider')) {
			$('slider').setStyle('display', 'none');
		} else {
			var slider = new Element('div', {id : 'slider', styles : {display : 'none'}}).inject('finder');
			new Element('div', {id : 'knob'}).inject(slider);
		}
				
		if(el.getHeight() > $('inner').getHeight()) {
			(function(){
				$('slider').setStyle('display', 'block');
				var slider = new Slider('slider', 'knob', {
					mode : 'vertical',
					wheel : true,
					onChange : function(step){
						el.setStyle('top', (el.getHeight() - $('inner').getHeight() + 8) * -(step/100));
					}.bind(this)
				});
				
				el.addEvent('mousewheel', function(e){
					new Event(e).stop();
					slider.set(slider.step - e.wheel * 10);
				});
			}).delay(500);
		}
	},
	
	slide_next : function(){
		var pos = this.options.build.width * -this.step;
		this.slider.start('left', pos);
	},
	
	makePath : function(opt){
		if (!opt || this.step == 0) {
			//clean path
			$('path').getChildren().dispose();
			
			//rebuild path array until step
			for (var i = 0, newPath = []; i < this.step; i++) newPath.push(this.path[i]);
			this.path = newPath;
		} else {
			if (opt && opt.txt) var theclass = 'tooltips', thetitle = opt.txt;
			else var theclass = '', thetitle = '';

			//make new element
			var step = this.step;
			var element = new Element('a', {
				html : this.options.language.steps[step-1],
				'class' : theclass,
				href : '#',
				title : thetitle,
				events : {
					click : function(e){
						this.tips.detach('#finder .tooltips');
						$$('.finderTip').destroy();
						this.tips = false;
						
						this.step = step-1;
						new Event(e).stop();
						$(this.labels[step-1].box).setStyle('top', 0);
						this.addScroll($(this.labels[step-1].box));
						this.slider.start('left', this.options.build.width * -this.step);
						this.makePath();
					}.bind(this)
				}
			}).store('tip:title', thetitle).store('tip:text', '');
			this.path.push(element);
		}	
		
		//make path
		this.path.each(function(el, i){
			el.setProperty('title', el.retrieve('tip:text'))
			if (i == this.step - 1) {
				el.setStyle('marginLeft', 300);
				new Fx.Tween(el).start('marginLeft', 0);
			}
			el.inject('path');
		}.bind(this));
		
		if (opt) this.labels[this.step] = opt;
		$('step-txt').set('html', this.options.language.steps[this.step]);
		$('step').set('html', ++this.step);
		if(this.tips) {
			this.tips.attach('#finder .tooltips');
		} else {
			this.tips = new Tips('#finder .tooltips', {
				className : 'finderTip',
				fixed : true
			});
		}
		
	},
	
	/*
	Function: hideBox
		Clean child box
		
		Parameters:
			parentbox - clean his child   
	*/
	hideBox : function(parentbox){
		var regex = /lvl(\d+)/;
		if (parentbox.match(regex)) {
			var lvl = parentbox.match(regex)[1].toInt() + 1;
			for (var i=lvl; i<=this.options.nbr_lvl; i++) { $$('ul.lvl'+i).set('html',""); }
		}
	},
	
	/*
	Function: getSchoolDetail
		Get school info and create the school detail list
		
		Parameters:
			cid - current categoryID
			box - current box
	*/
	getSchoolDetail : function(cid, box) {
		$(box).set('html', ''); // Clear the school detail box
		
		var fld = "language.name,language.iname,language.ID,language.alloworder,element.argo_provider_code,language.validated";
		
		new Request.JSON({
			url : window.location.protocol + "//" + window.location.hostname + "/" + this.options.CS3 + '?m=School&a=getInfo&cid=' + cid + 
				'&year=' + this.options.year + '&srvID=' + this.options.server_ID + "&lng="+this.options.lang + "&fld=" + fld,
			method: 'get',
			onSuccess: function(req, reqtxt) {
				if (req) {
					if (this.options.mode == 'formular_id') {
						new Element('li').set('html',this.options.language.select).inject($('fschooldetail')).addEvent('click', function(e){ 
							this.fillForm({
								country_id : this.labels[2].cid,
								country_name : this.labels[2].txt,
								town_id : this.labels[3].cid,
								town_name : this.labels[3].txt,
								school_cid : cid,
								school_id : req.language.ID,
								school_name : req.language.name,
								event : e,
								argo_code : req.element.argo_provider_code
							});
						}.bind(this));
					}else{
						new Element('li').set('html',this.options.language.schooldetail).inject($('fschooldetail')).addEvent('click', function(e){ 
							this._redirectURL("item_categoryID=" + cid, '0');
						}.bind(this));
					}
					var html = this.options.schoolDetail ? req.language.iname.clean().match(/^(.{0,170}) /mi)[1] + '...' : '';
					var li = new Element('li', {
						html: html,
						'class': 'detail'
					}).inject($('fschooldetail'), 'top');
					if(this.options.schoolImage) new Element('img', {src : '/data/school/s/' + req.language.ID + '.jpg'}).inject(li, 'top');
					new Element('h4', {html : req.language.name}).inject(li, 'top');
				}
				if (req.language.alloworder == '1' && this.options.mode != 'formular_id') {
					new Element('li').set('text',this.options.language.quickquote).inject($('fschooldetail')).addEvent('click', function(e){ 
						var param = "category_ident=quickquoteschool&ID_school=" + req.language.ID + "&CID_school=" + this.cid + "&UsedYear=" + this.options.year + "&ID_section=1";
						this._redirectURL(param, '1');							
					}.bind(this));
				}
				this.addScroll($('fschooldetail'));
				this.slide_next();
				this.makePath({box : 'ecoles', txt : req.language.name});
			}.bind(this)
		}).send();
	},
	
	/*
	Function: getSchoolList
		Get school list and create list
		
		Parameters:
			cid - current categoryID
			box - current box
	*/
	
	getSchoolsList : function(opt) {	
		$(opt.box).set('html', ''); // Clear the school detail box
		
		var params = '?lang='+this.options.lang+'&item_categoryID='+opt.ID+'&'+this.options.stepsParams[this.step+1];
		var url = window.location.protocol + "//" + window.location.hostname + "/" + this.options.CS2 + params
		new Request({
			url : url,
			method: 'get',
			onSuccess: function(req) {
				if (req) {
					//inject result
					$(opt.box).set('html', req);
					
					//parse links
					
					//addlinks on coco
				}
				this.addScroll($(opt.box));
				this.slide_next();
				this.makePath({box : 'ecoles', txt : opt.txt});
			}.bind(this)
		}).send();
	},
	
	fillForm : function(data){
		$('school_town_txt').set('html', data.country_name + ' :: ' + data.town_name + ' :: ' + data.school_name + '<br />');
		$('schoolfinder').set('html', this.options.language.change);
		
		$('school_town').value = data.town_id;
		$('sschool').value = data.school_cid;
		if ($('schoolID')) $('schoolID').value = data.school_id;
		if ($('school_provider_code')) $('school_provider_code').value = data.argo_code;
		
		this.close.fireEvent('terminate', data.event);
	},

	/*
	Function: _redirectURL
		Redirect user as his choice
		
		Parameters:
			param -	of the CMS url
			mode  - if open the page in the same page or in a new page
	*/	
	_redirectURL : function(param, mode){
		var url =  window.location.protocol + "//" + window.location.hostname + "/" + this.options.CS2 + "?server="+this.options.server+"&lang="+this.options.lang+"&" + param;
		
		if (mode == '0') { window.location = url; } 	// redirect user to the same page
		else { window.open(url); }					// redirect user to a new page or a new tab
	},
	
	/*
	Function: build
		Create box to the school finder
	*/
	_build : function() {
		this.finder = new Element('div', {
			'id' : 'finder',
			'class' : this.options.build.container,
			styles : {
				top : window.getScroll().y + 100,
				left : (window.getWidth() - this.options.build.width) / 2
			}
		});
		var main = new Element('div', {'id' : 'mfinder'}).inject(this.finder);
		new Element('h3', {'html' : this.options.language.schoolfinder}).inject(main);
		var step = new Element('div', {'class' : 'step'}).inject(main, 'top');
		new Element('span', {'id' : 'step', html : '1'}).inject(step);
		new Element('span', {'id' : 'step-txt', html : this.options.language.steps[0]}).inject(step);
		new Element('div', {'id' : 'path'}).injectInside(main);
		var inner = new Element('div', {'id' : 'inner'}).injectInside(main);
		this.options.boxes.each(function(box, i){
			new Element('ul', {'id' : box, 'class' : 'lvl' + i}).inject(inner);
		});
				
		this.close = new Element('a', {
			'class' : 'close',
			'href' : '#',
			events : {
				'terminate' : function(e){
					new Event(e).stop();
					$('finder').setStyle('display', 'none');
					if($('underlay'))
						$('underlay').setStyles({
							'display' : 'none',
							opacity : 0
						});
					if(Browser.Engine.trident && Browser.Engine.version == 4) $('underlay_ie').setStyle('display', 'none');
					$$('#fcountries, #ftowns, #fschools, #fschooldetail').set('html', '');
					
					//reset values
					this.step = 0;
					$(this.labels[0].box).setStyle('top', 0);
					this.addScroll($(this.labels[0].box));
					this.slider.set('left', this.options.build.width * -this.step);
					this.makePath();
				}.bind(this),
				click : function(e){
					this.fireEvent('terminate', e);
				}
			}
		}).inject(this.finder);
		
		this.finder.injectInside(document.body);
		
		new Drag('finder', {
			handle : $$('#finder h3')
		});
		
		//Underlay
		if(Browser.Engine.trident && Browser.Engine.version == 4)
			new Element('iframe', {
				id : 'underlay_ie',
				scrolling : 'no',
				frameborder : 0,
				src:'about:blank',
				styles : {
					position : 'absolute',
					top : 0,
					left : 0,
					display : 'block',
					filter: 'mask()',
					background : '#FFF',
					width : window.getWidth(),
					height : window.getScrollSize().y,
					opacity : 0.0001,
					zIndex : 99
				}
			}).inject(document.body);
		
		if (this.options.underlay) {
			new Element('div', {
				id : 'underlay',
				styles : {
					position : 'absolute',
					top : 0,
					left : 0,
					width : window.getWidth(),
					height : window.getScrollSize().y,
					background : '#000',
					opacity : 0,
					zIndex : 100
				},
				events : {
					click : function(e){
						this.close.fireEvent('terminate', e);
					}.bind(this)
				}
			}).inject(document.body);
			this.underfx = new Fx.Tween('underlay').start('opacity', 0, 0.3);
		}
			
		//make the FX
		this.slider = new Fx.Tween('inner', {
			link : 'chain',
			onComplete : function(){
				this.fxRunning = false;
			}.bind(this)
		});
	}
});
