// global vars
var aniInt = 5000;
var allowedNumberKeys = [8,9,48,49,50,51,52,53,54,55,56,57,96,97,98,99,100,101,102,103,104,105];

// Create the Mootools ZoomBox Class
var zoomBox = new Class({
	
	Implements : Options,
	// Editable Settings
    options: {
		zb_class:     '.zoomBox',                    // class of anchors/images to find on page.
		zb_element:   'zb_image',                    // id of zppmBox pop-up div
		zb_loader:    '/assets/images/loading.gif',  // path to loading image
		scale_image:  true,                          // scale large image if it is bigger than our screen size, bool true/false
		show_tips:    true,                          // Get title element from .zoomBox and shot a 'tip'.
//		add offset options for tips.
		win_width:    1024,                          // basic window width, ignore
		win_height:   768                            // basic window height, ignore
    },

	initialize: function(options){
		// set options and internal settings
		this.setOptions(options);
		this.setWindowSize();
		this.currentIndex;
		this.images = new Array();
		this.positions = new Array();
		
		// create our loading image
		this.zb_loading = new Element('img', { 
			'id'    : 'zb_loading', 
			'src'   : this.options.zb_loader,
			'styles': { 
				'position': 'absolute',
				'display' : 'none',
				'left'    : 0,
				'top'     : 0
			}
		}).inject(document.body, 'bottom');
		
		// create our description tip
		this.zb_tip = new Element('div', { 
			'id'    : 'zb_tip', 
			'html'  : '',
			'styles': { 
				'position'  : 'absolute',
				'left'      : '-1200px',
				'top'       : '-100px',
				'width'     : '300px',
				'min-height': '72px',
				'padding'   : '10px',
				'margin'    : 0,
				'border'    : '4px solid #81B7C4',
				'color'     : '#464646', 
				'background': '#ffffff',
				'z-index'   : 1000,
				'-webkit-box-shadow': '0px 0px 8px #000000',
				'-moz-box-shadow': '0px 0px 8px #000000',
				'box-shadow': '0px 0px 8px #000000'
			}
		}).inject(document.body, 'bottom');

		// scan page for our class.
		this.thumbs = $$(this.options.zb_class);
		
		var self = this;
		
		// attach each image.
		this.thumbs.each(function(zb, index) {
			self.attach(zb, index);
		});
		
		// add event listener if the user resizes their window to scale max size of images.
		window.addEvent('resize', self.setWindowSize.bind(this));
		
	},
	
	
	// attach out image and add event listeners.
	attach: function(zb, index) {
		var self     = this;
		// is we manually attach a new element this is needed.
		if(index == undefined) {
			index = (self.length + 1);
		}
		// set our basic width/heights.
		var zb_fx;
		var zb_src   = zb.get('href');
		var zb_org   = zb.getElements('img')[0];
		if(!zb_org) zb_org = zb;
		self.positions[index] = {};
		self.positions[index].zb_left   = zb_org.getPosition().x;
		self.positions[index].zb_top    = zb_org.getPosition().y;
		self.positions[index].zb_width  = zb_org.getWidth();
		self.positions[index].zb_height = zb_org.getHeight();
		// our element
		zb		
		// set title to rel tag for our tips
		.set('rel', zb.get('title')).set('title', '')
		// add out click event.
		.addEvents({
			'click': function(clk) {
				new Event(clk).stop();
				// no point opening it, if its already open !
				if(!document.id(self.options.zb_element) || !document.id(self.options.zb_element).get('src').match(zb.get('href'))) {
					// add out loading gif to the image about to be opened.
					self.zb_loading.setStyles({
						'display' : '',
						'top'     : self.positions[index].zb_top,
						'left'    : self.positions[index].zb_left
					});
					// if we have one open, let it be gone
					if(document.id(self.options.zb_element)) {
						self.close(self.currentIndex);
					}
					// set current index.
					self.currentIndex = index;
					// create and place on top of the thumbnail. but keep it hidden.
					self.images[index] = new Element('img', { 
						'id'    : self.options.zb_element, 
						'src'   : zb_src,
						'styles': { 
							'position': 'absolute',
							'opacity' : 0,
							'left'    : self.positions[index].zb_left,
							'top'     : self.positions[index].zb_top
						}
					})
					.addClass('shadow') // we don't need this. but its basic styling for large image.
					.inject(document.body, 'bottom') // inject at teh bottom of our page.
					.addEvent('click', function(clk) {
						// bind out close even on clicking the new large image
						new Event(clk).stop();
						self.close(index);
					})
					// bind a load event so once the large image has loaded, we open it.
					.addEvent('load', function() {
						// get our large image size
						var zb_width  = self.images[index].getWidth();
						var zb_height = self.images[index].getHeight();
						// see if we need to scale it, so the image fits on screen.
						if(self.options.scale_image) {
							if(self.options.win_width < zb_width) {
								zb_width  = (self.options.win_width - 50);
								zb_height = (zb_width / zb_height) * zb_width;
							} 
							if(self.options.win_height < zb_height) {
								zb_height = Math.floor(self.options.win_height - 50);
								zb_width  = Math.floor((zb_height / zb_width) * zb_height);
							}
						}
						// set the imahe the size of the thumbnail
						self.images[index].setStyles({
							'width'   : zb_org.getWidth(),
							'height'  : zb_org.getHeight(),
							'cursor'  : 'pointer'
						});
						// hide teh loading gif/indicator 
						self.zb_loading.setStyle('display', 'none');
						// animate it BIG ! and center it on the screen
						var zb_fx = new Fx.Morph(self.images[index]).start({
							'top'     : ((self.options.win_height / 2) - (zb_height / 2)) + window.getScroll().y,
							'left'    : ((self.options.win_width / 2) - (zb_width / 2)),
							'width'   : zb_width,
							'height'  : zb_height,
							'opacity' : 1
						});
					});
				} else {
					// we have used it before, lets load it up.
					self.images[index].fireEvent('load');
				}
				// bind the 'escape' key to close the current image.
				window.addEvent('keyup', function(key) {
					if(key.code == 27) {
						self.close(index);
					} 
				});
			},
			'mouseenter': function() {
				if(self.options.show_tips) {
					self.zb_tip.setStyles({
						'left'   : (self.positions[index].zb_left - self.zb_tip.getWidth()),
						'top'    : self.positions[index].zb_top
					})
					.set('html', zb.get('rel'))
					.fade('in');
				}
			}, 
			'mouseleave': function() {
				if(self.options.show_tips) self.zb_tip.empty().fade('out');
			}
		});

	},
	
	close: function(index) {
		var self = this;
		var zb_fx = new Fx.Morph(self.images[index], { 
			onComplete: function() {
				document.id(self.options.zb_element)
					.fade(0)
					.dispose();
			} 
		}).start({
			'top'     : self.positions[index].zb_top,
			'left'    : self.positions[index].zb_left,
			'width'   : self.positions[index].zb_width,
			'height'  : self.positions[index].zb_height,
			'opacity' : 0
		});
		window.removeEvents('keyup');
	},
	
	setWindowSize: function() {
		
		this.options.win_width = window.getWidth();
		this.options.win_height = window.getHeight();
		
	}
	
});

