var Site = {
	enlargeCookie: null,
	cookieDomain: 'monashheart.org.au',		// TODO: Change before golive
	fontSize: 0,
	address_flag: 0,
	
	start: function(){
		MooTools.lang.setLanguage("en-US");

		// Launch-in-new-window links automagically created
		var extLinks = $$('a.external');
		if ( extLinks.length ) {
			extLinks.each(function(elem, idx) { 
				elem.setProperty('target', '_blank');
			});
		}
		
		
		// Safari Suckerfish 'fix'
		if ( navigator.appVersion.toLowerCase().indexOf('safari') != -1 ) {
			var navElems = $$('#navigation li a');
			navElems.each(function(elem, idx) {
				elem.set('title', '');
			});
		}
		
		
		// Form validation automagic
		var valForms = $$('form.validate-form');
		if ( valForms.length ) {
			valForms.each(function(elem, idx) { 
				new FormValidator.Inline(elem, {
					'onFormValidate': Site.formHandler,
					'errorPrefix': '',
					'useTitles': true
				});
			});
			if ($('form-error-message')) {
				$('form-error-message').fade('hide');
			}
		}
		
		
		
		
		// Donation Form
		
		var is_gift_group= new Fx.Reveal('donation_memory_of_group');
		var send_acknowledgement_group= new Fx.Reveal('donation_send_acknowledgement_group');
		
		var is_gift_group_validated_fields = $$('#donation_memory_of_group .required');
		var send_acknowledgement_group_validated_fields = $$('#donation_send_acknowledgement_group .required');
		
		var send_acknowledgement_group_restore_validation = function() {
			send_acknowledgement_group_validated_fields.each(function(field) {
				field.addClass('required');
			});
		}
		
		var send_acknowledgement_group_remove_validation = function() {
			send_acknowledgement_group_validated_fields.each(function(field) {
				field.removeClass('required');
			});
		}
		
		var is_gift_group_restore_validation = function() {
			is_gift_group_validated_fields.each(function(field) {
				field.addClass('required');
			});
		}
		
		var is_gift_group_remove_validation = function() {
			is_gift_group_validated_fields.each(function(field) {
				field.removeClass('required');
			});
		}
		
		//Other Purpose Actions
		
		if ($('direction_purpose') && $('other_purpose_container')) {
		
			var other_purpose_container = new Fx.Reveal('other_purpose_container');
			
			if ($('direction_other_purpose').get('value').length >= 1) {
				other_purpose_container.reveal();
				$$('#other_purpose_container input').addClass('required');
			} else {
				other_purpose_container.dissolve();
				$$('#other_purpose_container input').removeClass('required');
			}
			
			$('direction_purpose').addEvent('change',function(event){
				if ($('direction_purpose').get('value') == 'Other, please specify') {
					other_purpose_container.reveal();
					$$('#other_purpose_container input').addClass('required');
				} else {
					other_purpose_container.dissolve();
					$$('#other_purpose_container input').removeClass('required');
				}
			});
		}
		
		//Memory of groups
		
		if ($('donation_memory_of_group')) {
			if ($('is_gift').get('value') !='1') {$('donation_memory_of_group').hide()};
			if ($('send_acknowledgement').get('value') !='1') {$('donation_send_acknowledgement_group').hide()};
			is_gift_group_remove_validation();
			send_acknowledgement_group_remove_validation();
		}
		
		if ($('is_gift')) {
			$('is_gift').addEvent('change', function(event) {
				if ($('is_gift').get('value') == '1') {
					is_gift_group.reveal();
					is_gift_group_restore_validation();			
				} else {
					is_gift_group.dissolve();
					is_gift_group_remove_validation();			
				}
			});
		}
		
		if ($('send_acknowledgement')) {
			$('send_acknowledgement').addEvent('change', function(event) {
				if ($('send_acknowledgement').get('value') == '1') {
					send_acknowledgement_group.reveal();
					send_acknowledgement_group_restore_validation();
				} else {
					send_acknowledgement_group.dissolve();
					send_acknowledgement_group_remove_validation();
				}
			});
		}
		
		//Amount checkboxes
		
		var donate_amount_checkboxes = $$('.donation-amount input[type=checkbox]');
		var donate_amount_other = $('donate_amount_other');
		var donate_amount = $('amount');
		
		if (donate_amount_checkboxes && donate_amount_other && donate_amount) {
		
			donate_amount_checkboxes.addEvent('click', function(e) {
				if (this.checked) {
					donate_amount_checkboxes.set('checked',false);
					this.set('checked',true);
					if (this.get('rel') && this.get('rel') != null) donate_amount.value = this.get('rel');
				} else {
					return false;
				}
			});
			
			donate_amount_other.addEvent('click', function(e) {
				if (this.checked) {
					donate_amount.set('value','');
					donate_amount.focus();
				}
			});
			
			donate_amount.addEvent('focus', function(e) {
				donate_amount_checkboxes.set('checked',false);
				donate_amount_other.set('checked',true);
			});
		
		}
		
		//Fake radio checkboxes
		//If for some reason the client requests the same functionality elsewhere, just wrap your checkboxes in a container with a class of fake_radio, and add a rel attribute to the inputs you wish to be grouped togethor. 
		$$('.fake_radio input[type=checkbox]').each(function(checkbox){
			checkbox.addEvent('click',function(e){
				$$('.fake_radio input[type=checkbox][rel='+this.get('rel')+']').set('checked',false);
				this.set('checked', true);
			});
		});
		
		
		//Company and ABN fields
		
		var abn_setup = function() {
			
			if ($('company') && $('abn')) {
				if ($('company').value.length >=1) {
					$('abn_container').show();
					$('abn').addClass('required');
				} else {
					$('abn_container').hide();
					$('abn').removeClass('required');
				}
			}
						
		}
		
		abn_setup();
		
		if ($('company')) $('company').addEvent('keydown',function() {
			abn_setup();
		});		
		
		
		
		/*
		var donationLookup = ['0','10','20','50','100','250','500'];
		
		if ($('donation_slider')) {
			var donationSlider = new Slider('donation_slider', 'donation_slider_knob', {
				range: [0, 6],
				steps: 6,
				snap: true,
				onChange: function(value){
					$('amount').value = donationLookup[value];
				}
			});
		}
		*/
		if ($('ccv_details')) {
			$('ccv_details').hide();
		
			$('ccv_help').addEvent('click',function() {
				$('ccv_details').toggle();
				return false;
			});
		}
		
		if ($('print_page')) {
			$('print_page').addEvent('click',function(e){
				window.print();
			});
		}
		
		
		
		
		// iDirectory Stuff
		Site.iDirectorySubmission();		
		
		// Form overtext magic
		Site.attachOverTexts();
		
		
		// Submission link automagic
		Site.attachSubmitLinks();
		
		
		// Do google map stuff
		Site.attachPageActions();
		
		// Do centered popup for virtual tours
		Site.attachCenteredPopup();


		Site.enlargeCookie = new Hash.Cookie('enlargeCookie', {	'duration': 	60,
																'domain': 		Site.cookieDomain,
																'path': 		'/'
															});
		
															
		// Page sizing functions
		if ( Site.enlargeCookie.get('current_size') ) {
			Site.modifyText(Site.enlargeCookie.get('current_size'));
		} else {
			Site.modifyText(0);
		}
		
		if ( $('text_smaller_link') ) {
			$('text_smaller_link').addEvent('click', function(event) {
				Site.modifyText(-1);
			});
		}
		
		if ( $('text_bigger_link') ) {
			$('text_bigger_link').addEvent('click', function(event) {
				Site.modifyText(1);
			});
		}
		
		if ( $('printer_friendly_link') ) {
			$('printer_friendly_link').addEvent('click', function(event) {
				window.print();
			});
		}
	},

	modifyText: function(modifier) {
		document.body.className = document.body.className.replace(/textsize\-\d/gi, '');
		var cur_size = Site.fontSize;
		
		// Now increase or decrease size based on modifier
		cur_size += modifier;
		
		// Boundary conditions
		if ( cur_size < 0 ) {
			cur_size = 0;
		}
		
		if ( cur_size > 5 ) {
			cur_size = 5;
		}

		// Add the appropriate class to the body
		document.body.className += ' textsize-' + cur_size;
		
		Site.enlargeCookie.set('current_size', cur_size);
		Site.fontSize = cur_size;
	},
	
	
	formHandler: function(pass, form, submitEvent) {
		if ($('form-error-message')) {
			if (pass) {
				$('form-error-message').fade('out');
			} else {
				$('form-error-message').fade('in');
			}
		}
		
		// Do anything necessary here
	},
	
	
	attachOverTexts: function() {
		var overElems = $$('input.overtext');
		if ( overElems.length ) {
			overElems.each(function(elem, idx) {
				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 = '';
							}
						}
					});
					
					// 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');
							}
						}
					});
					
					// Default state
					if ( elem.value == '') {
						if ( elem.getProperty('overType') == 'password' ) {
							elem = Site.cloneAndChangeInputType(elem, 'text');
						}
						
						elem.value = elem.getProperty('alt');
					}
				}
			});
		}
	},
	
	
	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();
						}
					});
				}
			});
		}
	},
	
	attachCenteredPopup: function() {
		var popupLinks = $$('a.centered-popup');
		var title = 'mypop1';
		var w = 680;
		var h = 600;
		var left = (screen.width/2)-(w/2);
		var top = (screen.height/2)-(h/2);
	
		if ( popupLinks.length ) {
			popupLinks.each(function(elem, idx) {
				elem.addEvent('click', function(event) {
					var pageURL = elem.get('href');
					var targetWin = window.open (pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
					return false;
				});			
			});
		}
	},
	
	iDirectorySubmission: function() {
		
		$$('.group_container').each(function(group_container) {
			var i = 0;
			group_container.getElements('.group_item').each(function(group_item) {
				if (i != 0) {
					group_item.hide();
					group_item.addClass('hidden');
				}
				i++;
			});
			
			var groupContainerClass = group_container.get('class');
			groupContainerClass = groupContainerClass.replace('group_container ','');
			
			var duplicatorButton  = new Element('button', {
				'html': 'Add Another',
				'class':'duplicator_button'
			});
			duplicatorButton.inject(group_container);
			
			duplicatorButton.addEvent('click',function(el) {
				el.stop();
				
				var nextGroupItem = Site.getNextHiddenFieldset(group_container);
				
				if (nextGroupItem) {
					nextGroupItem.reveal();
					nextGroupItem.removeClass('hidden');
				}
				
				if (!Site.getNextHiddenFieldset(group_container)) duplicatorButton.hide();
				
				return false;
			});
		});
	},
	
	getNextHiddenFieldset: function(parent) {
		return parent.getElement('fieldset.group_item.hidden');
	}, 
	
	attachPageActions: function () {
			// google addresses
		if ( $$('.address_details')[0] && $$('.address_more_info')[0] ) {
			var address_slides = new Object();
			for (var i=0; i < $$('.address_details').length; i++ ) {
				
				address_slides[i] = new Fx.Slide($$('.address_details')[i],
					{ 
						duration: 400
					}
				);
				address_slides[i].hide();
			}
			for (var i=0; i < $$('.address_more_info').length; i++ ) {			
				$$('.address_more_info')[i].addEvent('click', function(e) {
					for (var j=0; j < $$('.address_more_info').length; j++ ) {
						if (this == $$('.address_more_info')[j] && $$('.address_details')[j]) {
							address_slides[j].toggle();
						}
					}
					return false;
					
				});
			}
			
			
		}
		
		// Contacts Map
		if ( $('hospital_addresses_title') 
			&& $('chs_addresses_title') 
			&& $('community_rehabilitation_addresses_title') 
			&& $('aged_care_addresses_title') 
			&& $('hospital_addresses') 
			&& $('chs_addresses') 
			&& $('community_rehabilitation_addresses') 
			&& $('aged_care_addresses') 
			&& $('map'))
		{
			$('hospital_addresses_title').addEvent('click', function(e) {
				var open_section = false;
								
				if ($('hospital_addresses').style.display == 'none') {
					open_section = true;
				} else  {
					open_section = false;
				}
				  Site.closeContactElements(); 
				  
				if (open_section) {
					$('hospital_addresses').style.display = 'block';
					$('hospital_addresses_title').addClass('toggler_active');
				}
				Site.updateGMapNodes();
				return false;
			});
			$('chs_addresses_title').addEvent('click', function(e) {
				var open_section = false;
				
				if ($('chs_addresses').style.display == 'none') {
					open_section = true;
				} else  {
					open_section = false;
				}
				
				Site.closeContactElements();
				
				if (open_section) {
					$('chs_addresses').style.display = 'block';
					$('chs_addresses_title').addClass('toggler_active');
				}
				Site.updateGMapNodes();
				return false;
			});
			$('community_rehabilitation_addresses_title').addEvent('click', function(e) {
				var open_section = false;
				
				if ($('community_rehabilitation_addresses').style.display == 'none') {
					open_section = true;
				} else  {
					open_section = false;
				}
				
				Site.closeContactElements();
				
				if (open_section) {
					$('community_rehabilitation_addresses').style.display = 'block';
					$('community_rehabilitation_addresses_title').addClass('toggler_active');
				}
				Site.updateGMapNodes();
				return false;
			});
			$('aged_care_addresses_title').addEvent('click', function(e) {
				var open_section = false;
				
				if ($('aged_care_addresses').style.display == 'none') {
					open_section = true;
				} else  {
					open_section = false;
				}
				
				Site.closeContactElements();
				
				if (open_section) {
					$('aged_care_addresses').style.display = 'block';
					$('aged_care_addresses_title').addClass('toggler_active');
				}
				Site.updateGMapNodes();
				return false;
			});
			$('hospital_addresses_title').addEvent('mouseenter', function(e) {
				this.style.cursor = 'pointer';
			});
			$('chs_addresses_title').addEvent('mouseenter', function(e) {
				this.style.cursor = 'pointer';
			});
			$('community_rehabilitation_addresses_title').addEvent('mouseenter', function(e) {
				this.style.cursor = 'pointer';
			});
			$('aged_care_addresses_title').addEvent('mouseenter', function(e) {
				this.style.cursor = 'pointer';
			});
			
			Site.closeContactElements();
			
			GEvent.addDomListener($('map'), "DOMMouseScroll", wheelevent);
			$('map').onmousewheel = wheelevent; 
			Site.updateGMapNodes();
		}
		
		// google map scroller
		if ( $('map') && Site.address_flag ) {
			GEvent.addDomListener($('map'), "DOMMouseScroll", wheelevent);
			$('map').onmousewheel = wheelevent; 
			loadGMap();
		}
		
		// accordion listing
		if ( $('accordion') ) {
			
			//create our Accordion instance
			var myAccordion = new Accordion($('accordion'), 'h4.toggler', 'div.element', {
				alwaysHide: true,
				display: -1,
				opacity: false,

				onActive: function(toggler, element){
					toggler.addClass('toggler_active');
					element.addClass('element_active');
				},
				onBackground: function(toggler, element){
					toggler.removeClass('toggler_active');
					element.removeClass('element_active');
				}
			});
			
			// Change the cursor to a hand-pointer
			$$('h4.toggler').each(function(elem, idx) {
				elem.addEvent('mouseenter', function() {
					this.style.cursor = 'pointer';
				});
			});
		}
		
	},
	
	
	closeContactElements: function () {
		$('hospital_addresses').style.display = 'none';
		$('hospital_addresses_title').removeClass('toggler_active');
		$('chs_addresses').style.display = 'none';
		$('chs_addresses_title').removeClass('toggler_active');
		$('community_rehabilitation_addresses').style.display = 'none';
		$('community_rehabilitation_addresses_title').removeClass('toggler_active');
		$('aged_care_addresses').style.display = 'none';
		$('aged_care_addresses_title').removeClass('toggler_active');
	},
	
	rotateNextElement: function(parentId, elementPosition) {
		var nextPosition = 0;
		if ( $(parentId) && $(parentId).children[elementPosition] ) {
			$(parentId).children[elementPosition].get('tween').options.duration=1000;
			$(parentId).children[elementPosition].fade('out');
			
			if ($(parentId).children[elementPosition + 1]) {
				nextPosition = elementPosition + 1;
			}
			
			$(parentId).children[nextPosition].style.position = 'absolute';
			$(parentId).children[nextPosition].get('tween').options.duration=1000;
			$(parentId).children[nextPosition].fade('in');
			
			setTimeout("Site.rotateNextElement('" + parentId + "', " + nextPosition + ")", 4500);
		}
		
	},
	
	updateGMapNodes: function() {
		Site.address_flag = 0;
		if ( $('hospital_addresses') && $('chs_addresses') ) {
			for ( var i=0; i < index; i++ ){
				if ( i <= 4 ) {
					if ( $('hospital_addresses').style.display == 'none') {
						places[i].status = 'Failed';
					} else {
						places[i].status = 'Success';
						Site.address_flag = 1;
					}
				} else if ( i >= 14 && i <= 17 ) {
					if ( $('community_rehabilitation_addresses').style.display == 'none') {
						places[i].status = 'Failed';
					} else {
						places[i].status = 'Success';
						Site.address_flag = 1;
					}
				} else if ( i >= 18 && i <= 22 ) {
					if ( $('aged_care_addresses').style.display == 'none') {
						places[i].status = 'Failed';
					} else {
						places[i].status = 'Success';
						Site.address_flag = 1;
					}
				} else {
					if ( $('chs_addresses').style.display == 'none') {
						places[i].status = 'Failed';
					} else {
						places[i].status = 'Success';
						Site.address_flag = 1;
					}
				}
			}
		}
		
		if ( Site.address_flag ) {
			places[index-1].status = 'Failed';
		} else {
			places[index-1].status = 'Success';
		}
		
		loadGMap();
	}	
};


// Do stuff on load
window.addEvent('load', Site.start);
