/**
 * LAYER INDEX : the order of the z-index's
 *
 * 10 - Public Layer contains items that are removed from the flow to be positioned.
 **/

/**
 * VARIABLES
 **/

var selectedNav = null;
var active_accordion = null;
var subnavs = new Array();
var mainnav = null;
var last_toggler = null;
Clientcide.setAssetLocation("../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
				el.addEvents(
					{
						'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
				 }
			}
		}
	);
}


/**
* 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')) {
					if(el.getProperty('tab_style') == 'fade') {
						$(el.getProperty('tab')).setStyle('opacity',0);
					} else {
						$(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) {
												if(selected_tabs.get(this.getProperty('tab_group'))) {
													if(this.getProperty('tab_style') == 'fade') {
														$(this.getProperty('tab')).setStyle('display','block').fade('in');
														$(selected_tabs.get(this.getProperty('tab_group')).getProperty('tab')).fade('out');
													} else {
														$(this.getProperty('tab')).setStyle('display','block');
														$(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();
		}
	);
}


function setAdminNav() {
	var els = $$('.toggle');
	els.each(function(el,i) {
		el.set(
				{
					'events' : {
						'mouseover' : function() {		// on mouseover set the pointer and give it some style
										this.setStyle('cursor','pointer');
									},
						'mouseout' : function() {		// on mouseout set the cursor to normal and return the style (if it is not selected)
										this.setStyle('cursor','normal');
									},
						'click' : function() {			// on click hide the current, show the chosen and add some style
										new Fx.Reveal($(this.getProperty('target'))).toggle();
									}
					}
				}
		);
	});
}


function setSqueezeBox() {
	SqueezeBox.initialize({
			sizeLoading: {x: 200, y: 150},
			overlayOpacity: 0.3
	});

	SqueezeBox.assign($$('a.image_lightbox]'));
	SqueezeBox.assign($$('a.ajax_lightbox'), {
			size: {x: 600, y: 450},
			handler: 'ajax',
			closeable: false
	});
	SqueezeBox.assign($$('a.iframe_lightbox'), {
			size: {x: 600, y: 450},
			handler: 'iframe'
	});
}

function setXHR(requests) {
	var requests = (requests) ? [requests] : $$('*[xhr_type]');
	requests.each(function(el,i) {

		// get the values from the custom attributes
		var xhr_type = el.getProperty('xhr_type');	// get the type of request (update, delete, insert)
		var trigger = $chk(el.getProperty('trigger')) ? $(el.getProperty('trigger')) : null;
		var success_element = $(el.getProperty('success_element'));
		var fail_element = $(el.getProperty('fail_element'));

		// Do this if the element is a FORM
		if(el.get('tag') == 'form') {
			var url = el.getProperty('action');				// the url from the form
		} else {
		// Do this if the element is anything else
			var hlink = el.getProperty('href').split('&');	// split the url up
			var url = hlink.shift();						// get the host information
			var query = hlink.join('&');					// whats left over is the query string
			trigger = el;									// set the trigger
		}

		trigger.set({
					'events': {
						'click' : function(e){
								htmlRequest(url,success_element,fail_element,query,0,xhr_type,el);
								e.stop();
						}
					}
		});
	}); // end requests.each
}

function htmlRequest(url,success_element,fail_element,query,preload,xhr_type,formElement) {
	if(!url) url = 'http://localhost/ajax';			// default request location
	if(!query) query = formElement.toQueryString();	// get the formElement attributes

	var htmlResponse = new Request.HTML({
							'method' : 'post',
							'url' : url,
							'async' : false
							});
	htmlResponse.addEvents({
					'onRequest' : function() {

					},
					'onSuccess' : function(responseTree,responseElements,responseHTML,responseJS) {
							// $(fail_element).set('html',responseHTML.substr(6)).set('styles',{'display' : 'block'}).highlight('#ff0000');
							// return;
						// }
						// on update replace the element with a new copy
						if(xhr_type == 'update') {
							var updateElement = new Element('div',{'html' : responseHTML}).getChildren()[0].replaces($(success_element)); // replace the content with the new content received
							updateElement.getChildren()[0].highlight();
							if(updateElement.getProperty('xhr_type')) setXHR(updateElement);	// reset the ajax abilities for this element
						} else if(xhr_type == 'insert') {
							var updateElement = new Element('div',{'html' : responseHTML}).getChildren()[0].inject($(success_element)); // replace the content with the new content received
							updateElement.getChildren()[0].highlight();
							if(updateElement.getProperty('xhr_type')) setXHR(updateElement);	// reset the ajax abilities for this element
						} else if(xhr_type == 'delete') {
							$(success_element).fade().get('tween').chain(function() { this.element.destroy(); });	// destroy the element
						}
					},
					'onFailure' : function(t,x) {
						$('fail_element').setProperties({
								'html':'Communications failed.',
								'styles' : {
										'display' : 'block'
										}
								});
					}
				});
	htmlResponse.send(query);
}

var cbCheck;

var ZebraTable = new Class({
		//implements
		Implements: [Options,Events],

		//options
		options: {
			elements: 'table.list-table',
			cssEven: 'even',
			cssOdd: 'odd',
			cssHighlight: 'highlight',
			cssMouseEnter: 'mo'
		},

		//initialization
		initialize: function(options) {
			//set options
			this.setOptions(options);
			//zebra-ize!
			$$(this.options.elements).each(function(table) {
				this.zebraize(table);
			},this);
		},

		//a method that does whatever you want
		zebraize: function(table) {
			//for every row in this table...
			table.getElements('tr').each(function(tr,i) {
				//check to see if the row has th's
				//if so, leave it alone
				//if not, move on
				if(tr.getFirst().get('tag') != 'th') {
					//set the class for this based on odd/even
					var options = this.options, klass = i % 2 ? options.cssEven : options.cssOdd;
					// kenCode - don't change the class if it is preset to highlight
					if(!tr.hasClass(options.cssHighlight)) tr.addClass(klass);
					//start the events!
					if(tr.getProperty('checkbox')) {
						$(tr.getProperty('checkbox')).addEvent('click',function(e) {
							cbCheck = true;
						});
					}
					tr.addEvents({
						//mouseenter
						mouseenter: function () {
							if(!tr.hasClass(options.cssHighlight)) tr.addClass(options.cssMouseEnter).removeClass(klass);
						},
						//mouseleave
						mouseleave: function () {
							if(!tr.hasClass(options.cssHighlight)) tr.removeClass(options.cssMouseEnter).addClass(klass);
						},
						//click
						click: function() {
							//if it is currently not highlighted
							if(!tr.hasClass(options.cssHighlight)) {
								tr.removeClass(options.cssMouseEnter).addClass(options.cssHighlight);
							} else {
								tr.addClass(options.cssMouseEnter).removeClass(options.cssHighlight);
							}
							if(tr.getProperty('checkbox')) {
								if(!cbCheck) $(tr.getProperty('checkbox')).checked = !$(tr.getProperty('checkbox')).checked;
								cbCheck = false;
							}
						}
					});
				}
			},this);
		}
	});