// Framebreak
if (top.location!= self.location) { 
	top.location = self.location.href 
}

// Window size
var wsize = window.getSize();
Cookie.write('ssize', wsize.x+','+wsize.y, {'path':'/', 'duration':3600});


function value_of_radios(els)
{
	if (!els.length) return els.value;
	
	for(i=0;i<els.length;i++) if (els[i].checked) return els[i].value;
	
	return null;
}


var Wr = {
	
	init : function()
	{
		//alert('Hi');
		this.is_ie6 = (Browser.Engine.trident && (Browser.Engine.version<5)) || false;
	},
	
	isLoggedIn : function()
	{
		return (wr_user_id != null);
	},
	
	getUserId : function()
	{
		return wr_user_id;
	},
	
	showLoginPopup : function(return_url)
	{
		return_url = return_url || '';
		
		Popup.show('Sorry...', 400, 260);
		Popup.displayInlineUrl('/interface/loginSignupPopup?forward_url='+escape(return_url));
	},
	
	adnetSignLinks : function(root)
	{
		var create_cb = function(url)
		{
			var ret = function(ev){
				pageTracker._trackPageview(url);
			};
			
			return ret;
		}
		root = root || $(document.body);
		
		var links = root.getElements('.adnet');
		
		links.each(function(el){
			el.href += verify;			
			
			var goal_url = el.href.replace('http://adnet.worldreviewer.com/adnet/click/ad/wr/', '');
			goal_url = goal_url.replace(/\?.*/, '');
			goal_url = '/goal/'+goal_url;
			el.addEvent('click', create_cb(goal_url));
		});
	},
	
	showNewsletterPopup : function(type)
	{
		this.newsletter_type = type;
		Popup.show('Newsletter', 400, 270);
		var el = Popup.getContentElement();
		
		el.innerHTML = '<div style="padding:8px;font-size:medium;"><div style="padding: 10px;">Subscribe to our newsletter to receive our latest travel deals.	</div><table><tr><td style="vertical-align:top">Email address:</td><td><input id="newsletter_form_email" type="text" class="text" size="30" /></td></tr><tr><td>&nbsp;</td><td><input type="button" onclick="Wr.submitNewsletterForm()" value="Subscribe" /><input type="button" value="No thanks!" onclick="Popup.close()" /></td></tr></table><p style="font-size:small;color:#666;padding: 0 10px">We send the email approximately once a week. You can unsubscribe at any time.</p></div>';
	},
	
	
	submitNewsletterForm : function()
	{
		var el = $('newsletter_form_email');
		var email = el.value;
		
		if (!Wr.util.isValidEmail(email))
		{
			var er_el = new Element('div');
			er_el.className = 'error';
			er_el.style.fontSize = 'small';
			er_el.innerHTML = 'Please enter a valid email address';
			er_el.injectAfter(el);
		} else {
			var url = '/interface/newsletter/signup/';
			
			var data = {
				'email' : email,
				'type' : this.newsletter_type
			};
			
			Wr.util.sendRequest(url, 'post', null, data);
			Popup.close();
		}
	}
}


Wr.util = {};

Wr.util.sendRequest = function(url, method, callback_ok, data, callback_fail)
{
	method = method || 'get';
	callback_ok = callback_ok || function(){};
	callback_fail = callback_fail || function(){};
	data = data || {};

	data = Hash.toQueryString(data);

	var myreq = new Request({
		method: method,
		url : url,
		onSuccess : callback_ok,
		onFailure : callback_fail
	});
	myreq.send(data);
}

Wr.util.sendRequestJson = function(url, method, callback_ok, data, callback_fail)
{
	method = method || 'get';
	callback_ok = callback_ok || function(){};
	callback_fail = callback_fail || function(){};
	data = data || {};

	data = Hash.toQueryString(data);

	var myreq = new Request.JSON({
		method: method,
		url : url,
		onSuccess : callback_ok,
		onFailure : callback_fail
	});
	myreq.send(data);
}

Wr.util.loadInto = function(url, el, cb)
{
	cb = cb || null;
	Wr.util.showLoading(el);
	
	var fn = function(response)
	{
		Wr.util.hideLoading(el);
		el.innerHTML = response;
		
		if (cb) cb();
	}
	
	Wr.util.sendRequest(url, 'get', fn);
}


Wr.util.showLoading = function(el, message)
{
	message = message || 'Loading...';
	
	if (!el._loading_element){
		var div = new Element('div');
		document.body.appendChild(div);
		div.innerHTML = message;
		var co = el.getCoordinates();
		div.style.top = co.top+'px';
		div.style.left = (co.right-150)+'px';
		div.className = 'ui-loading';
		el._loading_element = div;
	}
	
	el._loading_element.style.display = 'block';
}

Wr.util.hideLoading = function(el)
{
	if (!el._loading_element) return;
	
	el._loading_element.style.display = 'none';
}


Wr.util.formElementError = function(el, message)
{
	el = $(el);
	//return;
	message = message.trim();
	var error_el = el.retrieve('error_element', null);
	
	if (!error_el){
		error_el = new Element('div');
		error_el.set('class', 'error');
		error_el.injectAfter(el);
		el.store('error_element', error_el);
	}
	
	if (message)
	{
		error_el.setStyle('display', 'block');
		error_el.set('text', message);
	} else {
		error_el.setStyle('display', 'none');
	}
}

// If the element is not on the screen, smooth scroll to it
Wr.util.smoothScrollTo = function(el)
{
	el = $(el);
	var coords = el.getCoordinates();
	var top = coords.top;
	var bottom = coords.bottom;
	
	var window_scroll = window.getScroll();
	var window_size = window.getSize();
	
	var window_top = window_scroll.y;
	var window_bottom = window_scroll.y+window_size.y;
	
	if (top < window_top) Wr.util.smoothScroll(window, window_scroll.x, top);
	if (bottom > window_bottom) Wr.util.smoothScroll(window, window_scroll.x, top);
}

