/**
 * LAYER INDEX : the order of the z-index's
 *
 * 10 - Public Layer contains items that are removed from the flow to be positioned.
 * 20 - Lightbox overlay
 * 30 - Subnavigation (as long as the main link is above the lightbox it will not get shown)
 * 40 - Lightbox window container
 **/

/**
 * VARIABLES
 **/

var lightBox = null;	// dynamically created lightbox
var currentBox = null;	// box currently visible via lightbox
var selectedNav = null;
var active_accordion = null;
var subnavs = new Array();
var mainnav = null;
var last_toggler = null;
Clientcide.setAssetLocation("http://localhost/assets/mooLive/images");

/**
* Make any tag into a clickable link. Just give it an href attribute.
*
* @return	null
* @access public
*/

function setLinks() {
	/* make any non <a> tag with an href into a link */
	/* <div href='http://www.google.com'>Click Me</div> */
	var links = $(document.body).getElements('*[href]');	// get the elements with an href
	links.each(
		function(el,i) {
			if(el.get('tag') != 'a' && el.get('class') != 'selected') {	// if it is not a <a> tag and it is not currently selected
				if(!el.get('lightbox')) el.addEvents(					// if it is not a lightbox link
					{
						'click' : function() {
									document.location = this.getProperty('href');
								  }
					}
				);
				if(!$(el.getProperty('nav'))) {												// if it does not have a subnav in the dom
					el.addEvents(
						{
							'mouseover': function(){
											el.set('class','selected');						// add the selected class
											el.setStyles({'cursor':'pointer'});				// give it a pointer
										 },
							'mouseout' : function() {
											el.removeClass('selected');
										 }
						}
					);
				}
			}

			if(el.get('class') == 'selected' && el.get('tag') != 'a') selectedNav = el;	// identify the link as currently selected so we do not shut it off
		}
	);
}

/**
* Create subnav / link association. Takes care of all the pointers, links and positioning.
*
* @param xxx $xxx	xxx
* @param xxx $xxx	xxx
* @return	xxx
* @access public
*/

// how do I make it work with multiple levels?

function setSubnavs(pos,padding) {
	/* associate sublinks with their parents */
	/* example <a href='#' nav='myDivID' />Navigation</a><div id='myDivID'>Sublinks</div> */

	var linkTimer;		// subnav hide timer
	var currentNav;		// last subnav shown
	var shownNav;
	var shownLink;
	var links = $(document.body).getElements('*[nav]');	// get the navigation links with defined subnavs
	links.each(			// go through all the found links
		function(el,i) {
			var subnav = $(el.getProperty('nav'));	// get the id of the subnav from the attribute 'nav'
			el.store('flag','0');

			if(el.get('class') == 'selected') {
				el.store('flag','1');
				shownNav = subnav;
				shownLink = el;
			}

			if(subnav) {
				subnav.store('nav', el);
				el.addEvents(
					{
						'mouseover': function(){
											if(shownLink) {
												if(shownNav) shownNav.hide();
												shownLink.removeClass('selected');
											}
											$clear(linkTimer);					// clear the linkTimer
											if(currentNav) {
												currentNav.hide();		// hide the previous subnav
												if(currentNav.retrieve('nav') != selectedNav) currentNav.retrieve('nav').removeClass('selected');
											}
											el.addClass('selected');	// add the selected class
											el.setStyles({'cursor':'pointer'});
											currentNav = subnav;					// set it globally
											subnav.show();						// show the current subnav
									 },
						'mouseout' : function() {
											linkTimer = (
												function(){
													currentNav.hide();
													if(el != selectedNav) currentNav.retrieve('nav').removeClass('selected');
													if(shownLink) {
														shownLink.addClass('selected');
														if(shownNav) shownNav.show();
													}
												}
											).delay(50,currentNav);
									 }
					}
				);

				subnav.addEvents(
					{
						'mouseover' : function() {
										$clear(linkTimer);					// clear the timer
									  },
						'mouseout' :  function() {
										if(currentNav && this.retrieve('nav').retrieve('flag') != '1') {
											linkTimer = (
															function(){
																currentNav.setStyle('display','none');
																if(el != selectedNav) currentNav.retrieve('nav').removeClass('selected');
																if(shownLink) {
																	shownLink.addClass('selected');
																	if(shownNav) shownNav.show();
																}
															}
														).delay(50,currentNav);
									  }
								  }
					}
				);
			} else {
				el.addEvents(
					{
						'mouseover': function(){
											if(currentNav) {
												currentNav.hide();		// hide the previous subnav
												if(currentNav.retrieve('nav') != selectedNav) currentNav.retrieve('nav').removeClass('selected');
											}
											if(shownLink && shownLink != this) {
												linkTimer = (
															function(){
																if(shownNav) shownNav.hide();
																shownLink.removeClass('selected');
															}
														).delay(50,shownNav);
											}
									 },
						'mouseout' : function() {
											if(shownLink && shownLink != this) {
												shownLink.addClass('selected');
												if(shownNav) shownNav.show();
											}
										}
					}
				);
			}
		}
	);
	setSubnavPositions(links);

	// sometimes the subnav's are not positioned correctly because all the images are not loaded - this will go through them again
	// and reset their position after the images have loaded - so subnav's maybe positioned incorrectly until all the images are loaded.
	window.addEvent('load', function(){
		setSubnavPositions(links);
	});
}

