//************************************************************************************************
//********* NUMBER.prototype *********************************************************************
//************************************************************************************************

//Number.toInteger() - Returns this number; useful because toInt must work on both Strings and Numbers.
//http://docs.mootools.net/Native/Number.js
if (typeof Number.prototype.toInteger !== 'function') {
	Number.prototype.toInteger = function () {
		return parseInt(this);
	};
};

//Number.random() - Returns a random number.
if (typeof Number.prototype.random !== 'function') {
	Number.prototype.random = function () {
		return Math.floor(Math.random() * this);
	};
};

//************************************************************************************************
//********* STRING.prototype *********************************************************************
//************************************************************************************************

//String.trim() - Give string object the trim method.
//http://www.webtoolkit.info/javascript-trim.html
if (typeof String.prototype.trim !== 'function') {
	String.prototype.trim = function() {
		return this.replace(/^\s+|\s+$/g, '');
	};
};

//String.replaceAll() - Replaces all instances of the given substring.
//http://dynamic-tools.net/toolbox/replaceAll/
if (typeof String.prototype.replaceAll !== 'function') {
	String.prototype.replaceAll = function(_this, _that) {
		return this.replace(new RegExp(_this,"g"), _that);
	};
};

//String.toInteger() - Parses a string to an integer.
//http://docs.mootools.net/Native/String.js
if (typeof String.prototype.toInteger !== 'function') {
	String.prototype.toInteger = function () {
		return parseInt(this, 10);
	};
};

// String.namespace() - Creates an object namespace chain extended from $object and delimited by the $separator.
// http://ajaxian.com/archives/namespaced-made-easy-with-prototype
// http://pastie.caboo.se/147291
if (typeof String.prototype.namespace !== 'function') {
	String.prototype.namespace = function(object, separator) {
		this.split(separator || '.').inject(object||window, function(parent, child) {
			return parent[child] = parent[child] || { };
		});
	};
};

// ************************************************************************************************
// ********* SPAFINDER.prototype ******************************************************************
// ************************************************************************************************