Wr.util.smoothScroll = function(el, x, y)
{
	var fx = new Fx.Scroll(el);
	fx.start(x,y);
}

Wr.util.isValidEmail = function(email)
{
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	return filter.test(email);
}

var InteractionBar = {
	
	init : function()
	{
		if(!$('interaction-bar')) return;
		
		if (!Wr.is_ie6) {
			var el = new Element('div');
			this.tooltip = el;
			el.id = 'interaction-bar-tooltip';
			this.hideTooltip();
			$(document.body).appendChild(el);
			
			this.el = $('interaction-bar');
			var links = this.el.getElements('a');
			links.each(function(link){
				link.store('title', link.get('title'));
				link.set('title', '');
			});
				
			links.addEvent('mouseover', this.buttonHovered.bind(this));
			links.addEvent('mouseout', this.buttonDehovered.bind(this));
		}
	},
	
	buttonHovered : function(ev)
	{
		ev = new Event(ev);
		ev.stop();
		this.showTooltip(ev.target);
	},
	
	buttonDehovered : function(ev)
	{
		this.hideTooltip();
	},
	
	hideTooltip : function()
	{
		if (Wr.is_ie6) return;
		this.tooltip.setStyle('display', 'none');
	},
	
	showTooltip : function(el)
	{
		el = $(el);
		
		if (Wr.is_ie6) return;
		this.tooltip.setStyle('display', 'block');
		this.tooltip.innerHTML = '<div></div>'+el.retrieve('title');
		
		var tw = this.tooltip.getWidth();
		
		var cos = el.getCoordinates();
		var x = (cos.left+cos.width/2)-(tw/2);
		this.tooltip.setStyle('left', x+'px');
	},
	
	jumpto : function()
	{
		Popup.show('World Reviewer sitemap', 780, 360);
		Popup.displayInlineUrl('/sitemap/popup/');
	}
	
}

var Popup = {
	
	els : {
		matte : null,
		win : null,
		shadow : null,
		titlebar : null
	},
	
	show : function(title, width, height)
	{
		var is_ie6 = (Browser.Engine.trident && (Browser.Engine.version<5)) || false;
		
		var header_height = 40;
		var height = height+header_height;
		
		var w_width = window.getWidth();
		var w_height = window.getHeight();
		
		var footer = $('page-footer');
		var footer_height = footer ? footer.getHeight() : 0;
		
		var d_width = document.getWidth();
		var d_height = $('page').getHeight()+footer_height;
		
		var scroll = window.getScroll();
		var w_top = scroll.y;
		var w_left = scroll.x;
				
		var top = (w_height/2)-(height/2);
		var left = (w_width/2)-(width/2);
		
		var s_width = 8;
		
		if (!this.els.matte) 
		{
			var matte = new Element('div');
			matte.className = 'popup-matte';
			this.els.matte = matte;
			matte.addEvent('click', this.close.bind(this));
			document.body.appendChild(matte);
		}
		
		if (is_ie6) {
			matte = this.els.matte;
			matte.style.position = 'absolute';
			matte.style.top = '0px';
			matte.style.left = '0px';
			matte.style.width = d_width+'px';
			matte.style.height = d_height+'px';
			matte.set('opacity', 0.5);
		}
		
		if (!this.els.win) 
		{
			var win = new Element('div');
			win.className = 'popup-window';
			this.els.win = win;
			document.body.appendChild(win);
			
			var titlebar = new Element('div');
			titlebar.className = 'popup-window-titlebar';
			win.appendChild(titlebar);
			
			var btn_close = new Element('span');
			btn_close.innerHTML = 'Close';
			btn_close.className = 'popup-close';
			btn_close.addEvent('click', this.close.bind(this));
			titlebar.appendChild(btn_close);
			
			var el_title = new Element('div');
			titlebar.appendChild(el_title);
			this.els.titlebar = el_title;
			
			var el_content = new Element('div');
			el_content.setStyle('overflow', 'hidden');
			win.appendChild(el_content);
			this.els.content = el_content;
			
			var iframe = new Element('iframe');
			this.els.iframe = iframe;
			iframe.style.zIndex = 70;
			iframe.setStyle('position', 'fixed');
			document.body.appendChild(iframe);
		}
		this.els.content.innerHTML = '';
		this.els.content.style.height = (height-header_height)+'px';
		
		var win = this.els.win;
		var iframe = this.els.iframe;
		
		win.style.width = width+'px';
		win.style.height = height+'px';
		iframe.style.width = width+'px';
		iframe.style.height = height+'px';
		
		if (is_ie6) {
			win.style.position = 'absolute';
			win.style.top = (w_top+top)+'px';
			win.style.left = left+'px';		
		} else {
			win.style.top = top+'px';
			win.style.left = left+'px';
			iframe.style.top = top+'px';
			iframe.style.left = left+'px';
		}
		
		if (!this.els.shadow) 
		{
			var shadow = new Element('div');
			shadow.className = 'popup-shadow';
			this.els.shadow = shadow;
			document.body.appendChild(shadow);
		}
		var shadow = this.els.shadow;
		shadow.style.width = (width+(s_width*2))+'px';
		shadow.style.height = (height+(s_width*2))+'px';
		if (is_ie6) {
			shadow.style.position = 'absolute';
			shadow.style.top = ((top-s_width)+w_top)+'px';
			shadow.style.left = (left-s_width)+'px';
		} else {
			shadow.style.top = (top-s_width)+'px';
			shadow.style.left = (left-s_width)+'px';
		}
		
		
		this.els.matte.style.display = '';
		this.els.win.style.display = '';
		this.els.shadow.style.display = '';
		this.els.titlebar.innerHTML = title+'&nbsp;';
	},
	
	getContentElement : function()
	{
		return this.els.content;
	},
	
	close : function()
	{
		this.els.iframe.style.display = 'none';
		this.els.matte.style.display = 'none';
		this.els.win.style.display = 'none';
		this.els.shadow.style.display = 'none';
	},
	
	displayInlineUrl : function(url)
	{
		this.setLoading(true);
		
		var myreq = new Request({
			method: 'get',
			url : url,
			onSuccess : this.inlineLoadComplete.bind(this),
			onError : this.loadError.bind(this)
		});
		myreq.send();
	},
	
	inlineLoadComplete : function(html)
	{
		this.setLoading(false);
		this.els.content.innerHTML = html;
	},
	
	loadError : function() {
		this.setLoading(false);
		this.els.content.innerHTML = 'Error...';
	},
	
	setLoading : function(is_loading)
	{
		if (is_loading)
			this.els.titlebar.addClass('popup-loading');
		else
			this.els.titlebar.removeClass('popup-loading');	
	}
}

