
window.addEvent('domready', function() {
	new SubMenu();

	var crop_elements = [];
	crop_elements.extend($ES('.devImageOverlay'));
	crop_elements.extend($ES('.sideButtons h4'));
	crop_elements.extend($ES('#bannerOverlay'));
	crop_elements.extend($ES('.newsTop'));
	crop_elements.push(new Element('div', {id: 'headerbg'}).injectInside($('header')));
	crop_elements.push(new Element('div', {id: 'footerbg'}).injectInside($('footer')));

	var scale_elements = [];
	scale_elements.extend($ES('.submenu li'));
	new PngFixer(crop_elements, scale_elements);

	runAccodians();
	new InputResetter();

	if ($('frmMoreInfo')) {
		$('frmMoreInfo').addEvent('submit', function(evt){
			new Event(evt).stop();

			var parent = this.getParent();
			parent.addClass('ajax-loading');
			this.setStyle('display', 'none');
			parent.getChildren().each(function(e){
				if (e != this) {
					e.remove();
				}
			}, this);

			this.send({
				onComplete: function(){
					parent.removeClass('ajax-loading');
					new Element('h5').setText('Thank You').injectInside(parent);
					new Element('p').setText('Thank you for your enquiry, we will be in touch at the earliest opportunity.').injectInside(parent);
				}
			});
		});
	}
	if ($('frmNewsletter')) {
		$('frmNewsletter').addEvent('submit', function(evt){
			new Event(evt).stop();

			var parent = this.getParent();
			this.setStyle('display', 'none');
			parent.getChildren().each(function(e){
				if (e != this) {
					e.remove();
				}
			}, this);
			var e = new Element('div').addClass('ajax-loading').injectInside(parent);

			this.send({
				onComplete: function(){
					e.removeClass('ajax-loading');
					new Element('h3').setText('Thank You').injectInside(e);
					new Element('p').setText('We look forward to sending you the next issue of our newsletter.').injectInside(e);
				}
			});
		});
	}
	if($('frmContactForm')) {
		$('frmContactForm').addEvent('submit', function(evt){
			if (!checkForm(this)) {
				new Event(evt).stop();
			}
		});
	}

	// get the rss feeds
	doRss();
});


var rssfeed = '';
function setFeed(s) {
	rssfeed = s
}
function doRss() {
	var el = $('rssNews');
	if (!el) {
		return;
	}
	var url = 'rss.php';
	if (rssfeed) {
		url += '?rss=' + rssfeed;
	}
	var path = (window.location.href.indexOf('/developments/') != -1) ? '../' : '';
	new Ajax(path + url, {
		method: 'get',
		update: el
	}).request();
}



function runAccodians(){
	var multi = $E('div.multi') ? true : false;

	var list = multi ? $ES('div.multi') : $ES('div.data');
	list.each(function(e){
		var p = e.parentNode;
		var n = new Element('div', {
			'class': 'dataAccordian',
			styles: {
				position: 'relative',
				overflow: 'hidden'
			}
		});
		p.replaceChild(n, e);
		n.appendChild(e);
	});

	$ES('#accordion h3').each(function(e){
		e.addEvent('mouseenter', function(){
			e.addClass('hover')
		});
		e.addEvent('mouseleave', function(){
			e.removeClass('hover')
		});
		new Element('span').injectInside(e);
	});

	var accordions = [];
	var options = {};
	if (multi) {
		var togglers = $ES('#accordion h3');
		var elements = $ES('div.dataAccordian');
		for (var i = 0; i < togglers.length; i++) {
			accordions.push({
				togglers: [togglers[i]],
				elements: [elements[i]]
			})
		}
		options = {
			show: -1,
			display: -1,
			alwaysHide: true,
			opacity: false
		}
	}
	else {
		accordions.push({
			togglers: $ES('#accordion h3'),
			elements: $ES('div.dataAccordian')
		});
		options = {
			show: -1,
			alwaysHide: true
		}
	}

	accordions.each(function(a){
		new Accordion(a.togglers, a.elements, $extend({
			onActive: function(toggler, el){
				toggler.addClass('active');
			},
			onBackground: function(toggler, el){
				a.elements.each(function(e){
					if (e.getStyle('height') == 'auto') {
						var h = e.getSize();
						e.setStyles({
							height: h.size.y
						});
					}
				});
				toggler.removeClass('active');
			},
			onComplete: function(){
				a.elements.each(function(e){
					if (e.getStyle('height').toInt() > 0) {
						e.setStyles({
							height: 'auto'
						});
					}
				});
			}
		}, options));
	});
}


