
(function($){function toIntegersAtLease(n)
{return n<10?'0'+n:n;}
Date.prototype.toJSON=function(date)
{return this.getUTCFullYear()+'-'+
toIntegersAtLease(this.getUTCMonth())+'-'+
toIntegersAtLease(this.getUTCDate());};var escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};$.quoteString=function(string)
{if(escapeable.test(string))
{return'"'+string.replace(escapeable,function(a)
{var c=meta[a];if(typeof c==='string'){return c;}
c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};$.toJSON=function(o,compact)
{var type=typeof(o);if(type=="undefined")
return"undefined";else if(type=="number"||type=="boolean")
return o+"";else if(o===null)
return"null";if(type=="string")
{return $.quoteString(o);}
if(type=="object"&&typeof o.toJSON=="function")
return o.toJSON(compact);if(type!="function"&&typeof(o.length)=="number")
{var ret=[];for(var i=0;i<o.length;i++){ret.push($.toJSON(o[i],compact));}
if(compact)
return"["+ret.join(",")+"]";else
return"["+ret.join(", ")+"]";}
if(type=="function"){throw new TypeError("Unable to convert object of type 'function' to json.");}
var ret=[];for(var k in o){var name;type=typeof(k);if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;var val=$.toJSON(o[k],compact);if(typeof(val)!="string"){continue;}
if(compact)
ret.push(name+":"+val);else
ret.push(name+": "+val);}
return"{"+ret.join(", ")+"}";};$.compactJSON=function(o)
{return $.toJSON(o,true);};$.evalJSON=function(src)
{return eval("("+src+")");};$.secureEvalJSON=function(src)
{var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};})(jQuery);
function make_tooltips(custom) {
	custom = custom || {}
	start_from = custom.start || $('.tooltip');
	start_from.each(function () {
		var distance = custom.distance || 10;
		var time = custom.time || 250;
		var hideDelay = custom.hide || 500;
		var onShow = custom.onshow || null;
		var onHide = custom.onhide || null;

		var hideDelayTimer = null;
		var beingShown = false;
		var shown = false;
		var trigger = $('.trigger', this);
		var info = $('.popup', this).css('opacity', 0);

		$([trigger.get(0), info.get(0)]).mouseover(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			if (beingShown || shown) {
				// don't trigger the animation again
				return;
			} else {
				// reset position of info box
				beingShown = true;

				if($.browser.msie && parseFloat($.browser.version) <= 6)
					$('select.bad').hide();

				if(onShow) onShow();

				info.css({
					top: 30,
					left: 0,
					display: 'block'
				}).animate({
					top: '-=' + distance + 'px',
					opacity: 1
				}, time, 'swing', function() {
					beingShown = false;
					shown = true;
				});
			}

			return false;
		}).mouseout(function () {
			if (hideDelayTimer) clearTimeout(hideDelayTimer);
			hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;

				if($.browser.msie && parseFloat($.browser.version) <= 6)
					$('select.bad').show();

				if(onHide) onHide();

				info.animate({
					top: '-=' + distance + 'px',
					opacity: 0
				}, time, 'swing', function () {
					shown = false;
					info.css('display', 'none');
				});

			}, hideDelay);

			return false;
		});
	});
}

$(document).ready(function(){make_tooltips();});

var toolTip2 = {
	xCord : 0,
	yCord : 0,
	opacity : true,
	tipOver: function(e, data)
	{
		data = data || {};
		toolTip2.opacity = data.transparency == null ? true : false	;

		if ( window.tID )
			clearTimeout(tID);
		if ( window.opacityID )
			clearTimeout(opacityID);
		tID = setTimeout("toolTip2.tipOutImmediate()", 50);

		obj = e;
		toolTip2.xCord = toolTip2.findPosX(obj);
		toolTip2.yCord = toolTip2.findPosY(obj) - 10;
		tID = setTimeout("toolTip2.tipShow(obj,'"+toolTip2.xCord+"','"+toolTip2.yCord+"')", 250);
		$(obj).mouseout(function(){ toolTip2.tipOut(); });
	},
	tipOver2: function(e)
	{
		if ( window.tID )
			clearTimeout(tID);
		if ( window.opacityID )
			clearTimeout(opacityID);

		var obj = document.getElementById('toolTip');
		if (toolTip2.opacity)
		{
		obj.style.opacity = '.90';
		obj.style.filter = "alpha(opacity:90)";
		}
	},
	tipOut: function(e)
	{
		if ( window.tID )
			clearTimeout(tID);
		if ( window.opacityID )
			clearTimeout(opacityID);
		tID = setTimeout("toolTip2.tipOutImmediate()", 500);
	},
	tipOutImmediate: function()
	{
		var div = document.getElementById('toolTip');
		if ( div )
			div.parentNode.removeChild(div);
	},
	tipShow: function(obj,x,y)
	{
		var newDiv = document.createElement('div');
		var scrX = Number(x);
		var scrY = Number(y);
		var tp = parseInt(scrY + 15);
		var lt = parseInt(scrX - 30);

		/*
		I believe it's the best method, but I don't understand why we need it... it only breaks design
		// the best well known method for detect IE7
		var ie7 = (document.all && !window.opera && window.XMLHttpRequest) ? true : false;
		if (ie7)
			lt = lt-600;
		**/
		if(lt + 250 > document.body.clientWidth)
		{
			lt = document.body.clientWidth - 250;
			newDiv.style.width = 235+'px';
		}
		if(lt < 5)
			lt = 5;
		tp += obj.offsetHeight/* - 17*/;
		//var addy = (anch.href.length > 25 ? anch.href.toString().substring(0,25)+"..." : anch.href);
		newDiv.id = 'toolTip';
		newDiv.className = 'tooltipdiv';
		newDiv.style.top = tp+'px'; newDiv.style.left = lt+'px';
		document.body.appendChild(newDiv);
		var objDesc = document.getElementById(obj.id + '_desc');
		if(objDesc)
			newDiv.innerHTML = "<p>" + objDesc.innerHTML + "</p>";
		else
			newDiv.innerHTML = "";
		newDiv.style.opacity = '.1';

		$(newDiv).mouseover(function(){ toolTip2.tipOver2(); });
		$(newDiv).mouseout(function(){ toolTip2.tipOut(); });

		toolTip2.tipFade('toolTip', 10);
		tID = setTimeout("toolTip2.tipOutImmediate()", 7000);
	},
	tipFade: function(div,opac)
	{
		var obj = document.getElementById(div);
		var passed = parseInt(opac);
		var newOpac = parseInt(passed + 10);
		if ( newOpac < 90 && toolTip2.opacity)
		{
			obj.style.opacity = '.'+newOpac;
			obj.style.filter = "alpha(opacity:"+newOpac+")";
			opacityID = setTimeout("toolTip2.tipFade('toolTip','"+newOpac+"')", 15);
		}
		else
		{
			if (toolTip2.opacity)
			{
			obj.style.opacity = '.90';
			obj.style.filter = "alpha(opacity:90)";
			}
			else
			{
				obj.style.opacity = '1.0';
				obj.style.filter = "alpha(opacity:100)";
			}
		}
	},
	findPosX: function(obj)
	{
		var curleft = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}
		else if (obj.x)
			curleft += obj.x;
		return curleft;
	},
	findPosY: function(obj)
	{
		var curtop = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y)
			curtop += obj.y;
		return curtop;
	}
};