/**
 *	Tabbed sections
 */
 
var TabbedSection = new Class({
	
	Implements: Events,
	
	initialize : function(el)
	{
		if (!el) return;
		this.el_ul = el;
		this.el_lis = el.getElements('li');
		
		for(var i=0;i<this.el_lis.length;i++) 
		{
			var link = this.el_lis[i].getFirst();
			link.addEvent('click', this.tabClicked.bind(this));
		}
	},
	
	tabClicked : function(ev)
	{
		ev = new Event(ev);
		
		this.setTabElement(ev.target.getParent());
		ev.stop();
	},
	
	setTabElement : function(selected_li)
	{
		for(var i=0;i<this.el_lis.length;i++) 
		{
			var li = this.el_lis[i];
			li.className = (selected_li == li) ? 'selected' : '';
		}
		
		var a_href = selected_li.getFirst().href.split('#')[1];
		
		this.fireEvent('changed', [selected_li, a_href]);
	}
});

var SimilarExperienceBlock = {
	
	init : function()
	{
		var el = $('similar-tabs');
		this.tabs = new TabbedSection(el);
		this.content = el.getParent().getNext();
		
		this.tabs.addEvent('changed', this.tabChanged.bind(this));
	},
	
	tabChanged : function(li, tab_id)
	{
		this.setLoading(true);
		
		var parts = tab_id.split(':');
		var tab_id = parts[1];
		
		var item_id = wr_item_id;
		var same_country = (tab_id == 'country') ? '&same_country=1' : '';
		
		var url = '/interface/similar/experiences?item_id='+item_id+same_country;
	
		this.setLoading(true);
		
		var myreq = new Request({
			method: 'get',
			url : url,
			onSuccess : this.loadContentCompleate.bind(this)
		});
		myreq.send();
	},
	
	setLoading : function(is_loading)
	{
		is_loading ? Wr.util.showLoading(this.content) : Wr.util.hideLoading(this.content);
	},
	
	loadContentCompleate : function(html)
	{
		this.setLoading(false);
		this.content.innerHTML = html;
	}
}

var WhatsNearbyBlock = {
	
	init : function()
	{
		var el = $('nearby-tabs');
		this.tabs = new TabbedSection(el);
		this.content = el.getParent().getNext();
		
		this.tabs.addEvent('changed', this.tabChanged.bind(this));	
	
	},
	
	tabChanged : function(li, tab_id)
	{
		this.setLoading(true);
		
		var parts = tab_id.split(':');
		var tab_id = parts[1];
		
		var path = wr_nearby_info[0];
		var lat = wr_nearby_info[1];
		var lng = wr_nearby_info[2];
		var item_id = wr_nearby_info[3];
		
		
		var url = '/interface/nearby/'+tab_id+'?path='+path+'&lat='+lat+'&lng='+lng+'&item_id='+item_id;
	
		this.setLoading(true);
		
		var myreq = new Request({
			method: 'get',
			url : url,
			onSuccess : this.loadContentCompleate.bind(this)
		});
		myreq.send();
	},
	
	setLoading : function(is_loading)
	{
		is_loading ? Wr.util.showLoading(this.content) : Wr.util.hideLoading(this.content);
	},
	
	loadContentCompleate : function(html)
	{
		this.setLoading(false);
		this.content.innerHTML = html;
	}
}