/**
* Set the subnavigation div's into their correct positions. Runs twice to ensure proper placement. This is due to the
* issue where images above the navigation placement - if not loaded immediately will cause the div to be placed incorrectly.
*
* @param xxx $xxx	xxx
* @param xxx $xxx	xxx
* @return	xxx
* @access public
*/
function setSubnavPositions(links) {
	if(!links) return;
	links.each(			// go through all the found links
		function(el,i) {
			var subnav = $(el.getProperty('nav'));	// get the id of the subnav from the attribute 'nav'
			var pos = el.getProperty('nav_pos');	// get position
			var pad = el.getProperty('nav_pad').toInt();	// get padding
			if(subnav) {
				var coords = el.getCoordinates(subnav.getParent());			// get location of the element
				var size = subnav.getDimensions();
				// console.log(size);
				switch(pos) {
					case 'top':
						subnav.setStyles(
                                                	{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.top-(size.y+pad),
								'left' : coords.left
							}
						);
						break;
					case 'left':
						subnav.setStyles(
							{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.top,
								'left' : coords.left-(size.x+pad)
							}
						);
						break;
					case 'right':
						subnav.setStyles(
							{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.top,
								'left' : coords.left+(size.x-pad)
							}
						);
						break;
					default :
						// console.log(coords.left+'-'+'('+size.x+'/'+2+')');
						var pos = coords.left-(size.x/2)+coords.width/2;
						if(pos<0) pos = 0;
						subnav.setStyles(										// remove and position the element
							{
								'z-index' : '1001',
								'position' : 'absolute',
								'top' : coords.bottom+pad,
								'left' : pos
							}
						);
						break;
			   }
			}
	});
}

/**
* set the tooltips up using
*
* @param xxx $xxx	xxx
* @param xxx $xxx	xxx
* @return	xxx
* @access public
*/
function setToolTips() {
	/* Add a tooltip to all elements with a tip attribute */
	/* Example <a href='#' tip='Title::Text' /> */

	var as = $$('*[tip]');	// get all the items with a tip attribute

	as.each(
		function(el,i) {
			var c = el.getProperty('tip').split('::');
			var mySticky = new StickyWin.PointyTip(c[0], c[1], {
			  point: 'left',
			  relativeTo: el,
			  width: '200',
			  pointyOptions: { theme: 'dark' },
			  onClose : function() {
					  el.store('no_hide','0');
				  }
			});
			mySticky.hide();
			el.addEvents({
				'click' : function() {
				},
				'mouseover': function(){
								el.setStyles({'cursor':'pointer'});				// give it a pointer
								mySticky.show();
							 },
				'mouseout' : function() {
								el.setStyles({'cursor':'normal'});				// give it a pointer
								if(this.retrieve('no_hide') != '1') mySticky.hide();
							 },
				'click' : function() {
							this.store('no_hide','1');
				}
			});
		}
	);
}

/**
* make the admin menu collapsable
*/
function setAdminMenu(start_pos) {
	var menuTween = new Fx.Tween($('admin_menu'),{'duration' : 'long'});

	var pos = start_pos;

	if(!pos) {
		menuTween.set('width','16');
		$('menu_link').set('src','images/universal/menu_open.gif');
	}

	$('menu_link').set({
			events : {
				'click' : function() {
					if(pos) {
						menuTween.start('width','16');
						this.set('src','images/universal/menu_open.gif');
						var jsonRequest = new Request.JSON(
								{
									url: 'callbacks/ajax&p=admin_menu&pos=0'
								}
							);
						jsonRequest.send();
						pos = 0;
					} else {
						menuTween.start('width','196');
						this.set('src','images/universal/menu_close.gif');
						var jsonRequest = new Request.JSON(
								{
									url: 'callbacks/ajax&p=admin_menu&pos=1'
								}
							);
						jsonRequest.send();
						pos = 1;
					}
				 },
				'mouseover': function(){
					this.setStyles({'cursor':'pointer'});				// give it a pointer
				 },
				'mouseout' : function() {
					this.setStyles({'cursor':'normal'});				// give it a pointer
				 }
			}
		}
	);
}

