/* --- character counter for adding message about a place --- */

var strLength = 0;
var maxLength = 160;
var textLength = 0;
var inputText = new String('');

/* --- main navigation menu --- */

var placeson = function() {
	$('tabplaces').setStyle('display', 'block');
	$('navplaces').setStyles({
		borderTop: '1px solid #00a0c6',
		borderRight: '1px solid #00a0c6',
		borderLeft: '1px solid #00a0c6'
	});
}

var placesoff = function() {
	$('tabplaces').setStyle('display', 'none');
	$('navplaces').setStyles({
		borderTop: '1px solid #1e1e1e',
		borderRight: '1px solid #1e1e1e',
		borderLeft: '1px solid #1e1e1e'
	});
}

var signinon = function() {
	$('tabsignin').setStyle('display', 'block');
	$('navsignin').setStyles({
		borderTop: '1px solid #00a0c6',
		borderRight: '1px solid #00a0c6',
		borderLeft: '1px solid #00a0c6'
	});
}

var signinoff = function() {
	$('tabsignin').setStyle('display', 'none');
	$('navsignin').setStyles({
		borderTop: '1px solid #1e1e1e',
		borderRight: '1px solid #1e1e1e',
		borderLeft: '1px solid #1e1e1e'
	});
}

/* --- overlay creator for pop-up pages --- */