//addEvent(window,'load',toolTip2.attachToolTipBehavior,false);


var zoomPict2 = {
	xCord : 0,
	yCord : 0,
/*	attachToolTipBehavior: function() {
		var links = document.getElementsByTagName('a');
		var i;
		for ( i=0;i<links.length;i++ )
			zoomPict2.attachToolTipBehaviorSingle(links[i]);
		links = document.getElementsByTagName('img');
		for ( i=0;i<links.length;i++ )
			zoomPict2.attachToolTipBehaviorSingle(links[i]);
	},
	attachToolTipBehaviorSingle: function(obj) {
		if(obj.title.length > 0)
		{
			addEvent(obj,'mouseover',zoomPict2.tipOver,false);
			addEvent(obj,'mouseout',zoomPict2.tipOut,false);
			obj.setAttribute('tip',obj.title);
			obj.removeAttribute('title');
		}
	},*/
	tipOver: function(e)
	{
		if ( window.tID )
			clearTimeout(tID);
		if ( window.opacityID )
			clearTimeout(opacityID);
		tID = setTimeout("zoomPict2.tipOutImmediate()", 50);

		obj = e;
		zoomPict2.xCord = zoomPict2.findPosX(obj);
		zoomPict2.yCord = zoomPict2.findPosY(obj);
		tID = setTimeout("zoomPict2.tipShow(obj,'"+zoomPict2.xCord+"','"+zoomPict2.yCord+"')", 50);
		$(obj).mouseout(function(){ zoomPict2.tipOut(); });
	},
	tipOver2: function(e)
	{
		if ( window.tID )
			clearTimeout(tID);
		if ( window.opacityID )
			clearTimeout(opacityID);

		var obj = document.getElementById('toolTip');
		obj.style.opacity = '.90';
		obj.style.filter = "alpha(opacity:90)";
	},
	tipOut: function(e)
	{
		if ( window.tID )
			clearTimeout(tID);
		if ( window.opacityID )
			clearTimeout(opacityID);
		tID = setTimeout("zoomPict2.tipOutImmediate()", 500);
	},
	tipOutImmediate: function()
	{
		var div = document.getElementById('toolTip');
		if ( div )
			div.parentNode.removeChild(div);
	},
	tipShow: function(obj,x,y)
	{
		var newDiv = document.createElement('div');
		var scrX = Number(x);
		var scrY = Number(y);
		var tp = parseInt(scrY);
		var lt = parseInt(scrX);

		tp -= 38;

		//var addy = (anch.href.length > 25 ? anch.href.toString().substring(0,25)+"..." : anch.href);
		newDiv.id = 'toolTip';
		newDiv.className = 'zoompictdiv';
		newDiv.style.top = tp+'px'; newDiv.style.left = lt+'px';
		document.body.appendChild(newDiv);
		var objDesc = document.getElementById(obj.id + '_desc');
		if(objDesc)
			newDiv.innerHTML = "<p>" + objDesc.innerHTML + "</p>";
		else
			newDiv.innerHTML = "";
		newDiv.style.opacity = '.1';

		$(newDiv).mouseover(function(){ zoomPict2.tipOver2(); });
		$(newDiv).mouseout(function(){ zoomPict2.tipOut(); });

		zoomPict2.tipFade('toolTip', 100);
		tID = setTimeout("zoomPict2.tipOutImmediate()", 7000);
	},
	tipFade: function(div,opac)
	{
		var obj = document.getElementById(div);
		var passed = parseInt(opac);
		var newOpac = parseInt(passed + 10);
		if ( newOpac < 90 )
		{
			obj.style.opacity = '.'+newOpac;
			obj.style.filter = "alpha(opacity:"+newOpac+")";
			opacityID = setTimeout("zoomPict2.tipFade('toolTip','"+newOpac+"')", 15);
		}
		else
		{
			obj.style.opacity = '.90';
			obj.style.filter = "alpha(opacity:90)";
		}
	},
	findPosX: function(obj)
	{
		var curleft = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curleft += obj.offsetLeft
				obj = obj.offsetParent;
			}
		}
		else if (obj.x)
			curleft += obj.x;
		return curleft;
	},
	findPosY: function(obj)
	{
		var curtop = 0;
		if (obj.offsetParent)
		{
			while (obj.offsetParent)
			{
				curtop += obj.offsetTop
				obj = obj.offsetParent;
			}
		}
		else if (obj.y)
			curtop += obj.y;
		return curtop;
	}
};




