var Site = {
	enlargeCookie: null,
	fontSize: 0,
	subClassifications: {},
	subLocations: {},

	styleSheets: Array("text-decrease","text-standard","text-increase"),
	styleSheetIndex: 1,
	styleSheetCookie: null,
	cookieDomain: 'www.endeavour.com.au',
	currentMenu: null,
	toggleMenu: null,
	topMenu: null,
	currentShowEvent: null,
	currentHideEvent: null,
	menuActive: false,
	menuDelayTime: 500,

	firstFail: null,

	start: function() {
		MooTools.lang.setLanguage("en-US");

		// IE7 Menu Floating Fix
		if ( navigator.appVersion.indexOf("MSIE 7.") != -1 ) {
			var nav_list = $$('#navigation .container-12')[0].getChildren('ul.grid-12');
			var top_levels = nav_list.getChildren('li')[0];

			$each(top_levels, function(top_item, top_idx) {
				var child_list = top_item.getChildren('ul');

				// If there's a child list, get its children...
				if ( child_list.length ) {
					var child_items = child_list.getChildren('li')[0];

					var min_height = 0;
					// Loop through the children and work out the min-height of each line
					$each(child_items, function(child_item, child_idx) {
						// If this is the start of a new row, or we're at the last element of the list
						// ie - we have 10 items, we need to apply the min-height to the last two
						if ( (child_idx % 4 == 0) || (child_idx == (child_items.length - 1)) ) {
							// If this is the first element, just reset our min-height
							if ( child_idx == 0 ) {
								min_height = 0;
							} else {
								// Work out the limit we need to go back and set a height for
								if ( (child_idx % 4 == 0) ) {
									var back = 4;
									var limit = child_idx;
								} else {
									var back = child_idx % 4;
									var limit = child_idx + 1;
								}

								// Apply the minheight to the previous / partial previous row
								for ( x = child_idx - back; x < limit; x++ ) {
									child_items[x].setStyle('minHeight', min_height+'px');
								}

								min_height = 0;
							}
						}

						// Only adjust our minheight UP
						if ( child_item.getSize().y > min_height ) {
							min_height = child_item.getSize().y;
						}
					});
				}
			});
		}

		Site.styleSheetCookie = Cookie.read("styleSheet");
		Site.styleSheetIndex = Site.styleSheetCookie ? Site.styleSheetCookie : Site.getPreferredStyleSheet();

		Site.setActiveStyleSheet(0);

		$(document.body).addClass('javascript-enabled');

		// Launch-in-new-window links automagically created
		Site.attachExternalLinks();


		// Safari Suckerfish 'fix'
		if ( navigator.appVersion.toLowerCase().indexOf('safari') != -1 ) {
			Site.applySafariFix();
		}


		// IE6 Suckerfish fix
		if ( navigator.appVersion.toLowerCase().indexOf('msie 6') != -1 ) {
			Site.applySuckerfishFix();
		}


		// Form validation automagic
		Site.attachFormValidators();


		// Form overtext magic
		Site.attachOverTexts();


		// Submission link automagic
		Site.attachSubmitLinks();


		// Jobs search widget
		if ( $('filter_classification') && $('filter_subclassification') ) {
			Site.attachClassificationEvents();
		}
		if ( $('filter_location') && $('filter_sublocation') ) {
			Site.attachLocationEvents();
		}

		/*
		if ($('navigation')) {
			var elements = $$('#navigation ul');
			var ul = elements[0];
			if (ul) {
				ul.addEvent('mouseenter', function(event) { this.setStyle('background-position', '50% bottom'); });
				ul.addEvent('mouseleave', function(event) { this.setStyle('background-position', '50% top'); });
			}
		}
		*/

		if ($('member-dropdown')) Site.attachMemberDropDown();

		if ($('home')) {
			var tabs = new Tabs( $$('.tabs li'), $$('.tabs-content-container .content'), {} );
		}

		if ($('text-increase') && $('text-decrease')) Site.addStyleEventListeners();
		if ($('print')) $('print').getElement('a').addEvent('click',function(e) { e.stop(); window.print(); });
		if ($('history')) Site.setupHistory();

		if ($('make-a-donation')) {
			Site.setupSidebarDonationForm();
		}


		Site.attachMenuListeners();


		if ( $('country-updater') ) {
			$('country-updater').addEvent('change', function() {
				if ( this.options[this.selectedIndex].value == 'Australia' ) {
					$('customer-state-other').setStyle('display', 'none');
					$('state-updater').setStyle('display', '');
				} else {
					$('customer-state-other').setStyle('display', '');
					$('state-updater').setStyle('display', 'none');
				}
			});
		}

		if ( $('donation_amount_other') ) {
			$('donation_amount_other').addEvent('blur', function(){
				if (this.getProperty('value') < 5) {
					$('minimum-amount-message').show();
				} else {
					$('minimum-amount-message').hide();
				}
			});
			$('donation_amount_other').fireEvent('blur');
		}

		//window.fx = new SmoothScroll({	duration: 1000 }, window);
	},


	attachMenuListeners: function() {
		$('navigation').addClass('delay-active');
		var top_level_menu = $('navigation').getElement('ul.grid-12');
		Site.topMenu = top_level_menu;
		var top_level_lis = top_level_menu.getChildren();

		top_level_lis.each(function(item, idx) {
			item.addEvent('mouseenter', function() {
				Site.menuActive = true;
				if (idx != 0 && idx != top_level_lis.length - 1) {
					var showBackground = true;
				}


				if ( Site.currentMenu == null ) {
					Site.menuShow(item, showBackground);
				} else if ( Site.currentMenu == item ) {
					if ( Site.currentShowEvent ) {
						window.clearTimeout(Site.currentShowEvent);
					}
					if ( Site.currentHideEvent ) {
						window.clearTimeout(Site.currentHideEvent);
					}
				} else {
					Site.currentShowEvent = window.setTimeout(function() { Site.menuShow(item, showBackground); }, Site.menuDelayTime);
				}

			});

			item.addEvent('mouseleave', function() {
				Site.menuActive = false;
				if ( Site.currentShowEvent ) {
					window.clearTimeout(Site.currentShowEvent);
				}

				if ( Site.currentMenu == item ) {
					Site.currentHideEvent = window.setTimeout(function() { Site.menuHide(item); }, Site.menuDelayTime);
				}
			});
		});
	},


	menuShow: function(item, showBackground) {

		if (showBackground) {
			Site.topMenu.setStyle('background-position', '50% bottom');
		}

		if ( Site.menuActive ) {
			item.addClass('force-show');


			if ( Site.currentMenu != null ) {
				Site.menuHide(Site.currentMenu, true);
			}

			Site.currentMenu = item;
		}
	},


	menuHide: function(item, force) {
		Site.topMenu.setStyle('background-position', '50% top');
		if ( Site.currentMenu == item || force ) {
			item.removeClass('force-show');
			Site.currentMenu = null;
		}

		if ( !Site.menuActive ) {
			Site.currentMenu = null;
		}
	},


	setupHistory: function() {

		var uri = new URI();
		var fragment = uri.get('fragment');

		var ids = /* of type String */ ['2010s','2000s','1990s','1980s', '1970s', '1960s', '1950s'];
		var timelines = $$('#history .timeline');
		var anchors = $$('#history .anchor a');

		var slider = $('history-slider');

		var historySlider = new Slider(slider, slider.getElement('.knob'), {
			steps: 6,	// There are 7 decades
			snap: true,
			wheel: true,
			onChange: function(value){
				timelines.each(function(element,i) {
					if (value != i) {
						element.setStyles({'position' : 'absolute', 'left' : '-9999px'});
					} else {
						element.setStyles({'position' : 'relative', 'left' : '0'});
					}
				});
			}
		});

		/* fallback */
		anchors.each(function(element,i) {
			element.addEvent('click', function(event) {
				if (event.stop()) event.stop();
				historySlider.set(i);
			});
		});

		ids.each(function(value,i) {
			if (value == fragment || i == 0 && !fragment) {
				historySlider.set(i);
				timelines[i].setStyles({'position':'relative', 'left' : '0'});
			} else {
				timelines[i].setStyles({'position':'absolute', 'left' : '-9999px'});
			}
		});

	},

	addStyleEventListeners : function() {

		$('text-increase').addEvent('click', function(e) {
			e.stop();
			Site.setActiveStyleSheet(1);
		});
		$('text-decrease').addEvent('click', function(e) {
			e.stop();
			Site.setActiveStyleSheet(-1);
		});

	},


	attachClassificationEvents: function() {
		var elem = $('filter_classification');

		elem.addEvent('change', function() {
			Site.updateSubclassificationList(this.selectedIndex);
		});
	},


	updateSubclassificationList: function(idx) {
		var sub_elem = $('filter_subclassification');

		if ( idx == 0 ) {
			sub_elem.empty();
			sub_elem.adopt(new Element('option', {	'value':	'',		'text':	'-- Select Classification --'}));
		} else {
			sub_elem.empty();
			sub_elem.adopt(new Element('option', {	'value':	'',		'text':	'-- Select Sub-Classification --'}));

			// Loop through the subclassifications if they exist, or display the fallback subslection option
			if ( Site.subClassifications[idx] ) {
				$each(Site.subClassifications[idx], (function(val, idx) {
					sub_elem.adopt(new Element('option', {	'value':	val,	'text':	val}));
				}));
			} else {
				sub_elem.adopt(new Element('option', {		'value':	'',		'text':	'-- No Sub-Classifications --'}));
			}
		}
	},


	attachLocationEvents: function() {
		var elem = $('filter_location');

		elem.addEvent('change', function() {
			Site.updateSublocationList(this.selectedIndex);
		});
	},


	updateSublocationList: function(idx) {
		var sub_elem = $('filter_sublocation');

		if ( idx == 0 ) {
			sub_elem.empty();
			sub_elem.adopt(new Element('option', {	'value':	'',		'text':	'-- Select Location --'}));
		} else {
			sub_elem.empty();
			sub_elem.adopt(new Element('option', {		'value':	'',		'text':	'-- Select Sub-Location --'}));

			// Loop through the sublocations if they exist, or display the fallback subslection option
			if ( Site.subLocations[idx] ) {
				$each(Site.subLocations[idx], (function(val, idx) {
					sub_elem.adopt(new Element('option', {	'value':	val,	'text':	val}));
				}));
			} else {
				sub_elem.adopt(new Element('option', {		'value':	'',		'text':	'-- No Sub-Locations --'}));
			}
		}
	},


	formHandler: function(pass, form, submitEvent) {
		// Do anything necessary here
	},


	/**
	 *	Suckerfish fix for IE6
	 *
	 */
	applySuckerfishFix: function() {
		var sfElems = $$('#navigation li.suckerfish_level1');

		// Fix the top level elements first
		sfElems.each(function(elem, idx) {
			elem.addEvent('mouseover', function() {
				this.addClass('sfhover');
			})
			elem.addEvent('mouseout', function() {
				this.removeClass('sfhover');
			})
		});

		var sfLists = $$('#navigation ul.suckerfish_level1');

		// Now fix top elements staying active when in a child list
		sfLists.each(function(elem, idx) {
			elem.addEvent('mouseenter', function() {
				this.getParent().addClass('childhover');
			})
			elem.addEvent('mouseleave', function() {
				this.getParent().removeClass('childhover');
			})
		});
	},


	/**
	 *	Safari hover-tooltip-fix for suckerfish menus
	 *
	 */
	applySafariFix: function() {
		var navElems = $$('#navigation li a');
		navElems.each(function(elem, idx) {
			elem.set('title', '');
		});
	},


	/**
	 *	Pre-emptive text for input fields
	 *
	 */
	attachOverTexts: function() {
		// We want to clear alt texts from values if the form is submitted
		var forms = $$('form');
		forms.each(function(elem, idx) {
			elem.addEvent('submit', function() {
				if ( elem.getProperty('valPassed') == true ) {
					formElems = elem.getElements('input, textarea');

					formElems.each(function(input, idx) {
						if ( input.getProperty('alt') == input.value ) {
							input.value = '';
						}
					});
				}
			});
		});


		var overElems = $$('input.overtext, textarea.overtext');
		if ( overElems.length ) {
			overElems.each(function(elem, idx) {

				if ( elem.getProperty('type') ) {
					elem.setProperty('overType', elem.getProperty('type'));
				}

				if ( elem.getProperty('alt') ) {
					// Focus state
					elem.addEvent('focus', function() {
						if ( this.value == this.getProperty('alt')) {
							if ( this.getProperty('overType') == 'password' ) {
								elem = Site.cloneAndChangeInputType(elem, 'password', true);
							} else {
								this.value = '';
							}

							this.removeClass('overtext');
						}
					});

					// Blur state
					elem.addEvent('blur', function() {
						if ( this.value == '') {
							if ( this.getProperty('overType') == 'password' ) {
								elem = Site.cloneAndChangeInputType(elem, 'text');
								elem.value = elem.getProperty('alt');
							} else {
								this.value = this.getProperty('alt');
							}

							this.addClass('overtext');
						}
					});

					// Default state
					if ( elem.value == '') {
						if ( elem.getProperty('overType') == 'password' ) {
							elem = Site.cloneAndChangeInputType(elem, 'text');
						}

						elem.value = elem.getProperty('alt');
					} else {
						if ( elem.value != elem.getProperty('alt') ) {
							elem.removeClass('overtext');
						}
					}
				}
			});
		}
	},


	/**
	 *	Submit forms from links functionality
	 *
	 */
	attachSubmitLinks: function() {
		// Submit link magic
		var submitLinks = $$('.submit-link');
		if ( submitLinks.length ) {
			submitLinks.each(function(elem, idx) {
				var props = elem.getProperty('class').split(' ');

				if ( props.length ) {
					props.each(function(propItem, pidx) {
						if ( propItem.indexOf(':') != -1 ) {
							var parsedProps = JSON.decode('{'+propItem+'}');
							elem.setProperties(parsedProps);
						}
					});
				}

				if ( elem.getProperty('submitTarget') ) {
					elem.addEvent('click', function(event) {
						if ( $(this.getProperty('submitTarget')).validate() ) {
							$(this.getProperty('submitTarget')).submit();
						}
					});

					// Inject a dummy submit button for form functionality to be maintained
					// I like hitting enter to submit
					elem.getParent().adopt(new Element('input', {	'type': 'submit',			'name': 'dummy-submit',
																	'class': 'dummy-submit'
																}));
				}
			});
		}
	},


	/**
	 *	Form validation automagic
	 *
	 */
	attachFormValidators: function() {
		var valForms = $$('form.validate-form');
		if ( valForms.length ) {
			valForms.each(function(elem, idx) {
				new FormValidator.Inline(elem, {
					'errorPrefix': '',
					'useTitles': true,
					'serial': false,
					'scrollToErrorsOnSubmit': false,
					'onFormValidate': function(passed, form, e) {
						elem.setProperty('valPassed', passed);

						if ( passed ) {
							elem.submit = null;
						} else {
							if ( $('error-msg-group').get('text') ) {
								var tmp = $('error-msg-group').get('text').split('.');
								alert(tmp[0]);
								$('error-msg-group').set('html', '');
								Site.firstFail.focus();
								Site.firstFail = null;
							}
						}
					},
					'onElementFail': function(e, val_msgs) {
						if ( Site.firstFail == null ) {
							Site.firstFail = e;
						}
					}
				});
			});
		}

		var valForms = $$('form.validate-form-custom');
		if ( valForms.length ) {
			valForms.each(function(elem, idx) {
				elem.setProperty('valPassed', false);

				new FormValidator(elem, {
					'errorPrefix': '',
					'useTitles': true,
					'serial': false,
					'scrollToErrorsOnSubmit': false,
					'onFormValidate': function(passed, form, e) {
						elem.setProperty('valPassed', passed);

						if ( passed ) {
							elem.submit = null;
						}
					}
				});
			});
		}
	},


	/**
	 *	External links in new window functionality
	 *
	 */
	attachExternalLinks: function() {
		var extLinks = $$('a.external');
		if ( extLinks.length ) {
			extLinks.each(function(elem, idx) {
				elem.setProperty('target', '_blank');
			});
		}
	},

	getActiveStyleSheet: function() { return Site.styleSheetIndex; },

	getPreferredStyleSheet: function() { return 1; },

	getCookie: function(name) { return Cookie.read(name); },

	setActiveStyleSheet: function(index) {

		Site.styleSheetIndex = parseInt(Site.styleSheetIndex) + index;
		if(Site.styleSheetIndex < 0){
			Site.styleSheetIndex = 0;
		} else if(Site.styleSheetIndex >= Site.styleSheets.length) {
			Site.styleSheetIndex = Site.styleSheets.length - 1;
		}

		Site.setCookie("styleSheet", Site.styleSheetIndex, 1);

		var title = Site.styleSheets[Site.styleSheetIndex];

		var i, a, main;
		for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
			if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && a.getAttribute("title").indexOf("text") > -1) {
				a.disabled = true;
				if(a.getAttribute("title") == title) a.disabled = false;
			}
		}

		if (Cufon)
			Cufon.refresh();

		return null;

	},

	setCookie: function(name,value,days) {
		Cookie.write(name, value, {domain : Site.cookieDomain, duration: days ? days : 0});
	},

	attachMemberDropDown: function() {
		var activeClass = 'dropdown-active';
		var parent = $('member-dropdown-toggle').getParent();

		parent.fx = new Fx.Tween(parent, {
			onComplete: function() {
				if (!parent.hasClass(activeClass)) {
					parent.setStyle('z-index', '0');
				}
			}
		});

		$('member-dropdown-toggle').addEvents({
			'click' : function(event){
				if(event) event.stopPropagation();
				if(event) event.preventDefault();
				show();
			}
/*			,
			'focus' : function(event) {
				if(event) event.stopPropagation();
				if(event) event.preventDefault();
				show();
			}
*/
		});

		$('member-dropdown-close').addEvents({
			'click' : function(event){
				if(event) event.stopPropagation();
				if(event) event.preventDefault();
				hide();
			}
/*			,
			'focus' : function(event) {
				if(event) event.stopPropagation();
				if(event) event.preventDefault();
				show();
			}
*/
		});

		var show = function() {
			if (!parent.hasClass(activeClass)) {
				parent.addClass(activeClass);
				parent.setStyle('z-index', '10000');
				parent.fx.start('top', 0);
			} else {
				hide();
			}
		}
		var hide = function() {
			if (parent.hasClass(activeClass)) {
				parent.removeClass(activeClass);
				parent.fx.start('top', -252);
			}
		}
	},

	setupSidebarDonationForm: function() {
		// Make the donation buttons write their value to the input box
		$$('#make-a-donation a.donate').each(function(elem){
			elem.addEvent('click', function(event){
				var classes = this.getProperty('class').split(' ');
				var amount = '';
				classes.each(function(classname){
					if (classname.contains('amount:')) {
						amount = classname.replace('amount:', '');
					}
				});
				$('donate-amount').setProperty('value', amount);
				return false;
			});
		});
	}
};




function ucfirst (str) {
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1);
}


function number_format(number, decimals, dec_point, thousands_sep) {
    var n = !isFinite(+number) ? 0 : +number,
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }    return s.join(dec);
}


// Do stuff on load
window.addEvent('load', Site.start);
