/**
 * 
 * Routes Online - Site.js
 * Copyright © Fluid Creativity 2008
 *
 * Main site Javascript functionality. Dependent on Mootools 1.2 SVN
 *
 */

Site = {
	
	popup: null,
	popupTimer: null,
	inboxFeed: null,
	proposalsFeed: null,
	
	init: function () {
		// temp
		Site.searchSetup();
		
		Site.rollOvers();
		Site.clearDefaults();
		Site.navigation();
		Site.uploadDocuments();
		Site.uploadRoutes();
		Site.infoBoxen();
		Site.tabCreator();
		Site.sideScrollers();
		Site.profileDataAnimation();
		Site.initRouteList();
		Site.homepageFlash();
		Site.confirmDelete();
		Site.EventPRC();
		Site.initTickerTape();
		
		var inboxFolder = $('navigation').getElement('.inboxFolder');
		if (inboxFolder) {
			new Request.JSON({
				url: '/ajax/inbox-pop.php',
				onSuccess: function(data) {
					Site.inboxFeed = data;
					Site.inboxPopup(inboxFolder, data);
				}
			}).get({ folder: 'inbox', lang: MultiLingual.langCode });
		}
		
		var inboxProposals = $('navigation').getElement('.inboxProposals');
		if (inboxProposals) {
			new Request.JSON({
				url: '/ajax/inbox-pop.php',
				onSuccess: function(data) {
					Site.proposalsFeed = data;
					Site.inboxPopup(inboxProposals, data);
				}
			}).get({ folder: 'proposals', lang: MultiLingual.langCode });
		}
		
		if ($('meetingRequests')) {
			// preload loading image
			var preload = new Image();
			preload.src = "/images/ajax-loader.gif";
			
			// replace submit button with loading icon
			$('meetingRequests').adopt(
				new Element('img', {
					'src': '/images/ajax-loader.gif',
					'alt': 'Loading meeting requests'
				})
			).getElement('#meetingSubmit').destroy();
			
			$('meetingRequests').submit();
		}
		
		/*if (!Cookie.read('survey_status') && $('headerNotice')) {
			$('headerNotice').destroy();
			Site.displaySurveyDialog();
		}*/
	},
	
	// temp - 03-06-2008 ;)
	searchSetup: function () {
		if ($('searchForm')) {
			var links = $('searchForm').getElement('ul.tabList').getChildren('li');
			var fieldset = $('searchForm').getElement('fieldset');
		}
		
		var userGuideSelected = false;
		var p = null;
		
		links.addEvent('click', function(event) {
			event.stop();
			links.removeClass('selected');
			this.addClass('selected');
		});
	},

	clearDefaults: function () {
		$$('.hasDefault').addClass('active').addEvent('focus', function() {
			if (this.value == this.defaultValue && !this.retrieve('cleared')) {
				this.value = '';
				this.store('cleared', true);
				
				this.removeClass('active');
			}
		});
	},

	rollOvers: function () {
		var preload = new Image();
		
		$$('.rollOver').each(function(el){
			if (el.src.test(/\.(gif|jpg|jpeg|png)$/i)) {
				
				// preload images
				preload.src = el.src.replace(/\.(gif|jpg|jpeg|png)/, '-over.$1');
				
				el.addEvents({
					mouseover: function() {
						this.src = this.src.replace(/\.(gif|jpg|jpeg|png)/, '-over.$1');
					},
					
					mouseout: function() {
						this.src = this.src.replace(/-over\.(gif|jpg|jpeg|png)/, '.$1');
					}
				});
			}
		});
	},
	
	// purely for visual effects.
	navigation: function () {
		$('mainNav').getElements('li > a').each(function (el, i) {
			if (el.getParent().hasClass('selected')) return;
			
			el.store('morphInst', new Fx.Morph(el, {
				duration: 170,
				link: 'cancel'
			}));
			
			if (el.getParent().getParent().hasClass('firstLevel')) {
				el.addEvent('mouseenter', function () {
					el.setStyle('border-left', '5px solid #b1d1e4');
					el.retrieve('morphInst').start({
						'border-color': ['#b1d1e4', '#39839f'],
						'color': '#C90D19'
					});
				}).addEvent('mouseleave', function () {
					el.retrieve('morphInst').start({
						'border-color': ['#39839f', '#b1d1e4'],
						'color': '#6f6f6f'
					});
				});
			} else if (el.getParent().getParent().hasClass('secondLevel')) {		
				el.addEvent('mouseenter', function () {
					el.setStyle('border-left', '5px solid #e2e2e2');
					el.retrieve('morphInst').start({
						'border-color': ['#e2e2e2', '#bdbdbd'],
						'color': '#87a0af'
					})
				}).addEvent('mouseleave', function () {
					el.retrieve('morphInst').start({
						'border-color': ['#bdbdbd', '#e2e2e2'],
						'color': '#3983af'
					})
				});
			}			
		});
		
		if ($('quickLinksMenu')) {
			$('quickLinksMenu').addEvent('change', function(e) {
				if (this.value.length > 0) {
					this.getParent('form').submit();
				}
			}).getNext().addClass('hidden');
		}
		
		var airportList = $('airportList');
		
		if (airportList) {
			airportList.store('origWidth', airportList.getStyle('width').toInt());
			airportList.store('origHeight', airportList.getStyle('height').toInt());
			var airportLinks = airportList.getElements('li > a');

			airportList.set('tween', { 'link': 'chain', 'duration': 100, 'transition': 'quad:out' });

			airportList.getElement('.internal').adopt(
				new Element('div', { 'id': 'airportListItems' })
			);

			airportList.getElement('.internal').adopt(
				new Element('a', { 'id': 'airportListClose', 'href': '#', 'text': MultiLingual.getString('js_close') }).fade('hide').addEvent('click', function(e) {
					e.stop();

					if (airportList.retrieve('isOpen')) {						
						this.fade('hide');			
						$('airportListItems').empty();
						airportLinks.getParent().removeClass('selected');
						
						airportList.removeClass('active').removeClass('loading').eliminate('isOpen').tween('height', airportList.retrieve('origHeight')).tween('width', airportList.retrieve('origWidth'));
					}
				})
			);
		
			airportLinks.addEvent('click', function(e) {
				e.stop();
				
				airportLinks.getParent().removeClass('selected');
				this.getParent().addClass('selected');

				var airportListItems = $('airportListItems').empty();

				if (!airportList.retrieve('isOpen')) {
					airportList.addClass('active').store('isOpen', true).tween('width', 700);
					$('airportListClose').fade('show');
				}
				
				airportList.addClass('loading');
				
				new Request.JSON({
					url: '/ajax/enhanced-airports.php',
					onSuccess: function(data) {
						if (!airportList.retrieve('isOpen')) return;
										
						if (data && data.length > 0) {
							var airportProfiles = new Element('ul').inject($('airportListItems'));
							var perColumn = Math.ceil(data.length / 2);
							
							$each(data, function(profile, i) {
								airportProfiles.adopt(new Element('li').adopt(new Element('a', { 'href': profile.href, 'text': profile.title })));
								
								if (data.length > 4 && (i + 1) % perColumn == 0 && i + 1 < data.length) {
									airportProfiles = new Element('ul').inject($('airportListItems'));
								} 
							});
						} else {
							airportListItems.adopt(new Element('p').adopt(new Element('em', { 'text': MultiLingual.getString('js_noairports') })));
						}
						
						airportListItems.adopt(new Element('div', { 'class': 'clearer' }));
						
						var maxHeight = airportList.retrieve('origHeight');
						
						$('airportListItems').getElements('ul').each(function(el) {
							maxHeight = Math.max(maxHeight, el.getStyle('height').toInt() + 10);
						});
						
						airportList.tween('height', maxHeight).removeClass('loading');
					}
				}).get({ continent: this.get('rel'), lang: MultiLingual.langCode });
			});

			document.addEvent('keyup', function(e) {				
				e.stop();
				if (e.key != 'esc' || !airportList.retrieve('isOpen')) return;
				
				$('airportListClose').fade('hide');					
				$('airportListItems').empty();
				airportLinks.getParent().removeClass('selected');
				
				airportList.removeClass('active').removeClass('loading').eliminate('isOpen').tween('height', airportList.retrieve('origHeight')).tween('width', airportList.retrieve('origWidth'));
			});
			
			airportList.addEvent('blur', function(e) {				
				e.stop();
				if (!airportList.retrieve('isOpen')) return;
							
				$('airportListClose').fade('hide');					
				$('airportListItems').empty();
				airportLinks.getParent().removeClass('selected');
				
				airportList.removeClass('active').removeClass('loading').eliminate('isOpen').tween('height', airportList.retrieve('origHeight')).tween('width', airportList.retrieve('origWidth'));
			});
		}
	},
	
	uploadDocuments: function () {
		if ($('uploadDocuments')) {
			$('uploadDocuments').adopt(new Element("fieldset").addClass("firstItem").adopt($('uploadDocuments').getChildren()));
			new Element("legend", { text: MultiLingual.getString('js_uploaddocuments') }).inject($('uploadDocuments'), 'top');
			
			$('uploadDocuments').adopt(new Element("div", { id: 'addLink' }).adopt(new Element("a", { href: '#', text: MultiLingual.getString('js_adddocument') }).addEvent("click", function(e) {
				e.stop();

				var fieldset = $('uploadDocuments').getElement("fieldset").clone().inject(this.getParent(), 'before');
				fieldset.removeClass("firstItem").getElements("input").set({ value: '', styles: { height: 'auto' }});

		                fieldset.adopt(new Element("a", { href: '#', text: MultiLingual.getString('js_remove') }).addEvent("click", function(e) {
		                	e.stop();
		                	
		                	$(this.parentNode).dispose();
				}));
			})));
		}
	},

	uploadRoutes: function () {
		if ($('uploadRoutes') && $('routeList')) {
			$('routeList').getElements("a").addEvent("click", Site.editRoute);
			
			$('uploadRoutes').adopt(new Element("div", { id: 'addLink' }).adopt(new Element("a", { href: '#', text: MultiLingual.getString('js_addroute') }).addEvent("click", function(e) {
				e.stop();
				
				var airportId = $('airportid').value ;
				var routeType = $('routetype').value;
				
				if (airportId && routeType) {
					var rowCount = $('routeList').getElements("tr").length - 1;
					
					$('routeList').getElement('tbody').adopt(new Element("tr").adopt(
						new Element("td", { text: $('airportid').getElements('option')[$('airportid').selectedIndex].text }),
						new Element("td", { text: $('routetype').getElements('option')[$('routetype').selectedIndex].text }),
						
						new Element("td").adopt(
							new Element("a", { href: '#', text: 'Edit' }).addEvent("click", Site.editRoute)
						),
						
						new Element("td").adopt(
							new Element("input", { type: 'hidden', name: 'airportid['+ rowCount + ']', value: airportId }),
							new Element("input", { type: 'hidden', name: 'routetype[' + rowCount + ']', value: routeType }),
							new Element("input", { type: 'checkbox', name: 'delete[' + rowCount + ']', value: 'true' })
						)
					));
					
					$('airportid').value = '';
					$('routetype').value = '';
				}
			})));
		}
	},
	
	editRoute: function (e) {
		e.stop();

		$('routeList').store('currentRoute', $(e.target).getParent());
		var routeId = $(e.target).get('rel');
					
		var existingData = $(e.target).getParent().getNext().getElements('input[type=hidden]');

		if (existingData.length > 0) {
			var route = {};

			existingData.each(function(el) {
				route[el.name.match(/[a-z]+/)] = el.value;
			});
			
			Site.displayRouteDialog(route);
		} else if (routeId > 0) {
			new Request.JSON({
				url: '/ajax/opportunity-data.php',
				onSuccess: function(data) {
					Site.displayRouteDialog(data);
				}
			}).get({ 'routeid': routeId, lang: MultiLingual.langCode });
		} else {
			Site.displayRouteDialog();
		}
	},

	displayRouteDialog: function(route) {	
		if (!Site.opportunityDialog) {
			new Request.HTML({
				url: '/ajax/opportunity-form.php',
				onSuccess: function(tree, elements, html) {				
					var dialogHTML = new Element("div", { 'id': 'opportunityDialog', 'class': 'popupDialog' }).adopt(tree);
					$(document.body).adopt(dialogHTML);
										
					Site.opportunityDialog = new PopupDialog(dialogHTML, { 'actionSelector': 'div.submit input' });
					Site.opportunityDialog.callback = Site.saveRoute;
					tinyMCE.execCommand('mceAddControl', false, 'descriptionPopup');
					
					Site.loadRoute(route);
				}
			}).get({ lang: MultiLingual.langCode });
		} else {
			Site.loadRoute(route);
		}
	},

	loadRoute: function(route) {
		var dialog = $(Site.opportunityDialog.dialog);
		
		if (dialog) {
			dialog.getElementById('routetypePopup').value = (route.routetype ? route.routetype : '');
			dialog.getElementById('airportidPopup').value = (route.airportid ? route.airportid : '');
			dialog.getElementById('descriptionPopup').value = (route.description ? route.description : '');
	
			var editor = tinyMCE.getInstanceById('descriptionPopup');
			if (editor) editor.setContent(route.description ? route.description : '');
	
			Site.opportunityDialog.openDialog();
		}
	},
	
	saveRoute: function() {
		var dialog = $(Site.opportunityDialog.dialog);
					
		var description = (tinyMCE.activeEditor ? tinyMCE.activeEditor.getContent() : dialog.getElementById('descriptionPopup').value);	
		var routeType = dialog.getElementById('routetypePopup').value;
		var airportId = dialog.getElementById('airportidPopup').value;
		
		var currentRoute = $('routeList').retrieve('currentRoute').getParent();
		
		var rowData = currentRoute.getChildren();
		rowData[0].set('text', dialog.getElementById('airportidPopup').getElements('option')[dialog.getElementById('airportidPopup').selectedIndex].text);
		rowData[1].set('text', dialog.getElementById('routetypePopup').getElements('option')[dialog.getElementById('routetypePopup').selectedIndex].text);

		currentRoute.getLast().getElements('input[type=hidden]').destroy();

		currentRoute.getLast().adopt(
			new Element("input", { 'type': 'hidden', 'name': 'airportid[' + (currentRoute.rowIndex-1) + ']', 'value' : airportId }),
			new Element("input", { 'type': 'hidden', 'name': 'routetype[' + (currentRoute.rowIndex-1) + ']', 'value' : routeType}),
			new Element("input", { 'type': 'hidden', 'name': 'description[' + (currentRoute.rowIndex-1) + ']', 'value' : description })
		);
	},

	displaySurveyDialog: function() {	
		new Request.HTML({
			url: '/ajax/survey.php',
			onSuccess: function(tree, elements, html) {				
				var dialogHTML = new Element("div", { 'id': 'surveyDialog', 'class': 'popupDialog' }).adopt(tree);
				$(document.body).adopt(dialogHTML);
									
				var opportunityDialog = new PopupDialog(dialogHTML);
				opportunityDialog.closeCallback = function() {
					Cookie.write('survey_status', 'delayed', { 'duration': 2 });
				};			
				opportunityDialog.openDialog()
			}
		}).get({ lang: MultiLingual.langCode });
	},

	loadRoute: function(route) {
		var dialog = $(Site.opportunityDialog.dialog);
		
		if (dialog) {
			dialog.getElementById('routetypePopup').value = (route.routetype ? route.routetype : '');
			dialog.getElementById('airportidPopup').value = (route.airportid ? route.airportid : '');
			dialog.getElementById('descriptionPopup').value = (route.description ? route.description : '');
	
			var editor = tinyMCE.getInstanceById('descriptionPopup');
			if (editor) editor.setContent(route.description ? route.description : '');
	
			Site.opportunityDialog.openDialog();
		}
	},

	// These are the boxes for My Messages and My Favourites
	infoBoxen: function () {
		$$('div.infoBox').each(function (infobox, i) {
			var ul = infobox.getElement('ul');
			var li = ul.getChildren('li').setStyle('position', 'static');
			var trigger = infobox.getElement('h2').setStyle('cursor', 'pointer');
			
			var deleteLinks = ul.getElements('.deleteLink');
			if (deleteLinks) deleteLinks.setStyle('display', 'none');
			
			ul.set('slide', { 
				duration: 700, 
				transition: 'quad:out', 
				link: 'chain', 
				onStart: function () { 
					if (infobox.hasClass('open')) {
						deleteLinks.setStyle('display', 'none');
						li.setStyle('position', 'static');
					}
					infobox.toggleClass('open').toggleClass('closed');
				},
				onComplete: function () {
					if (infobox.hasClass('open')) {
						deleteLinks.setStyle('display', 'block');
						li.setStyle('position', 'relative');
					}
				}
			});
			
			// keep mail open by default
			if (infobox.id == 'messageBox' || infobox.hasClass('onContactPage')) {
				infobox.addClass('open');
			} else {				
				ul.get('slide').hide();
				infobox.addClass('closed');
			}
			
			trigger.addEvent('click', function () {
				ul.get('slide').toggle();
			});
		});
	},
	
	// FOR I AM THE CREATOR OF TABS!
	tabCreator: function () {
		$$('.tabWrapper').each(function (el) {
			if (el.getChildren('.tabTitle').length) {
				el.store('tabs', new Tabr(el));
			}
		});
	},
	
	// latest members scrollers
	sideScrollers: function () {
		$$('.sideBox').each(function (el, i) {
			var type = el.id.match(/^(.*?)SideBox$/)[1];
			
			new Slidr(el, type, {
				initialDelay: (i * 2000 + 3000),
				animDuration: 2000,
				rows: (el.hasClass('singleRow') ? 1 : 2)
			});
		});
	},
	
	initLiveSearch: function () {
		new LiveSearch('searchText', '/search.php');
	},
	
	profileDataAnimation: function () {
		var triggers = $$('.contentBlock + a');
		
		var minHeight = 30;
		
		var contentBlocks = $$('.contentBlock').setStyle('overflow', 'hidden');
		
		contentBlocks.each(function (el) {
			el.store('origHeight', el.getSize().y);
			el.store('tweenFx', new Fx.Tween(el).set('height', minHeight));
			el.store('open', false);
		});
		
		triggers.addEvent('click', function (e) {
			e.stop();
			
			var content = this.getPrevious('div');
			var open = content.retrieve('open');
			var fx = content.retrieve('tweenFx');
			var origHeight = content.retrieve('origHeight');
			
			// make sure all content blocks are "closed"
			contentBlocks.each(function (el) {
				if (el.retrieve('open')) {
					el.retrieve('tweenFx').start('height', minHeight);
					el.store('open', false);
					if (el.hasClass('selected')) el.removeClass('selected');
				}
			});
			
			if (!open) {
				fx.start('height', origHeight);
				content.store('open', true);
				content.toggleClass('selected');
			} else {
				fx.start('height', minHeight);
				content.store('open', false);
				content.toggleClass('selected');
			}
			
		});
	},
	
	initRouteList: function () {
		if ($('routeList')) {
			var triggers = $('routeList').getElements("dt + dd").getPrevious();
			var contentBlocks = $('routeList').getElements("dd").setStyle('overflow', 'hidden');
	
			contentBlocks.each(function(el) {
				el.store('origHeight', el.getSize().y);
				el.store('tweenFx', new Fx.Tween(el).set('height', 0));
				el.store('open', false);
			});
			
			triggers.each(function(el) {
				if (el.getNext().hasChildNodes()) {
					el.adopt(new Element("a", { 'href': '#', 'class': 'viewLink', 'text': MultiLingual.getString('js_viewdetails') }).addEvent("click", function(e) {
						e.stop();
						
						var content = el.getNext();
						var open = content.retrieve('open');
						var fx = content.retrieve('tweenFx');
						var origHeight = content.retrieve('origHeight');
	
						this.toggleClass("open");
			
						if (!open) {
							fx.start('height', origHeight);
							content.store('open', true);
						} else {
							fx.start('height', 0);
							content.store('open', false);
						}	
					}));
				}
			});
		}
	},
	
	homepageFlash: function () {
		var staticBase = "http://static.routesonline.com";

		if ($('promoVideo')) {
			var swf = new Swiff(staticBase + '/flash/promo.swf', {
				container: 'promoVideo',
				width: 656,
				height: 369
			});
		}
		
		if ($('uploadPromo')) {
			var swf = new Swiff(staticBase + '/flash/uploadPromo.swf', {
				container: 'uploadPromo',
				width: 576,
				height: 112
			});
		}
	},
	
	inboxPopup: function (inboxLink, inboxFeed) {
		
		if (inboxLink && inboxFeed.length) {
			inboxLink.addEvent('mouseenter', function () {
				this.popupTimer = this.buildPopup.delay(300, this, inboxLink, inboxFeed);
			}.bindWithEvent(this));
			
			inboxLink.addEvent('mouseleave', function () {
				this.popupTimer = $clear(this.popupTimer);
				if (this.popup) this.removePopup();
			}.bindWithEvent(this));
		}
	},
	
	buildPopup: function (inboxLink) {
		// do an ajax call, get inbox feed and on complete, do the following:
		this.popupTimer = $clear(this.popupTimer);
		var popup  = new Element('div', { 'class': 'hoverPopup' }).fade('hide');
		var nested = new Element('div', { 'class': 'popupNestedElement' }).inject(popup);
		
		new Element('strong', { text: MultiLingual.getString('js_inboxsummary') }).inject(nested);
		
		var dl = new Element('dl').inject(nested);
		
		Site.inboxFeed.each(function (message, i) {
			var dt = new Element('dt', { text: message.subject.truncate(30) }).inject(dl);
			var dd = new Element('dd', { text: message.content.truncate(65) }).inject(dl);
			
			if (!message.read) dt.addClass('unread');
			if (i < 1) dt.addClass('firstItem');
		});
		
		this.popup = popup.inject(document.body);
		
		var elCoords = inboxLink.getCoordinates();
		
		if (Browser.Engine.trident4) {
			elCoords.top -= 5;
			elCoords.width += 86;
		}
		
		this.popup.setStyles({
			position: 'absolute',
			top: elCoords.top - 10,
			left: elCoords.left + elCoords.width - 6
		});
		
		var fx = new Fx.Tween(this.popup, { duration: 400 });
		if (Browser.Engine.trident) {
			fx.set('opacity', 1);
		} else {
			fx.start('opacity', 1);
		}
	},
	
	removePopup: function () {
		if (Browser.Engine.trident) {
			this.popup.destroy();
		} else {
			new Fx.Tween(this.popup, {
				// fade it out before another popup is inserted into the markup ;)
				duration: 250,
				onComplete: function () {
					this.popup.destroy();
				}.bind(this)
			}).start('opacity', 0);
		}
	},
	
	confirmDelete: function (e) {
		var linkDeletes  = $$('a.delete');
		
		linkDeletes.addEvent('click', function(e) {
			if(!confirm('Are you sure you want to delete this section?')) {
				e.stop();
			}
		});
	},
	
	EventPRC: function (e) {
		$$('label.useOtherSurname').each(function(el) {
			var checkbox = el.getElement('input[type=checkbox]');
			
			checkbox.addEvent('click', function(e) {
				el.getNext('label.labelOtherSurname').setStyle('display', ((!e.target.checked) ? 'none' : ''));
			});

			el.getNext('label.labelOtherSurname').setStyle('display', ((!checkbox.checked) ? 'none' : ''));
		});		
	},
	
	initTickerTape: function() {
		var promoMessage = $('headerNotice');
		if (promoMessage.getElement('div').getElements('p').length == 1) {
			// remove the whole notice
			promoMessage.destroy();
		} else {
			// just remove the ticker item
			if ($('randomTickerItem')) {
				$('randomTickerItem').destroy();
			}
		}
		
		// set up news ticker
		new NewsToolbar({id: 'toolbar'});
		
		// add additional padding to footer to avoid toolbar
		$('footer').setStyle('margin-bottom', $('toolbar').getHeight());
	}
}

Element.implement({
	applyRollOver: function () {
		if (this.src.test(/\.(gif|jpg|jpeg|png)$/i)) {
			// preload image
			var preload = new Image();
			preload.src = this.src.replace(/\.(gif|jpg|jpeg|png)/, '-over.$1');
			
			this.addEvents({
				mouseover: function() {
					this.src = this.src.replace(/\.(gif|jpg|jpeg|png)/, '-over.$1');
				},
				
				mouseout: function() {
					this.src = this.src.replace(/-over\.(gif|jpg|jpeg|png)/, '.$1');
				}
			});
		}
	
		return this;
	}
});

String.prototype.truncate = function (length) {
	return (this.length > length ? this.substr(0, length) + '...' : this).replace(/^\s+|\s+$/g, '');
};

window.addEvent('domready', Site.init);