/*
 * params: {
 * 		title || obj.title
 * 		src || obj.href
 * 		shiftX, shiftY, targetX, targetY center - deprecated
 * 		todo: eval(eval)
 * 		todo: local
 * }
 */

var Dialog = {
	open: function(obj, params)
	{
		params = params || {};

		options = {
		    modal: true,
			resizable: false,
		    overlay: {
		        opacity: 0.3,
		        background: "black"
		    },
			height: 100,
		    title: params.title || obj.title
		};

		$("#dialog_wait").remove();
		$("#dialog_box").remove();
		$(".ui-dialog").remove();
		$("<div id='dialog_box' style='display:none'>" +
		  "<div id='dialog_box_cnt' style='padding:30px'></div></div>").appendTo("body");

		$('select.bad').hide();

		if(params.local)
		{
			$("#dialog_box_cnt").html($('#' + params.local).html());
			Dialog.set_data("#dialog_box", params, options);
			return false;
		}

		$("<div id='dialog_wait' style='width:200px; height:80px'>" +
		  "<img src='http://cdn.trustedplaces.net/img/indicator.white.gif' alt='Loading...' /> Loading...</div>").appendTo("body");
		Dialog.set_data("#dialog_wait", {}, options);

		$("#dialog_box_cnt").load(params.src || obj.href, {}, function(){ Dialog.set_data("#dialog_box", params, options); });

		return false;
	},
	set_data: function(objname, params, options)
	{
		if (params.width)
			var width = params.width;
		else
			var width = $(objname).width() + 0;
		var height = $(objname).height() + 50;
		options.width = width;
		options.height = height;
		if(objname != "#dialog_wait")
			$("#dialog_wait").dialog("close");
		$(objname).show();
		if(objname != "#dialog_wait")
			$(objname).bind('dialogclose', function(){ $('select.bad').show(); });
		$(objname).dialog(options);

		// Handle rounded corners
		$('.ui-dialog-container').prepend($('<span class="corner_lt"/>'));
		$('.ui-dialog-container').prepend($('<span class="corner_rt"/>'));
		$(objname).prepend($('<span class="corner_lb"/>'));
		$(objname).prepend($('<span class="corner_rb"/>'));

		if(params.eval)
			eval(params.eval);
	},
	close: function()
	{
		$("#dialog_box").dialog("close");
		return false;
	}
};

var global_after_complete = '';

function SetLocationNEW()
{
	selected_country	= $('#country').val();
	selected_state		= ($('#state').length == 0 || $('#divStatesList:visible').length == 0)
							? '' : $('#state').val();
	selected_city		= $('#city').length == 0 ? '' : $('#city').val();
	selected_district	= $('#district').length == 0 ? '' : $('#district').val();

	if(parseInt(selected_district) != 0 && objJSON.district != selected_district)
		objJSON.district = selected_district;

	if(parseInt(selected_city) != 0 && objJSON.city != selected_city)
	{
		objJSON.city = selected_city;
		objJSON.district = '';
		$('#district').attr('disabled', true);
	}

	var inputCity = CreateInputCity();
	inputCity.attr('value', 'Loading...');
	$('#list-cities').html(inputCity);
	$('#city_text').attr('disabled', true);

	if(selected_state != '' && objJSON.state != selected_state)
	{
		objJSON.state = selected_state;
		objJSON.city = '';
		objJSON.district = '';
//		$('#city').attr('disabled', true);
	}

	if(objJSON.country != selected_country)
	{
		objJSON.country = selected_country;
		objJSON.state = '';
		objJSON.city = '';
		objJSON.district = '';
		objJSON.popular = 1;
//		$('#city').attr('disabled', true);
		$('#state').attr('disabled', true);
	}

	if(objJSON.district == -2)
	{
		var inputDistrict = $('<input type="text" />');
		inputDistrict.attr('id', 'district_text');
		inputDistrict.attr('name', 'district_text');
		inputDistrict.addClass('text');
		inputDistrict.attr('value', 'Loading...');
		$('#list-districts').html(inputDistrict);
		$('#district_text').attr('disabled', true);
	}

	$.get("/member/setlocationgetcitiesnew/?json=" + $.toJSON(objJSON), function(data){
		json = $.evalJSON(data);

		has_states = json.hasstates != null && eval(json.hasstates) == 1;
		if(has_states)
		{
			FillSelect('state', objJSON.stateClass, json.states, json.state, SetLocationNEW, $('#list-states'));
			$("#state").removeAttr('disabled');
			$('#divStatesList').show();
		}
		else
		{
			$('#list-states').html("");
			$('#divStatesList').hide();
			objJSON.state = '';
		}

		if(json.cities)
		{
			FillCities(json.cities, json.city);
			$("#city").removeAttr('disabled');
		}
		else if(!has_states || escape($('#state').val()) > 0)
			SetLocationNEW();

		if(json.districts)
		{
			FillSelect('district', objJSON.stateClass, json.districts, json.district, function(){
				var district = $('#district').length == 0 ? '' : $('#district').val();
				if(district == -2)
					SetLocationNEW();
			}, $('#list-districts'));

			$('#divAreasList').show();
		}
		else
			$('#divAreasList').hide();
	});
}

function CreateInputCity()
{
	var inputCity = $('<input type="text" />');
	inputCity.attr('id', 'city_text');
	inputCity.attr('name', 'city_text');
	inputCity.addClass('text');
	return inputCity;
}