var WallBlock = {
	
	init : function()
	{
		var el = $('wall-tabs');
		
		if (el)
		{
			this.tabs = new TabbedSection(el);
			
			this.tab_showing = 'all';
			this.tabs.addEvent('changed', this.tabChanged.bind(this));
		} else {
			$$('.wall-form-row-radios').setStyle('display', 'none');
			this.tab_showing = 'all';
		}
		
		this.content = $('wall-content');
		
		this.initForm();
	},
	
	smoothScrollTo : function()
	{
		Wr.util.smoothScrollTo(this.content);
	},
	
	tabChanged : function(el, tab_id)
	{
		var parts = tab_id.split(':');
		this.tab_showing = parts[1];
		
		this.reload();
	},
	
	reload : function()
	{	
		this.setLoading(true);
		var g_id = data_WallBlock.g_id;

		var url = '/interface/wall/render/'+g_id+'?show='+this.tab_showing;
		
		Wr.util.sendRequest(url, 'get', this.loadContentCompleate.bind(this));
	},
	
	loadContentCompleate : function(html)
	{
		this.setLoading(false);
		
		this.content.innerHTML = html;
		
		this.initForm();
		
		if (this.after_load_callback) this.after_load_callback();
		this.after_load_callback = null;
	},
	
	setLoading : function(is_loading, el, message)
	{
		el = el || this.content;
		
		is_loading ? Wr.util.showLoading(el,message) : Wr.util.hideLoading(el,message);
	},
	
	// Main form
	
	initForm : function()
	{
		var form = $('wall-form');
		this.form = form;
			
		// Radios
		var radios = form.getElements('input[type=radio]');
		radios.addEvent('click', this.formRadioChanged.bind(this));
		this.formRadioChanged();		
		
		// Hide email / name form if logged in
		if (Wr.isLoggedIn()) form.getElement('.wall-form-row-user').setStyle('display', 'none');
	},
	
	formRadioChanged : function()
	{
		var titles = {
			'REVIEW' : 'Review title',
			'COMMENT' : '',
			'QUESTION' : 'Your question'
		};
		
		var bodies = {
			'REVIEW' : 'Your review',
			'COMMENT' : 'Your comment',
			'QUESTION' : 'Question detail'
		};
		
		var value = value_of_radios(this.form.type);
		
		$$('.wall-form-row-rating').setStyle('display', (value != 'REVIEW') ? 'none' : 'block');
		
		$$('.wall-form-row-title').setStyle('display', (value == 'COMMENT') ? 'none' : 'block');
		
		$$('.wall-form-row-title').getElement('h5').set('text', titles[value]);
		$$('.wall-form-row-body').getElement('h5').set('text', bodies[value]);
	},
	
	submitFormClicked : function()
	{
		var form = this.form;
		var type = value_of_radios(form.type);
		var title = form.title.value.trim();
		var body = form.body.value.trim();
		var rating = form.rating.value.trim();
				
		var user_name = form.user_name.value.trim();
		var user_email = form.user_email.value.trim();
				
				
		// Validate
		var valid = true;
		
		Wr.util.formElementError(form.body, '');
		Wr.util.formElementError(form.title, '');
		Wr.util.formElementError(form.rating, '');
		Wr.util.formElementError(form.user_name, '');
		Wr.util.formElementError(form.user_email, '');

		
		if (body == '')
		{
			Wr.util.formElementError(form.body, 'Please enter some text.');
			valid = false;
		}
		
		if (body.length > 0 && body.length < 20)
		{
			Wr.util.formElementError(form.body, 'Text must be at least 20 characters in length.');
			valid = false;
		}
		
		if (type != 'COMMENT' && title == '')
		{
			Wr.util.formElementError(form.title, 'Please enter some text.');
			valid = false;
		}
		
		if (type != 'COMMENT' && title.length > 0 && title.length < 5)
		{
			Wr.util.formElementError(form.title, 'Text must be at least 5 characters in length.');
			valid = false;
		}
		
		if (type == 'REVIEW' && !rating)
		{
			Wr.util.formElementError(form.rating, 'Please select a rating.');
			valid = false;
		}
		
		if (!Wr.isLoggedIn()) {
			if (user_name == '')
			{
				Wr.util.formElementError(form.user_name, 'Please enter your name. This name will be visible to others.');
				valid = false;
			}

			if (user_name.length > 0 && user_name.length < 5)
			{
				Wr.util.formElementError(form.user_name, 'Your name must be at least 5 characters');
				valid = false;
			}
			
			if (user_email == '')
			{
				Wr.util.formElementError(form.user_email, 'Please enter your email. This will not be visible on the site.');
				valid = false;
			}

			if (user_email.length > 0 && (user_email.length < 5 || !Wr.util.isValidEmail(user_email)))
			{
				Wr.util.formElementError(form.user_email, 'Please enter a valid email.');
				valid = false;
			}
		}
		
		if (!valid) return;
		
		// Submit
		this.setLoading(true, this.form, 'Saving...');
		
		
		var password = null;
		if ($('need-password-box')) password = $('need-password-box').value;
		
		var data = {
			'title' : title,
			'body' : body,
			'rating' : rating,
			'type' : type,
			'verify' : verify,
			'user_name' : user_name,
			'user_email' : user_email,
			'password' : password
		};
		
		var g_id = data_WallBlock.g_id;
		var url = '/interface/wall/post/'+g_id;
		
		Wr.util.sendRequestJson(url, 'post', this.sendFormCompleate.bind(this), data);
	},
	
	sendFormCompleate : function(reply)
	{
		this.setLoading(false, this.form);
		
		if (reply.status == 'fail') alert(reply.message);
		
		if (reply.result && reply.result=='password_required') {
			
			var error = null;
			if (reply.error) error=reply.error;
			
			this.showPasswordRequest(error);
		
		} else if (reply.result && reply.result=='new_user') {

				var error = null;
				if (reply.error) error=reply.error;

				this.showNewUser(error);
		
		} else {
			this.reload();
			Wr.util.smoothScrollTo(this.content);
		}
	},
	
	// Reply form
	
	openReplyForm : function(comment_id)
	{
		if (!Wr.isLoggedIn()) return Wr.showLoginPopup(window.location.href);
		
		var el = $('comment-'+comment_id);
		
		var form = el.retrieve('reply_form', false);
		
		if (!form) 
		{
			form = this.makeReplyForm(comment_id);
			el.store('reply_form', form);
		
			form.injectAfter(el.getNext());
		} 
		
		// Scroll toif not on screen
		Wr.util.smoothScrollTo(form);
	},
	
	makeReplyForm : function(comment_id)
	{
		var outer = new Element('div');
		outer.className = 'wall-item-reply-form';
		outer.innerHTML = '<form><textarea rows="4" cols="100"></textarea><br /><input type="button" onclick="javascript:void(WallBlock.submitReplyClicked('+comment_id+'))" value="Submit" /></form>';
		
		return outer;
	},
	
	submitReplyClicked : function(comment_id)
	{
		var el = $('comment-'+comment_id);
		var form = el.retrieve('reply_form', false);
		if (!form) return;
	
		var ta = form.getElement('textarea');
		var body = ta.value.trim();
		
		if (body == '')
		{
			Wr.util.formElementError(ta, 'Please enter some text.');
			return;
		}
		
		var data = {
			'body' : body,
			'verify' : verify
		};
		
		var url = '/interface/wall/reply/'+comment_id;
		
		Wr.util.sendRequestJson(url, 'post', this.sendReplyCompleate.bind(this), data);
	},
	
	sendReplyCompleate : function(res)
	{
		if (res.stats && res.status!='ok') return;
		
		if (this.content) // Hack. If wall mode, reload, if thread page mode reload page
		{
			this.reload();
		} else {
			window.location.reload();
		}
	},
	
	// Password stuff
	showPasswordRequest : function(error)
	{
		Popup.show('Password required', 400, 200);
		Popup.displayInlineUrl('/interface/wall/password-required?error='+error);
	},
	
	passwordRequestEntered : function()
	{
		Popup.close();
		this.submitFormClicked();
	},
	
	showNewUser  : function(error)
	{
		Popup.show('Welcome!', 400, 200);
		Popup.displayInlineUrl('/interface/wall/new-user?error='+error);
	},
	
	newUserRequestEntered : function()
	{
		Popup.close();
		this.submitFormClicked();
	},
	
	scrollToForm : function()
	{
		Wr.util.smoothScrollTo(this.form);
	},
	
	scrollToQuestion : function()
	{
		this.form.type[1].checked = true;
		this.formRadioChanged();
		Wr.util.smoothScrollTo(this.form);
	}
}