/**
 * SqueezeBox - Expandable Lightbox
 *
 * Allows to open various content as modal,
 * centered and animated box.
 *
 * Dependencies: MooTools 1.2 trunk (04/2008)
 *
 * Inspired by
 *  ... Lokesh Dhakar	- The original Lightbox v2
 *
 * @version		1.1 rc2
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */
var SqueezeBox = {

	presets: {
		size: {x: 600, y: 450},
		sizeLoading: {x: 200, y: 150},
		marginInner: {x: 20, y: 20},
		marginImage: {x: 50, y: 75},
		handler: false,
		target: null,
		closable: true,
		closeBtn: true,
		zIndex: 65555,
		overlayOpacity: 0.7,
		classWindow: '',
		classOverlay: '',
		overlayFx: {},
		resizeFx: {},
		contentFx: {},
		parse: false, // 'rel'
		parseSecure: false,
		ajaxOptions: {},
		onOpen: $empty,
		onClose: $empty,
		onUpdate: $empty,
		onResize: $empty,
		onMove: $empty,
		onShow: $empty,
		onHide: $empty
	},

	initialize: function(presets) {
		if (this.options) return this;
		this.presets = $merge(this.presets, presets);
		this.options = {};
		this.setOptions(this.presets).build();
		this.bound = {
			window: this.reposition.bind(this, [null]),
			scroll: this.checkTarget.bind(this),
			close: this.close.bind(this),
			key: this.onKey.bind(this)
		};
		this.isOpen = this.isLoading = false;
		return this;
	},

	build: function() {
		this.overlay = new Element('div', {
			id: 'sbox-overlay',
			styles: {display: 'none', zIndex: this.options.zIndex}
		});
		this.content = new Element('div', {id: 'sbox-content'});
		this.closeBtn = new Element('a', {id: 'sbox-btn-close', href: '#', html: 'Close <img src="http://thumbprintcity.com/img/static/ico/ico_close_16x16.gif" alt="close" />'});
		this.win = new Element('div', {
			id: 'sbox-window',
			styles: {display: 'none', zIndex: this.options.zIndex + 2}
		}).adopt(this.closeBtn, this.content);
		this.fx = {
			overlay: new Fx.Tween(this.overlay, $merge({
				property: 'opacity',
				onStart: Events.prototype.clearChain,
				duration: 250,
				link: 'cancel'
			}, this.options.overlayFx)).set(0),
			win: new Fx.Morph(this.win, $merge({
				onStart: Events.prototype.clearChain,
				unit: 'px',
				duration: 750,
				transition: Fx.Transitions.Quint.easeOut,
				link: 'cancel',
				unit: 'px'
			}, this.options.resizeFx)),
			content: new Fx.Tween(this.content, $merge({
				property: 'opacity',
				duration: 250,
				link: 'cancel'
			}, this.options.contentFx)).set(0)
		};
		$(document.body).adopt(this.overlay, this.win);
	},

	assign: function(to, options) {
		return to.addEvent('click', function() {
			return !SqueezeBox.fromElement(this, options);
		});
	},

	fromElement: function(from, options) {
		this.initialize();
		if (this.element) this.trash();
		this.element = $(from);
		this.setOptions($merge(this.presets, options || {}));
		if (this.element && this.options.parse) {
			var obj = this.element.getProperty(this.options.parse);
			if (obj && (obj = JSON.decode(obj, this.options.parseSecure))) this.setOptions(obj);
		}
		this.assignOptions();
		this.url = ((this.element) ? (this.options.url || this.element.get('href')) : from) || '';
		var handler = this.options.handler;
		if (handler) return this.setContent(handler, this.parsers[handler].call(this, true));
		var ret = false;
		this.parsers.some(function(parser, key) {
			var content = parser.call(this);
			if (content) {
				ret = this.setContent(key, content);
				return true;
			}
			return false;
		}, this);
		return ret;
	},

	assignOptions: function() {
		this.overlay.set('class', this.options.classOverlay);
		this.win.set('class', this.options.classWindow);
		if (Browser.Engine.trident4) this.win.addClass('sbox-window-ie6');
	},

	close: function(e) {
		var stoppable = ($type(e) == 'event');
		if (stoppable) e.stop();
		if (!this.isOpen || (stoppable && !$lambda(this.options.closable).call(this, e))) return this;
		this.fx.overlay.start(0).chain(this.toggleOverlay.bind(this));
		this.win.setStyle('display', 'none');
		this.trash();
		this.toggleListeners();
		this.isOpen = false;
		this.fireEvent('onClose', [this.content]);
		return this;
	},

	trash: function() {
		this.element = this.asset = null;
		this.options = {};
		this.removeEvents().setOptions(this.presets).callChain();
	},

	onError: function() {
		this.asset = null;
		this.setContent('string', 'Error during loading');
	},

	setContent: function(handler, content) {
		if (!this.handlers[handler]) return false;
		this.content.className = 'sbox-content-' + handler;
		this.applyTimer = this.applyContent.delay(this.fx.overlay.options.duration, this, this.handlers[handler].call(this, content));
		if (this.overlay.retrieve('opacity')) return this;
		this.toggleOverlay(true);
		this.fx.overlay.start(this.options.overlayOpacity);
		return this.reposition();
	},

	applyContent: function(content, size) {
		this.applyTimer = $clear(this.applyTimer);
		this.hideContent();
		if (!content) {
			this.toggleLoading(true);
		} else {
			if (this.isLoading) this.toggleLoading(false);
			this.fireEvent('onUpdate', [this.content], 20);
		}
		this.content.empty();
		if (['string', 'array', false].contains($type(content))) this.content.set('html', content || '');
		else this.content.adopt(content);
		this.callChain();
		if (!this.isOpen) {
			this.toggleListeners(true);
			this.resize(size, true);
			this.isOpen = true;
			this.fireEvent('onOpen', [this.content]);
		} else {
			this.resize(size);
		}
	},

	resize: function(size, instantly) {
		var box = document.getSize(), scroll = document.getScroll();
		this.size = $merge((this.isLoading) ? this.options.sizeLoading : this.options.size, size);
		var to = {
			width: this.size.x,
			height: this.size.y,
			left: (scroll.x + (box.x - this.size.x - this.options.marginInner.x) / 2).toInt(),
			top: (scroll.y + (box.y - this.size.y - this.options.marginInner.y) / 2).toInt()
		};
		$clear(this.showTimer || null);
		this.hideContent();
		if (!instantly) {
			this.fx.win.start(to).chain(this.showContent.bind(this));
		} else {
			this.win.setStyles(to).setStyle('display', '');
			this.showTimer = this.showContent.delay(50, this);
		}
		return this.reposition();
	},

	toggleListeners: function(state) {
		var fn = (state) ? 'addEvent' : 'removeEvent';
		this.closeBtn[fn]('click', this.bound.close);
		//this.overlay[fn]('click', this.bound.close);
		document[fn]('keydown', this.bound.key)[fn]('mousewheel', this.bound.scroll);
		window[fn]('resize', this.bound.window)[fn]('scroll', this.bound.window);
	},

	toggleLoading: function(state) {
		this.isLoading = state;
		this.win[(state) ? 'addClass' : 'removeClass']('sbox-loading');
		if (state) this.fireEvent('onLoading', [this.win]);
	},

	toggleOverlay: function(state) {
		this.overlay.setStyle('display', (state) ? '' : 'none');
		$(document.body)[(state) ? 'addClass' : 'removeClass']('body-overlayed');
	},

	showContent: function() {
		if (this.content.get('opacity')) this.fireEvent('onShow', [this.win]);
		this.fx.content.start(1);
	},

	hideContent: function() {
		if (!this.content.get('opacity')) this.fireEvent('onHide', [this.win]);
		this.fx.content.set(0);
	},

	onKey: function(e) {
		switch (e.key) {
			case 'esc': this.close(e);
			case 'up': case 'down': return false;
		}
	},

	checkTarget: function(e) {
		return this.content.hasChild(e.target);
	},

	reposition: function() {
		var size = document.getSize(), scroll = document.getScroll();
		this.overlay.setStyles({
			left: scroll.x + 'px',
			top: scroll.y + 'px',
			width: size.x + 'px',
			height: size.y + 'px'
		});
		this.win.setStyles({
			left: (scroll.x + (size.x - this.win.offsetWidth) / 2).toInt() + 'px',
			top: (scroll.y + (size.y - this.win.offsetHeight) / 2).toInt() + 'px'
		});
		return this.fireEvent('onMove', [this.overlay, this.win]);
	},

	removeEvents: function(type){
		if (!this.$events) return this;
		if (!type) this.$events = null;
		else if (this.$events[type]) this.$events[type] = null;
		return this;
	},

	extend: function(properties) {
		return $extend(this, properties);
	},

	handlers: new Hash(),

	parsers: new Hash()

};