function FillSelect(name, nclass, arr, selected, changefn, html_to)
{
	var obj_select = $('<select />');
	obj_select.attr('id', name);
	obj_select.attr('name', name);
	if(nclass != null)
		obj_select.addClass(nclass);

	for (var i = 0; i < arr.length; i++)
	{
		var optionState = $('<option />');
		if(eval(arr[i].id) == eval(selected))
			optionState.attr('selected', 'selected');
		optionState.attr('value', arr[i].id);
		optionState.html(arr[i].name);
		obj_select.append(optionState);
	}

	obj_select.change(changefn);
	html_to.html(obj_select);
	obj_select.focus();
}

function FillCities(arr, city)
{
	if(arr.length > 0)
	{
		obj_select = FillSelect('city', objJSON.cityClass, arr, city, OnChangeCity, $('#list-cities'));

		if(eval(city) == -1)
		{
			createOtherCity($('#list-cities'), objJSON.city_text);
			$('#city').hide();
			$('#divAreasList').hide();
		}
	}
	else
	{
		var inputCity = CreateInputCity();

		if(objJSON.city_text != null)
			inputCity.attr('value', objJSON.city_text);
		if(objJSON.cityClass != null)
			inputCity.addClass(objJSON.cityClass);
		if(global_after_complete.trim() != '')
			inputCity.onblur = function(){ eval(global_after_complete); }

		$('#list-cities').html(inputCity);
		inputCity.focus();
	}
}

function OnChangeCity()
{
	if($('#city').val() == '-1')
	{
		$('#city').hide().val(0);
		if($('#city_text').length == 0 && $('#select_label').length == 0)
			createOtherCity($('#list-cities'), null);
		else
		{
			$('#select_label').show();
			$('#city_text').show();
		}
	}
	else if($('#city').val() == '-2')
	{
//		$('#city').attr('disabled', true);
		objJSON.popular = 0;
		SetLocationNEW();
	}
	else if($('#city').val() == '257')
	{
		objJSON.city = '257';
		SetLocationNEW();
	}
	else
		$('#divAreasList').hide();

	if (global_after_complete.trim() != '')
		eval(global_after_complete);
}

function createOtherCity(appendTo, cityValue)
{
	var inputCity = CreateInputCity();

	if (cityValue != null)
		inputCity.attr('value', cityValue);
	if (global_after_complete.trim() != '')
		inputCity.blur(function(){ eval(global_after_complete); });
	appendTo.append(inputCity);
	var inputText = $('<a href="#" />');
	inputText.attr('id', 'select_label');
	inputText.click(function(){
		$('#select_label').hide();
		$('#city_text').hide();
		$('#city').show().val(0);
		return false;
	});
	inputText.addClass('likehref');
	inputText.html('or select from list');
	appendTo.append(inputText);
	inputCity.focus();
}

function BuildJSON()
{
	objJSON = $.evalJSON($('#locationJSON').html().trim());
}

function SetLocation()
{
	window.location.href = "/member/setlocationdo?" + $('#form_location').serialize();
}

function MemberAccess(url, func_eval)
{
	if (js_logged_in)
	{
		if(url == "")
			url = window.location.href;
		if(url.substr(0, 4) != 'http')
			url = 'http://' + window.location.host + url;

		if(func_eval == "" || !func_eval)
			window.location.href = url;
		else
			eval(func_eval);
	}
	else
	{
		if(url == "")
			url = window.location.href;
		window.location.href = 'http://' + window.location.host + '/login?redirect=' + encodeURIComponent(url);
	}
	return false;
}

var geo_coords_set = false;
function showAddListForm()
{
	if ($('#selectUserLists').val() == 'new')
	{
		$('#divAddNewList').show();
		$('#createnew').val('1');
	}
	else
	{
		$('#divAddNewList').hide();
		$('#createnew').val('0');
	}
}

function submitListForm()
{
	/*if ($('createnew').value == "0" ||  $('txtAddNewList').value.trim() != "")
	{
		window.location = '/places/addtolist/?'+Form.serialize('form_addtolist');
	}
	*/
	new Ajax.Updater('divContainerAdd', '/places/addtolist/?'+Form.serialize('form_addtolist'), {
	  parameters: {  }
	});
}

function SetLocationLoadCities()
{
	$("#city").attr('disabled', true);

	$.get("/member/setlocationgetcities/" + escape($("#country").val())+"/?type=city", function(data){
		if(data.slice(0, 1) != "%")
			return;
		res = data.split("%_%");
		if (res[1] == "city")
		{
			$("#city").attr('disabled', false);
			$("#list-cities").html(res[2]);
			SetLocationLoadDistricts();
		}
	});
}

function SetLocationLoadCitiesStates(hideothers, location)
{
	$("#city").attr('disabled', true);
	var hideothers = (hideothers == null) ? false : eval(hideothers);
	var location = (location == null) ? 'home' : location;
	var str = hideothers ? '&hide=1' : '';
		str = str + '&location='+location;

	$.get("/member/setlocationgetcities/" + escape($('#country').val())+"/?type=stateorcity"+str, function(data){
		SetLocationLoadCitiesStatesComplete(data);
	});
}

function SetLocationLoadCitiesStatesComplete(data)
{
	if(data.slice(0, 1) != "%")
		return;

	res = data.split("%_%");
	if (res[1] == "state")
	{
		$("#divStatesList").show();
		$("#list-states").html(res[2]);
		SetLocationLoadCitiesByState(res[3], res[4]);
	}
	else if (res[1] == "city")
	{
		if (res[3] != "new")
		{
			$("#divStatesList").hide();
			$('#state').val('0');
			$("#list-states").html("");
			isHide = res[3];
		}
		else
			isHide = res[4];
		$("#list-cities").html(res[2]);
		SetLocationLoadDistricts(isHide);
	}
}