var WhosBeenHereBlock = {
	
	init : function()
	{
		var el = $('whos_been_here_button');
		this.content = el.getParent('h3').getNext();
		el.addEvent('click', this.buttonClicked.bind(this));
	},
	
	beenThereAction : function()
	{
		RatingReviewPopup.showRatingPopup();
		//if (!Wr.isLoggedIn()) return Wr.showLoginPopup(window.location.href);
		
		if (Wr.isLoggedIn()) this.sendRequest('post');
	},
	
	buttonClicked : function()
	{
		this.beenThereAction();
	},
	
	updateContent : function()
	{
		this.sendRequest('get');
	},
	
	sendRequest : function(method)
	{
		this.setLoading(true);
		var g_id = data_WhosBeenHereBlock.g_id;
		
		var url = '/interface/rating/been-there/?g_id='+g_id;
		
		Wr.util.sendRequest(url, method, this.loadContentCompleate.bind(this));
	},
	
	reload : function()
	{
		this.sendRequest('get');
	},
	
	loadContentCompleate : function(html)
	{
		this.setLoading(false);
		
		this.content.innerHTML = html;
	},
	
	setLoading : function(is_loading)
	{
		is_loading ? Wr.util.showLoading(this.content) : Wr.util.hideLoading(this.content);
	}
}

var RatingReviewPopup = {
	
	showRatingPopup : function(g_id)
	{
		this.g_id = g_id || data_WhosBeenHereBlock.g_id;
		Popup.show('', 450, 300);
		Popup.displayInlineUrl('/interface/reviewPopup/rating');
	},
	
	showReviewPopup : function()
	{
		Popup.show('', 550, 378);
		Popup.displayInlineUrl('/interface/reviewPopup/review');
	},
	
	saveRatingReviewClicked : function()
	{
		var form = $('rating-review-form');
		
		// Get the data together
		var data = {};
		data.g_id = this.g_id;//data_WhosBeenHereBlock.g_id;
		data.rating = value_of_radios(form.score);
		data.title = form.title ? form.title.value : null;
		data.body = form.body ? form.body.value : null;;
		
		var errors = new Hash();
		
		// validate
		if (data.rating==null) errors.set('score', 'Please select a rating');
		
		if (data.title!=null && data.title.length<5) errors.set('title','Title must be at least 5 letters long.'); 

		if (data.body!=null && data.body.length<20) errors.set('body','Review must be at least 20 letters long.');
		
		if (errors.getLength()>0) {
			alert(errors.getValues().join("\n"));
			return;
		}
		
		// Validation ok
		this.data = data;
		
		if (Wr.isLoggedIn()) 
		{
			this.sendRequest();
		} else {
			this.popupLoginSignupForm();
		}
	},
	
	loginSignupClicked : function()
	{
		var form = $('login-signup-form');
		var data = this.data;
		
		data.login_mode = value_of_radios(form.login_mode);
		data.email = form.email.value.trim();
		data.password = form.password.value.trim();
		data.name = form.name.value.trim();
		
		var errors = new Hash();
		
		// Validate
		if (!Wr.util.isValidEmail(data.email)) errors.set('email', 'Please enter a valid email address');
		
		if (!data.password || data.password.length<5) errors.set('password','Password must be at least 5 letters long');
		
		if (data.login_mode=='join' && (!data.name || data.name.length<5)) errors.set('name','Display name must be at least 5 letters long');
		
		if (errors.getLength()>0)
		{
			alert(errors.getValues().join("\n"));
			return;
		}
		// Validation ok
		
		this.sendRequest();
	},
	
	popupLoginSignupForm : function()
	{
		Popup.show('', 550, 420);
		Popup.displayInlineUrl('/interface/loginSignupPopup/form');
	},
	
	
	sendRequest : function()
	{
		Popup.setLoading(true);
		
		var url = '/interface/review/';
		
		Wr.util.sendRequest(url, 'post', this.loadContentCompleate.bind(this), this.data, this.loadContentFail.bind(this));
	},
	
	loadContentCompleate : function(json)
	{
		Popup.setLoading(false);
		
		var response = JSON.decode(json);
		
		if (response.status=='fail')
		{	
			alert(response.message);
		} else {
			
			wr_user_id = response.user_id;
			
			Popup.close();
			WhosBeenHereBlock.reload();
			
			if (this.data.title){
				WallBlock.reload();
				WallBlock.smoothScrollTo();
			}
		}
	},
	
	loadContentFail : function()
	{
	},
	
	loginModeChanged : function()
	{
		var form = $('login-signup-form');
		var mode = value_of_radios(form.login_mode);
		
		$('login-signup-form-name').style.display = (mode=='login') ? 'none' : 'block';
		
		$('login-signup-form-button').value = (mode=='login') ? 'Login' : 'Join now';
		
		$('login-signup-form-email').getElement('span.faint').innerHTML = (mode=='login') ? '- the email address you used to register' : '- we never share this with anyone else';
		
		$('login-signup-form-password').getElement('span.faint').innerHTML = (mode=='login') ? '- <a href="/auth/forgotten-password" target="_blank">I have forgotten my password</a>' : '- choose a password so you can login again';
	}
}