var spafinder = {
	Array: {
		// http://www.safalra.com/programming/javascript/queues/
		Queue: function() {
			var queue = new Array();
			var space = 0;
			this.enqueue = function(element) {
				queue.push(element);
			};
			this.dequeue = function() {
				if ( queue.length ) {
					var element = queue[space];
					if ( ++space * 2 >= queue.length ) {
						for ( var i=space; i<queue.length; i++ ) {
							queue[i-space] = queue[i];
						}
						queue.length -= space;
						space = 0;
					}
					return element;
				} else {
					return undefined;
				}
			};
		}
	},
	Window: {
		opened: [],
		open: function(url, options) {
			this.options = Object.extend({
				url: (url || '#'),
				name: '_NAME_',
				width: 800,
				height: 600,
				left: Math.floor((screen.availWidth - (this.width || screen.width)) / 2) - (screen.width - screen.availWidth),
				top: Math.floor((screen.availHeight - (this.height || screen.height)) / 2) - (screen.height - screen.availHeight),
				dependent: 'no',
				directories: 'no',
				fullscreen: 'no',
				location: 'no',
				menubar: 'no',
				resizable: 'no',
				scrollbars: 'no',
				status: 'no',
				toolbar: 'no',
				opener: ''
			}, options || {});
			
			if ( this.options.fullscreen.toLowerCase() == 'yes' ) {
				this.options.width = screen.availWidth - 10;
				this.options.height = screen.availHeight - 30;
				this.options.left = 0;
				this.options.top = 0;
			}
			if ( this.options.left < 0 ) {
				this.options.left = 0;
			}
			if ( this.options.top < 0 ) {
				this.options.top = 0;
			}
			
			// ie 4.5 and 5.0 mac - windows are 2 pixels too short; if a statusbar is used, the window will be an additional 15 pixels short
			var agent = navigator.userAgent.toLowerCase();
			if ( ((agent.indexOf("mac") != -1)
				&& (agent.indexOf("msie") != -1)
				&& ((agent.indexOf("msie 4") != -1))
				|| (agent.indexOf("msie 5.0") != -1)) ) {
				this.options.height += ( this.options.status ? 17 : 2);
			}
			
			var properties = 'width=' + this.options.width + ',height=' + this.options.height;
			properties += ',screenX=' + this.options.left + ',screenY=' + this.options.top;
			properties += ',left=' + this.options.left + ',top=' + this.options.top;
			properties += ',dependent=' + this.options.dependent + ',directories=' + this.options.directories;
			properties += ',location=' + this.options.location + ',fullscreen=' + this.options.fullscreen;
			properties += ',menubar=' + this.options.menubar + ',resizable=' + this.options.resizable;
			properties += ',scrollbars=' + this.options.scrollbars + ',status=' + this.options.status;
			properties += ',toolbar=' + this.options.toolbar;
			
			var reference = window.open(this.options.url, this.options.name, properties);
			
			if ( window.focus ) {
				reference.focus();
			}
			
			if ( this.options.opener && window.top ) {
				window.top.name = this.options.opener;
			}
			
			spafinder.Window.opened[reference] = this;
			return reference;
		}
	},
	Cookie: {
		get: function(name) {
			var arg = name + "=",
			alen = arg.length,
			clen = document.cookie.length,
			i = 0;
			while ( i < clen ) {
				var j = i + alen;
				if ( document.cookie.substring(i, j) == arg ) {
					var endstr = document.cookie.indexOf(";", j);
					if ( endstr == -1 ) {
						endstr = document.cookie.length;
					}
					return unescape(document.cookie.substring(j, endstr));
				}
				i = document.cookie.indexOf(" ", i) + 1;
				if ( i == 0 ) {
					break;
				}
			}
			return null;
		},
		set: function(name, value) {
			var argv = arguments,
			argc = arguments.length,
			expires = (argc > 2) ? argv[2] : null,
			path = (argc > 3) ? argv[3] : null,
			domain = (argc > 4) ? argv[4] : null,
			secure = (argc > 5) ? argv[5] : false;
			document.cookie = name + "=" + escape(value) +
			((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
			((path == null) ? "" : ("; path=" + path)) +
			((domain == null) ? "" : ("; domain=" + domain)) +
			((secure == true) ? "; secure" : "");
		},
		remove: function(name) {
			var argv = arguments,
			argc = arguments.length,
			path = (argc > 1) ? argv[1] : null,
			domain = (argc > 2) ? argv[2] : null,
			secure = (argc > 3) ? argv[3] : false,
			cval = spafinder.Cookie.get(name),
			exp = new Date();
			exp.setTime(exp.getTime() - 1000000000);
			document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString() +
			((path == null) ? "" : ("; path=" + path)) +
			((domain == null) ? "" : ("; domain=" + domain)) +
			((secure == true) ? "; secure" : "");
		}
	},
	Document: {
		getDefaultImage: function(element, url) {
			if ( (typeof(element) != 'undefined') && (element !== null) ) {
				if ( (typeof(element.onErrored) == 'undefined') || (element.onErrored == null) ) {
					if (!url && element.src && (element.src.indexOf('javascript:') == -1)) {
						url = element.src.replace(/(\d{0,})\/(prm|large)/, 'default');
						if ( (url.indexOf('144x100') != -1) || (url.indexOf('80x67') != -1)|| (url.indexOf('184x69') != -1) ) {
							url = url.replace('.jpg', '/0' + ((8).random() + 1) + '.jpg');
						}
					}
					if (url) {
						element.src = url;
						element.setAttribute('onErrored', true);
						element.onErrored = true;
					}
				}
			}
		},
		stars: function(element, rating, options) {
			var img = new Image(),
			settings = jQuery.extend(true, {
				ratedUrl: '/assets/images/common/star-blue-10x9.gif',
				ghostUrl: '/assets/images/common/star-gray-10x9.gif'
			}, options);
			img.onload = function(options){
				var markup = '<div style="width:'+(5*this.width)+'px;background:transparent url('+settings.ghostUrl;
				markup += ') 0 0 repeat-x;"><div style="width:'+(rating*this.width)+'px;height:'+this.height;
				markup += 'px;background:transparent url('+settings.ratedUrl+') 0 0 repeat-x;" /></div></div>';
				jQuery(element).html(markup);
			};
			img.src = settings.ratedUrl; //http://www.thefutureoftheweb.com/blog/image-onload-isnt-being-called
		}
	},
	Form: {
		search: function(form) {
			if ( (typeof(form) != 'undefined') && (form !== null) ) {
				var keywords = form.elements['keywords'],
				location = form.elements['location'];
				if (keywords.value == keywords.title) {
					keywords.value = '';
				}
				if (location.value == location.title) {
					location.value = '';
				}
			}
			return true;
		},
		onblur: function(element) {
			element = jQuery(element);
			if (element.val().length === 0) {
				element.val(element[0].defaultValue);
				element.css('color', element.attr('color'));
			}
		},
		onfocus: function(element) {
			element = jQuery(element);
			if (element[0].value === element[0].defaultValue) {
				element.val('').attr('color', element.css('color'));
				element.css('color', jQuery('#spafinder').css('color'));
			}
		}
	},
	classes: {
	}
};
jQuery(document).ready(function() {
		
	//add "active" class to menu items to fix IE-6 :hover pseudo-class issue
	//add "z-index" to menu to fix layering issue
	jQuery('#menu li.parent').each(function(index, element){
		jQuery(element).mouseenter(function(){
			jQuery(element).addClass('active');
			jQuery('#menu ul').css('zIndex', 2147483646);
		}).mouseleave(function(){
			jQuery(element).removeClass('active');
			jQuery('#menu ul').css('zIndex', 0);
		});
	});
	
	//add "active" class to menu items to fix IE-6 :hover pseudo-class issue
	jQuery('#header .navigation li').mouseenter(function(){
		jQuery(this).addClass('active');
	}).mouseleave(function(){
		jQuery(this).removeClass('active');
	});
	
	//add autocomplete to location fields
	jQuery(['search','localize']).each(function(index, prefix){
		var locationName = jQuery('#'+prefix+'-location'),
		locationId = jQuery('#'+prefix+'-locid');
		locationName.autocomplete({
			minLength: 2,
			source: function(request, response) {
				jQuery.ajax({
					url: "/search/locations",
					data: {autocomplete: request.term},
					success: function(data) {
						response(jQuery.map(jQuery(data).children('ul li').toArray(), function(item) {
							return {label: item.innerHTML, value: item.id};
						}));
					}
				});
			},
			focus: function(event, ui) {
				locationName.val(ui.item.label);
				locationId.val(ui.item.value);
				return false;
			},
			select: function(event, ui) {
				locationName.val(ui.item.label);
				locationId.val(ui.item.value);
				jQuery('#search-results').submit();
				return false;
			}
		});
	});
	
	//tooltip on location field
	jQuery('.not-location').click(function(){
		jQuery('#tooltip').toggle();
		jQuery('#search-location').trigger('focus');
		jQuery('#search-location').keypress(function(){
			jQuery('#tooltip').hide();
		});
	});
	jQuery('#tooltip .tooltip-close').click(function(){
		jQuery('#tooltip').hide();
	});
	
	//toggle international flags
	jQuery('.il8n').click(function(){
		jQuery('.il8n').toggleClass('flag-width', false);
		jQuery('.secondary-flags').toggle('slow');
	});
	

	//add focus to location field
	try {
		var where = jQuery('#search-location');
		if (where.val() === where.attr('title')) {
			where.focus();
		}
	} catch(e) {}
	
});