function SetLocationLoadCitiesByState(hideothers, location)
{
	var location = (location == null) ? 'home' : location;
	var hideothers = (hideothers == null) ? false : eval(hideothers);
	var str = hideothers ? '&hide=1' : '';
	str = str + '&location='+location;

	$("#city").attr('disabled', true);

	$.get("/member/setlocationgetcities/" + escape($("#state").val())+"/?type=state"+str, function(data){
		if(data.slice(0, 1) != "%")
			return;
		res = data.split("%_%");
		if (res[1] == "city")
		{
			$("#list-cities").html(res[2]);
			SetLocationLoadDistricts(res[3]);
		}
	});
}

function SetLocationLoadDistricts(hideothers)
{
	var hideothers = (hideothers == null) ? false : true;
	if (hideothers)
		var str = '?hide=1';
	$("#district").attr('disabled', true);

	$.get("/member/setlocationgetdistricts/" + escape($("#city").val())+ str, function(data){
		if(data.slice(0, 1) != "_")
			return;

		$("#list-districts").html(data.slice(1));
	});
}

function SetLocationOnChangeCity(hideothers)
{
	var hideothers = (hideothers == null) ? false : true;
	var str = hideothers ? '&hide=1' : '';
	if($("#city").val() == "0")
	{
		$.get("/member/setlocationgetcities/0/?type=city"+str, function(data){
			SetLocationLoadCitiesStatesComplete(data);
		});
	}
	else
		SetLocationLoadDistricts(hideothers);
}

function SetLocationOnChangeDistrict()
{
	if ($('#district').val() == 0)
		$('#list-districts').html('<input id="district" name="district" type="hidden" value="0" />' +
							'<input id="district_text" name="district_text" type="text" value="" class="width180" />' +
							' <small class="likehref" onclick="SetLocationOnChangeCity()">or select from the list...</small>');
}

function AddTagsToField(cbId, tag)
{
	if ($(cbId).checked)
	{
		if ($('txtReviewTags').value.trim() == '')
			$('txtReviewTags').value = tag;
		else
			$('txtReviewTags').value += ', '+tag;
	}
	else
	{
		$('txtReviewTags').value = $('txtReviewTags').value.replace(tag+', ', '');
		$('txtReviewTags').value = $('txtReviewTags').value.replace(tag, '');
	}
}

function submitPublishReview()
{
	$('#errReviewRating').hide();
	$('#errNoReviewName').hide();
	$('#errNoReviewBody').hide();

	if ($('#txtReviewName').val().trim() == '')
	{
		$('#errNoReviewName').show();
		return false;
	}
	if ($('#hdnReviewRating').val() == '0')
	{
		$('#errReviewRating').show();
		return false;
	}
	if ($('#txtReviewBody').val().trim() == '')
	{
		$('#errNoReviewBody').show();
		return false;
	}
	return true;
}

function bigStarClicked(id)
{
	$('#hdnReviewRating').val(id);
	$(".big-rating .star-rating .current").width(15 * id);
}

function unselectall(obj)
{
	var form = $(obj);
	for(i=0;i<form.elements.length;i++){
		if(form.elements[i].checked == true) form.elements[i].checked = false;
	}

}

function SubmitAddPlace()
{
	$('#divChooseGeo').hide();
	$('#imgNext').hide();
	$('#errAddPlaceName').hide();
	$('#errAddPlaceCity').hide();
	$('#errAddPlaceAddress').hide();
	$('#errAddPlacePostcode').hide();

	if ($('#txtAddPlaceName').val() == '')
	{
		$('#errAddPlaceName').show();
		$('#imgNext').show();
		return false;
	}

	if ($('#city').length == 0 || $("#city").get(0).options == null)
	{
		if ($('#city_text').val() == '')
		{
			$('#errAddPlaceCity').show();
			$('#imgNext').show();
			return false;
		}
	}

	if($('#txtAddPlacePostcode').val().length > 15)
	{
		$('#errAddPlacePostcode').show();
		$('#imgNext').show();
		return false;
	}

	$('#imgNext').attr('disabled', true);

	return true;
}


function SwitchFileUploadType(uplType)
{
	if (uplType == 'file')
	{
		$('divVideoCode').style.display = 'none';
		$('divVideoFile').style.display = 'block';
		$('hdnVideoType').value = 'file';
	}
	else if (uplType == 'code')
	{
		$('divVideoFile').style.display = 'none';
		$('divVideoCode').style.display = 'block';
		$('hdnVideoType').value = 'embed';
	}
}

function changeVideosInProfile(divid)
{
	$('divShowVideo').innerHTML = $('divHiddenVid_'+divid).innerHTML;
}

function TogglePeoplePageHeader()
{
	$('#people_header_1').toggle();
	$('#people_header_2').toggle();
}

function SubmitIf(formid, quest)
{
	if (window.confirm(quest))
		$('#' + formid).submit();
}

function SetCookie(cookieName,cookieValue,nDays)
{
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString();
}

var params = null;

function StartParentSearch()
{
	new Ajax.Updater('divSearchResults', '/system/multi/find_parent/?'+Form.serialize('formParentFind'), {
	  parameters: {  }
	});
}

function SetNewParent(id, text, obj)
{
	$('hdnParentID').value = id;
	$('lblParent').innerHTML = text;
	Dialog.close();
}


function updateSubcategoriesList(_selectCategory, _selectSubCategory, _divSubCat, hideSelect)
{
	var selectCategory = (_selectCategory == null) ? "selectCategory" : _selectCategory;
	var selectSubCategory = (_selectSubCategory == null) ? "selectSubcategory" : _selectSubCategory;
	var divSubCat = (_divSubCat == null) ? "subcategory-div" : _divSubCat;
	var hideSelectStr = (hideSelect == null) ? "" : "/hide";
	$('#' + selectSubCategory).attr('disabled', true);

	$.get("/places/getsubcategories/" + escape($('#' + selectCategory + ' option:selected').val()) + hideSelectStr, function(data){
		res =  data.split('%_%');
		if(res[0].trim() != "ok")
			return;

		if (hideSelectStr)
			$('#' + selectSubCategory).html(res[1]);
		else
			$('#' + divSubCat).html(res[1]);

		$('#' + selectSubCategory).attr('disabled', false);
	});
}