var MultiListBlock = {
	
	init : function()
	{
		var el = $('multilist-tabs');
		this.tabs = new TabbedSection(el);
		this.content = el.getParent().getNext();
		this.tabs.addEvent('changed', this.tabChanged.bind(this));
	},
	
	tabChanged : function(li, tab_id)
	{
		var parts = tab_id.split('-');
		if (parts.length!=2 || parts[0] != 'list') return;
		var list_id = parts[1];
		
		var url = '/interface/list/'+list_id;
	
		this.setLoading(true);
		
		Wr.util.sendRequest(url, 'get', this.loadContentCompleate.bind(this));
	},
	
	loadContentCompleate : function(html)
	{
		this.setLoading(false);
		this.content.innerHTML = html;
	},
	
	setLoading : function(is_loading)
	{
		is_loading ? Wr.util.showLoading(this.content) : Wr.util.hideLoading(this.content);
	}
}

var RatingWidget = {
	
	init : function(){
		this.els = $$('.rating-widget-button-outer');
	},
	
	dontgoClicked : function()
	{
		if (!Wr.isLoggedIn()) return Wr.showLoginPopup(window.location.href);
		
		this.ratingClicked(-1);
		
		this.setSelected(0);
	},
	
	goClicked : function()
	{
		if (!Wr.isLoggedIn()) return Wr.showLoginPopup(window.location.href);
		
		this.ratingClicked(2);
		
		this.setSelected(1);
	},
	
	mustgoClicked : function()
	{
		if (!Wr.isLoggedIn()) return Wr.showLoginPopup(window.location.href);
		
		this.ratingClicked(5);
		
		this.setSelected(2);
	},
	
	setSelected : function(index)
	{
		for(var i=0;i<3;i++){
			var el = this.els[i].getParent();
			(i==index) ? el.addClass('selected') : el.removeClass('selected');
		}
	},
	
	ratingClicked : function(score)
	{	
		var g_id = data_RatingWidget.g_id;
		
		var url = '/interface/rating/vote/?g_id='+g_id+'&vote='+score;
		Wr.util.sendRequest(url, 'post', this.saveComplete.bind(this));
	},
	
	// Interface controller returns json array of scores e.g. ["55%","45%","-"]
	saveComplete : function(json)
	{
		var scores = JSON.decode(json);
		
		this.els[0].getNext().innerHTML = scores[0];
		this.els[1].getNext().innerHTML = scores[1];
		this.els[2].getNext().innerHTML = scores[2];
	}
}

var CollapsableTree = new Class({
	
	initialize : function(id)
	{
		this.id = id;
		this.el = $(id);
		this.initUi();
	},
	
	initUi : function()
	{
		var var_name = 'data_CollapsableTree_'+this.id;
		var selected_uri = 'http://'+window.location.host+window[var_name].selected;
		
		//alert(selected_uri);
		var _this = this;
		var el = this.el;
		var lis = el.getElements('li');
		
		lis.each(function(li){
			var a = li.getElement('a');
			
			if (li.getElements('ul').length > 0) {
				a.addEvent('click', _this.toggleElement.bind(_this));
				li.set('class', 'tree-closed');
			}
			
			if (a.href==selected_uri) {
				a.addClass('tree-selected');
				var parents = a.getParents('.tree-closed');
				parents.addClass('tree-open');
				parents.removeClass('tree-closed');
			}
		});
	},
	
	toggleElement : function(ev)
	{
		ev = new Event(ev);
		
		var li = ev.target.getParent('li');
		
		(li.hasClass('tree-closed')) ? this.openListItem(li) : this.closeListItem(li);
		
		return false;
	},
	
	openListItem : function(li)
	{
		li.addClass('tree-open');
		li.removeClass('tree-closed');
	},
	
	closeListItem : function(li)
	{
		li.addClass('tree-closed');
		li.removeClass('tree-open');
	}
	
});


