/** 
includes:
login.js
popup.js
feed.js
milkbox.js
nav.js
**/

/** 
login.js
**/
var ButtonRecover = function ()
{
	$('btnRecover').addEvent('click', function(e) {
		new Event(e).stop(); 
		if($('email').value) { 
			var req = new Request.HTML({ 
				method: 'post',
				data: $('frmRecover'),
				url: '../inc/login.recover.php',
				update: $('msg')
			}).send();
		} else {
			alert('Please enter your email address.');
		}
	});
}

var ButtonSignup = function()
{
	$('btnSignup').addEvent('click', function(e) {
		new Event(e).stop(); 
		if($('name').value && $('email').value && $('terms').checked) { 
			if($('email').value!=$('emailconfirm').value) { 
				alert('Email addresses do not match.');
			} else {
				var req = new Request.HTML({ 
					method: 'post',
					data: $('frmSignup'),
					url: '../inc/login.signup.php',
					update: $('msg'),
					onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) { 
						if(!responseHTML.replace(/^\s+/,'')) { 
							TabLogin('website', '', $('email').value);
						}
					}
				}).send();
			}
		} else {
			alert('Please enter your name, email and accept the terms.');
		}
	});
}

var ButtonLogin = function(redirect)
{
	$('btnLogin').addEvent('click', function(e) {
		new Event(e).stop(); 
		if($('username').value && $('password').value) { 
			var req = new Request.HTML({ 
				method: 'post',
				data: $('frmLogin'),
				url: '../inc/login.form.php?redirect=' + redirect,
				//update: $('msg'),
				onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
					var response = responseHTML.replace(/^\s+/,'');
					if(response.indexOf('http')!='-1') { 
						MochaUI.closeWindow($('modalLogin'));
						location.href = response;
					} else {
						alert(response);
					}
				}
			}).send();
		} else {
			alert('Please enter your username and password.');
		}
	});
}

var ButtonActivateLogin = function()
{
	if($('btnLogin')) { 
		$('btnLogin').addEvent('click', function(e) {
			new Event(e).stop(); 
			if($('username').value && $('password').value) { 
				var req = new Request.HTML({ 
					method: 'post',
					data: $('frmLogin'),
					url: '../inc/login.activate.php',
					update: $('msg')
				}).send();
			} else {
				alert('Please enter your username and password.');
			}
		});
	}
}

var ButtonActivateSignup = function()
{
	if($('btnSignup')) { 
		$('btnSignup').addEvent('click', function(e) {
			new Event(e).stop(); 
			if($('name').value && $('email').value && $('terms').checked) { 
				if($('email').value!=$('emailconfirm').value) { 
					alert('Email addresses do not match.');
				} else {
					var req = new Request.HTML({ 
						method: 'post',
						data: $('frmSignup'),
						url: '../inc/login.activate.php',
						update: $('msg2')					
					}).send();
				}
			} else {
				alert('Please enter your name, email and accept the terms.');
			}
		});
	}
}

var TabSignup = function()
{
	MochaUI.selected($('panelTabs2Link'), $('panelTabs'));
	MochaUI.updateContent({
		'element':  $('help-panel'),
		'url':       'inc/login.signup.php',
		onContentLoaded: function(){ ButtonSignup(); }
	});
}

var TabActivate = function()
{
	MochaUI.selected($('panelTabs2Link'), $('panelTabs'));
	MochaUI.updateContent({
		'element':  $('help-panel'),
		'url':       'inc/login.activate.php',
		onContentLoaded: function(){ ButtonActivateSignup(); ButtonActivateLogin();  }
	});
}

var TabLogin = function(type, redirect, signedup)
{
	type = (type) ? type : 'website';
	MochaUI.selected($('panelTabs1Link'), $('panelTabs'));
	MochaUI.updateContent({
		'element':  $('help-panel'),
		'url':       'inc/login.form.php?redirect=' + redirect,
		onContentLoaded: function(){ 
			ButtonLogin(redirect); 
			$('login-form-location').value = type;	
			if($('sign-up-link') && type=='website') { 
				$('sign-up-link').style.display = 'block';
			} else if($('sign-up-link') && type=='admin') { 
				$('sign-up-link').style.display = 'none';
			}
			if($('login-msg') && type=='website') { 
				$('login-msg').style.display = 'block';
			}
			if(signedup) { 
				$('msg').set('text','Please check your email for your password.');
				$('username').value = signedup;
			}
			if(type=='admin' && $('remember')){
				$('remember').style.display = 'block';
			}

		}
	});
}

var TabRecover = function()
{
	MochaUI.selected($('panelTabs3Link'), $('panelTabs'));
	MochaUI.updateContent({
		'element':  $('help-panel'),
		'url':       'inc/login.recover.php',
		onContentLoaded: function(){ ButtonRecover(); }
	});	
}

var TabsInit = function(type)
{
	MochaUI.initializeTabs('panelTabs');
	$('panelTabs1Link').addEvent('click', function(e){ TabLogin(type); });
	//$('panelTabs2Link').addEvent('click', function(e){ TabSignup(); });
	$('panelTabs3Link').addEvent('click', function(e){ TabRecover(); });

	if($('login-hhj') && $('login-hhj').value) { 
		$('panelTabs2Link').getChildren('a').set('text', 'Activate Your Card');
		$('panelTabs2Link').addEvent('click', function(e){ TabActivate(); });
	} else {
		$('panelTabs2Link').style.display = 'none';
	}

	/*
	$('panelTabs4Link').addEvent('click', function(e){
		MochaUI.updateContent({
			'element':  $('help-panel'),
			'url':       'inc/login.benefits.php'			
		});
	});
	*/
}


var Login = function(type, redirect) {  

	var domain = 'http://' + window.location.hostname;
	redirect = redirect.replace(domain,'');


	MUI.Desktop.initialize();
	MUI.Dock.initialize();

	var w = ($('login-hhj').value==1) ? '700' : '500';	
	var h = ($('login-hhj').value==1) ? '430' : '300';	
	
	new MUI.Modal({
		id: 'modalLogin',
		title: 'Log In',
		content: '<div id="pageWrapper"></div>',
		width: w,
		height: h,
		onContentLoaded: function(){
							
			//column required for tabs
			new MochaUI.Column({
				id: 'mainColumn',
				container: 'modalLogin_contentWrapper',
				placement: 'main',	
				width: null,
				resizeLimit: [100, 300]
			});

			//tab panel
			new MochaUI.Panel({
				id: 'help-panel',
				loadMethod: 'xhr',
				contentURL: 'inc/login.form.php?redirect=' + redirect,
				column: 'mainColumn',
				tabsURL: 'inc/login.tabs.php',
				onContentLoaded: function(){
					//init tabs
					TabsInit(type);
					if(type=='signup') { 
						//TabSignup();		
						if($('login-hhj') && $('login-hhj').value) { 
							TabActivate();
						} else {
							TabSignup();
						}
					} else if(type=='recover') { 
						TabRecover();
					} else {
						TabLogin(type, redirect); 
					}
				
				}
			});
			
		} // end onContentLoaded
		
		
	}); // end New Window

	//destroy event for close button and add new one
	$$('#modalLogin .mochaCloseButton').each(function(el2) { 
		el2.removeEvents('click');
		el2.addEvent('click', function(e) {
			new Event(e).stop();
			LoginClose();
		}.bind(el2));
	});
	
}

var LoginClose = function()
{
	if($('modalLogin')) { $('modalLogin').style.visibility = 'hidden'; }
	if($('modalOverlay')) { $('modalOverlay').style.visibility = 'hidden'; }
}

var LoginOpen = function(type, redirect) //type: admin, website, signup, recover
{
	if($('modalLogin')) { 
		MUI.centerWindow($('modalLogin'));
		$('modalLogin').style.visibility = 'visible'; 
		$('modalOverlay').style.visibility = 'visible';
		if(type=='signup') { 
			//TabSignup();
			if($('login-hhj') && $('login-hhj').value) { 
				TabActivate();
			} else {
				TabSignup();
			}
		} else if(type=='recover') { 
			TabRecover();
		} else {
			TabLogin(type, redirect);
		}
	}
	else {	
		Login(type, redirect); 
	}
}

var LoginLink = function(el)
{
	var redirect = (el.href && el.href.indexOf('#')==-1) ? el.href : '';
	var type = (el.rel) ? el.rel : 'website'; 
	if(type=='admin') {
		var req = new Request.HTML({ 
			method: 'get',
			data: { 'checkauthstatus' : '1' },
			url: '../inc/login.form.php',
			onComplete: function(responseTree, responseElements, responseHTML, responseJavaScript){
				var response = responseHTML.replace(/^\s+/,'');
				if(response.indexOf('http')!='-1') { 
					location.href = response;
				}else{
					LoginOpen(type, redirect);
				}
			}					
		}).send();
	} else {
		LoginOpen(type, redirect);
	}
}

window.addEvent('domready', function()
{
	//Login link in header
	$$('.login').each(function(el) {  
		el.addEvent('click', function(e){
			new Event(e).stop();
			LoginLink(el);
		}.bind(el));
	});
});


/** 
popup.js
**/