function SetLocationOnChangeCityEditPlace()
{
	if($("city").value == "0")
	{
		new Ajax.Request(
			"/member/setlocationgetcities/0",
			{
				method: 'get',
				parameters: '',
				onComplete: SetLocationLoadCitiesCompleteEditPlace
			});
	}
	else
	{
		new Ajax.Request(
		"/member/setlocationgetdistricts/" + escape($("city").value)+"?editplace=1",
		{
			method: 'get',
			parameters: '',
			onComplete: SetLocationLoadDistrictsCompleteEditPlace
		});
	}
}

function SetLocationLoadCitiesCompleteEditPlace(req)
{
	if(req.responseText.slice(0, 1) != "_")
		return;

	$("list-cities").innerHTML = req.responseText.slice(1);
	SetLocationLoadDistrictsEditPlace();
}

function SetLocationLoadDistrictsCompleteEditPlace(req)
{
		$("list-districts").innerHTML = req.responseText.slice(1);
}

function OnSelectDistrictEditPlace(num)
{
	if ($("district_"+num).options[$("district_"+num).selectedIndex].value == "-1")
		$('pDistrictContainer_'+num).innerHTML = '<input id="district_'+num+'" name="district_'+num+'" type="hidden" value="0" ><input id="district_text_'+num+'" name="district_text_'+num+'" type="text" value="" class="width180" >';
}

function SaveWiki()
{
	$.post('/places/areawiki/?' + $('#form_areawiki').serialize(), function(data){
		$('#divWiki').html(data);
	});
}


function AjaxUpdater(objId, url, formId)
{
	var str = url;
	if (formId != null)
		str += '/?' + Form.serialize(formId);
	new Ajax.Updater(objId, str, {
	  parameters: {  }
	});
}

function ShowAdZone(zone_id)
{
   	$('#adzone_' + zone_id).show();
}

function HideAdZone(zone_id)
{
   	$('#adzone_' + zone_id).hide();
}

function GetLocationStr(country_id, city_id, citytext_id, address_id, postcode_id)
{
	var location;
	var country = $('#'+country_id).get(0).options[$('#'+country_id).get(0).selectedIndex].innerHTML;
	location = $('#'+address_id).val();
	if (country == "United Kingdom" && $('#'+postcode_id).val() != "")
	{
		if(location != "")
			location += ", ";
		location += $('#'+postcode_id).val();
//		return location + $('#'+postcode_id).val() + ', '+country;
	}

	if($('#'+city_id).length != 0 && $('#'+city_id).get(0).options != null && $('#'+city_id).val() != -1)
	{
		if(location != "")
			location += ", ";
		location +=  $('#'+city_id).get(0).options[$('#'+city_id).get(0).selectedIndex].innerHTML;
	}
	else
	{
		if($('#'+citytext_id).val() != "")
		{
			if(location != "")
				location += ", ";
			location += $('#'+citytext_id).val();
		}
	}
	if(location != "")
		location += ", ";
	if ("Russian Federation" == country)
		country = "Russia";

	location += country;

	return location;
}
var global_longitude_id = '';
var global_latitude_id = '';
var global_to_eval = '';
function SetLocationValues(location, longitude_id, latitude_id, to_eval)
{
	global_longitude_id = longitude_id;
	global_latitude_id  = latitude_id;
	global_to_eval = to_eval;
	var geocoder = new GClientGeocoder();
		geocoder.getLatLng(
			location,
			function(point){
			   	if(point){
					$('#'+global_longitude_id).val(point.x);
					$('#'+global_latitude_id).val(point.y);
					eval(global_to_eval);
				}
			}
		);
}


function LoggerAddRecord(data)
{
	var uniqid = ((new Date()).getTime() + '' + Math.floor(Math.random() * 1000000)).substr(0, 10);
	var params = '?_u=' + uniqid + '&ajax=1' + '&u=' + encodeURIComponent(window.location.href);
	for(var property in data)
		params += '&' + property + '=' + encodeURIComponent(data[property]);

	$.get('/s2' + params);
}

function SwitchAreas(path, alpha, currTab)
{
	$('#divAllTabs a').removeClass('currentpage');
	$('#' + currTab).addClass('currentpage');

	$('#ulMoreAreas').load('/places/moreareas/?alpha=' + alpha + '&browse=' + path + '&dialog');

	return false;
}


var hideDelayTimer = null;

function intextad_hover_show()
{
	if (hideDelayTimer) clearTimeout(hideDelayTimer);

	if (!$('#intextad_hover img').attr( "complete" ))
		return false;

	position = $(this).offset();

	$('#intextad_hover').css('left', position.left + this.offsetWidth/2 - 100);
	$('#intextad_hover').css('top', position.top - 70);
	$('#intextad_hover').show();
}

function intextad_hover_keep()
{
	if (hideDelayTimer) clearTimeout(hideDelayTimer);
}

function intextad_hover_hide()
{
	hideDelayTimer = setTimeout(function () {
		hideDelayTimer = null;
		$('#intextad_hover').hide();
	}, 500);
}

function intextad_hover_click()
{
	window.open("http://ad.doubleclick.net/clk;217750670;37962457;r?http://trustedplaces.com/idk/" + __current_city__);
}

function init_intextad_hover()
{
	$('.intextad_link').mouseover(intextad_hover_show).mouseout(intextad_hover_hide).click(intextad_hover_click);
	$('#intextad_hover').mouseover(intextad_hover_keep).mouseout(intextad_hover_hide).click(intextad_hover_click);
}

