var Site = {
	enlargeCookie: null,
	fontSize: 0,
	subClassifications: {},
	subLocations: {},

	styleSheets: Array("text-decrease","text-standard","text-increase"),
	styleSheetIndex: 1,
	styleSheetCookie: null,
	cookieDomain: 'careflight.localhost',

	start: function() {
		MooTools.lang.setLanguage("en-US");

		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();


		// Shop AJAX calls
		Site.attachShopAJAX();


		// Attache page actions
		Site.attachPageActions();


		// Submission link automagic
		Site.attachSubmitLinks();

		Site.attachAccordions();

		if ($('mooCalendar2')) {
			Site.addCalendar();
		}

	},


	formHandler: function(pass, form, submitEvent) {
		// Do anything necessary here
	},


	/**
	 *	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, {
					'onFormValidate': Site.formHandler,
					'errorPrefix': '',
					'useTitles': true
				});
			});
		}

		var valForms = $$('form.validate-form-custom');
		if ( valForms.length ) {
			valForms.each(function(elem, idx) {
				elem.setProperty('valPassed', false);

				new FormValidator(elem, {
					'onFormValidate': Site.formHandler,
					'errorPrefix': '',
					'useTitles': true,
					'onFormValidate': function(passed, form, e) {
						elem.setProperty('valPassed', passed);
					}
				});
			});
		}
	},


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

		Cufon.refresh();

		return null;

	},

	setCookie: function(name,value,days) {
		Cookie.write(name, value, {domain : Site.cookieDomain, duration: days ? days : 0});
	},

	addCalendar: function () {
		var calendar = new mooCalendar2.Event($('calendarInner'), 	{
																'calType': 'calTypeInline',
																'dayLength': 'dayLengthShort',

																'onCreate': function() {
																	Cufon.refresh();
																	// Show calendar holder on load to allow non-js fallback
																	$('calendar-holder-full').show();
																},
																'onRender': function() { Cufon.refresh(); },

																//'onDayClick': function(cell, date) { alert(date.format('%Y-%m-%d')); },
																//'onFilterChange': function (filter) { alert('Filter Changed - ' + filter); },
																//'onViewChange': function (view) { alert('View Changed - ' + view); },
																//'onWeekChange': function (week) { alert('Week Changed - ' + week); },


																'eventFrame': $('event-holder'),
																'viewFrame': $('calViewHolder'),
																'filterFrame': $('calFilterOptionHolder'),
																'weekFrame': $('calWeekHolder'),

																'initialView': 'month',
																'linkTooltipTitle': true,

																'requestUrl': './&rtemplate=3126'/*,

																'filterOptions': {
																		'fr': 'Fundraising / Charity Events',
																		'co': 'Conferences / Announcements',
																		'ot': 'Other'
																		}	*/
															});
	},

	attachPageActions: function() {

		if ( $('shop') || $('donation-form') ) {
			Site.attachShopDescriptionHovers();
		}

		if ( $('text-decrease') ) {
			$('text-decrease').addEvent('click', function(e) {
				e.stop();
				Site.resizeText(-1);
			});
		}

		if ( $('text-increase') ) {
			$('text-increase').addEvent('click', function(e) {
				e.stop();
				Site.resizeText(1);
			});
		}

		if ( $('search') && $('query') ) {
			$('query').addEvent('focus', function(event) {
				$('search').addClass('search-focus');
			});

			$('query').addEvent('blur', function(event) {
				if ( $('query').value == '' ) {
					$('search').removeClass('search-focus');
				}
			});
		}

		if ( $('btn-print') ) {
			$('btn-print').addEvent('click', function(e) {
				e.stop();
				window.print();
			});
		}


		if ( $('recipient_me') ) {
			$('recipient_me').addEvent('click', function(event) {

				if ( $('recipient_info') ) {
					$('recipient_info').style.display = '';
				}

				if ( $('charity_info') ) {
					$('charity_info').style.display = 'none';
				}

				if ( $('card-message') ) {
					$('card-message').style.display = 'none';
				}

				if ( $('sender_info') ) {
					$('sender_info').style.display = 'none';
				}
			});
		}

		if ( $('recipient_gift') ) {
			$('recipient_gift').addEvent('click', function(event) {

				if ( $('recipient_info') ) {
					$('recipient_info').style.display = '';
				}

				if ( $('charity_info') ) {
					$('charity_info').style.display = 'none';
				}

				if ( $('card-message') ) {
					$('card-message').style.display = '';
				}

				if ( $('sender_info') ) {
					$('sender_info').style.display = '';
				}
			});
		}

		if ( $('recipient_charity') ) {
			$('recipient_charity').addEvent('click', function(event) {

				if ( $('recipient_info') ) {
					$('recipient_info').style.display = 'none';
				}

				if ( $('charity_info') ) {
					$('charity_info').style.display = '';
				}

				if ( $('card-message') ) {
					$('card-message').style.display = 'none';
				}

				if ( $('sender_info') ) {
					$('sender_info').style.display = '';
				}
			});
		}

		if ( $('empty-cart') ) {
			$('empty-cart').addEvent('click', function(event) {
				return confirm("Are you sure you want to empty your cart?");
			});
		}

		if ( $('cart-form') ) {
			if ( $('donation') ) {
				$('donation').addEvent('click', function(event) {

					if ( $('donation-row') ) {
						$('donation-row').style.display = $('donation').checked ? '' : 'none';
					}

					if ( $('donation-amounts') ) {
						$('donation-amounts').style.display = $('donation').checked ? '' : 'none';
					}
					if ( $('donation').checked ) {

						$$('.donation-amount').each( function(elem, idx) {
							if( elem.checked ) {
								Site.updateCartTotalDonation(getComplementaryStr(elem.id, 'donation-amount-'));
							}
						});
					} else {
						Site.updateCartTotalDonation(0);
					}
				});

				$$('.donation-amount').each( function(elem, idx) {

					elem.addEvent('click', function(event) {
						Site.updateCartTotalDonation(getComplementaryStr(elem.id, 'donation-amount-'));
					});
				});
			}
		}

		if ( $('donation-form') ) {
			if ( $('donation_behalf') ) {

				$('donation_behalf').addEvent('click', function(event) {

					if ( $('friend-details') ) {
						$('friend-details').style.display = $('donation_behalf').checked ? '' : 'none';
					}

					if ( $('donation-types') ) {
						$('donation-types').style.display = $('donation_behalf').checked ? '' : 'none';
					}


					if ( $('donation_behalf').checked ) {

						$$('.donation-type').each( function(elem, idx) {
							if( elem.checked ) {
								$('friend-email-container').style.display = (elem.value == 'memory') ? 'none' : '';
							}
						});
					}
				});
			}

			if ( $('donation_behalf_gift') ) {
				$('donation_behalf_gift').addEvent('click', function(event) {
					if ( $('friend-email-container') ) {
						$('friend-email-container').style.display = ''
					}
				});
			}

			if ( $('donation_behalf_memory') ) {
				$('donation_behalf_memory').addEvent('click', function(event) {
					if ( $('friend-email-container') ) {
						$('friend-email-container').style.display = 'none';
					}
				});
			}

			if ( $('donation_behalf_celebration') ) {
				$('donation_behalf_celebration').addEvent('click', function(event) {
					if ( $('friend-email-container') ) {
						$('friend-email-container').style.display = '';
					}
				});
			}


			if ( $$('.donation-package-amount') ) {

				$$('.donation-package-amount').each(function(elem, idx) {
					elem.addEvent('click', function() {
						if ( elem.checked ) {
							if ( elem.value == 'other' ) {
								$('donation-amount-other').value = '0.00';
							} else {
								$('donation-amount-other').value = formatNumber(elem.value.substr(0, elem.value.indexOf(':')));
							}
						}
					});
				});
			}

			if ( $('donation-amount-other') && $('package-other') ) {
				$('donation-amount-other').addEvent('keyup', function() {
					$('package-other').checked = true;
				});
			}
		}


		if ($('shipping-donation')) {
			$('shipping-donation').addEvent('click', function(){
				$('shipping-donation-row').setStyle('display', this.checked ? '' : 'none');
				Site.updateCartTotalDonation(0);
			});
		}

		if ( $$('.clear-date') && $$('.clear-date').length ) {
			$$('.clear-date').each(function (elem, idx) {

				elem.addEvent('click', function(e) {
					e.stop();
					var inputId = getComplementaryStr(this.href, '#');
					if ( $(inputId) ) {
						$(inputId).value = '';
					}
				});

			});
		}

		if (typeof(mooCalendar2) == 'function' && typeof(mooCalendar2.prototype) == "object") {
			if (typeof(mooCalendar2.Input) == 'function' && typeof(mooCalendar2.Input.prototype) == "object") {
				new mooCalendar2.Input();
			}
		}
	},

	updateCartTotalDonation: function(donation_amount) {
		var new_total = parseFloat($('base-total').innerHTML);

		if ($('shipping-donation') && $('shipping-donation').checked) {
			new_total += 2;
		}

		if ( donation_amount ) {
			var actual_donation_amount = 0.00;

			if ( donation_amount > 0) {
				// Add Donation to order total
				actual_donation_amount = parseInt((Math.round(parseFloat(donation_amount) * 100))) + parseInt(Math.round(new_total * 100));

				// Round down total to nearest 5
				actual_donation_amount = parseFloat(donation_amount) - (actual_donation_amount % 500 / 100);

				if ( actual_donation_amount == 0.00 ) {
					actual_donation_amount = donation_amount;
				}
				new_total += actual_donation_amount;
			}


			$('donation-label').innerHTML = formatNumber(donation_amount);
			$('donation-amount').innerHTML = formatNumber(actual_donation_amount);
		}
		$('total-amount').innerHTML = formatNumber(new_total);


	},

	attachShopAJAX: function() {
		$$('.ajax-link').each( function(elem, idx) {

			elem.addEvent('click', function(event) {

				$$('.ajax-link').each( function(shop_link, idx) {
					shop_link.removeClass('shop-link-active');
				});

				// Add active state for this row
				this.addClass('shop-link-active');

				if ( $('shop') ) {

					var request_url = this.href;

					// Check if we need a question mark or ampersand on the request
					var url_parts = request_url.split('/');
					request_url += ( url_parts[url_parts.length-2] == 'shop' ? '?' : '&') + 'ajax=1';

					//make the ajax call
					new Request.HTML({	'url':				request_url,
										'method':			'get',
										'onRequest':		Site.createSpinner($('shop')),
										'onComplete':		function() {
																Site.destroySpinner($('shop'));
																Shadowbox.clearCache();
																if ( $$('.item-image-link') ) {
																	Shadowbox.setup($$('.item-image-link'));
																}
																Cufon.refresh();
																Site.attachShopDescriptionHovers();
															},
										'update':			$('shop'),
										'onFailure':		function(response) {
																$('shop').innerHTML= '<p>Unable to retrieve data.</p>'
															}
									}).send();

					return false;
				} else {
					window.location = this.href;
				}

				// Remove the unread status
				this.removeClass('mail-row-unread');
			});
		});

	},


	createSpinner: function(target) {
		var spinner = new Element('div', {	'class':	'spinner'	});

		spinner.adopt(new Element('div', {	'class':	'spinner-img'	}));

		spinner.fx = new Fx.Morph(spinner, {	'duration':		250,
												'transition':	Fx.Transitions.Quad.easeInOut,
												'link':			'chain'
											});

		target.adopt(spinner);

		spinner.fx.start({	'opacity':	[0, 0.9] });
	},


	destroySpinner: function(target) {
		var spinner = target.getElement('.spinner');
		if (spinner) {
			spinner.fx.start({	'opacity':	[0.9, 0] }).chain(function() {		spinner.dispose();	});
		}
	},

	resizeText: function(multiplier) {
		if ($('primary').style.fontSize == "") {
			$('primary').style.fontSize = "1em";
		}

		var fontSize = parseFloat($('primary').style.fontSize);

		if ( (fontSize > 0.6 && multiplier < 0) || (fontSize < 1.4 && multiplier > 0) ) {
			fontSize += (multiplier * 0.2);
		}

		$('primary').style.fontSize = fontSize + 'em';
	},

	attachShopDescriptionHovers: function() {
		if ( $$('.item-info') && $$('.description') )
			$$('.item-info').each( function(elem, idx) {

				if ( $$('.description')[idx] && $$('.description')[idx].innerHTML ) {

					elem.store('tip:title', '');
					elem.store('tip:text', $$('.description')[idx].innerHTML);

					var previewTip = new Tips(elem, {
						fixed: false,
						className: 'tip-container'
					});
				}

		});
	},

	attachAccordions: function() {
		// accordion listing
		if ( $$('.accordion') ) {

			$$('.accordion').each(function(elem, idx) {
				//create our Accordion instance
				var myAccordion = new Accordion(elem, '.accordion .toggler', '.accordion .element', {
					alwaysHide: 1,
					display: -1,
					opacity: false,

					onActive: function(toggler, element){
						var setActive = function(){
							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
				$$('.accordion .toggler').each(function(elem, idx) {
					elem.addEvent('mouseenter', function() {
						this.style.cursor = 'pointer';
					});
				});
			});
		}
	}

	};


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


function getComplementaryStr(str, token) {
	if (str.indexOf(token) >= 0) {
		return str.substr(str.indexOf(token)+token.length, str.length);
	}
	return str;
}

function formatNumber(num) {

	num="" + Math.floor(num*100.0 + 0.5)/100.0;

	var i=num.indexOf(".");

	if ( i<0 ) {
		num+=".00";
	} else {
		num=num.substring(0,i) + "." + num.substring(i + 1);
		var nDec=(num.length - i) - 1;
		if ( nDec==0 ) {
			num+="00";
		} else if ( nDec==1 ) {
			num+="0";
		} else if ( nDec>2 ) {
			num=num.substring(0,i + 3);
		}
	}

	return num;
}