window.addEvent('domready', function()
{
	//MochaUI.Desktop = new MochaUI.Desktop();
	//MochaUI.Dock = new MochaUI.Dock();
	var regExp = /^\s+/;

	var PopUpShare = function(url, title)
	{
		//domain = location.href.substring(0, location.href.lastIndexOf('/') + 1);
		//url = domain + responseText.replace(regExp,'');
		var img = new Element('img', {
			'id': 'btnShare',
			'class': 'mochaShareButton',
			'title': 'Share',
			'alt': 'Share',
			'src': 'http://s7.addthis.com/static/btn/lg-share-en.gif'
		}).inject($('popup_closeButton'), 'before');
		var a = new Element('a', {
			'title': 'Share',
			'href': 'http://www.addthis.com/bookmark.php',
			'events': {
				'click': function(){ return addthis_sendto(); },
				'mouseover': function(){ return addthis_open(this, '', url, title); },
				'mouseout': function(){ addthis_close(); }
			}
		}).wraps($('btnShare'));
	}

	var PopUpTitle = function(url)
	{
		var title = '';
		var req = new Request({ 
			method: 'get',
			data: { "page_url" : url, "data" : "page_title" },
			url: "./inc/popup.php",
			onSuccess: function(responseText) {
				title = responseText.replace(regExp,'');
				$('popup_title').set('text',title);
				PopUpShare(url, title);
			}
		}).send();
	}


	MochaUI.PopUp = function(url) 
	{ 
		var domain = 'http://' + window.location.hostname;
		url = url.replace(domain,'');
		new MochaUI.Window({
			id: 'popup',
			type: 'window',
			title: '',
			loadMethod: 'xhr',
			contentURL: './inc/popup.php?page_url=' + url,
			width: 530,
			height: 300,
			//headerStartColor: [10,33,67],
			//headerStopColor: [99,132,181],
			footerHeight: 10,
			onContentLoaded: function() { 
				PopUpTitle(url);
				var print = new Element('img', {
					'id': 'btnPrint',
					'class': 'mochaPrintButton',
					'title': 'Print',
					'alt': 'Print',
					'src': 'http://www.metroya.com/assets/img/elements/print.gif'
				}).inject($('popup_closeButton'), 'before');
				$('btnPrint').addEvent('click', function(e){
					new Event(e).stop();
					window.print();
				});
			}

		});
	}

	var PopUpClickTracker = function(page_url, sponsor_id)
	{
		var req = new Request({ 
			method: 'get',
			data: { "page_url" : page_url, "sponsor_id" : sponsor_id },
			url: "./inc/popup.php"
		}).send();
	}

	$$('.popup').each(function(el) 
	{  
		el.addEvent('click', function(e){
			new Event(e).stop();
			var page_url = el.href;
			if(el.rel.indexOf('sponsor')!=-1) { 
				var sponsor_id = el.rel.replace('sponsor','');
				PopUpClickTracker(page_url, sponsor_id);
			}
			MochaUI.PopUp(page_url);
		}.bind(el));
	});

});

/** 
feed.js
**/


	var Ticker = new Class({
		setOptions: function(options) {
			this.options = Object.extend({
				speed: 5000,
				delay: 5000,
				direction: 'vertical',
				onComplete: Class.empty,
				onStart: Class.empty
			}, options || {});
		},
		initialize: function(el,options){
			this.setOptions(options);
			this.el = $(el);
			this.items = this.el.getElements('div');

			var mover = new Fx.Move(this.items[0], {
				relativeTo: $('feed_items'),
				position: 'upperLeft',
				edge: 'upperLeft'
			});
			mover.start(); 

			var mover = new Fx.Move(this.items[0], {
				relativeTo: $('feed_target'),
				position: 'upperLeft',
				edge: 'upperLeft'
			});
			mover.start(); 

			var mover = new Fx.Move(this.items[0], {
				relativeTo: $('feed_items'),
				position: 'upperLeft',
				edge: 'upperLeft'
			});
			mover.start(); 

			this.previous = 0;
			this.current = 0;
			this.next();
		},
		next: function() {
			this.previous = this.current;
			this.current++;
			if (this.current >= this.items.length) this.current = 0;
			var pos = this.items[this.current];

			this.items[this.current].style.visibility = 'visible';
			var mover = new Fx.Move(this.items[this.current], {
				relativeTo: $('feed_target'),
				position: 'upperLeft',
				edge: 'upperLeft'
			});
			mover.start(); 

			this.items[this.previous].style.visibility = 'hidden';
			var mover = new Fx.Move(this.items[this.previous], {
				relativeTo: $('feed_items'),
				position: 'upperLeft',
				edge: 'upperLeft'
			});
			mover.start(); 

			

			this.next.bind(this).delay(this.options.delay);
		}
	});



/**
	milkbox.js

	Milkbox v2.2.1 - required: mootools.js v1.2.1 core + more: Assets
		
	by Luca Reghellin (http://reghellin.com/milkbox/) February 2009, MIT-style license.
	Inspiration Lokesh Dhakar (http://www.lokeshdhakar.com/projects/lightbox2/)
	AND OF COURSE, SPECIAL THANKS TO THE MOOTOOLS DEVELOPERS
*/

