/**
 * 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

/**
* 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');
										 }
						}
					);
				}
			}
		}
	);
}

/**
* 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
*/
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 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'
			if(subnav) {
				subnav.store('nav', el);
				el.addEvents(
					{
						'mouseover': function(){
										$clear(linkTimer);					// clear the linkTimer
                                        if(currentNav) {
											currentNav.setStyle('display','none');		// hide the previous subnav
											currentNav.retrieve('nav').removeClass('selected');
										}
										el.set('class','selected');	// add the selected class
										el.setStyles({'cursor':'pointer'});
										currentNav = subnav;					// set it globally
										subnav.setStyle('display','block');						// show the current subnav
									 },
						'mouseout' : function() {
										// linkTimer = currentNav.hide.delay(50,currentNav);	// hide the subnav on a timer
										if(currentNav) linkTimer = (
															function(){
																currentNav.setStyle('display','none');
																currentNav.retrieve('nav').removeClass('selected');
															}
														).delay(50,currentNav);
									 }
					}
				);

				if(subnav) {
					subnav.addEvents(
						{
							'mouseover' : function() {
											$clear(linkTimer);					// clear the timer
										  },
							'mouseout' :  function() {
											// if(currentNav) linkTimer = currentNav.hide.delay(50,currentNav);	// hide the subnav on a timer
											if(currentNav) linkTimer = (
																function(){
																	currentNav.setStyle('display','none');
																	currentNav.retrieve('nav').removeClass('selected');
																}
															).delay(50,currentNav);
										  }
						}
					);
				}
			}
		}
	);
	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.getSize();
				switch(pos) {
					case 'top':
						subnav.setStyles(
                                                	{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.top-(size.y+pad),
								'left' : coords.left
							}
						).setStyle('display','none');
						break;
					case 'left':
						subnav.setStyles(
							{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.top,
								'left' : coords.left-(size.x+pad)
							}
						).setStyle('display','none');
						break;
					case 'right':
						subnav.setStyles(
							{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.top,
								'left' : coords.left+(size.x-pad)
							}
						).setStyle('display','none');
						break;
					default :
						subnav.setStyles(										// remove and position the element
							{
								'z-index' : '30',
								'position' : 'absolute',
								'top' : coords.bottom+(size.y-pad),
								'left' : coords.left
							}
						).setStyle('display','none');
						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 = $(document.body).getElements('*[tip]');	// get all the items with a tip attribute
	as.each(
		function(el,i) {
			var c = el.getProperty('tip').split('::');
			el.store('tip:title', c[0]);
			el.store('tip:text', c[1]);
		}
	);

	var tip = new Tips(									// add the tip to all of the items
		as,
		{
			fixed: false,
			hideDelay: 50,
			showDelay: 50
		}
	);

	tip.addEvents({										// fade them in and out
			'show': function(t) {
						t.fade('in');
					},
			'hide': function(t) {
						t.fade('out');
					}
	});
}

/**
* make the admin menu draggable
*/
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 centerLoginBox(el) {
	var win = window.getSize();
	var sz = $('lightbox_login').getSize();
	var el = $('lightbox_login').dispose();
	el.inject($(document.body));
	el.setStyles({
		'z-index' : 40,
		position : 'absolute',
		top : (win.y/2)-90,
		left : (win.x/2)-110
	});
	el.setStyle('display','none');
}

/**
* create the lightbox background
*/
function setLightbox() {
	centerLoginBox();
	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');
			}
			var a = el.getElement('a');
			if($chk(a)) a.set('href','#');
		}
	);
	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 default_set = false;		// if no default tab is set use the first tab
	var selected_tab = null;		// the currently selected tab

	// go through all the found tabs
	tabs.each(
		function(el) {
			var t = $(el.getProperty('tab'));		// get the content for the tab
			var g = el.getProperty('tab_group');	// @todo start using tab groups so the site can have more than one tab set

/*
			if(el.getProperty('tab_default')) {		// if there is a default tab set it
				t.setStyle('display','block');
				el.addClass('tab_selected');
				default_set = true;
			} else {
				t.setStyle('display','none');		// if not hide the contents (though they should be hidden using css already)
			}
*/
			t.setStyle('display','none');
			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_tab != this) this.removeClass('tab_selected');
									},
						'click' : function() {			// on click hide the current, show the chosen and add some style
										if(selected_tab != this) {
											$(this.getProperty('tab')).setStyle('display','block');
											$(selected_tab.getProperty('tab')).setStyle('display','none');
											selected_tab.removeClass('tab_selected');
											selected_tab = this;
										}
									}
					}
				}
			);
		}
	);

	// if no default tab was chosen select the first tab
	if(!$chk(default_set) && tabs.length > 0) {
		var dt = $(tabs[0].getProperty('tab'));
		dt.setStyle('display','block');
		tabs[0].addClass('tab_selected');
		selected_tab = tabs[0];
	}
}


/**
* make a list sortable if it has a 'sort' param.
*/
function setSortables() {
	var sorts = new Sortables($$('*[sort]'),
		{
			constrain: true,
			snap: 20,
			handle: 'img',
			onComplete: function() {
				console.log(sorts.serialize());
			}
		}
		);
}

/**
* enable ajax links
*/
function setNavEditor() {
	var ajs = $$('*[xhr]');
	ajs.each(
		function(el,i) {
			el.addEvents(
				{
					'click' : function() {
						var myConf = new Confirmer({		// confirmer
						msg: 'your changes are saved!',
						positionOptions: {
							relativeTo: 'navlist',
							position: 'topRight'
						}
					});

					var jsonRequest = new Request.JSON(
						{
							url: 'ajax.php?p=menu_delete&id='.el.getProperty('nav_id'),
							onComplete: function(d) {
								var destroyEl = el.getProperty('destroy');
								var successText = el.getProperty('success');
								var failureText = el.getProperty('failure');
								if($chk(destroyEl)) {
									$(destroyEl).destroy();
									myConf.prompt({msg: successText});
								}
							}
						}
					);
					jsonRequest.send();
					el.getElement('img').set(
						{
							'src' : '../images/universal/loading.gif',
							'styles' : {
								'width' : '16px',
								'height' : '16px'
							}
						}
					);
				  }
				}
			);
		}
	);
}

function setSignupForm() {

}

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