var MapBlock = new Class({
	
	initialize : function(id)
	{
		enable_map_extras();
		
		window.sparks = window.sparks || {};
		window.sparks[id] = this;
	
		
		this.markers = [];
		
		var var_name = 'data_MapBlock_'+id;
		this.data = window[var_name];
		this.el = $(id);
		if (!this.el) return;
		
		this.map = new GMap2(this.el);
		window.onunload = GUnload;
	
		this.tooltip = new MapTooltip(this.map);
		this.map.addOverlay(this.tooltip);
		
		//var marker = new GMarker(latlng);
		//this.map.addOverlay(marker);
		this.addMarkers(this.data['markers']);
		if (this.data['polylines'] && this.data['polylines'].length>0) this.addPolylines(this.data['polylines']);
		
		this.map.addMapType(G_PHYSICAL_MAP);
		this.map.addControl(new GSmallZoomControl3D());
		this.map.addControl(new GMenuMapTypeControl());
		
		if (this.data.map_type) this.map.setMapType(window[this.data.map_type]);
		
		GEvent.addListener(this.map, 'click', this.mapClicked.bind(this));
				
		if (this.data.latlng)
		{
			var latlng = new GLatLng(parseFloat(this.data['latlng'][0]),parseFloat(this.data['latlng'][1]));
			var zoom = this.data['zoom'];
			this.map.setCenter(latlng, zoom);
			
		} else {
		
			if (this.data.zoom_to_markers && this.markers.length>0) 
			{
				this.zoomToFitMarkers();
			} else {
				this.zoomToWorld();
			}
		}
	},
	
	zoomToFitMarkers : function()
	{
		var bounds = new GLatLngBounds();
		for (var i=0; i< this.markers.length; i++) 
		{
		   bounds.extend(this.markers[i].getLatLng());
	   	}
	  	var z = this.map.getBoundsZoomLevel(bounds);//-1;
		if (z<0) z=0;
		
		var world_zoom = this.getWorldZoomLevelForSize();
		if (world_zoom > z) z = world_zoom;
		
		if (z > 15) z = 15;
		
	   	this.map.setCenter(bounds.getCenter(), z);
	},
	
	zoomToWorld : function()
	{
		var zoom = this.getWorldZoomLevelForSize();
		var c = new GLatLng(20,0);
		
		this.map.setCenter(c, zoom);
	},
	
	getWorldZoomLevelForSize : function()
	{
		var size = this.map.getSize();
		var zoom = 0;
		if (size.width > 400) zoom ++;
		if (size.width > 800) zoom ++;
		return zoom;
	},
	
	addMarkers : function(markers)
	{
		for(var i=0;i<markers.length;i++)
		{
			this.addMarker(markers[i]);
		}
	},
	
	addPolylines : function(polylines)
	{
		for(var i=0;i<polylines.length;i++)
		{
			var info = polylines[i];
			var latlngs = [];
			
			for(var j=0;j<info[0].length;j++) latlngs.push(new GLatLng(parseFloat(info[0][j][0]),parseFloat(info[0][j][1])));
			
			var polyline = new GPolyline(latlngs, info[1], parseInt(info[2]));
			this.map.addOverlay(polyline);
		}
	},
	
	addMarker : function(marker)
	{
		var title = marker['title'] || 'Marker';
		var icon  = marker['icon'] || 'default';
		var scale  = marker['icon-scale'] || 1;
		
		var latlng = new GLatLng(parseFloat(marker['latlng'][0]),parseFloat(marker['latlng'][1]));
		marker.latlng = latlng;
		
		var icon = this.getIcon(icon,scale);
		var overlay = new GMarker(latlng, {'title': title, 'icon':icon});
		overlay._marker_info = marker;
				
		this.map.addOverlay(overlay);
		this.markers.push(overlay);
		
		overlay._mb = this;
		
		GEvent.addListener(overlay, 'mouseover', this.markerHover);
		GEvent.addListener(overlay, 'mouseout', this.markerDeHover);
	},
	
	mapClicked : function(overlay, latlng)
	{
		if (overlay)
		{
			this.markerClicked(overlay);
		}
	},
	
	markerClicked : function(overlay)
	{
		if (!overlay._marker_info) return;
		
		var marker = overlay._marker_info || {};
		var html = this.generatePopupHtml(marker);
		
		if (html) overlay.openInfoWindowHtml(html, {'maxWidth':this.data.popup.width});
	},
	
	markerHover : function(latlng)
	{
		this._mb.tooltip.show(this, this.getTitle());
	},
	
	markerDeHover : function()
	{
		this._mb.tooltip.hide();
	},
	
	popup_callbacks : null,
	generatePopupHtml : function(marker_info)
	{
		var cls = marker_info.cls || 'default';
	
		if (this.popup_callbacks && this.popup_callbacks.has(cls)) return this.popup_callbacks.get(cls)(marker_info);
	
		if (cls == 'default')
			return this.generatePopupHtml_default(marker_info);
	},
	
	addPopupRenderer : function(cls, cb)
	{
		if (!this.popup_callbacks) this.popup_callbacks = new Hash();
		
		this.popup_callbacks.set(cls, cb);
	},
	
	generatePopupHtml_default : function(marker_info)
	{
		var title = marker_info.title || '';
		var snippet = marker_info.snippet || '';
		var image_url = marker_info.image || '';
		var url = marker_info.url || '';
		var read_more = marker_info.read_more || 'More information &raquo;';
		
		
		var popup = this.data.popup;
		var style = '';
		if (popup.width) style += 'width:'+popup.width+'px;';
		if (popup.height) style += 'height:'+popup.height+'px;';
		
		var css_class='';
		if (popup.css_class) css_class = ' '+popup.css_class;
		
		var img = '';
		if (image_url) img = '<td width="1%" style="padding-right:5px"><img src="'+image_url+'" class="tmb" /></td>';
		
		var title_html = title;
		if (url) title_html = '<a href="'+url+'">'+title_html+'</a>';
		
		var read_more_html = '';
		if (url) read_more_html = '<a href="'+url+'">'+read_more+'</a>';
		
		return 	'<table class="map-popup'+css_class+'" style="'+style+'"><tr>'+
				img+
				'<td>'+
				'<h4>'+title_html+'</h4>'+
				'<p>'+snippet+'</p>'+read_more_html+
				'</td>'+
				'</tr></table>';
	},
	
	icon_cache: {},
	getIcon : function(type, scale)
	{
		scale = scale || 1;
		
		if (this.icon_cache[type] && scale==1) return this.icon_cache[type];
		var icon = new GIcon(G_DEFAULT_ICON);
		
		var parts = type.split(':');
		
		if (parts[0] == 'small')
		{
			icon.image = "http://labs.google.com/ridefinder/images/mm_20_"+parts[1]+".png";
			icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
			icon.iconSize = new GSize(12, 20);
			icon.shadowSize = new GSize(22, 20);
			icon.iconAnchor = new GPoint(6, 20);
			icon.infoWindowAnchor = new GPoint(6, 8);
		
		} else if (parts[0] == 'gmaps') {
			
			icon.image = "/_files/map-icons/google-map-icons/"+parts[1]+".png";
			icon.shadow = null;
			icon.iconSize = new GSize(32, 37);
			icon.shadowSize = new GSize(32, 37);
			icon.iconAnchor = new GPoint(16, 37);
			icon.infoWindowAnchor = new GPoint(16, 8);
		} else if (parts[0] == 'dots') {
			icon.image = "http://maps.google.com/mapfiles/kml/pal3/icon49.png";
			icon.shadow = null;
			icon.iconSize = new GSize(9*scale, 9*scale);
			icon.shadowSize = null;//new GSize(32, 37);
			icon.iconAnchor = new GPoint(5*scale, 5*scale);
			icon.infoWindowAnchor = new GPoint(5*scale,5*scale);
		} else if (parts[0] == 'special') {
			icon.image = "/_resources/Wr.Ski/ski-resort.png";//http://maps.google.com/mapfiles/kml/pal4/icon35.png";
			icon.shadow = null;
			icon.iconSize = new GSize(17*scale, 17*scale);
			icon.shadowSize = null;//new GSize(32, 37);
			icon.iconAnchor = new GPoint(8*scale, 8*scale);
			icon.infoWindowAnchor = new GPoint(8*scale,8*scale);
		}

		this.icon_cache[type] = icon;
		return icon;
	}	
});