var InputResetter = new Class({
	inputs: [],
	options: {
		classes: ['inputReset']
	},
	initialize: function(options) {
		this.setOptions(options);

		this.options.classes.each(function (c) {
			$ES('input.' + c).each(function (e) {
				this.inputs.push({
					element: e,
					value: e.value
				});
				e.addEvent('focus', this.focus.bindWithEvent(this));
				e.addEvent('blur', this.blur.bindWithEvent(this));
			}, this);
		}, this);
	},
	focus: function (e) {
		var e = e.target;
		e.value = '';
	},
	blur: function (e) {
		var e = e.target;
		if (e.value == '') {
			this.inputs.each(function (input) {
				if (input.element == e) {
					e.value = input.value;
					return;
				}
			});
		}
	}
});
InputResetter.implement(new Options);



var SubMenu = new Class({
	initialize: function () {
		var submenus = $ES('#navBar .submenu');

		this.shadows = ['nw', 'nn', 'ne', 'ee', 'se', 'ss', 'sw', 'ww'];
		this.submenus = submenus;

		this.isIE6 = /MSIE\s6/.test(navigator.userAgent);
		this.isIE = /MSIE/.test(navigator.userAgent);

		// set the menu to be in position but hidden so that the sizes will be calculated correctly
		this.submenus.each(function (submenu) {
			submenu.setStyles({
				visibility: 'hidden',
				display: 'block'
			})
		});

		// do the setup required for all browsers
		this.submenus.each(function (submenu) {
			var topLink = submenu.getElement('a');
			if (topLink) {
				topLink.addClass('top');
			}
			var s = {};

			// increase the width of the submenu by 1
			// to make the right edge line up with the
			// right edge of the menu above
			var size = submenu.getSize().size;
			submenu.setStyles({
			//	width: size.x + 1 - 8
			});

			this.shadows.each(function (shadow) {
				var e = $(document.createElement('div'));
				e.addClass(shadow.toString());
				submenu.appendChild(e);
				e.size = e.getSize().size;
				s[shadow] = e;
			});

			var size = submenu.getSize().size;
			var offset = {x: 3, y: 4};
			var offset = {x: 0, y: 0};

			s.nn.setStyles({
				width: size.x - s.nw.size.x - s.ne.size.x - offset.x
			})
			s.ee.setStyles({
				height: size.y - s.ne.size.y -  s.se.size.y - offset.y
			})
			s.ss.setStyles({
				width: size.x - s.sw.size.x - s.se.size.x - offset.x
			})
			s.ww.setStyles({
				height: size.y - s.nw.size.y -  s.sw.size.y - offset.y
			})
		}, this);

		if (this.isIE) {
			this.prepForIE();
		}
		if (this.isIE6) {
			this.prepForIE6();
		}

		// hide the menu again
		this.submenus.each(function (submenu) {
			submenu.setStyles({
				display: '',
				visibility: ''
			})
		});
	},
	prepForIE: function () {
		this.submenus.each(function (submenu) {
			var paddings = $E('a', submenu).getStyles('paddingLeft', 'paddingRight');
			var width = 0;
			var links = submenu.getElements('a')
			links.each(function (e) {
				width = e.offsetWidth > width ? e.offsetWidth : width;
			});
			width = width - parseInt(paddings.paddingLeft) - parseInt(paddings.paddingRight);
			links.each(function (e) {
				e.setStyle('width', width);
			});
		});
	},
	prepForIE6: function () {
		$ES('#navBar li').each(function (e) {
			e.addEvent('mouseenter', function () {e.addClass('hover')});
			e.addEvent('mouseleave', function () {e.removeClass('hover')});
		});

		var regex = /url\(['"](.*)['"]\)/;
		this.submenus.each(function (submenu) {
			var p = submenu.getParent();

			var size = submenu.getSize().size;
			//p.addEvent('mouseenter', function () {submenu.setStyles({display: 'block'})});
			//p.addEvent('mouseleave', function () {submenu.setStyles({display: ''})});

			this.shadows.each(function (shadow) {
				var e = $E('.' + shadow, submenu);
				if (shadow.substr(0, 1) == 's') {
					e.setStyles({
						bottom: 'auto',
						top: size.y - e.getSize().size.y - parseInt(e.getStyle('bottom'))
					})
				}
				if (shadow.substr(1, 1) == 'e') {
					e.setStyles({
						right: 'auto',
						left: size.x - e.getSize().size.x - parseInt(e.getStyle('right'))
					})
				}

				var matches = regex.exec(e.getStyle('backgroundImage'));
				if (matches) {
					e.setStyles({
						background: 'none',
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="crop", src="' + matches[1] + '")'
					})
				}
			});
		}, this);
	}
});



var PngFixer = new Class({
	initialize: function(crop_elements, scale_elements) {
		if (!/MSIE\s6/.test(navigator.userAgent)) {
			// not IE6
			return;
		}
		var imgs = $ES('img');
		var pngs = new Array();
		imgs.each(function (e) {
			if (/\.png$/i.test(e.src)) {
				var p = e.getParent();
				p.setStyles({
					width: e.offsetWidth,
					height: e.offsetHeight,
					display: 'block',
					filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=\'crop\', src=\'' + e.src + '\')'
				});
				e.setStyles({
					display: 'none'
				})
				if (p.nodeName == 'A') {
					p.style.cursor = 'pointer';
				}
			}
		});

		var regex = /url\(['"](.*)['"]\)/;
		if (crop_elements) {
			crop_elements.each(function (e) {
				var matches = regex.exec(e.getStyle('backgroundImage'));
				if (matches) {
					e.setStyles({
						background: 'none',
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="crop", src="' + matches[1] + '")'
					})
				}
			});
		}
		if (scale_elements) {
			scale_elements.each(function (e) {
				var matches = regex.exec(e.getStyle('backgroundImage'));
				if (matches) {
					e.setStyles({
						background: 'none',
						filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod="scale", src="' + matches[1] + '")'
					})
				}
			});
		}
	}
});


function checkForm(frm) {
	frm = $(frm);

	// check all required fields
	var fields = frm.getElements('.jpFrmRequired');
	var error = 0;

	fields.each(function (e) {
		var bad = false;
		switch (e.type.toLowerCase()) {
			case 'text':
			case 'password':
			case 'textarea':
			case 'file':
				bad = e.value == '' ? 1 : 0;
				if (!bad) {
					if (e.hasClass('jpFrmEmail')) {
						bad = e.value.match(/.+\@.+\..+/) ? 0 : 1;
					}
					else if (e.hasClass('jpFrmNumeric')) {
						bad = e.value.match(/\d+/) ? 0 : 1;
					}
				}
				break;
		}
		error += bad;
		if (bad) {
			// highlight field
			e.addClass('jpFrmError');
		}
		else {
			e.removeClass('jpFrmError');
		}
	});

	var msg = $('jpFrmMessage');
	if (msg) {
		msg.remove();
	}
	if (error) {
		var msg = new Element('div', {id: 'jpFrmMessage'}).appendText('Please fill in all the required fields');
		msg.injectTop(frm);
		new Fx.Scroll(window, {wheelStops: false, duration: 100}).toElement(frm);
		return false;
	}

	return true;
}

function writeTestimonial(testimonials) {
	if (!testimonials.length) {
		return;
	}
	var testimonial = testimonials.getRandom();
	document.write('				<div id="testimonials">\n');
	document.write('					<h2>Testimonials</h2>\n');
	document.write(testimonial.copy);
	document.write('					<p><strong>' + testimonial.person + '</strong>\n');
	document.write('					<br />' + testimonial.jobTitle + '</p>\n');
	document.write('					<div id="topTestimonial"></div>\n');
	document.write('				</div>\n');
}