var initMap = function() {
	if (!document.id('Map')) return;
	$$('#Map area').addEvents({
		'mouseover': function() {
			$$('.map-content').setStyle('display','none');
			$(this.id.replace('map-', 'content-')).setStyle('display','block');
		},
		'click': function(ev) {
			new Event(ev).stop();
		}
	});
}

// load google analytics
var initGA = function() {
	new Element('script', { src: 'http://www.google-analytics.com/ga.js', type: 'text/javascript' }).inject('wrapper', 'after');
}

var trackGA = function() {
	try {
		var pageTracker = _gat._getTracker('UA-2004844-16');
		pageTracker._trackPageview();
	} catch(err) {}

	if(pageTracker) {
		$$('a').each(function(el) {
			if(el.get('href').match(/http:\/\//i)) {
				el.addEvent('click', function() {
					var dd = '/outgoing/' + document.id(this).get('href').replace('http://','');
					pageTracker._trackPageview(dd);
					return true;
				});
			}
		});
	}
}

// domReady Event
window.addEvents({
	'domready': function(){
		Element.implement({
			//implement show
			show: function() {
			  this.setStyle('display','');
			},
			//implement hide
			hide: function() {
			  this.setStyle('display','none');
			}
		  });
		initGA();
		if ($$('#homeGallery').length > 0) initHomeGallery();
		if ($$('#quoteForm').length > 0) initQuoteForm();
		if ($$('.tTip').length > 0) initToolTips();
		var flashTiles = new Swiff('/assets/flash/tiles.swf', { id: 'flashTilesFlash', width: 400, height: 200, container: 'flashTiles', params: { wMode: 'transparent' } });
		var myZoomBox  = new zoomBox({show_tips: false});
		initMap();
		initFeedback();
	},
	'load': trackGA.bind(this)
});



// init HomePage Gallery
var initHomeGallery = function() {	
	var imageArr = document.id('homeGallery').getElements('img');
	var imageSel = 0;
	
	for(var i = 0; i < imageArr.length; i++) {
		if (i == imageSel) {
			imageArr[i].set('styles', {
				'opacity': '1',
				'visibility': 'visible'
			}).erase('class');
		} else {
			imageArr[i].set('styles', {
				'opacity': '0',
				'visibility': 'hidden'
			});
		}
	}
	
	(function() {
		imageArr[imageSel].fade('out');
		imageSel = ((imageSel + 1) < imageArr.length) ? (imageSel + 1) : 0;
		imageArr[imageSel].fade('in');
	}).periodical(aniInt);
	
}

// init QuoteForm (for adding new size fields)
var initQuoteForm = function() {
	
	document.id('quoteForm').addEvent('submit', function() {
		document.id('supply_only').set('disabled', '');
		$$('.tg_dimensions input', '.ag_dimensions input').each(function(ele) {
			if (ele.get('value') == 'mm') {
				ele.set('value', 0);
			}
		});
	});
	
	if(document.id('supply_only')) {
		var i_set = false;
		var origHeight = document.id('step3Wrapper').setStyle('overflow', 'hidden').getHeight();
		// adds an event on the supply_only change
		document.id('supply_only').addEvent('change', function() {
			if (document.id('supply_only').get('checked')) {
				document.id('step3Wrapper').set('morph', { duration: 'normal' }).morph({ height: 0, opacity: 0 });
				document.id('step4').getElement('legend').set('html', 'Step 3');
				document.id('annealed-glass').fade('out');
			} else {
				document.id('step3Wrapper').set('morph', { duration: 'normal' }).morph({ height: origHeight, opacity: 1 });
				document.id('step4').getElement('legend').set('html', 'Step 4');
				document.id('annealed-glass').fade('in');
			}
		});
		// checks to see if its checked on load~
		if (document.id('supply_only').get('checked')) {
			document.id('step3Wrapper').set('morph', { duration: 'normal' }).morph({ height: 0, opacity: 0 });
			document.id('step4').getElement('legend').set('html', 'Step 3');
			document.id('annealed-glass').fade('out');
		}
		
		document.id('fitting_kit').addEvent('change', function() {
			if(document.id('fitting_kit').getSelected().get('value') > 0) {
				
				document.id('supply_only').set('disabled', 'disabled');
				if (!document.id('supply_only').get('checked')) {
					i_set = true;
					document.id('supply_only').set('checked', 'checked');
					document.id('step3Wrapper').set('morph', { duration: 'normal' }).morph({ height: 0, opacity: 0 });
					document.id('step4').getElement('legend').set('html', 'Step 3');
					document.id('annealed-glass').fade('out');
				} 
			} else {
				document.id('supply_only').set('disabled', '');
				if(i_set == true) {
					i_set = false;
					document.id('supply_only').set('checked', '');
					document.id('step3Wrapper').set('morph', { duration: 'normal' }).morph({ height: origHeight, opacity: 1 });
					document.id('step4').getElement('legend').set('html', 'Step 4');
					document.id('annealed-glass').fade('in');
				}
			}
		});
		// checks to see if its checked on load~
		if(document.id('fitting_kit').getSelected().get('value') > 0) {
			i_set = true;
			document.id('supply_only').set('checked', 'checked').set('disabled', 'disabled');
			document.id('step3Wrapper').set('morph', { duration: 'normal' }).morph({ height: 0, opacity: 0 });
			document.id('step4').getElement('legend').set('html', 'Step 3');
			document.id('annealed-glass').fade('out');
		}
	}
	
	
	if(document.id('tg_dimensions')) initCloneFields('tg_');
	if(document.id('ag_dimensions')) initCloneFields('ag_');

	
	if(document.id('colour')) {
		document.id('colour').addEvent('change', function() {
			document.id('step4').fade(1);
			var parts = document.id(this).get('value').toLowerCase().split(' - ');
			if (document.id(this).get('value').toLowerCase() == "other") {
				document.id('clear_float').erase('checked').fade('out');
				document.id('low_iron').set('checked', 'checked').fade('in');
				document.id('glass-type-range').erase('checked').fade('in');
				var otherInput = new Element('input', { type: 'text', id: 'otherColour', name: 'otherColour' });
				otherInput.inject(this);
			} else if(parts[0].contains('l')) {
				if(document.id('otherColour')) document.id('otherColour').dispose();
				document.id('glass-type-range').erase('checked').fade('in');
				document.id('clear_float').erase('checked').fade('out');
				document.id('low_iron').set('checked', 'checked').fade('in');
			} else {
				document.id('glass-type-range').erase('checked').fade('in');
				document.id('low_iron').erase('checked').fade('out');
				document.id('clear_float').set('checked', 'checked').fade('in');
				if(document.id('otherColour')) document.id('otherColour').dispose();
			}
			if(parts[0].contains('er|')) {
				alert("I'm Sorry the Glass Effects range is temporary unavailable.\nPlease price on application.");
				document.id('step4').fade(0);
				if(document.id('otherColour')) document.id('otherColour').dispose();
				document.id('glass-type-range').erase('checked').fade('out');
				document.id('clear_float').erase('checked').fade('out');
				document.id('low_iron').set('checked', 'checked').fade('out');
			}
		});
	}
	
	if(document.id('how_did_you')) {
		document.id('how_did_you').addEvent('change', function() {
			var parts = document.id(this).get('value').toLowerCase().split(' - ');
			if (document.id(this).get('value').toLowerCase() == "other") {
				if(!document.id('other_how_did_you')) new Element('input', { type: 'text', id: 'other_how_did_you', name: 'other_how_did_you' }).inject(this).fade(1);
			} else {
				if(document.id('other_how_did_you')) document.id('other_how_did_you').fade(0); 
			}
		});
	}
	
	if(document.id('curved_rangehood')) {
		var curved_rangehood = function() {
			if(document.id('curved_rangehood').checked == true) {
				document.id('curved_rangehood_size').fade(1);
			} else {
				document.id('curved_rangehood_size').fade(0);
			}
		}
		curved_rangehood();
		document.id('no_rangehood').addEvent('click', curved_rangehood.bind());
		document.id('curved_rangehood').addEvent('click', curved_rangehood.bind());
		document.id('flat_rangehood').addEvent('click', curved_rangehood.bind());
	}
	
	if(document.id('city')) {
		document.id('city').addEvent('change', function() {
			if (document.id('city').get('value') != '') {
				var loader = new Element('img', { src: path + 'assets/images/loader.gif', id: 'loader', align: 'left' });
				var jsonRequest = new Request.JSON({
					url: path + "select-suburb/" + document.id(this).get('value'),
					onRequest: function() {
						if(document.id('suburb')) document.id('suburb').dispose();
						loader.inject('city');
					},
					onSuccess: function(json) {
						loader.dispose();
						if (json != null) {
							var suburbs = new Element('select', { name: 'suburb', id: 'suburb' });
							var suburb = new Element('option', { value: '', html: 'Please select a Suburb' });
							suburb.inject(suburbs);
							for (var i = 0; i < json.length; i++) {
								var suburb = new Element('option', { value: json[i].id, html: json[i].name });
								suburb.inject(suburbs);
							}
							suburbs.inject('city', 'after');
						}
					}
				}).send();
			}
		});
	}
}

var initCloneFields = function(prefix) {
	document.id(prefix + 'dimensions').getElements('input').addEvents({
		'keydown': checkIfNumber,
		'focus': function() {
			if (checkIfValue(this, 'mm')) {
				document.id(this).set('value', '').removeEvents('focus');
			}
		}
	});
	document.id(prefix + 'addMore').addEvent('click', function() {
		var clone = document.id(prefix + 'dimensions').clone();
		clone.getElement('a').dispose();
		clone.getElements('input').addEvents({
			'keydown': checkIfNumber,
			'focus': function() {
				if (checkIfValue(this, 'mm')) {
					document.id(this).set('value', '').removeEvents('focus');
				}
			}
		}).set('value', 'mm');		
		clone.inject($$('.' + prefix + 'dimensions').getLast(), 'after');
		return false;
	});
}

var checkIfNumber = function(key) {
	for (i = 0; i < allowedNumberKeys.length; i++) {
		if(allowedNumberKeys[i] == key.code) {
			return true;
		}
	}
	return false;
}

var checkIfValue = function(ele, value) {
	if (document.id(ele).get('value') == value) {
		return true;
	} else {
		return false;
	}
}

var initToolTips = function() {
	var imgRegEx = /\.(png|jpg|gif)$/i;
	$$('.tTip').each(function(element, index) {
		var content = element.get('title').split('::');
		element.store('tip:title', content[0]);
		var joinContent = '';
		for (var i = 1; i < content.length; i++) {
			if (content[i].test(imgRegEx)) {
				joinContent += '<div class="tip-image"><img src="' + content[i] + '" /></div>';
			} else {
				joinContent += content[i];
			}
		}
		element.store('tip:text', joinContent);
		element.addEvent('click', function() { return false; });
	});
		
	//create the tooltips
	var toolTips = new Tips('.tTip',{
		className: 'toolTip',
		fixed: true,
		hideDelay: 50,
		showDelay: 50
	});

}

var initFeedback = function() {
	
	if(document.id('feedback')) {
		
		var feedback  = document.id('feedback');
		var overlay   = new Element('div', { 'styles': { 'position': 'fixed','z-index': 2, 'top': 0, 'left': 0, 'right': 0, 'bottom': 0, 'background': '#ffffff', 'opacity': 0, 'display':'none' }}).inject(document.body, 'bottom');
		var container = new Element('div', { 'styles': { 'position': 'fixed','z-index': 3, 'top': '100px', 'left': '-310px', 'width': '600px', 'height': '500px', 'margin': '0 0 0 50%', 'padding': '5px', 'background': '#ffffff', 'border': '10px solid #000000', 'box-shadow':'0 0 10px #000000', 'display':'none', 'color': '#000000'}}).inject(document.body, 'bottom');
		var flash     = document.id('flashTiles');
		
		var request = new Request.HTML({
			'url': feedback.get('href'),
			onRequest: function() {
				overlay.setStyle('display', 'block').fade(0.25);
				flash.fade(0);
			},
			onComplete: function(r1, r2, html, js) {
				actions(html);
			}
		});
		
		var actions = function(html) {
			container.setStyle('display', 'block').fade(1).set('html', html);
			document.id('cancel-feedback').addEvent('click', function(clk) {
				clk.stop();
				container.set('html', 'thanks for your feedback').fade(0).setStyle('display', 'none');
				overlay.fade(0).setStyle('display', 'none');
				flash.fade(1);
			});
			if(document.id('feedback-form')) {
				var form = document.id('feedback-form');
				form.addEvent('submit', function(sub) {
					sub.stop();
					new Request.HTML({
						'url': form.get('action'),
						'data': form,
						onComplete: function(r1, r2, html, js) {
							actions(html);
						}
					}).send();
				});
			}
		}
		
		feedback.addEvent('click', function(clk) {
			clk.stop();
			request.send();
		});
		
	}
	
}