/**
* center the login lightbox
*/
function centerLightBoxContent(el) {
	var win = window.getSize();
	var sz = el.getSize();
	var el2 = el.dispose();
	el2.inject($(document.body));
	el2.setStyles({
		'z-index' : 40,
		position : 'absolute',
		top : (win.y/2)-(sz.y/2),
		left : (win.x/2)-(sz.x/2)
	});
	el2.setStyle('display','none');
}

/**
* create the lightbox background
*/
function setLightbox() {
	var win = $(document.body).getSize();
	var lt = new Element('div', {
							styles: {
							   'height' : win.y,
							   'width' : win.x,
							   'z-index' : 20,
							   'background-color' : '#000',
							   'position' : 'absolute',
							   'top' : 0,
							   'left' : 0,
							   'opacity' : 0
							},
							'events' : {
								'click' : hideLightbox
							}
						}
					);
	lt.inject($(document.body));
	lightBox = lt;
}

/**
* enable all the lightbox links so that they interface with the lightbox component
*/
function setLightboxLinks() {
	var lbs = $$('*[lightbox]');
	lbs.each(
		function(el,i){
			if($(el.get('lightbox')) != null) {
				el.set(
					{
						'events' : {
							click: showLightbox
						},
						styles : {
							'cursor' : 'pointer'
						}
					}
				);
				$(el.get('lightbox')).setStyle('display', 'none');

				centerLightBoxContent($(el.get('lightbox')));
				var cnl = $(el.get('lightbox')).getElement('#btn_cancel');
				cnl.set(
					{
						'events' : {
							click: hideLightbox
						}
					}
				);
			}
		}
	);
	setLightbox();
}

/**
* hide the lightbox
*/
function hideLightbox(t) {
	if($chk(currentBox)) currentBox.setStyle('display', 'none');;
	lightBox.fade(0);
	$(document.html).setStyle('overflow', 'auto');
}

/**
* show the lightbox and display the correct element
*/
function showLightbox(el) {
	var el = $(this.get('lightbox'));
	el.setStyle('display', 'block');
	lightBox.fade(.7);
	currentBox = el;
	currentBox.adopt(
		new Element('img',
			{
				src : '../images/universal/cancel.png',
				styles : {
					'position' : 'absolute',
					'top' : 6,
					'right' : 6,
					'cursor' : 'pointer'
				},
				events : {
					'click' : hideLightbox
				}
			}
		)
	);
	$(document.html).setStyle('overflow', 'hidden');
}

/**
* create a tab structure -
*/
function setTabs() {
	var tabs = $$('*[tab]');		// get all the tab links
	var selected_tab = null;		// the currently selected tab

	var selected_tabs = new Hash();

	// go through all the found tabs
	if(tabs.length > 0) {
		tabs.each(
			function(el) {
				if(!el.getProperty('default_tab')) {
					$(el.getProperty('tab')).setStyle('display','none');		// if not hide the contents (though they should be hidden using css already)
				} else {
					selected_tabs.set(el.get('tab_group'),el);
					$(el.getProperty('tab')).setStyle('display','block');
					el.addClass('tab_selected');
				}

				el.set(
					{
						'events' : {
							'mouseover' : function() {		// on mouseover set the pointer and give it some style
											this.setStyle('cursor','pointer');
											this.addClass('tab_selected');
										},
							'mouseout' : function() {		// on mouseout set the cursor to normal and return the style (if it is not selected)
											this.setStyle('cursor','normal');
											if(selected_tabs.get(this.getProperty('tab_group')) != this) this.removeClass('tab_selected');
										},
							'click' : function() {			// on click hide the current, show the chosen and add some style
											if(selected_tabs.get(this.getProperty('tab_group')) != this) {
												$(this.getProperty('tab')).setStyle('display','block');
												if(selected_tabs.get(this.getProperty('tab_group'))) {
													$(selected_tabs.get(this.getProperty('tab_group')).getProperty('tab')).setStyle('display','none');
													selected_tabs.get(this.getProperty('tab_group')).removeClass('tab_selected');
												}
												selected_tabs.set(this.getProperty('tab_group'),this);
											}
										}
						}
					}
				);
			}
		);
	}
}

function setProfitReportForm() {
	$$('input.DatePicker').each( function(el){
		new DatePicker(el, {
					options : {
						yearOrder: 'desc',
						yearStart: 2000
					}
				});
});
}