$(document).ready(function(){init_intextad_hover();});

function IsUKPostcode($postcode)
{
	uk_postcode = /^([A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1})[\s]{0,1}([0-9][A-Z]{2})?/i;
	if ($postcode!= null && $postcode.match(uk_postcode) != null && $postcode.match(uk_postcode)[0].trim() != '')
		return true;

	return false;
}

String.prototype.gsub = function(pattern, replacement)
{
    var result = '', source = this, match;

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += replacement;
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
}


function UpdateRecommendedPlaces()
{
	new Ajax.Request(
		'/homepage/RecommendedPlaces',
		{
			method: 'get',
			onComplete: CallbackRecommendedPlaces
		});

	function CallbackRecommendedPlaces(req)
	{
		$("recommend_places").innerHTML = req.responseText;
	}
}


// workaround for safari issue with file submits from modals
function AddPhoto()
{
	$('#add_photo_step1').hide();
	$('#add_photo_step2').show();
}

function AddWallpaper()
{
	$('#add_wallpaper_step1').hide();
	$('#add_wallpaper_step2').show();
}

var onceCleaned_tpmembers = false;
var onceCleaned_emails = false;

function ShareReviewOpen(elem, url)
{
	onceCleaned_tpmembers = false;
	onceCleaned_emails = false;

//  TODO: redo autocompleter for usernames, init it on eval:

	return Dialog.open(elem, { center: true, title: 'Share review', src: url } );
}

function ShareReviewInterface(elem)
{
	elem = $(elem).get(0);
	if (elem.id == 'tpmembers')
	{
		if (!onceCleaned_tpmembers)
		{
			onceCleaned_tpmembers = true;
			elem.value  = "";
		}
		members = elem.value.gsub(/\s/,',');
		members = members.gsub(/,+/,',');
		membersArr = members.split(',');

		friendsArr = document.getElementsByName('friend');
		for (i=0; i<friendsArr.length; i++)
		{
			friendname = friendsArr[i].id.split('_-_')[2];
			if (membersArr.indexOf( friendname.toLowerCase() ) != -1) {
				friendsArr[i].checked = true;
			}
			else
				friendsArr[i].checked = false;
		}
	}
	else if (elem.id == 'emails')
	{
		if (!onceCleaned_emails)
		{
			onceCleaned_emails = true;
			elem.value  = "";
		}
	}
	else
	{
		if (!onceCleaned_tpmembers)
		{
			onceCleaned_tpmembers = true;
			$('#tpmembers').val('');
		}
		friendname = elem.id.split('_-_')[2];
		if (elem.checked)
		{
			if($('#tpmembers').val() != "")
				$('#tpmembers').val($('#tpmembers').val() + ', ')

			$('#tpmembers').val($('#tpmembers').val() + friendname);
		}
		else
		{
			x = new RegExp(friendname + "[\s,]*", "i");
			$('#tpmembers').val($('#tpmembers').val().gsub(x,''));
		}
	}
}

function ShareReviewPost(memberid, reviewid)
{
	ShareReviewInterface('#tpmembers');
	ShareReviewInterface('#emails');

	$("#ShareReviewMessage").hide();

	$("#ShareReviewMessage").html("<div style='text-align: center; height: 40px; padding: 20px 0 20px 0'><img src='http://cdn.trustedplaces.net/img/indicator.green.gif'/><br /> Sending...</div>");
	$.post('/my/sharereview/' + memberid + '/' + reviewid + '/send?' + $('#ShareReview').serialize(), function(data){
		if(data.indexOf("_") == 0)
		{
			Dialog.close();

			$('#anouncement_body').html('Thanks for sharing. Your review has been sent to your friends.');
			$('#anouncement').show();
			$("<div id='thank_you'>Your review has been sent to your friends.</div>").appendTo('body');
			Dialog.open(null, { local: 'thank_you', title: 'Thanks for sharing', center: true });
		}
		else
		{
			$("#ShareReviewMessage").html(data);
			$("#ShareReviewMessage").show();
		}
	});
}


var gPlaceName = '';
var onceCleaned_email = false;

function SubscribeInterface()
{
	if (!onceCleaned_emails)
		{
			onceCleaned_emails = true;
			$('email').value  = "";
		}
}


function SubscribePost(type, placeid, placename, email)
{
	gPlaceName = placename;

	$("SubscribeMessage").innerHTML = "<div style='text-align: center; height: 40px; padding: 20px 0 20px 0'><img src='http://cdn.trustedplaces.net/img/indicator.green.gif'/><br /> Sending...</div>";
	$("SubscribeMessage").show();
	new Ajax.Request(
		'/subscriptions/subscribedo/'+ type +'/' + placeid,
		{
			method: 'post',
			parameters: $('Subscribe').serialize(),
			onComplete:  SubscribeComplete
		}
	);
}

function  SubscribeComplete(req)
{
	if (req.responseText.indexOf("_") == 0)
	{
		Dialog.close();
		if (req.responseText.indexOf("/") == 1)
		{
			window.location = req.responseText.substr(1, req.responseText.length - 1);
		}
		else
		{
			$('special_offer_subscription_div').hide();
			$('anouncement_body').innerHTML = 'Thanks for subscribing. We will let you know as soon as we receive special offers from ' + gPlaceName;
			$('anouncement').show();
		}
	}
	else
	{
		$("SubscribeMessage").innerHTML = req.responseText;
		$("SubscribeMessage").show();
	}
}

	var reqReviewId = null;

	function doOver(hElm){
		hElm.style.background = '#FDFFB9';
	}

	function doOut(hElm){
		hElm.style.background = '#ffffff';
	}

	function RatingClick(reviewid, rating, isNew)
	{
		isNew = (isNew == undefined) ? 0 : 1;
		reqReviewId = reviewid;

		$("#ratesaved_" + reqReviewId).html('');

		if("{{ memberid }}" == "0")
		{
			$("#ratesaved_" + reqReviewId).html(
				"<font color='red'>You have to be logged in first. " +
				"<a href='/'>Click here</a> to log in or register.</font>");
			return;
		}

		$("#ratesaved_" + reqReviewId).html("Saving rating... <img src='http://cdn.trustedplaces.net/img/indicator.green.gif'/>");

		$.get("/review/reviewrating?reviewid=" + reviewid + "&rating=" + rating + '&new='+isNew, function(data){
			if(data.slice(0, 1) == "_")
			{
				$("#ratereview_" + reqReviewId).html(data.slice(1));
				$("#ratesaved_" + reqReviewId).html("Rating is saved.");
			}
			else
			{
				$("#ratesaved_" + reqReviewId).html('');
			}
		});
		return false;
	}