var Milkbox = new Class({

	Implements:[Options,Events],
	
	options:{//set all the options here
		overlayOpacity:0.7,
		topPosition:50,
		initialWidth:250,
		initialHeight:250,
		canvasBorderWidth:'0px',
		canvasBorderColor:'#000000',
		canvasPadding:'0px',
		resizeDuration:500,
		resizeTransition:'sine:in:out',/*function (ex. Transitions.Sine.easeIn) or string (ex. 'bounce:out')*/
		autoPlay:false,
		autoPlayDelay:7,
		removeTitle:false,
		onXmlGalleries:$empty,
		onClosed:$empty,
		onFileReady:$empty
	},
	
	initialize: function(options){
		
		this.setOptions(options);
		this.autoPlayBkup = { autoPlayDelay:this.options.autoPlayDelay, autoPlay:this.options.autoPlay };
		this.fullOptionsBkup = {};
		this.galleries = [];
		this.families = [];
		this.xmlFiles = [];
		this.loadedImages = [];//to check the preloaded images
		this.currentFile = null;
		this.currentIndex = null;
		this.currentGallery = null;
		this.currentRequest = null;
		this.currentResponse = null;
		
		this.mode = null;//'singleFile','fileGallery'
		this.closed = true;
		this.busy = true;//to control keyboard and autoplay events
		this.paused = true;
		this.fileReady = false;//to prevent overlapping loadFile calls via next_prev_aux()
		this.eventsok = false;
		this.first = true;//true if it's the first file since it opened 
		
		this.intObj = null;
		
		this.formtags = null;
		this.prepareGalleries();
		//if no galleries, stop here and prevent extra memory usage.
		//so you can keep milkbox in every page of a site.
		if(this.galleries.length == 0){ return; };
				
		this.initMilkbox();
		this.saveOptions();//then use restoreOptions()
	},//end init
	
	initMilkbox:function(){

		this.prepareHTML();
		this.prepareEffects();
		this.prepareEvents();
		
		this.formtags = $$('select','textarea');
		this.activated = true;
	},
	
	/* ****** SHOW/HIDE ****** */
	
	//runs only 1 time per gallery
	openMilkbox:function(gallery,index){

		if($('flashcontent')) $('flashcontent').style.visibility = 'hidden';

		this.closed = false;
		
		if(this.formtags.length != 0){ this.formtags.setStyle('display','none') };

		this.overlay.setStyles({ 'top': -$(window).getScroll().y,'height':$(window).getScrollSize().y+$(window).getScroll().y });
		this.center.setStyle('top',$(window).getScroll().y+this.options.topPosition);

		this.currentGallery = gallery;
		this.currentIndex = index;
		this.overlay.tween('opacity',this.options.overlayOpacity);//onComplete: center.tween opacity
		
		if(gallery.length == 1){
			this.mode = 'singleFile';
			this.loadFile(gallery[index],index);
		} else {
			this.mode = 'fileGallery';
			var playpauseWidth = 0;
			//interface
			$$(this.prev, this.next, this.count).setStyle('display','block');
			if(this.options.autoPlay){ 
				this.playpause.setStyle('display','block');
				var playpauseWidth = this.playpause.getSize().x;
			}
			var border = this.center.getStyle('border-right-width').toInt();//border-right is just ok for design purposes..
			var navWidth = this.prev.getSize().x+this.next.getSize().x+this.close.getSize().x+playpauseWidth+border;
			this.navigation.setStyle('width',navWidth);
			this.description.setStyle('margin-right',navWidth);
			//files
			var next = (index != gallery.length-1) ? gallery[index+1] : gallery[0];
			var prev = (index != 0) ? gallery[index-1] : gallery[gallery.length-1];
			var preloads = (prev == next) ? [prev] : [prev,next]; //if gallery.length == 2, then prev == next
						
			this.loadFile(gallery[index],preloads);
		}//end else
	},
	
	loadFile:function(fileObj,preloads){
		this.fileReady = false;
		var swf = this.checkFileType(fileObj,'swf');
		if(!swf){ 
			if(!this.loadedImages.contains(fileObj.retrieve('href'))){ this.center.addClass('mbLoading'); } 
			this.loadImage(fileObj.retrieve('href'));
		} else {
			this.loadSwf(fileObj);
		}
		
		if(preloads){ this.preloadFiles(preloads); }
	},
	
	preloadFiles:function(preloads){
		preloads.each(function(fileObj,index){
			var swf = this.checkFileType(fileObj.retrieve('href'),"swf");
			if(!swf){ this.preloadImage(fileObj.retrieve('href')); }
		},this);
	},
	
	loadImage:function(file){
		var imageAsset = new Asset.image(file, { onload:function(img){
			if(!this.loadedImages.contains(file)){ this.loadedImages.push(file); };//see next/prev events
			this.currentFile = img;
			this.loadAux(this.currentFile);
		}.bindWithEvent(this)});
	},
	
	preloadImage:function(file){
		if(!this.loadedImages.contains(file)){
			var imageAsset = new Asset.image(file, { onload:function(img){
					this.loadedImages.push(file);
			}.bindWithEvent(this)});
		}
	},
	

	loadSwf:function(swf){

		var swfObj = new Swiff(swf.retrieve('href'),{
			width:swf.retrieve('width').toInt(),
			height:swf.retrieve('height').toInt(),
			params:{ wMode:'opaque', swLiveConnect:'false' }
		});
		
		this.currentFile = swfObj;
		this.loadAux(swf);
	},
	
	loadAux:function(file){
		this.fileReady = true; //the file is loaded and ready to be showed (see next_prev_aux())
		this.fireEvent('fileReady');
		$$(this.description,this.navigation).setStyle('visibility','hidden');
		this.navigation.setStyle('height','');//reset the height setted in center.morph.onComplete
		$$(this.next,this.prev,this.close).setStyle('backgroundPosition','0 0');
		this.showFile(file);
	},
	
	
	showFile:function(file){
 		
 		if(this.closed){ return; };//if you close the Milkbox and an onload event is still running
 		
 		var fileSize = new Hash();
 		var targetSize = {};
 		var b = null;
 		var p = null;
 		if(this.options.canvasBorderWidth.toInt() != 0 && this.canvas.getStyle('borderWidth').toInt() == 0){
 			b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 			this.canvas.setStyle('border',b);
 		}
 		
 		if(this.options.canvasPadding.toInt() != 0 && this.canvas.getStyle('padding').toInt() == 0){
 			p = this.options.canvasPadding;
 			this.canvas.setStyle('padding',p);
 		}
 		
 		var canvasSize = this.canvas.getSize();
 		var canvasAddSize = this.canvas.getStyle('borderWidth').toInt()*2 + this.canvas.getStyle('padding').toInt()*2;
 		this.canvas.setStyles({'opacity':0, 'width':'', 'height':''});
 		
 		if(!file.retrieve('width')){//is an image file
 			fileSize = fileSize.extend(file.getProperties('width','height')).map(function(item, index){ return item.toInt(); });
 		} else {//is an swf file
 			fileSize.extend({ 'height':file.retrieve('height').toInt(), 'width':file.retrieve('width').toInt() });
 		}

 		var centerSize = new Hash(this.center.getStyles('width','height')).map(function(item, index){ return item.toInt(); });

 		if(fileSize.width != centerSize.width){ 
 			targetSize.width = fileSize.width + canvasAddSize;
 			targetSize.marginLeft = -(targetSize.width/2).round();
 		}
 		 		
 		var gap = (canvasSize.y-canvasAddSize > 0) ? centerSize.height - canvasSize.y : 0; 

 	   targetSize.height = fileSize.height + canvasAddSize + gap;
 	   
		//so nav doesn't move when you click next/prev
		this.canvas.setStyles({'width':fileSize.width, 'height':fileSize.height});

 		this.center.removeClass('mbLoading');
 		
 		var d = 0;
 		if(this.first){ d = 500; this.first = false; }
 		(function(){ this.center.morph(targetSize); }).delay(d,this)//onComplete: show all items
	},

	
	//{ gallery:'gall1', index:2, autoplay:true, delay:7 }
	showGallery:function(opt){
		if(!opt || !opt.gallery){ return; }
		var fileIndex = ($chk(opt.index)) ? opt.index : 0;
		var g = this.getGallery(opt.gallery);
		var auto = false;
		var d;
		if(opt.autoplay || (g['options'] && g['options'].autoplay)){ auto = true; }
		if(g != -1 && !this.opened){
			if(auto){
				d = (opt && opt.delay) ? opt.delay : (g['options'] && g['options'].delay) ? g['options'].delay : this.autoPlayDelay;
				this.startAutoPlay({ gallery:g, index:fileIndex, delay:d });
			} else {
				this.openMilkbox(g,fileIndex);
			}
		}
	},
	
	/* ******* XML/AJAX ******* */

	addGalleries:function(xmlfile){
		this.currentRequest = new Request({
			method:'get',
			autoCancel:true,
			url:xmlfile,
			onRequest:function(){
				//placeholder
			}.bindWithEvent(this),
			onSuccess:function(text,xml){
				var t = text.replace(/(<a.+)\/>/gi,"$1></a>");
				this.setGalleries(new Element('div',{ html:t }),xmlfile);
			}.bindWithEvent(this),
			onFailure:function(transport){ alert('Milkbox :: addGalleries: XML file path error or local Ajax test: please test addGalleries() on-line'); }
		});
		
		this.currentRequest.send();
	},
	
	setGalleries:function(container,xmlfile){
		if(!this.xmlFiles.contains(xmlfile)){ this.xmlFiles.push(xmlfile); }
		var c = container;
		var galleries = c.getElements('.gallery');
		var links = [];
		var aplist = [];
		galleries.each(function(gallery,i){
						
			var obj = { 
				gallery:gallery.getProperty('name'), 
				autoplay:Boolean(gallery.getProperty('autoplay')),
				delay:Number(gallery.getProperty('delay'))
			}
			
			var l = gallery.getChildren('a');
			var lx = l.map(function(link){ return link.setProperty('rel','milkbox['+obj.gallery+']'); });
			links.push(lx);
			if(obj.autoplay){ aplist.push(obj); }
		});
		
		this.prepareGalleries(links.flatten());
		this.setAutoPlay(aplist);
		
		if(!this.activated){ this.initMilkbox(); }
		
		this.fireEvent('xmlGalleries');
	},
	
	
	
	/* ****** UTILS ****** */
	
	checkFileType:function(file,type){
		var href = null;
		if($type(file) != 'string'){ href = file.retrieve('href'); } 
		else{ href = file; }
		var regexp = new RegExp("\.("+type+")$","i");
		return href.split('?')[0].test(regexp);
	},
	
	//retrieves galleries from strings like 'gall1' or 'milkbox[gall1]' or 'milkbox:gall1'
	getGallery:function(gallery){
		var f = null;
		if(gallery.test(/^milkbox/i)){
			f = this.families;
		} else {
			//create a temporary array with names without 'milkbox'
			f = this.families.map(function(item){
				var trimmed = item.trim();
				var name = trimmed.slice(0,trimmed.length).substr(8);
				var cleanName = name.replace(/(.+)]$/,"$1");
				return cleanName;
			});
		}
		var i = f.indexOf(gallery);
		var g = (i != -1) ? this.galleries[i] : i;
		return g;
	},
	
	setFileProps:function(fileObj,propString){
		var s = propString.split(',');
		s.each(function(p,i){
			var clean = p.trim().split(':');
			fileObj.store(clean[0].trim(),clean[1].trim())
		},this);
	},
	
	changeOptions:function(obj){
		if(!obj){ return; }
		this.setOptions(obj);
 		this.center.get('morph').setOptions({ transition:this.options.resizeTransition,  duration:this.options.resizeDuration });
	},
	
	saveOptions:function(obj){
		if($chk(obj)){
			this.fullOptionsBkup = obj;
		} else {
			this.fullOptionsBkup = this.options;
		}
	},
	
	restoreOptions:function(){
		this.setOptions(this.fullOptionsBkup);
 		b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 		this.canvas.setStyles({ 'border':b, 'padding':this.options.canvasPadding});
 		this.center.get('morph').setOptions({ transition:this.options.resizeTransition,  duration:this.options.resizeDuration });
	},
	
	reloadGalleries:function(){
	
		this.galleries = [];
		this.families = [];
		//re-check for tags
		this.formtags = $$('select','textarea');
		
		//reload standard galleries
		this.prepareGalleries();
		this.removeGalleriesEvents();
		this.setGalleriesEvents();
		
		if(this.xmlFiles.length == 0){ return; }
		//reload xmlGalleries
		this.xmlFiles.each(function(xmlfile,index){
			this.addGalleries(xmlfile);
		}.bind(this));
	},
	
	/* ****** AUTOPLAY ****** */
	
	//list:Array of objects or an object > [ { gallery:'gall1', autoplay:true, delay:6 } ]
	//to permanently define autoplay options for any gallery 
	setAutoPlay:function(list){
		var l = ($type(list) == 'object') ? [list] : list;
		l.each(function(item){
			var g = this.getGallery(item.gallery);
			if(g == -1){ return; }
			var a = (item.autoplay == true) ? item.autoplay : false;
			var d = ($chk(item.delay) && a) ? item.delay : this.options.autoPlayDelay;
			g['options'] = { autoplay:a, delay:d }
		},this);
	},
	
	startAutoPlay:function(opt){//opt: gallery, index, delay (in seconds)
		
		var g = -1;
		var i,d;
		if(opt && opt.gallery){
			if($type(opt.gallery) == 'array'){ g = opt.gallery }
			else if($type(opt.gallery) == 'string'){ 
				g = this.getGallery(opt.gallery);
			}
		}
		
		if(g == -1){ g = this.galleries[0]; }
		
		d = (opt && opt.delay && ($type(opt.delay) == 'number')) ? opt.delay*1000 : (g['options'] && g['options'].delay) ? g['options'].delay*1000 : this.options.autoPlayDelay*1000;
		i = (opt && opt.index && ($type(opt.index) == 'number')) ? opt.index : 0;
		if(d < this.options.resizeDuration*2){ d = this.options.resizeDuration*2 };
		this.options.autoPlayDelay = d/1000;//save autoPlayDelay because now it is customized
		
		if(!this.options.autoPlay){ this.setOptions({ autoPlay:true, autoPlayDelay:this.options.autoPlayDelay }); }
		
		if(this.closed){ 
			this.openMilkbox(g,i); 
			if(this.mode != 'fileGallery'){ return; }
			this.addEvent('fileReady',function(){
				//wait until the first file is loaded
				this.intObj = this.next_prev_aux.periodical(d,this,[null,'next']);
				this.removeEvents('fileReady');
			}.bindWithEvent(this));
		} else {
			if(!this.closed){ this.next_prev_aux(null,'next'); }
			this.intObj = this.next_prev_aux.periodical(d,this,[null,'next']);
		}

		this.paused = false;
	},
	
	stopAutoPlay:function(){
		if(this.intObj){ $clear(this.intObj); this.intObj = null; }
		this.playpause.setStyle('backgroundPosition','0 -44px');
		this.paused = true;
	},
	
	
	/* ****** INIT/CLOSE ****** */
	
	removeGalleriesEvents:function(){
		this.galleries.each(function(gallery){
			$$(gallery).removeEvents('click');
		},this);
	},
	
	setGalleriesEvents:function(){
		this.galleries.each(function(gallery){
		
			$$(gallery).addEvent('click',function(e){
				//console.log('click');
				var button=($(e.target).match('a')) ? $(e.target) : $(e.target).getParent('a');
				e.preventDefault();
				
				var g = this.getGallery(button.rel);
				if(g.options && g.options.autoplay){
					this.setOptions({ autoPlay:g.options.autoplay, autoPlayDelay:g.options.delay });
				}

				if(this.options.autoPlay){
					this.startAutoPlay({ gallery:gallery, index:gallery.indexOf(button) });
				} else { 
					this.openMilkbox(gallery, gallery.indexOf(button)); 
				}
				
			}.bindWithEvent(this));
		},this);
	},
	
	//all the main events
	prepareEvents:function(xml){
	
		//galleries
		this.setGalleriesEvents();
		
		//next, prev, see next_prev_aux()
		this.next.addEvent('click',this.next_prev_aux.bindWithEvent(this,'next'));
		this.prev.addEvent('click',this.next_prev_aux.bindWithEvent(this,'prev'));
		
		
		//css hover doesn't work in ie6, so I must do it via js...
		$$(this.next,this.prev,this.close).addEvents({
			'mouseover':function(){ this.setStyle('backgroundPosition','0 -22px'); },
			'mouseout':function(){ this.setStyle('backgroundPosition','0 0'); }
		});

		//keyboard next/prev/close
		$(window.document).addEvent('keydown',function(e){
			if(this.mode != 'fileGallery' || this.busy == true){ return; }
			if(e.key == 'right' || e.key == 'space'){ this.next_prev_aux(e,'next'); }
			else if(e.key == 'left'){ this.next_prev_aux(e,'prev'); }
			else if(e.key == 'esc'){ this.closeMilkbox(); }
		}.bindWithEvent(this));
		
		//playpause for autoPlay
		this.playpause.addEvents({
				'mouseover':function(e){ 
					if(this.paused == false){ this.playpause.setStyle('backgroundPosition','0 -22px'); } 
					else { this.playpause.setStyle('backgroundPosition','0 -66px'); }
				}.bindWithEvent(this),
				'mouseout':function(){ 
					if(this.paused == false){ this.playpause.setStyle('backgroundPosition','0 0'); } 
					else { this.playpause.setStyle('backgroundPosition','0 -44px'); }
				}.bindWithEvent(this),
				'click':function(){
					if(this.paused == false){ 
						this.stopAutoPlay();
						this.paused = true;
						this.playpause.setStyle('backgroundPosition','0 -66px');
					} else {
						var d = (this.currentGallery.options && this.currentGallery.options.delay) ? this.currentGallery.options.delay : this.options.autoPlayDelay;
						this.startAutoPlay({gallery:this.currentGallery, index:this.currentIndex+1, delay:d });
						this.paused = false;
						this.playpause.setStyle('backgroundPosition','0 0');
					}
				}.bindWithEvent(this)
		});
		
		//overlay
		this.overlay.get('tween').addEvent('onComplete',function(){
			if(this.overlay.getStyle('opacity') == this.options.overlayOpacity){ 
				this.center.tween('opacity',1);
			} else if(this.overlay.getStyle('opacity') == 0) {
				this.overlay.setStyles({'height':0,'top':''});
			};
		}.bindWithEvent(this));
		
		//center
		this.center.get('morph').addEvent('onComplete',function(){
						
			 if($type(this.currentFile) == "element"){//is image file
				this.canvas.grab(this.currentFile);
			 } else {//object: is swf file
			 	(function(){ this.canvas.grab(this.currentFile); }).delay(500,this);
			 }
 			 
			 this.canvas.tween('opacity',1);
			 			 
			 var d = (!(this.mode == 'showThisImage')) ? this.currentGallery[this.currentIndex].retrieve('title') : this.specialDescription;
			 if($chk(d)){ this.description.innerHTML = d; };
			 
			 if(this.mode == 'fileGallery'){
			 	this.count.appendText((this.currentIndex+1)+' of '+this.currentGallery.length); 
			 }
			 
			 var currentCenterHeight = this.center.getStyle('height').toInt();
			 
			 //this.navigation.setStyle('height',this.bottom.getStyle('height').toInt());//to have the right-border height == total bottom height
			 //var bottomSize = this.bottom.getSize().y;
			 this.navigation.setStyle('height',this.top.getStyle('height').toInt());//to have the right-border height == total bottom height
			 var bottomSize = this.bottom.getSize().y;
			 var topSize = this.top.getSize().y;
			 
			 //after the 1st time, currentCenterHeight is always > this.canvas.getSize().y
			 //var targetOffset = (currentCenterHeight > this.canvas.getSize().y) ? (this.bottom.getSize().y+this.canvas.getSize().y)-currentCenterHeight : bottomSize;
			 var targetOffset = (currentCenterHeight > this.canvas.getSize().y) ? (this.top.getSize().y+this.bottom.getSize().y+this.canvas.getSize().y)-currentCenterHeight : topSize+bottomSize;
				
			 this.bottom.setStyle('display','none');//to avoid rendering problems during setFinalHeight
			 this.top.setStyle('display','none');//to avoid rendering problems during setFinalHeight

			 this.center.retrieve('setFinalHeight').start(currentCenterHeight,currentCenterHeight+targetOffset);
			/**/
		}.bindWithEvent(this));
		
		this.center.retrieve('setFinalHeight').addEvent('onComplete',function(){
			this.bottom.setStyles({'visibility':'visible','display':'block'});
			this.top.setStyles({'visibility':'visible','display':'block'});
			$$(this.description,this.navigation).setStyle('visibility','visible');
			//reset overlay height based on position and height
			var scrollSize = $(window).getScrollSize().y;
			var scrollTop = $(window).getScroll().y;
			
			this.overlay.setStyles({'height':scrollSize+scrollTop, 'top':-scrollTop });
			this.busy = false;
		}.bindWithEvent(this));
		
		//reset overlay height and position onResize
		window.addEvent('resize',function(){
			if(this.overlay.getStyle('opacity') == 0){ return; };//resize only if visible
			var scrollSize = $(window).getScrollSize().y;
			var scrollTop = $(window).getScroll().y;
			this.overlay.setStyles({ 'height':scrollSize+scrollTop,'top':-scrollTop });
		}.bindWithEvent(this));

		//close
		$$(this.overlay,this.close).addEvent('click',function(){ this.closeMilkbox(); }.bindWithEvent(this));
		
		//check
		this.eventsok = true;
	},
	
	next_prev_aux:function(e,direction){
		
		if(e){ 
			e.preventDefault();
			this.stopAutoPlay();
		} else { 
			//if there's no event obj, than this is called by autoPlay()
			if(this.busy || !this.fileReady){ return; }//stop autoplay()
		}

		this.busy = true; //for keyboard and autoplay
		
		var backupIndex = this.currentIndex;
		
		if(direction == "next"){
			var i= (this.currentIndex != this.currentGallery.length-1) ? this.currentIndex += 1 : this.currentIndex = 0;
			var _i= (this.currentIndex != this.currentGallery.length-1) ? this.currentIndex + 1 : 0;
		} else {
			var i= (this.currentIndex != 0) ? this.currentIndex -= 1 : this.currentIndex = this.currentGallery.length-1;
			var _i= (this.currentIndex != 0) ? this.currentIndex - 1 : this.currentGallery.length-1;		
		};
		
		this.canvas.empty();
		this.description.empty();
		this.count.empty();

		this.loadFile(this.currentGallery[i],[this.currentGallery[_i]]);
	},
	
	prepareEffects:function(){
		this.overlay.set('tween',{ duration:'short',link:'cancel' });
		this.center.set('tween',{ duration:'short',link:'chain' });
		this.center.set('morph',{ duration:this.options.resizeDuration,link:'chain',transition:this.options.resizeTransition });
		this.center.store('setFinalHeight',new Fx.Tween(this.center,{property:'height',duration:'short'}));
		this.canvas.set('tween',{ link:'chain' });
	},
	
	prepareGalleries:function(responseElements){
		var milkbox_a = [];
		var gIndex;
		var a_tags = (responseElements) ? responseElements : $$('a');
				
		a_tags.each(function(a){
			//test 'milkbox' and link extension, and collect all milkbox links
			if(a.rel && a.rel.test(/^milkbox/i) && a.href.split('?')[0].test(/\.(gif|jpg|jpeg|png|swf)$/i)){
				if(a.rel.length>7 && !this.families.contains(a.rel)){ this.families.push(a.rel); };
				milkbox_a.push(a);
			}
		},this);

		//create an array of arrays with all galleries
		milkbox_a.each(function(a){
			$(a).store('href',a.href);
			$(a).store('rel',a.rel);
			$(a).store('title',a.title);
			if(this.checkFileType(a.href,"swf")){ this.setFileProps($(a),a.rev); }

			if(this.options.removeTitle){ $(a).removeProperty('title'); }
			if(a.rel.length > 7){
				this.families.each(function(f,i){
					if(a.rel == f){
						var gMounted = false;
						var index;
						this.galleries.each(function(g,k){
							if(g[0].rel == f){ 
								gMounted = true;
								index = k;
								return;
							}
						});
						
						if(gMounted == true){ this.galleries[index].push($(a)); } 
						else { this.galleries.push([$(a)]); }
					};
				},this);
			} else { this.galleries.push([$(a)]); };
		},this);
		
		//console.log(this.galleries);
	},
		
	prepareHTML:function(){		
		
		this.overlay = new Element('div', { 'id':'mbOverlay','styles':{ 'opacity':0,'visibility':'visible','height':0,'overflow':'hidden' }}).inject($(document.body));
		
		this.center = new Element('div', {'id':'mbCenter', 'styles':{'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2),'opacity':0 }}).inject($(document.body));
		this.canvas = new Element('div', {'id':'mbCanvas'}).inject(this.center);
		
		this.top = new Element('div',{'id':'mbTop'}).inject(this.center, 'top').setStyle('visibility','hidden');
		this.bottom = new Element('div',{'id':'mbBottom'}).inject(this.center).setStyle('visibility','hidden');
		this.navigation = new Element('div',{'id':'mbNavigation'}).setStyle('visibility','hidden');
		this.description = new Element('div',{'id':'mbDescription'}).setStyle('visibility','hidden');

		this.top.adopt(this.navigation);
		this.bottom.adopt(this.description, new Element('div',{'class':'clear'}));
		
		this.close = new Element('a',{'id':'mbCloseLink'});
		this.next = new Element('a',{'id':'mbNextLink'});
		this.prev = new Element('a',{'id':'mbPrevLink'});
		this.playpause = new Element('a',{'id':'mbPlayPause'});
		this.count = new Element('span',{'id':'mbCount'});
		
		$$(this.next, this.prev, this.count, this.playpause).setStyle('display','none');
		
		this.navigation.adopt(this.close, this.next, this.prev, this.playpause, new Element('div',{'class':'clear'}), this.count);
	},
	
	closeMilkbox:function(){
		
		if($('flashcontent')) $('flashcontent').style.visibility = 'visible';

		this.cancelAllEffects();
		this.stopAutoPlay();
		this.setOptions(this.autoPlayBkup);

		this.currentFile = null;
		this.currentIndex = null;
		this.currentGallery = null;
		this.currentRequest = null;
		this.currentResponse = null;
 		
		$$(this.prev, this.next, this.playpause, this.count).setStyle('display','none');
		this.playpause.setStyle('backgroundPosition','0 0');
		var border = this.center.getStyle('border-right-width').toInt();
		var navWidth = this.close.getSize().x+border;
		this.navigation.setStyles({'width':navWidth,'height':'','visibility':'hidden'});
		this.description.setStyle('margin-right',navWidth);
		this.description.empty();
		this.top.setStyles({'visibility':'hidden','display':''});
		this.bottom.setStyles({'visibility':'hidden','display':''});
		
   	this.canvas.setStyles({'opacity':0, 'width':'', 'height':''});
 		this.canvas.empty();
 		
 		this.count.empty();
		
		this.center.setStyles({'opacity':0,'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2)});
		this.overlay.tween('opacity',0);//see onComplete in prepareEvents() 
		
		if(this.formtags.length != 0){ this.formtags.setStyle('display','') };
		
		this.mode = null;
		this.closed = true;
		this.first = true;
		this.fileReady = false;
		this.fireEvent('closed');
	},
	
	cancelAllEffects:function(){
		this.overlay.get('tween').cancel();
		this.center.get('morph').cancel();
		this.center.get('tween').cancel();
		this.center.retrieve('setFinalHeight').cancel();
		this.canvas.get('tween').cancel();
	}
	
});//END MILKBOX;

window.addEvent('domready', function(){ 
	milkbox = new Milkbox();
});

/**
   nav.js
 * menuMatic  http://greengeckodesign.com/?q=menumatic
 * @version 0.68.3 (beta)
 * @author Jason J. Jaeger | greengeckodesign.com
 * @copyright 2008 Jason John Jaeger
 * @license MIT-style License
 *			Permission is hereby granted, free of charge, to any person obtaining a copy
 *			of this software and associated documentation files (the "Software"), to deal
 *			in the Software without restriction, including without limitation the rights
 *			to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *			copies of the Software, and to permit persons to whom the Software is
 *			furnished to do so, subject to the following conditions:
 *	
 *			The above copyright notice and this permission notice shall be included in
 *			all copies or substantial portions of the Software.
 *	
 *			THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *			IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *			FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *			AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *			LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *			OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *			THE SOFTWARE.
 *	
 *  @changeLog_________________________________________________________________________________
 *  
 *  Nov  15th 2008
 *  JJJ - incremented version to 0.68.3
 *  	- Fixed bug which occured when ol was used instead of ul.. was because you cannot use selectors such 
 *  		as 'ul, ol' with getParent() and getNext() despite the mootool documentation saying "if Selectors 
 *  		is included, a full CSS selector can be passed."
 *  
 *  Nov 4th 2008
 *  JJJ - incremented version to 0.68.2
 *  	- Removed extranious comma which threw an error in IE. (Thanks to Robert S. for catching that)
 *  	- Added check to change the opacity to 99.9 if it is over 99 due to the fact that 
 *  		setting the opaicty to 100% in safari caused misc strange behaviour (thanks to Roland Barker 
 *  		at xnau webdesign for reporting this one)
 *  
 *  Nov 3rd 2008
 *  JJJ - Renamed menuWidth option to stretchMainMenu and made it work much quicker
 *  
 *  Nov 2nd 2008
 *  JJJ - Finished adding several callback functions
 *  	- Added fixHasLayoutBug option
 *  
 *  Oct 4th 2008
 *  JJJ - Continued to go through code to optimize and clean it up
 *  	- Added center option
 *  
 *  Sept 28th 2008
 *  JJJ - Incremented version to 0.68
 *  	- Began optimizing & better commenting code
 *  
 *  Sept 16th 2008
 *  JJJ - Incremented version to 0.67
 *  	- Specifically set each submenu z-index on show, incrementing each time. Set z-index back to 1 on hide.
 *  
 *  Sept 14th 2008
 *  JJJ - Added bottom edge detection and redirection (if bottom of subsequent submenu is lower than the scrollheight of the body)
 *  
 *  Sept 10th 2008
 *  JJJ - Did a google search for MooMenu and it looks like that name is already being used, so I must reluctently change the name.
 *  		The name I have chose to move forward with is: MenuMatic.
 *  
 *  Sept 8th 2008
 *  JJJ - Incremented version to 0.66
 *  	- Fixed IE bug whiched caused some events to be incorrectly attached to parent buttons causing sub submenus to not open
 *  	  correctly when transitions are enabled. This error was introduced in 0.65. 
 *  
 *  August 10th 2008
 *  JJJ - Incremented verion to 0.65
 *  	- Fixed bug with edge detection and redirection
 *  	- Improved javascript and CSS to assure the submenus will always be on top
 *  	- Improved edge detection and redirection logic
 *  	- Added subMenusContainerId option so that if you have multiple MooMenu instances on a page they can be styled differently
 *  
 *  May 7th 2008
 *  JJJ - Incremented version to 0.64
 *  	- Fixed bug with that occured when firing events
 *  
 *  April 28th 2008:
 *  JJJ - Incremented version to 0.63
 *  	- Added killDivider option
 *  	- Removed focus on hover since it adds browser default dotted outline
 *  	- Changed menuWidth option to use actual width of nav element (so it can be set in css) instead of a width set in javascript
 *  
 *  Feb 17th 2008:
 *  JJJ - Incremented version to 0.62
 *  	- Added mmbClassName and mmbFocusedClassName options to allow morphing of main menu btns
 *  
 *  Feb 16th 2008:
 *  JJJ - Incremented version to 0.61
 *  	- Made changes to options syntax. 
 *  	- Improved keyboard accessability to take into account a menu's orientation, and its x and y direction when using arrow keys
 *  	- Added matchWidthMode option.
 *  
 *  Feb 14th 2008:
 *  JJJ - Incremented version to 0.60
 *  	- Added menuWidth option to simulate a table based layout for the main menu when the orienation is horizontal
 **/


/*
 * To Do:
 * 
 * 1. Make screencast tutorials
 * 
 * 2. Add more examples to website
 * 
 * 3. Clean up/optimize CSS / make easier to edit 
 * 
 * 4. Make online generator 
 * 
 * 5. Add rounded corners option
 * 
 * 6. Add drop shadow option
 * 
 * 7. Add sound integration 
 * 
 */

var MenuMatic = new Class({
	Implements: Options,
	options: {
        id: 'nav',//the id of the main menu (ul or ol)
        subMenusContainerId:'subMenusContainer',//id of the container div that will be generated to hold the submenus 
		
		//subMenu behavior
		effect: 'slide & fade',// 'slide', 'fade', 'slide & fade', or  null
		duration: 600,//duration of the effect in milliseconds
		physics: Fx.Transitions.Pow.easeOut,//how the effect behaves
		hideDelay: 1000,//in milliseconds, how long you have after moving your mouse off of the submenus before they dissapear
		
		//layout
		stretchMainMenu:false,//stretch main menu btn widths to fit within the width {set in the css} of the parent UL or OL
		matchWidthMode:false,//initial submenus match their parent button's width
		orientation: 'horizontal',//horizontal or vertical
		direction:{	x: 'right',	y: 'down' },//for submenus ( relative to the parent button )left or right, up or down
		tweakInitial:{ x:0, y:0	},//if you need to tweak the placement of the initial submenus
		tweakSubsequent:{ x:0, y:0 },//if you need to tweak the placement of the subsequent submenus
		center: false,// will attempt to center main nav element
		
		//dynamic style
		opacity: 95,//of the submenus
		mmbFocusedClassName:null,//main menu button classname, used for morphing to focused state
		mmbClassName:null,//main menu button classname, used for morphing back to original state
		killDivider:null,	
		
		fixHasLayoutBug:false,	
		
		onHideAllSubMenusNow_begin: (function(){}),
		onHideAllSubMenusNow_complete: (function(){}),
		
		onInit_begin: (function(){}),
		onInit_complete: (function(){})		

    },
	
	hideAllMenusTimeout:null,
	allSubMenus:[],
	subMenuZindex:1,
	
	initialize: function(options){		
		//if(Browser.Engine.webkit419){return;}		
        this.setOptions(options);
		this.options.onInit_begin();
		if(this.options.opacity > 99){this.options.opacity = 99.9;}
		this.options.opacity = this.options.opacity /100;

		Element.implement({
		    getId: function(){
				//If this element does not have an id, give it a unique one
		        if(!this.id){ 
					var uniqueId = this.get('tag') + "-" + $time();
					while($(uniqueId)){
						//make sure it is absolutely unique
						uniqueId = this.get('tag') + "-" + $time();						
					}
					this.id = uniqueId;						
				}
			    return this.id;
		    }
		});
		
		//initialize directions
		this.options.direction.x = this.options.direction.x.toLowerCase();
		this.options.direction.y = this.options.direction.y.toLowerCase();
		if(this.options.direction.x === 'right'){
			this.options.direction.xInverse = 'left';
		}else if(this.options.direction.x === 'left'){
			this.options.direction.xInverse = 'right';
		}
		if(this.options.direction.y === 'up'){
			this.options.direction.yInverse = 'down';
		}else if(this.options.direction.y === 'down'){
			this.options.direction.yInverse = 'up';
		}
		
		var links = $(this.options.id).getElements('a');
		
		links.each(function(item,index){
			
			//store parent links & child menu info
			item.store('parentLinks', item.getParent().getParents('li').getFirst('a'));
			
			item.store('parentLinks',item.retrieve('parentLinks').erase(item.retrieve('parentLinks').getFirst()));
			item.store('childMenu',item.getNext('ul') || item.getNext('ol'));
			
			//determine submenu type
			theSubMenuType = 'subsequent';
			
			//console.log($(this.options.id).getElements('ul, ol'));
			//console.log(item.getParent(['body ul,ol']));
			
			//console.log($(item.getParent('ul') || item.getParent('ol') ));
			
			if( $(item.getParent('ul') || item.getParent('ol') ).id === this.options.id){theSubMenuType = 'initial';	}
			item.store('subMenuType',theSubMenuType );
			
			//add classes to parents
			if(theSubMenuType === 'initial' && $(item.getNext('ul') || item.getNext('ol') )){
				item.addClass('mainMenuParentBtn');
			}else if($(item.getNext('ul') || item.getNext('ol') )){
				item.addClass('subMenuParentBtn');
			}			
		}.bind(this));
		
		//rip the submenus apart into separate divs inside of subMenusContainer
		var subMenusContainer = new Element('div', { 'id': this.options.subMenusContainerId	}).inject( $(document.body) ,'bottom');
		$(this.options.id).getElements('ul, ol').each(function(item,index){	
			new Element('div',{'class': 'smOW'}).inject(subMenusContainer).grab(item);		
		}.bind(this));		
		
		//set tabindex to -1 so tabbing through links in page does not go through hidden links in submenus container, since arrow keys can be used to navigate through submenus
		subMenusContainer.getElements('a').set('tabindex','-1'); 
		
		links.each(function(item,index){
			//only apply to links with subMenus
			if (!item.retrieve('childMenu')) {return;}
			
			//update childMenu pointer to look at smOW DIVs
			item.store('childMenu', item.retrieve('childMenu').getParent('div'));
			
			//add to allSubMenus array
			this.allSubMenus.include(item.retrieve('childMenu'));			
			
			//store parentSubMenus
			item.store('parentSubMenus',item.retrieve('parentLinks').retrieve('childMenu'));

			//now create the MenuMaticSubMenu class instances 
			var aSubMenu = new MenuMaticSubMenu(this.options,this, item);

		}.bind(this));
			
		//attach event handlers to non-parent main menu buttons
		var nonParentBtns = $(this.options.id).getElements('a').filter(function(item, index){ return !item.retrieve('childMenu'); });
		nonParentBtns.each(function(item, index){
			item.addEvents({
				'mouseenter': function(e){					
					//e = new Event(e).stop();
					this.hideAllSubMenusNow();	
					if(this.options.mmbClassName && this.options.mmbFocusedClassName){
						$(item).retrieve('btnMorph', new Fx.Morph(item, { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel'})).start(this.options.mmbFocusedClassName); 
					}								
				}.bind(this),
				
				'focus': function(e){
					//e = new Event(e).stop();
					this.hideAllSubMenusNow();	
					if(this.options.mmbClassName && this.options.mmbFocusedClassName){
						$(item).retrieve('btnMorph', new Fx.Morph(item, { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel'})).start(this.options.mmbFocusedClassName); 
					}
				}.bind(this),
				
				'mouseleave':function(e){
					//e = new Event(e).stop();
					if (this.options.mmbClassName && this.options.mmbFocusedClassName) {						
						$(item).retrieve('btnMorph', new Fx.Morph(item, {	'duration': (this.options.duration * 5),transition: this.options.physics,link: 'cancel'	})).start(this.options.mmbClassName);
					}	
				}.bind(this),
				
				'blur':function(e){
					//e = new Event(e).stop();
					if (this.options.mmbClassName && this.options.mmbFocusedClassName) {						
						$(item).retrieve('btnMorph', new Fx.Morph(item, {	'duration': (this.options.duration * 5),transition: this.options.physics,link: 'cancel'	})).start(this.options.mmbClassName);
					}					
				}.bind(this),
				
				'keydown' : function(e){
				    var event = new Event(e);
					if (e.key === 'up' || e.key === 'down' || e.key === 'left' || e.key === 'right') {	e.stop();	}
					
					if( e.key === 'left' && this.options.orientation === 'horizontal' || 
						e.key === 'up' && this.options.orientation === 'vertical'){
						
						if(item.getParent('li').getPrevious('li')){
							item.getParent('li').getPrevious('li').getFirst('a').focus();
						}else{
							item.getParent('li').getParent().getLast('li').getFirst('a').focus();
						}
					}else if(e.key === 'right' && this.options.orientation === 'horizontal' || 
							 e.key === 'down' && this.options.orientation === 'vertical'){
						if(item.getParent('li').getNext('li')){
							item.getParent('li').getNext('li').getFirst('a').focus();
						}else{
							item.getParent('li').getParent().getFirst('li').getFirst('a').focus();
						}	
					}
				}.bind(this)
			});
		}, this);

		
		this.stretch();
		this.killDivider();
		this.center();
		this.fixHasLayoutBug();
		this.options.onInit_complete();		
    },
	
	fixHasLayoutBug:function(){
		if(Browser.Engine.trident && this.options.fixHasLayoutBug){
			$(this.options.id).getParents().setStyle('zoom',1);
			$(this.options.id).setStyle('zoom',1);
			$(this.options.id).getChildren().setStyle('zoom',1);
			$(this.options.subMenusContainerId).setStyle('zoom',1);
			$(this.options.subMenusContainerId).getChildren().setStyle('zoom',1);
		}		
	},
	
	center:function(){
		if(!this.options.center){return;}
		$(this.options.id).setStyles({'left':'50%','margin-left': -($(this.options.id).getSize().x/2) });
	},
	
	stretch:function(){
		//stretch main menu btn widths to fit within the width of the parent UL or OL
		if(this.options.stretchMainMenu  && this.options.orientation === 'horizontal'){
			var targetWidth = parseFloat($(this.options.id).getCoordinates().width) ;
			var totalBtnWidth = 0;
			var mainBtns = $(this.options.id).getElements('a');
			mainBtns.setStyles({'padding-left':0,'padding-right':0});
			mainBtns.each(function(item,index){ totalBtnWidth+= item.getSize().x; }.bind(this));
			if(targetWidth < totalBtnWidth){return;}
			var increment = (targetWidth - totalBtnWidth)/ mainBtns.length;
			mainBtns.each(function(item,index){ item.setStyle('width',item.getSize().x+increment);	}.bind(this));
			mainBtns.getLast().setStyle('width',mainBtns.getLast().getSize().x-1);
		}
	},
	
	killDivider:function(){
		if(this.options.killDivider && this.options.killDivider.toLowerCase() === 'first'){
			$($(this.options.id).getElements('li')[0]).setStyles({'background':'none'});
		}else if(this.options.killDivider && this.options.killDivider.toLowerCase() === 'last'){
			$($(this.options.id).getElements('li').getLast()).setStyles({'background':'none'});
		}
	},

	hideAllSubMenusNow: function(){
		this.options.onHideAllSubMenusNow_begin();
		$clear(this.hideAllMenusTimeout);
		$$(this.allSubMenus).fireEvent('hide');
		this.options.onHideAllSubMenusNow_complete();	
	} 
	
});

var MenuMaticSubMenu = new Class({
	Implements: Options,
	Extends: MenuMatic,
    options: {
		onSubMenuInit_begin: (function(subMenuClass){}),
		onSubMenuInit_complete: (function(subMenuClass){}),
		
		onMatchWidth_begin: (function(subMenuClass){}),
		onMatchWidth_complete: (function(subMenuClass){}),
		
		onHideSubMenu_begin: (function(subMenuClass){}),
		onHideSubMenu_complete: (function(subMenuClass){}),
		
		onHideOtherSubMenus_begin: (function(subMenuClass){}),
		onHideOtherSubMenus_complete: (function(subMenuClass){}),		
		
		onHideAllSubMenus_begin: (function(subMenuClass){}),
		onHideAllSubMenus_complete: (function(subMenuClass){}),
		
		onPositionSubMenu_begin: (function(subMenuClass){}),
		onPositionSubMenu_complete: (function(subMenuClass){}),
		
		onShowSubMenu_begin: (function(subMenuClass){}),
		onShowSubMenu_complete: (function(subMenuClass){})
	},
	root:null,
	btn:null,
	hidden:true,
	myEffect:null,
		
	initialize: function(options,root,btn){
		this.setOptions(options);		
		this.root = root;
		this.btn = btn;
		this.childMenu = this.btn.retrieve('childMenu');
		this.subMenuType = this.btn.retrieve('subMenuType');
		this.childMenu = this.btn.retrieve('childMenu');
		this.parentSubMenus =  $$(this.btn.retrieve('parentSubMenus'));
		this.parentLinks =  $$(this.btn.retrieve('parentLinks'));
		this.parentSubMenu = $(this.parentSubMenus[0]);
		if(this.parentSubMenu ){this.parentSubMenu =this.parentSubMenu.retrieve('class');}
		this.childMenu.store('class',this);
		this.btn.store('class',this);
		this.childMenu.store('status','closed')
		
		this.options.onSubMenuInit_begin(this);		
		
		//add hide Event
		this.childMenu.addEvent('hide',function(){this.hideSubMenu();}.bind(this));
		
		//add show Event
		this.childMenu.addEvent('show',function(){this.showSubMenu();}.bind(this));

		if(this.options.effect){
			this.myEffect = new Fx.Morph(
				$(this.childMenu).getFirst(), {	duration: this.options.duration, transition: this.options.physics,  link: 'cancel' } 
			);
		}
		if(this.options.effect === 'slide' || this.options.effect === 'slide & fade'){
			if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' ) {
				this.childMenu.getFirst().setStyle('margin-top','0' );
			}else {
				this.childMenu.getFirst().setStyle('margin-left', '0');
			}
			
		}else if (this.options.effect === 'fade' || this.options.effect === 'slide & fade'){
			this.childMenu.getFirst().setStyle('opacity',0 );
		}
		
		if (this.options.effect != 'fade' && this.options.effect != 'slide & fade') {
			this.childMenu.getFirst().setStyle('opacity',this.options.opacity);
		}

		
		//attach event handlers to non-parent sub menu buttons
		//var nonParentBtns = $(this.childMenu).getElements('a').filter(function(item, index){ return !item.retrieve('childMenu'); });
		var nonParentBtns = $(this.childMenu).getElements('li').filter(function(item, index){ return !item.retrieve('childMenu'); });
		nonParentBtns.each(function(item, index){
			$(item).addClass('subMenuBtn');
			
			item.addEvents({
				'mouseenter': function(e){
					this.cancellHideAllSubMenus();					
					this.hideOtherSubMenus();	
					this.childMenu.fireEvent('show');
				}.bind(this),
				
				'focus': function(e){
					this.cancellHideAllSubMenus();		
					this.hideOtherSubMenus();
					this.childMenu.fireEvent('show');
				}.bind(this),
				
				'mouseleave': function(e){
					this.cancellHideAllSubMenus();
					this.hideAllSubMenus();					
				}.bind(this),
				
				'blur': function(e){
					this.cancellHideAllSubMenus();
					this.hideAllSubMenus();
				}.bind(this),
				
				'keydown' : function(e){
				    var event = new Event(e);
					
					if (e.key === 'up' || e.key === 'down' || e.key === 'left' || e.key === 'right' || e.key === 'tab') {	e.stop();	}
					
					if(e.key === 'up'){
						if(item.getParent('li').getPrevious('li')){
							//move focus to the next link up if possible
							item.getParent('li').getPrevious('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='down'){
							//move focus to the parent link
							this.btn.focus();
						}else if(this.options.direction.y ==='up'){
							//move focus to the last link in the subMenu
							item.getParent('li').getParent().getLast('li').getFirst('a').focus();
						}
					}else if(e.key === 'down'){
						if(item.getParent('li').getNext('li')){
							//move focus to the next link down if possible
							item.getParent('li').getNext('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='down'){
							//move focus to the first link in the submenu
							item.getParent('li').getParent().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='up'){
							//move focus to the parent link
							this.btn.focus();
						}
					}else if(e.key === this.options.direction.xInverse){
						this.btn.focus();
					}
				}.bind(this)
			});
			
		}, this);
		
		$(this.btn).removeClass('subMenuBtn');
		
		if (this.subMenuType == 'initial') {
			this.btn.addClass('mainParentBtn');	
		}else{	
			this.btn.addClass('subParentBtn');	
		}
		
		//attach event handlers to parent button
		$(this.btn).addEvents({
			'mouseenter' : function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideOtherSubMenus();
				this.showSubMenu();
				if(this.subMenuType === 'initial' && this.options.mmbClassName && this.options.mmbFocusedClassName){
					$(this.btn).retrieve('btnMorph', new Fx.Morph($(this.btn), { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel' })).start(this.options.mmbFocusedClassName);
				}
			}.bind(this),
			
			'focus' : function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideOtherSubMenus();
				this.showSubMenu();
				if(this.subMenuType === 'initial' && this.options.mmbClassName && this.options.mmbFocusedClassName){
					$(this.btn).retrieve('btnMorph', new Fx.Morph($(this.btn), { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel' })).start(this.options.mmbFocusedClassName);
				}
			}.bind(this),
				
			'mouseleave': function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideAllSubMenus();
			}.bind(this),
			
			'blur': function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideAllSubMenus();
			}.bind(this),
			
			'keydown' : function(e){
			    e = new Event(e)
				if (e.key === 'up' || e.key === 'down' || e.key === 'left' || e.key === 'right') {	e.stop();	}
				
				if(!this.parentSubMenu){
					//main menu parent buttons
					if(
						this.options.orientation === 'horizontal' && e.key === this.options.direction.y ||
						this.options.orientation === 'vertical' && e.key === this.options.direction.x
					){
						if(this.options.direction.y ==='down'){
							//move focus to the first link in the child menu
							this.childMenu.getFirst().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='up'){
							//move focus to the first link in the child menu
							this.childMenu.getFirst().getLast('li').getFirst('a').focus();
						}
					}else if(
						this.options.orientation === 'horizontal' && e.key === 'left' ||
						this.options.orientation === 'vertical' && e.key === this.options.direction.yInverse 
					){
						//move focus to the previous link if possible, if not, move focus to the last link in the menu
						if(this.btn.getParent().getPrevious()){
							this.btn.getParent().getPrevious().getFirst().focus();
						}else{
							this.btn.getParent().getParent().getLast().getFirst().focus();
						}
					}else if(
						this.options.orientation === 'horizontal' && e.key === 'right' ||
						this.options.orientation === 'vertical' && e.key === this.options.direction.y 
					){
						//move focus to the next link if possible, if not, move focus to the first link in the menu
						if (this.btn.getParent().getNext()) {
							this.btn.getParent().getNext().getFirst().focus();
						}else{
							this.btn.getParent().getParent().getFirst().getFirst().focus();
						}
					}
				}else{
					if(e.key === 'tab'){e.stop();}
					//submenu parent buttons
					if (e.key === 'up') {
						if (this.btn.getParent('li').getPrevious('li')) {
							//move focus to the next link up
							this.btn.getParent('li').getPrevious('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'down'){
							//move focus to the parent link
							this.parentSubMenu.btn.focus();
						}else if(this.options.direction.y === 'up'){
							//move focus to the bottom link in this submenu
							this.btn.getParent('li').getParent().getLast('li').getFirst('a').focus();
						}
					}else if(e.key === 'down'){
						if(this.btn.getParent('li').getNext('li')){
							//move focus to the next link down
							this.btn.getParent('li').getNext('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'down'){
							//move focus to the top link in this submenu
							this.btn.getParent('li').getParent().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'up'){
							//move focus to the parent link
							this.parentSubMenu.btn.focus();
						}
					}else if(e.key === this.options.direction.xInverse){
						this.parentSubMenu.btn.focus();
					}else if(e.key === this.options.direction.x){
						if(this.options.direction.y === 'down'){
							this.childMenu.getFirst().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'up'){
						//	this.childMenu.getFirst().getLast('li').getFirst('a').focus();
						}
					}
				}
			}.bind(this)	
		});
		
		this.options.onSubMenuInit_complete(this);
		
    },
	
	matchWidth:function(){
		if (this.widthMatched || !this.options.matchWidthMode || this.subMenuType === 'subsequent'){return;}
		this.options.onMatchWidth_begin(this);
		var parentWidth = this.btn.getCoordinates().width;
		$(this.childMenu).getElements('a').each(function(item,index){
			var borderWidth = parseFloat($(this.childMenu).getFirst().getStyle('border-left-width')) + parseFloat($(this.childMenu).getFirst().getStyle('border-right-width'));
			var paddingWidth = parseFloat(item.getStyle('padding-left')) +	 parseFloat(item.getStyle('padding-right'));
			var offset = borderWidth + paddingWidth ;
			if(parentWidth > item.getCoordinates().width){
				item.setStyle('width',parentWidth - offset);
				item.setStyle('margin-right',-borderWidth);
			}
		}.bind(this));
		this.width = this.childMenu.getFirst().getCoordinates().width;
		this.widthMatched = true;
		this.options.onMatchWidth_complete(this);
	},
	
	hideSubMenu: function() {	
		if(this.childMenu.retrieve('status') === 'closed'){return;}	
		this.options.onHideSubMenu_begin(this);
		if (this.subMenuType == 'initial') {
			if(this.options.mmbClassName && this.options.mmbFocusedClassName){
				$(this.btn).retrieve('btnMorph', new Fx.Morph($(this.btn), { 'duration':(this.options.duration), transition:this.options.physics, link:'cancel' })).start(this.options.mmbClassName )
				.chain(function(){
					$(this.btn).removeClass('mainMenuParentBtnFocused');
					$(this.btn).addClass('mainMenuParentBtn');
				}.bind(this));
			}else{
				$(this.btn).removeClass('mainMenuParentBtnFocused');
				$(this.btn).addClass('mainMenuParentBtn');
			}
		}else{
			$(this.btn).removeClass('subMenuParentBtnFocused');
			$(this.btn).addClass('subMenuParentBtn');
		}
		
		this.childMenu.setStyle('z-index',1);
		
		if(this.options.effect && this.options.effect.toLowerCase() === 'slide'){
			if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'down') {
				this.myEffect.start({ 'margin-top': -this.height }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'up') {
				this.myEffect.start({ 'margin-top': this.height }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'right'){
				this.myEffect.start({ 'margin-left': -this.width }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'left'){
				this.myEffect.start({ 'margin-left': this.width }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}
		}else if(this.options.effect == 'fade'){
			this.myEffect.start({ 'opacity': 0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
		}else if(this.options.effect == 'slide & fade'){
			
			if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'down') {
				this.myEffect.start({ 'margin-top': -this.height,opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'up') {
				this.myEffect.start({ 'margin-top': this.height,opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'right'){
				this.myEffect.start({ 'margin-left': -this.width,opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'left'){
				this.myEffect.start({ 'margin-left': this.width, opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}
		}else{
			this.childMenu.style.display = "none";
		}
		this.childMenu.store('status','closed');
		this.options.onHideSubMenu_complete(this);
	},
	
	hideOtherSubMenus: function() {		
		this.options.onHideOtherSubMenus_begin(this);
		//set up otherSubMenus element collection
		if(!this.btn.retrieve('otherSubMenus')){
			this.btn.store('otherSubMenus', $$(this.root.allSubMenus.filter(function(item){ return !this.btn.retrieve('parentSubMenus').contains(item) && item != this.childMenu; }.bind(this)) ));
		}		
		this.parentSubMenus.fireEvent('show');
		this.btn.retrieve('otherSubMenus').fireEvent('hide');
		this.options.onHideOtherSubMenus_complete(this);
	},
	
	hideAllSubMenus: function(){
		this.options.onHideAllSubMenus_begin(this);
		$clear(this.root.hideAllMenusTimeout);
		this.root.hideAllMenusTimeout = (function(){
			$clear(this.hideAllMenusTimeout);			
			$$(this.root.allSubMenus).fireEvent('hide');			
		}).bind(this).delay(this.options.hideDelay);
		this.options.onHideAllSubMenus_complete(this);		
	},

	cancellHideAllSubMenus: function(){ 
		$clear(this.root.hideAllMenusTimeout);	
	},
	
	showSubMenu: function(now){		
		if(this.childMenu.retrieve('status') === 'open'){return;}
		this.options.onShowSubMenu_begin(this);
		if (this.subMenuType == 'initial') {
			$(this.btn).removeClass('mainMenuParentBtn');
			$(this.btn).addClass('mainMenuParentBtnFocused');	
		}else{
			$(this.btn).removeClass('subMenuParentBtn');
			$(this.btn).addClass('subMenuParentBtnFocused');
		}
		this.root.subMenuZindex++;
		this.childMenu.setStyles({'display':'block','visibility':'hidden','z-index':this.root.subMenuZindex});
		
		if(!this.width || !this.height ){
			this.width = this.childMenu.getFirst().getCoordinates().width;
			this.height = this.childMenu.getFirst().getCoordinates().height;
			this.childMenu.setStyle('height',this.height,'border');
			if(this.options.effect === 'slide' || this.options.effect === 'slide & fade'){
				if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' ) {
					this.childMenu.getFirst().setStyle('margin-top','0' );
					if(this.options.direction.y === 'down'){
						this.myEffect.set({ 'margin-top': - this.height });
					}else if(this.options.direction.y === 'up'){
						this.myEffect.set({ 'margin-top': this.height });
					}
				}else {
					if(this.options.direction.x === 'left'){
						this.myEffect.set({ 'margin-left': this.width });
					}else{
						this.myEffect.set({ 'margin-left': -this.width });
					}
				}
			}
		}
		this.matchWidth();
		this.positionSubMenu();
		
		if(this.options.effect === 'slide' ){
			this.childMenu.setStyles({'display':'block','visibility':'visible'});
			if (this.subMenuType === 'initial' && this.options.orientation === 'horizontal') {
				if(now){
					this.myEffect.set({ 'margin-top': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}else{
					this.myEffect.start({ 'margin-top': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}
			}else{
				if (now) {
					this.myEffect.set({ 'margin-left': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}else{
					this.myEffect.start({ 'margin-left': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}
			}
		}else if(this.options.effect === 'fade' ){
			if (now) {
				this.myEffect.set({'opacity': this.options.opacity}).chain(function(){	this.showSubMenuComplete();	}.bind(this));
			}else{
				this.myEffect.start({'opacity': this.options.opacity}).chain(function(){	this.showSubMenuComplete();	}.bind(this));
			}
		}else if(this.options.effect == 'slide & fade'){
			this.childMenu.setStyles({'display':'block','visibility':'visible'});
			this.childMenu.getFirst().setStyles({'left':0});
			if (this.subMenuType === 'initial' && this.options.orientation === 'horizontal') {
				if (now) {
					this.myEffect.set({ 'margin-top': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}else{
					this.myEffect.start({ 'margin-top': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}
			}else{
				if (now) {
					if (this.options.direction.x === 'right') {
						this.myEffect.set({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}else if (this.options.direction.x === 'left') {
						this.myEffect.set({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}	
				}else{
					if (this.options.direction.x === 'right') {						
						this.myEffect.set({ 'margin-left': -this.width, 'opacity': this.options.opacity });						
						this.myEffect.start({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}else if (this.options.direction.x === 'left') {
						this.myEffect.start({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}
				}
			}
		}else{
			this.childMenu.setStyles({'display':'block','visibility':'visible'}).chain(function(){	this.showSubMenuComplete(this);	}.bind(this));
		}
		this.childMenu.store('status','open');
		
	},
	
	showSubMenuComplete:function(){		
		this.options.onShowSubMenu_complete(this);
	},
	
	positionSubMenu: function(){
		this.options.onPositionSubMenu_begin(this);
		this.childMenu.setStyle('width',this.width) ;
		this.childMenu.getFirst().setStyle('width',this.width) ;
				
		//if any parent has bounced off a viewport edge, inherit that new direction
		if (this.subMenuType === 'subsequent') {
			if(this.parentSubMenu && this.options.direction.x != this.parentSubMenu.options.direction.x){
				if(this.parentSubMenu.options.direction.x === 'left' && this.options.effect && this.options.effect.contains('slide')){
					this.myEffect.set({ 'margin-left': this.width });	
				}
			}
			this.options.direction.x = this.parentSubMenu.options.direction.x;
			this.options.direction.xInverse = this.parentSubMenu.options.direction.xInverse;
			this.options.direction.y = this.parentSubMenu.options.direction.y;
			this.options.direction.yInverse = this.parentSubMenu.options.direction.yInverse;
		}

		var top;
		var overlap
		if(this.subMenuType == 'initial'){
			if(	this.options.direction.y === 'up'){				
				if(this.options.orientation === 'vertical'){
					top = this.btn.getCoordinates().bottom - this.height + this.options.tweakInitial.y ;
				}else{			
					top = this.btn.getCoordinates().top - this.height + this.options.tweakInitial.y ;
				}
				this.childMenu.style.top = top+ 'px';
			}else if(this.options.orientation == 'horizontal'){
				this.childMenu.style.top = this.btn.getCoordinates().bottom + this.options.tweakInitial.y + 'px';
			}else if(this.options.orientation == 'vertical'){
				top = this.btn.getPosition().y + this.options.tweakInitial.y ;				
				if((top + this.childMenu.getSize().y) >= $(document.body).getScrollSize().y){
					overlap = (top + this.childMenu.getSize().y) - $(document.body).getScrollSize().y  ;
					top = top - overlap - 20;
				}	
				this.childMenu.style.top = top+ 'px';
			}
			if(	this.options.orientation == 'horizontal'){
				this.childMenu.style.left = this.btn.getPosition().x + this.options.tweakInitial.x + 'px';
			}else if(this.options.direction.x == 'left'){
				this.childMenu.style.left = this.btn.getPosition().x - this.childMenu.getCoordinates().width + this.options.tweakInitial.x + 'px';
			}else if(this.options.direction.x == 'right'){
				this.childMenu.style.left = this.btn.getCoordinates().right + this.options.tweakInitial.x + 'px';
			}
		}else if(this.subMenuType == 'subsequent'){
			
			if(this.options.direction.y === 'down'){
				if( (this.btn.getCoordinates().top + this.options.tweakSubsequent.y+ this.childMenu.getSize().y) >= $(document.body).getScrollSize().y ){
					overlap =  (this.btn.getCoordinates().top + this.options.tweakSubsequent.y+ this.childMenu.getSize().y) -$(document.body).getScrollSize().y  ;
					this.childMenu.style.top = (this.btn.getCoordinates().top + this.options.tweakSubsequent.y) - overlap - 20+ 'px';
				}else{
					this.childMenu.style.top = this.btn.getCoordinates().top + this.options.tweakSubsequent.y + 'px';
				}
			}else if(this.options.direction.y === 'up'){
				if((this.btn.getCoordinates().bottom - this.height + this.options.tweakSubsequent.y)< 1){
					this.options.direction.y = 'down';
					this.options.direction.yInverse = 'up';
					this.childMenu.style.top = this.btn.getCoordinates().top + this.options.tweakSubsequent.y + 'px';
				}else{
					this.childMenu.style.top = this.btn.getCoordinates().bottom - this.height + this.options.tweakSubsequent.y + 'px';
				}
			}
			if(this.options.direction.x == 'left'){
				this.childMenu.style.left = this.btn.getCoordinates().left - this.childMenu.getCoordinates().width + this.options.tweakSubsequent.x + 'px';
				
				if( this.childMenu.getPosition().x < 0){					
					this.options.direction.x = 'right';
					this.options.direction.xInverse = 'left';
					this.childMenu.style.left = this.btn.getPosition().x + this.btn.getCoordinates().width + this.options.tweakSubsequent.x + 'px';
					
					if(this.options.effect === 'slide' || this.options.effect === 'slide & fade'){
						this.myEffect.set({ 'margin-left': -this.width, 'opacity': this.options.opacity });						
					}
				}
			}else if(this.options.direction.x == 'right'){
				this.childMenu.style.left = this.btn.getCoordinates().right + this.options.tweakSubsequent.x + 'px';
				var smRight = this.childMenu.getCoordinates().right;
				var viewportRightEdge = document.getCoordinates().width + window.getScroll().x;				
				if( smRight > viewportRightEdge ){
					this.options.direction.x = 'left';
					this.options.direction.xInverse = 'right';
					this.childMenu.style.left = this.btn.getCoordinates().left - this.childMenu.getCoordinates().width + this.options.tweakSubsequent.x + 'px'
					if (this.options.effect === 'slide' || this.options.effect === 'slide & fade') {
						this.myEffect.set({	'margin-left': this.width,	'opacity': this.options.opacity	});
					}
				}
			}
		}
		this.options.onPositionSubMenu_complete(this);
	}	
});