/**
* set default form text values and make them disappear when the form is selected.
*/
function setTextDefaults() {
	var txts = $$('*[default]');
	txts.each(
		function(el,i) {
			var def = el.get('default');	// get the default value
			el.set(
				{
					'value' : def			// set the default value
				}
			);
			el.addEvents(
				{
					'focus' : function() {
						if(def == 'password') {
							el.set(
								{
									'type' : 'password'
								}
							)
						};
						if(el.get('value') == def) {
							el.set(
								{
									'value' : ''
								}
							)
						};
					},
					'blur' : function() {
						if(def == 'password' && el.get('value') == '') {
							el.set(
								{
									'type' : 'text'
								}
							)
						};
						if(el.get('value') == '') {
							el.set(
								{
									'value' : def
								}
							)
						};
					}
				}
			);
		}
	);
}

function setAccordionNav() {
	var cords = $(document.body).getElements('*[accordion]');	// get all the navigations (can have more than one) defined by accordion='true'
	cords.each(
		function (el,i) {
			var subs = el.getElements('*[toggler]');	// get all the subnavigations
			subs.each(
				function(el,i2) {
					var pos = null;
					var t = el.getElements('.'+el.get('toggler'));	// get the subnav togglers
					var p = el.getElements('.'+el.get('panes'));	// get the subnav elements
					pos = t[0].get('pos');
					var n = new Accordion(el, t, p,{
							opacity: false,
							onActive: function(toggler, element){
								active_accordion = this;
								toggler.addClass('toggler1_selected');
							},
							onBackground: function(toggler, element){
								toggler.removeClass('toggler1_selected');
							},
							alwaysHide : true,
							display: null
					});
					subnavs.push(n);
				}
			)

			var t = el.getElements('.'+el.get('toggler'));
			var p = el.getElements('.'+el.get('panes'));
			mainnav = new Accordion(el, t, p, {
					opacity: false,
					onActive: function(toggler, element){
					},
					onBackground: function(toggler, element){
						element.setStyle('height',element.getSize().y);
					},
					onComplete:function(toggler, element){
						this.elements[this.previous].setStyle('height','auto');
						if($chk(active_accordion)) {
							active_accordion.display(null);		// hide the last child subnav to be opened
						}
					},
					display: null
			});
			el.setStyle('display','block');
		}
	);
}

function setHighlights() {
	if(!Browser.Engine.trident) {
		var hls = $$('*[highlight]');
		hls.each(
			function(el,i) {
				el.store('bg',el.getStyle('background-color'));
				el.addEvents(
					{
						'mouseover' : function() {
							this.setStyle('background-color',this.get('highlight'));
						},
						'mouseout' : function() {
							this.setStyle('background-color',this.retrieve('bg'));
						}
					}
				)
			}
		);
	}
}

function setValidation() {
	var frms = $$('.validate');
	frms.each(function(el,i) {
		var fv = new FormValidator.Tips(el);

		// validate matching fields : make sure they both equal the same thing
		fv.add('validate-match', {
			errorMsg: 'This field should match the password field',
			test: function(el,props){
				if($(props.matchField).get('value') == el.get('value')) return true;	// if they match return true
				return false;
			}
		});

		// validate if no is selected : if no is selected than this field should be filled in
		fv.add('validate-if-matchNull', {
			errorMsg: 'If no please fill in this field and select no',
			test: function(el,props){
				var v = document.getElement('input[name='+props.matchField+']:checked');
				if(!v) return false;
				if((v.get('value') != props.nullValue) || el.get('value') != '') return true;
				return false;
			}
		});

		// validate if no is selected : if no is selected than this field should be filled in
		fv.add('validate-radio', {
			errorMsg: 'Please choose an option',
			test: function(el,props) {
				var v = document.getElement('input[name='+el.get('name')+']:checked');
				if(v) return true;
				return false;
			}
		});
	});
}

function increaseFontSize() {
	var el = $('content_container');
	if(el.getStyle('font-size').toInt() > 18) return;
	el.setStyle('font-size',el.getStyle('font-size').toInt()+2);
	el.setStyle('line-height',el.getStyle('line-height').toInt()+2);
}

function decreaseFontSize() {
	var el = $('content_container');
	if(el.getStyle('font-size').toInt() < 11) return;
	el.setStyle('font-size',el.getStyle('font-size').toInt()-2);
	el.setStyle('line-height',el.getStyle('line-height').toInt()-2);
}

function setFontTools() {
	$('increase_font').addEvent('click',
		function(e) {
			increaseFontSize();
			e.stop();
		}
	);
	$('decrease_font').addEvent('click',
		function(e) {
			decreaseFontSize();
			e.stop();
		}
	);
}