SqueezeBox.extend(new Events($empty)).extend(new Options($empty)).extend(new Chain($empty));

SqueezeBox.parsers.extend({

	image: function(preset) {
		return (preset || (/\.(?:jpg|png|gif)$/i).test(this.url)) ? this.url : false;
	},

	clone: function(preset) {
		if ($(this.options.target)) return $(this.options.target);
		if (this.element && !this.element.parentNode) return this.element;
		var bits = this.url.match(/#([\w-]+)$/);
		return (bits) ? $(bits[1]) : (preset ? this.element : false);
	},

	ajax: function(preset) {
		return (preset || (this.url && !(/^(?:javascript|#)/i).test(this.url))) ? this.url : false;
	},

	iframe: function(preset) {
		return (preset || this.url) ? this.url : false;
	},

	string: function(preset) {
		return true;
	}
});

SqueezeBox.handlers.extend({

	image: function(url) {
		var size, tmp = new Image();
		this.asset = null;
		tmp.onload = tmp.onabort = tmp.onerror = (function() {
			tmp.onload = tmp.onabort = tmp.onerror = null;
			if (!tmp.width) {
				this.onError.delay(10, this);
				return;
			}
			var box = document.getSize();
			box.x -= this.options.marginImage.x;
			box.y -= this.options.marginImage.y;
			size = {x: tmp.width, y: tmp.height};
			for (var i = 2; i--;) {
				if (size.x > box.x) {
					size.y *= box.x / size.x;
					size.x = box.x;
				} else if (size.y > box.y) {
					size.x *= box.y / size.y;
					size.y = box.y;
				}
			}
			size.x = size.x.toInt();
			size.y = size.y.toInt();
			this.asset = $(tmp);
			tmp = null;
			this.asset.setProperties({width: size.x, height: size.y});
			if (this.isOpen) this.applyContent(this.asset, size);
		}).bind(this);
		tmp.src = url;
		if (tmp && tmp.onload && tmp.complete) tmp.onload();
		return (this.asset) ? [this.asset, size] : null;
	},

	clone: function(el) {
		return el.clone();
	},

	adopt: $arguments(0),

	ajax: function(url) {
		this.asset = new Request.HTML($merge({
			method: 'get'
		}, this.options.ajaxOptions)).addEvents({
			onSuccess: function(resp) {
				this.applyContent(resp);
				this.asset = null;
			}.bind(this),
			onFailure: this.onError.bind(this)
		});
		this.asset.send.delay(10, this.asset, [{url: url}]);
	},

	iframe: function(url) {
		return new Element('iframe', $merge({
			src: url,
			frameBorder: 0,
			width: this.options.size.x,
			height: this.options.size.y
		}, this.options.iframeOptions));
	},

	string: function(str) {
		return str;
	}

});

SqueezeBox.handlers.url = SqueezeBox.handlers.ajax;
SqueezeBox.parsers.url = SqueezeBox.parsers.ajax;
SqueezeBox.parsers.adopt = SqueezeBox.parsers.clone;

/* --- ### --- */

var runScroller = function() {
	var opt = {
	  duration: 1200,
	  delay: 5000,
	  auto:true,
	  buttons: {next:'js_next',prev:'js_prev'},
	  onMouseEnter: function(){this.stop();},
	  onMouseLeave: function(){this.play();}
	}
	var scroller = new QScroller('qscroller','js_teasers','manchester','js_sendmessage','js_messageinput','js_sendbutton', opt);
}

/* --- horizontal scroller with inbuilt character counter --- */

/* QScroller Copyright 2008 Massimo Giagnoni. All rights reserved.

Version 1.0.1 (Mootools 1.11)
Updated 27/10/2008 PF for Mootools 1.2
Updated 27/10/2008 PF with addition of charcounter functionality:
setCharCounter(), updateCharCount(), "this.setCharCounter();" in show(), "$('messageinput').addEvent('keyup', this.updateCharCount);" in initialize();


QScroller is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

var idxSlide = 0;
var strlength = 0;
var maxlength = 160;
var inputText = new String('');

var QScroller = new Class({
	Implements : [Options,Events],
	options: {
		slides: 'qslide',
		direction: 'h',
		duration: 3000,
		auto: false,
		delay: 1000,
		transition: Fx.Transitions.linear
	},
	//initialize: function(wrapper,controls,options) {
	initialize: function(wrapper,controls,city,form,textarea,button,options) {
		this.setOptions(options);
		this.wrapper = $(wrapper);
		this.controls = $(controls);
		this.city = $(city); //
		this.form = $(form); //
		this.textarea = $(textarea); //
		this.button = $(button); //
		this.wrapper.setStyles({
			position: 'relative',
			overflow: 'hidden'
		});
		this.controls.addEvent('mouseenter', this.fireEvent.pass('onMouseEnter',this));
		this.controls.addEvent('mouseleave', this.fireEvent.pass('onMouseLeave',this));
				
		this.slideOut = new Element('div').setStyles({
			position: 'absolute',
			overflow: 'hidden',
			top: 0,
			left: 0,
			width: this.wrapper.getStyle('width'),
			height: this.wrapper.getStyle('height')
		}).injectInside(this.wrapper);

		this.slideIn = this.slideOut.clone();
		this.slideIn.injectInside(this.wrapper);
				
		this.slides = $$('.'+this.options.slides);
		
		if($defined(this.options.buttons)) {
			if($defined(this.options.buttons.next)) {
				$(this.options.buttons.next).addEvent('click', this.next.bind(this));
			}
			if($defined(this.options.buttons.prev)) {
				$(this.options.buttons.prev).addEvent('click', this.prev.bind(this));
			}	
			if($defined(this.options.buttons.play)) {
				$(this.options.buttons.play).addEvent('click', this.play.bind(this));
			}	
			if($defined(this.options.buttons.stop)) {
				$(this.options.buttons.stop).addEvent('click', this.stop.bind(this));
			}	
		}
		this.auto = this.options.auto;
		this.step = 0;
		this.isFirst = true;
		this.load();
		//$('messageinput').addEvent('keyup', this.updateCharCount);
		this.textarea.addEvent('keyup', this.updateCharCount.bind(this));
		this.button.addEvent('click', this.sendForm.bind(this));
	},
	load: function() {
		if(!this.isFirst) {
			idxSlide += this.step;
			if(idxSlide > this.slides.length-1) {
				idxSlide = 0;
			} else if(idxSlide < 0) {
				idxSlide = this.slides.length-1;
			}
		}
		this.curSlide = this.slides[idxSlide].clone();
		this.show();
	},
	show: function() {
		var slide = this.slideIn.getElement('div');
		if(slide) {
			this.curSlide.replaces(slide);
		} else {
			this.curSlide.injectInside(this.slideIn);
		}
		//if ($('messageinput').get('value').length == 0) {
		if (this.textarea.get('value').length == 0) {
			this.doEffect();
		}
		this.setCharCounter();
	},
	doEffect: function() {
		this.fxOn = true;
		var d = this.isFirst ? 0:this.options.duration;
		var t = this.options.transition;
		
		var fxObj = new Fx.Morph(this.slideIn, {
			duration:d,
			transition: t
		});
		var inX = 0;
		var inY = 0;
		var outX = 0;
		var outY = 0;
		var ww = this.wrapper.getStyle('width').toInt();
		var wh = this.wrapper.getStyle('height').toInt();
		if(this.step > 0) {
			if(this.options.direction == 'h') {
				inX = -ww;
				outX = ww;
			} else {
				inY = -wh;
				outY = wh;
			}
		} else {
			if(this.options.direction == 'h') {
				inX = ww;
				outX = -ww;
			} else {
				inY =  wh;
				outY = -wh;
			}
		}
		if(this.isFirst) {
			if(this.auto) {
				this.step = 1;
			}
			this.isFirst = false;
		}
		fxObj.start({
			top: [inY, 0],
			left: [inX, 0],
			opacity: [1, 1]
		});
		var thisMorph = new Fx.Morph(this.slideOut, ({
			duration: d,
			transition: t
		})).start({
			top: [0, outY],
			left: [0, outX]
		});
		
		this.fxEnd.delay(d + 75, this);
	},
	fxEnd: function() {
		this.fxOn = false;
		this.swapSlides();
		if(this.auto) {
			$clear(this.timer);
			this.timer = this.load.delay(this.options.delay, this);
		}
	},
	stop: function(){
		$clear(this.timer);
		this.auto = false;
	},
	play: function() {
		if(!this.auto ) {
			$clear(this.timer);
			this.auto=true;
			this.step = 1;
			if(!this.fxOn) {
				this.load();
			}
		}
	},
	next: function() {
		///$('messageinput').set('value', '');
		this.textarea.set('value', '');
		this.stop();
		if(this.fxOn) { return; }
		this.step = 1;
		this.load();
	},
	prev: function() {
		this.textarea.set('value', '');
		this.stop();
		if(this.fxOn) { return; }
		this.step = -1;
		this.load()
	},
	swapSlides: function() {
		this.slideOut.setStyles({
			zIndex: 0,
			opacity: 0
		});
		var t = this.slideOut;
		this.slideOut =this.slideIn;
		this.slideIn = t;
	},
	setCharCounter: function() {
		var myStr = new String(this.slideIn.getElement('.blocked').get('html'));
		strlength = myStr.length + 1;
		var text = maxlength - strlength + ' characters remaining';
		$('charcount').set('text', text);
	},
	updateCharCount: function() {
		inputText = this.textarea.get('value');
		var maxallowed = maxlength - strlength;
		var textlength = maxallowed - inputText.length;
		var text = textlength + ' characters remaining';
		$('charcount').set('text', text);
		if (textlength < 0) {
			$('js_sendbutton').addClass('disabled');
			$('charcount').setStyle('color', '#ff6600');
		} else if (textlength >= 0) {
			$('js_sendbutton').removeClass('disabled'); 
			$('charcount').setStyle('color', '#333333');
		}
	},
	sendForm: function(e) {
		if (this.textarea.get('value') == '' || $('js_sendbutton').hasClass('disabled')) {
			e.preventDefault();
		} else {
			var myStr = new String(this.slideOut.getElement('.blocked').get('html'));
			var action = this.form.get('action') + myStr;
			this.form.set('action', action);
			this.form.send();
			window.parent.location.href = action;
		}
	}
});

/* --- tabbed menu for place edit overlay page --- */

var setTabs = function() {
	 //if ($('js_status').get('value') == 'mapped') showinfo();
	 //else
	 showaddress();
}

var showinfo = function() {
	$('editaddress').setStyle('display', 'none');
	$('editinfo').setStyle('display', 'block');
	$('naveditaddress').removeClass('tabon');
	$('naveditaddress').addClass('taboff');
	$('naveditinfo').removeClass('taboff');
	$('naveditinfo').addClass('tabon');
	var addressparent = $('naveditaddress').getParent('li');
	addressparent.removeClass('navon');
	addressparent.addClass('navoff');
	var infoparent = $('naveditinfo').getParent('li');
	infoparent.removeClass('navoff');
	infoparent.addClass('navon');
}

var showaddress = function() {
	$('editaddress').setStyle('display', 'block');
	$('editinfo').setStyle('display', 'none');
	$('naveditaddress').removeClass('taboff');
	$('naveditaddress').addClass('tabon');
	$('naveditinfo').removeClass('tabon');
	$('naveditinfo').addClass('taboff');
	var addressparent = $('naveditaddress').getParent('li');
	addressparent.removeClass('navoff');
	addressparent.addClass('navon');
	var infoparent = $('naveditinfo').getParent('li');
	infoparent.removeClass('navon');
	infoparent.addClass('navoff');
}

var closeOverlay = function() {
	parent.SqueezeBox.close();
}

var submitForm = function() {
	alert('some kind of form validation required');
	parent.SqueezeBox.close();
}

/* --- accordion creator --- */

var launchAccordion = function() {
	var togglers = new Array();
	var cnt;
	var acc = new Accordion('h3.toggler', 'div.js_content', {
		opacity: false,
		onActive: function(toggler, element) {
			toggler.addClass("open");
		},
		onBackground: function(toggler, element) {
			togglers[cnt] = toggler;
			cnt++;					
		},
		onComplete: function(toggler, element) {
			var i;
			for (i = 0; i < togglers.length; i++) {
				togglers[i].removeClass("open");
			}
			togglers.length = 0;
			cnt = 0;				
		}
	});
}; 

/* --- captcha creator --- */

var captcha = function() {
	var rand = $random(0, 100000000000000000)/100000000000000000;
	$('js_captcha').src = '/img/captcha.png?' + rand;
	return false;
}

/* --- GMapping class for Google maps --- */

var GMapping = new Class({
	initialize: function(map, size, xml_file, city, lat, lng, zoom){

		window.addEvent('unload', GUnload);
		if (GBrowserIsCompatible()) {

			var map = new GMap2($(map));
			map.setCenter(new GLatLng(lat, lng), zoom);

			if (size == 'small') map.addControl(new GSmallMapControl());
			else map.addControl(new GLargeMapControl());

			map.disableDoubleClickZoom();

			var mgr = new MarkerManager(map);

			if (xml_file == '') {

				var batch = [];
				var marker = new GMarker(new GLatLng(lat, lng));
				batch.push(marker);
				mgr.addMarkers(batch, 11);
				mgr.refresh();
			} else {
				var xmlfile = xml_file + '?dt=' + $time();
				GDownloadUrl(xmlfile, function(data, responseCode) {
					var batch = [];
					var xml = GXml.parse(data);
					var markers = xml.documentElement.getElementsByTagName("marker");
					var point = null;
					var marker = null;
					var place = '';
					var myHtml = '';
					for (var i = 0; i < markers.length; i++) {
						point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
						marker = new GMarker(point);
						marker.value = i+1;
						place = markers[i].getAttribute("place");
						myHtml = '<a href="http://www.thumbprintcity.com/' + city + '/' + place + '">' + place.substring(0, 1).toUpperCase() + place.substring(1); + '</a>' + ' ' + markers[i].getAttribute("blurb");
						GEvent.addListener(marker, "click", function() {
							windowOptions = { maxWidth:200 };
							map.openInfoWindowHtml(point, myHtml, windowOptions);
						});
						batch.push(marker);
					}
					mgr.addMarkers(batch, 11);
					mgr.refresh();
				});
			}
		}

	}
});

/* --- ### --- */

var runTabs = function() {
	$('tabplaces').addEvents({
		'mouseenter': placeson,
		'mouseleave': placesoff
	});
	$('navplaces').addEvents({
		'mouseenter': placeson,
		'mouseleave': placesoff
	}); 
	//$('tabsignin').addEvents({
	//	'mouseenter': signinon,
	//	'mouseleave': signinoff
	//});
	if ($('navsignin')) {
		$('navsignin').addEvents({
			'mouseenter': signinon,
			'mouseleave': signinoff
		}); 
	}
}

/* --- ### --- */

var runOverlay = function() {
	SqueezeBox.assign($$('.js_launch'), {
		parse: 'rel'
	});
}

/* --- ### --- */

var runCounter = function() {
	setCharCounter();

	$('messageinput').addEvent('keyup', function() {
		updateCharCount();
		messageForm();
	});
}

/* --- ### --- */

var runCaptcha = function() {
	if ($('js_refresh')) {
		var action = $('js_refresh').addEvent('click', captcha);
	}
}

/* --- ### --- */

var runCreatePlace = function() {
	$('js_cancel').addEvent('click', closeOverlay); 
	$('js_submit').addEvent('click', function() {
		var place = $('js_newplace').get('value');
		// need to strip non-alphanumerics from place and message
		var message = $('js_firstmessage').get('value');
		if (place.length < 3) {
			alert('The place name must have at least 3 characters');
		} else if (message.length == 0) {
			alert('You need to write a message!');
		} else if (message.length < 3) {
			alert('Your message needs at least 3 characters!');
		} else {
			if ($('user_status').get('value') == 'signed_in') {
				var req = new Request({  
					method: 'post',  
					url: $('js_city').get('value') + '/ajaxcreateplace/',  
					data: { 'newplace' : place, 'message' : message },  
					onComplete: function(response) { 
						if (response != ''){
							var page = $('js_city').get('value');
							window.parent.location.href = page;
						}
						parent.SqueezeBox.close();
					}
				}).send(); 
			} else {
				var req = new Request({  
					method: 'post',  
					url: $('js_city').get('value') + '/ajaxholdplace/',  
					data: { 'place' : place, 'message' : message },  
					onComplete: function(response) { 
						if (response != ''){
							var page = $('js_city').get('value') + '/register/' + response;
							window.parent.location.href = page;
						}
						parent.SqueezeBox.close();
					}
				}).send(); 
			}
		}
	});
}

/* --- ### --- */
var closeButtons = function() {
	var buttons = $$('.js_close');
	buttons.each(function(button) {
		button.addEvent('click', function(e) {
			e.stop();
			parent.SqueezeBox.close();
		});
	});
}

var runEditPlace = function() {
	setTabs();
	$('naveditaddress').addEvent('click', showaddress);
	$('naveditinfo').addEvent('click',showinfo);
	$('js_cancel').addEvent('click', closeOverlay); 
	$('js_submit').addEvent('click', function(e) {
		e.stop();
		var tsr = $('js_heading').get('value');
		if (tsr.length > 120) {
			alert('Please keep questions under 120 characters in length');
		} else {
			var req = new Request({
				method: 'post',  
				url: '/' + $('js_city').get('value') + '/ajaxeditplace/' + $('js_form_place').get('value'),  
				data: { 'building' : $('js_building').get('value'), 'street' : $('js_street').get('value'), 'postcode' : $('js_postcode').get('value'), 'tel' : $('js_tel').get('value'), 'email' : $('js_email').get('value'), 'web' : $('js_web').get('value'), 'details' : $('js_details').get('value'), 'heading' : $('js_heading').get('value'), 'latitude' : $('js_lat').get('value'), 'longitude' : $('js_long').get('value'), 'status' : $('js_status').get('value')},
				//onRequest: function() { alert('Request made. Please wait...'); },  
				onComplete: function(response) {
					//alert('Response: ' + response);
					if (response == ''){
						alert('Sorry. An error occured. Please try saving your information again.');
					} else if (response == 'no data') {
						parent.SqueezeBox.close();
					} else {
						var page = '/' + $('js_city').get('value') + '/' + $('js_form_place').get('value');
						window.parent.location.href = page;
						parent.SqueezeBox.close();
					}
				}
			}).send();
		}
	});
}

var ImageTabs = new Class({
	Implements: [Options, Events],
	options: {
		selected: '0', // the panel to be shown by default
		position: '0px 0px',
		hoverposition: '0px -200px',
		selectedposition: '0px -100px'
	},
	initialize: function(tabs, panels, opts) {
		this.setOptions(opts);
		this.tabs = $$(tabs);
		this.panels = $$(panels);
		if (this.tabs.length > 0) {
			this.attach();
			this.displaymain();
			this.switchtabs();
		}
	},
	attach: function() {
		this.tabs.each(function(tab, index){
			tab.addEvent('click', function(event){
				event.preventDefault();
				this.options.selected = index;
				this.displaymain();
				this.switchtabs();
			}.bind(this));
			tab.addEvent('mouseover', function(){
				tab.setStyle('background-position', this.options.hoverposition);
			}.bind(this));
			tab.addEvent('mouseout', function(){
				if (this.options.selected == index) {
					tab.setStyle('background-position', this.options.selectedposition);
				} else {
					tab.setStyle('background-position', this.options.position);
				}
			}.bind(this));
		}, this);
	},
	displaymain: function() {
		this.panels.each(function(panel) {
			panel.setStyle('display', 'none');
		}, this);
		var elem = this.panels[this.options.selected];
		elem.setStyle('display', 'block');
	},
	switchtabs: function() {
		this.tabs.each(function(tab) {
			tab.setStyle('background-position', this.options.position);
		}, this);
		var elem = this.tabs[this.options.selected];
		elem.setStyle('background-position', this.options.selectedposition);
	}
});

var setCharCounter = function() {
	if ($('js_placetitle'))
	{
		var myStr = $('js_placetitle').get('html');
		strLength = myStr.length + 1;
		var text = maxLength - strLength + ' characters remaining';
	}
	else
	{
		var text = maxLength + ' characters remaining';
	}
	$('charcount').set('text', text);
};

var updateCharCount = function() {
	inputText = $('messageinput').get('value');
	var maxallowed = maxLength - strLength;
	textLength = maxallowed - inputText.length;
	var text = textLength + ' characters remaining';
	$('charcount').set('text', text);
	if (textLength < 0) {
		$('charcount').setStyle('color', '#ff6600');
		if ($('js_add_message_button')) $('js_add_message_button').addClass('disabled');
	} else {
		$('charcount').setStyle('color', '#333333');
		if ($('js_add_message_button')) $('js_add_message_button').removeClass('disabled');
	}
};

var messageForm = function() {
	if ($('js_sendmessage_place')) {
		$('js_sendmessage_place').addEvent('submit', function(e) {
			if (textLength < 0) e.stop();
		});
	}
}

window.addEvent('domready', function(){
	closeButtons();
});