/*var PopupMap = {
	
	show : function(lat, lng)
	{
		Popup.show('Map', 700, 500);
		
		this.map = new GMap2(Popup.getContentElement());
		
		
		var latlng = new GLatLng(lat, lng);
		var zoom = 13;
		this.map.setCenter(latlng, zoom);		
		
		var marker = new GMarker(latlng);
		this.map.addOverlay(marker);
		
		this.map.addControl(new GLargeMapControl3D());
		
	}
	
}*/

var PopupMap = {
	
	showPlace : function(name)
	{
		var w = 800;
		var h = 460;
		var zoom = 13;
		var qs = 'place='+escape(name);
		
		Popup.show('Map [<a href="/explore/?'+qs+'">Full screen map</a>]', w, h);
		
		var iframe = new Element('iframe');
		iframe.style.width = w+'px';
		iframe.style.height = h+'px';
		iframe.src = 'http://old.worldreviewer.com/explore2/map/iframe?'+qs;
		
		Popup.getContentElement().appendChild(iframe);
	},
	
	show : function(lat, lng)
	{
		var w = 800;
		var h = 460;
		var zoom = 13;
		var qs = 'lat='+lat+'&lng='+lng+'&zoom='+zoom;
		
		Popup.show('Map [<a href="/explore/?'+qs+'">Full screen map</a>]', w, h);
		
		var iframe = new Element('iframe');
		iframe.style.width = w+'px';
		iframe.style.height = h+'px';
		iframe.src = 'http://old.worldreviewer.com/explore2/map/iframe?'+qs;
		
		Popup.getContentElement().appendChild(iframe);
	}
}

/**
 *	Quotes
 */
var Quotes = {
	
	showQuote : function(id)
	{
		var el = $('quote-'+id);
		var url = '/interface/quote/render/'+id+'/';
		Wr.util.loadInto(url, el);
	}
	
}

var AdnetMatchbox = {
	
	init : function(options)
	{
		this.options = options;
		var el = $('adnetmb-tabs');
		if (el)
		{
			this.tabs = new TabbedSection(el);
			this.tabs.addEvent('changed', this.tabChanged.bind(this));
		}
			
		this.content = $('adnetmb');
		
		this.signLinks();
	}, 
	
	signLinks : function()
	{
		if (this.content) Wr.adnetSignLinks(this.content);
	},
	
	tabChanged : function(el, tab_id)
	{
		var parts = tab_id.split(':');
		var tab_id = parts[1];
		
		var qs = Hash.toQueryString(this.options);
		
		
		var url = '/interface/matchbox/'+tab_id+'/?'+qs;
		Wr.util.loadInto(url, this.content, this.tabContentLoaded.bind(this));
	},
	
	tabContentLoaded : function()
	{
		this.signLinks();
	}
}









function enable_map_extras()
{
	window.MapTooltip = function()
	{

	}	

	MapTooltip.prototype = new GOverlay();

	$extend(MapTooltip.prototype, {

		gmap : null,
		el : null,
		latlng : null, // Position on map
		yoffset : 0,   // Height from ground (pixels)

		//
		//	Function required by API
		//
		initialize : function(map)
		{
			this.map = map;

			this.els = {};
			var outer = new Element('div',{'class' : 'wr_map_tooltip'});
			var inner = new Element('div');
			outer.style.display = 'none';

			if (window.ie6) outer.className = 'wr_map_tooltip_ie6';

			outer.style.position = 'absolute';

			outer.appendChild(inner);
		  	this.map.getPane(G_MAP_FLOAT_PANE).appendChild(outer);

			this.latlng = null;

			this.els.outer = outer;
			this.els.inner = inner;
		},

	 	remove : function() 
		{
		  this.els.outer.parentNode.removeChild(this.els.outer);
		},

		copy : function()
		{
			return new MapTooltip();
		},

		redraw : function(force) 
		{
			if (!force) return;

			if (!this.latlng) return;

			var p = this.map.fromLatLngToDivPixel(this.latlng);

			var s = this.els.outer.getSize();

			var x = p.x-(s.x/2);
			var y = p.y-this.yoffset-s.y;		

			this.els.outer.style.left = x+'px';
			this.els.outer.style.top = y+'px';
		},

		//
		//	Extra
		//
		show : function(marker, title)
		{
			if (this.els) 
			{
				this.yoffset = marker.getIcon ? marker.getIcon().iconAnchor.y : 0;


				this.latlng = marker.getLatLng();
				title = title || marker.getTitle() || '';
				this.els.inner.innerHTML = title;
				this.els.outer.style.display = 'block';
				this.redraw(true);
			}
		},

		hide : function()
		{
			if (this.els) this.els.outer.style.display = 'none';
		}

	});
	
}