var QuickRate = {
	ExpandBox: function(id, nofocus)
	{
		$('#text_' + id).hide();
		$('#break_' + id).show();
		$('#save_' + id).show();
		$('#texta_' + id).css('fontSize', '12px');
		$('#texta_' + id).css('color', '#000');
		$('#texta_' + id).val('');
		if (nofocus == null || nofocus == false)
			$('#texta_' + id).focus();
	},

	MouseOver: function(id, num, clname, override)
	{
		if($('#' + id + 'div').rated && !override)
			return;
		if(clname == 'newstar')
			for (i = 1; i <= 5; i++)
				$('#' + id + 'star' + i).className = (i <= num) ? clname + '_rated' : clname;
		else if(clname == 'newfav' || clname == 'newwant')
			$('#' + id + 'obj').className = (num == 1) ? clname + '_rated' : clname;
	},

	Click: function(id, num, clname)
	{
		$('#hdn' + id).val(num);
		multiplier = (clname == '15') ? 15 : 11;
		$(".div" + id + " .star-rating .current").width(multiplier * num);
	},

	Toggle: function(id)
	{
		ok = $('#' + id).val() == 0;
		if(ok)
			$('#' + id + 'div').get(0).className += '1';
		else
			$('#' + id + 'div').get(0).className = $('#' + id + 'div').get(0).className.slice(0, -1);
		$('#' + id).val(ok ? 1 : 0);
	},

	ClickRate: function(id, num, clname, placeid, ratetype)
	{
		str = (ratetype != null) ? '&type='+ratetype : '';
		multiplier = (str == '') ? 15 : 11;
		$('#' + id + " .star-rating .current").width(multiplier * num);
		return Dialog.open($('#' + id + 'div'), {src: '/review/quickrate?placeid=' + placeid + '&rating=' + num + str, title: 'Thanks!'});
	},

	MouseOut: function(id, clname)
	{
		if($('#' + id + 'div').rated)
			return;
		$('#' + id + 'div').rating = 0;
		QuickRate.MouseOver(id, 0, clname);
	},

	MouseOutValue: function(id, clname, value)
	{
		if($('#' + id + 'div').rated)
			return;
		$('#' + id + 'div').rating = value;
		QuickRate.MouseOver(id, value, clname);
	},

	GetInt: function(val)
	{
		var a = parseInt(val);
		if(isNaN(a))
			a = 0;
		return a;
	},

	Submit: function(id)
	{
		var review = $('#texta_' + id).val();
		var rating = $('#hdnr_' + id).val();
		var empty_review = (review.replace(/\s*/g, "") == '');

		if(rating > 0 && empty_review)
		{
			alert("You must write a review as well. Tell the world what you loved or didn't like about this place. Your opinion matters.");
			return;
		}

		if(!empty_review && rating == 0)
		{
			alert("You must rate this place as well to post a review.");
			return;
		}

		var fav    = QuickRate.GetInt($("#f_" + id).val());
		var wantgo = QuickRate.GetInt($("#g_" + id).val());

		if(rating == 0 && empty_review && fav == 0 && wantgo == 0)
		{
			alert("You must provide a rating and review.");
			return;
		}

		$('#block_' + id).hide();
		$('#saving_' + id).show();

		$.get("/places/quickrate?placeid=" + id + "&review=" + encodeURIComponent(review) + "&rating=" + rating
				+ "&fav=" + fav + "&wantgo=" + wantgo, function(data){
			var result = data.split(';');

			if(result[0] == 'OK')
			{
				$('#saving_' + id).hide();

				if(review != '')
				{
					$('#saved1_'  + id).show();
					$('#review_link1_' + id).href = result[1];
				}
				else
				{
					$('#saved2_'  + id).show();
					$('#review_link2_' + id).href = result[1];
				}
			}
			else
			{
				$('#saving_' + id).hide();
				$('#error_' + id).show();
			}
		});
	},

	SubmitPic: function(id)
	{
		var params = $('#formRatePic_' + id).serialize();
		if ($('#texta_' + id).value == '')
		{
			$('#error_'+id).show();
			return false;
		}
		window.location = '/review/ratepic/?'+params;
	}
};

	var req_polltag = null;

	function PollClick(pollid, polltag, questionid, answerid)
	{
		req_polltag = polltag;

//		$("poll_" + req_polltag).innerHTML = "Saving... <img src='http://cdn.trustedplaces.net/img/indicator.green.gif'/>";

		new Ajax.Request(
			"/poll/vote",
			{
				method: 'get',
				parameters: "pollid=" + pollid + "&a[" + questionid + "]=" + answerid,
				onComplete: PollReceived
			});
	}

	function PollSubmit(pollid, polltag)
	{
		$.get("/poll/vote?" + $("#poll_" + pollid).serialize(), function(data){
			if(data.trim().slice(0, 1) == "_")
				$("#poll_" + polltag).html(data.trim().slice(1));
		});
	}

