var isBrowsing = true;
var json_history = Array();
var json_history_maxlength = 5;

function Set_Cookie(name, value)
{
    document.cookie = name + "=" + escape(value);
}

function EnableQuickMode(val)
{
	StateJSON.quickrate = val ? 1 : 0;
	window.location = BuildURL();
}

function parse_str(str, array){
	// http://kevin.vanzonneveld.net
	// +   original by: Cagri Ekin
	// +   improved by: Michael White (http://crestidg.com)
	// *     example 1: parse_str('first=foo&second=bar');
	// *     returns 1: { first: 'foo', second: 'bar' }
	// *     example 2: parse_str('str_a=Jack+and+Jill+didn%27t+see+the+well.');
	// *     returns 2: { str_a: "Jack and Jill didn't see the well." }

	var glue1 = '=';
	var glue2 = '&';

	var array2 = str.split(glue2);
	var array3 = [];
	for (var x1 = 0; x1 < array2.length; x1++) {
		var tmp = array2[x1].split(glue1);
		if (tmp[1] != null)
			array3[unescape(tmp[0])] = unescape(tmp[1]).replace(/[+]/g, ' ');
	}

	return array3;
}

function UpdateStateJSON(url)
{
	var arr_url = url.split('?');
	var path 	= arr_url[0].split('/');
	if (arr_url[1] != null)
	{
		var url_params;
		url_params = parse_str(arr_url[1]);
		if (url_params['sort1'] != '' && StateJSON.sort1 != url_params['sort1'])
		{
			StateJSON.sort1 = url_params['sort1'];
			StateJSON.page = 1;
		}

		if (url_params['page'] != null && StateJSON.page != url_params['page'])
			StateJSON.page = url_params['page'];

		StateJSON.search = url_params['search'] 		!= null ? encodeURIComponent(url_params['search'].replace(/"/g, '\\"')) : '';
		StateJSON.search = url_params['tag'] 			!= null ? encodeURIComponent(url_params['tag'].replace(/"/g, '\\"')) : '';
		StateJSON.offer = url_params['offer'] 			!= null ? url_params['offer'] : 0;
		StateJSON.menu = url_params['menu']				!= null ? url_params['menu'] : 0;
		StateJSON.booking = url_params['booking']		!= null ? url_params['booking'] : 0;
		StateJSON.booking = url_params['privatehire']	!= null ? url_params['privatehire'] : 0;
		StateJSON.lowcost = url_params['lowcost'] 		!= null ? url_params['lowcost'] : 0;
		StateJSON.highcost = url_params['highcost'] 	!= null ? url_params['highcost'] : 0;
		StateJSON.user = url_params['user'] 	    	!= null ? encodeURIComponent(url_params['user'].replace(/"/g, '\\"')) : '';
		StateJSON.friends = url_params['friends'] 		!= null ? url_params['friends'] : 0;
	}
	else
	{
		StateJSON.sort1 = 'rating';
		StateJSON.page = 1;
		StateJSON.search = '';
		StateJSON.tag = '';
		StateJSON.offer = 0;
		StateJSON.menu = 0;
		StateJSON.booking = 0;
		StateJSON.privatehire = 0;
		StateJSON.lowcost = 0;
		StateJSON.highcost = 0;
		StateJSON.user = '';
		StateJSON.friends = 0;
	}

	var category_index = 6;
	var uk_postcode = /^([A-Z]{1,2}[0-9]{1,2}[A-Z]{0,1})[\s]{0,1}([0-9][A-Z]{2})?/i;
//	var postcodes  	= uk_postcode.exec(path[5]);
	if (path[5]!= null && path[5].match(uk_postcode) != null && path[5].match(uk_postcode)[0].trim() != '') {
		StateJSON.halfpostcode = path[5];
	}
	else {
		if (path[4] == 'uk' && path[5] == 'london') {
			category_index = 7;
			if (path[6] != 'all' && StateJSON.district != path[6]) {
				StateJSON.district = path[6];
				StateJSON.page = 1;
			}
			else
				if (path[6] == 'all' && StateJSON.district != 'all')
					StateJSON.district = 'all';
		}

		if (path[4] == 'us' || path[4] == 'canada' || path[4] == 'australia' || path[4] == 'new-zealand') {
			if (path[5] != '' && path[5] != StateJSON.state) {
				StateJSON.state = path[5];
				StateJSON.page = 1;
			}

			if (path[6] != '' && path[6] != StateJSON.city) {
				StateJSON.city = path[6];
				StateJSON.page = 1;
			}
			category_index = 7;
		}
		else
			if (path[5] == null || path[5] != StateJSON.city) {
				StateJSON.city = path[5];
				StateJSON.page = 1;
			}
		StateJSON.halfpostcode = '';
	}

	var subcategory_index = category_index + 1;

	// If category or subcategory changes, reset page to 1
	if (path[category_index] == null)
		path[category_index] = '';
	if (path[subcategory_index] == null)
		path[subcategory_index] = '';
	if (path[category_index] != StateJSON.category ||
		path[subcategory_index] != StateJSON.subcategory)
		StateJSON.page = 1;

	StateJSON.category = path[category_index];
	StateJSON.subcategory = path[subcategory_index];
}

function ShowMainCategories()
{
	new Effect.BlindUp($('ulSubCategories'));
	new Effect.BlindDown($('ulCategories'));
}

function ShowSubCategories()
{
	if ($('ulSubCategories') != null)
	{
		new Effect.BlindDown($('ulSubCategories'));
		new Effect.BlindUp($('ulCategories'));
	}
}

function ClearFilters()
{
	$('#search_input').val('');
	$('#search_input1').val('');
	$('#price_show').get(0).checked = false;
	$('#price_menu').get(0).checked = false;
	$('#price_booking').get(0).checked = false;
	$('#price_privatehire').get(0).checked = false;
	$('#price_price1').get(0).checked = true;
	$('#price_price2').get(0).checked = false;
	$('#price_price3').get(0).checked = false;
	$('#price_price4').get(0).checked = false;
	if($('#price_friends').length)
	$('#price_friends').get(0).checked = false;
	$('#price_member').val('');

	StateJSON.search = '';
	StateJSON.tag = '';
	StateJSON.offer = 0;
	StateJSON.menu = 0;
	StateJSON.booking = 0;
	StateJSON.privatehire = 0;
	StateJSON.lowcost = 0;
	StateJSON.highcost = 0;
	StateJSON.friends = 0;
	StateJSON.user = '';
}

function BrowseFilters(search_input)
{
	if (typeof(search_input) == 'string')
		StateJSON.search = $('#' + search_input).val();
	else
		StateJSON.search = $('#search_input').val();

	StateJSON.offer 		= ($('#price_show').get(0).checked) ? 1 : 0;
	StateJSON.menu 			= ($('#price_menu').get(0).checked) ? 1 : 0;
	StateJSON.booking 		= ($('#price_booking').get(0).checked) ? 1 : 0;
	StateJSON.privatehire 	= ($('#price_privatehire').get(0).checked) ? 1 : 0;

	var arr = GetPrice(document.getElementsByName('price_price'));
	StateJSON.lowcost 	= arr[0];
	StateJSON.highcost 	= arr[1];
	StateJSON.page 		= 1;
	if($('#price_friends').length)
		StateJSON.friends = $('#price_friends').get(0).checked ? 1 : 0;
	StateJSON.user 	= $('#price_member').val();
	if($('#postcode_postcode').length > 0 && String($('#postcode_postcode').val()).trim() != '') {
		StateJSON.halfpostcode = $('#postcode_postcode').val();
		StateJSON.city = '';
		StateJSON.district = '';
	}
	var hr = BuildURL();

	window.location.href = 'http://' + window.location.host + hr;
	return false;
}

function GetPrice(radios)
{
	var low = 0;
	var high = 0;
	for (var i = 0; i < radios.length; i++)
	{
		if (radios[i].checked)
		{
			return radios[i].value.split(',');
		}
	}
}

function CancelBrowse()
{
	isBrowsing = false;
	initPlaces();
//	new Effect.Fade($('divLoading'), {duration: 0.01});
// 	new Effect.Fade($('dialog_overlay'), {duration: 0.1});
}


var within_history_handler = false;
function RemoveWithinHistory()
{
	within_history_handler = false;
}


function AddLinkToBottom(hr)
{
	(function($) { // block scope

		var obj_history = $('<a>history</a>').addClass('brhist').attr('href', hr).hide();
		obj_history.appendTo(document.body);

	})(jQuery);
}

function BuildURL(){
	var url = '/places/'+StateJSON.country;
	var hasall = false;
	if (StateJSON.country == 'us' || StateJSON.country == 'canada' || StateJSON.country == 'new-zealand' || StateJSON.country == 'australia') {
		if (StateJSON.state == '' || StateJSON.state == 'all')
			hasall = true;
		url += '/' + ((hasall) ? 'all' : StateJSON.state);
	}

	if (StateJSON.country == 'uk' && StateJSON.halfpostcode != '')
		url += '/' + encodeURIComponent(StateJSON.halfpostcode);
	else {
	if (!hasall) {
			url += '/' + ((StateJSON.city != null && StateJSON.city != 'all' && StateJSON.city != '') ? StateJSON.city : 'all');
	}
	if (StateJSON.country == 'uk' && StateJSON.city == 'london') {
			url += '/' + ((StateJSON.district != 'all' && StateJSON.district != '' && StateJSON.district != null) ? StateJSON.district : 'all');
	}
	}

	if (StateJSON.category != '')
		url += '/' + StateJSON.category;

	if (StateJSON.subcategory != '')
		url += '/' + StateJSON.subcategory;

	var str_params = '';

	if (StateJSON.sort1 != '' && StateJSON.sort1 != null && StateJSON.sort1 != 'rating')
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'sort1=' + StateJSON.sort1;
	if (StateJSON.page != '' && StateJSON.page != null && StateJSON.page != 1)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'page=' + StateJSON.page;
	if (StateJSON.search != '' && StateJSON.search != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'search=' + encodeURIComponent(StateJSON.search);
	if (StateJSON.tag != '' && StateJSON.tag != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'tag=' + encodeURIComponent(StateJSON.tag);
	if (StateJSON.offer != '0' && StateJSON.offer != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'offer=' + StateJSON.offer;
	if (StateJSON.menu != '0' && StateJSON.menu != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'menu=' + StateJSON.menu;
	if (StateJSON.booking != '0' && StateJSON.booking != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'booking=' + StateJSON.booking;
	if (StateJSON.privatehire != '0' && StateJSON.privatehire != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'privatehire=' + StateJSON.privatehire;
	if (StateJSON.lowcost != '0' && StateJSON.lowcost != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'lowcost=' + StateJSON.lowcost;
	if (StateJSON.highcost != '0' && StateJSON.highcost != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'highcost=' + StateJSON.highcost;
	if (StateJSON.friends != '0' && StateJSON.friends != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'friends=' + StateJSON.friends;
	if (StateJSON.user != '' && StateJSON.user != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'user=' + encodeURIComponent(StateJSON.user);
	if (StateJSON.quickrate != '0' && StateJSON.quickrate != null)
		str_params += (str_params.indexOf('?') > -1 ? '&' : '?') + 'quickrate=' + encodeURIComponent(StateJSON.quickrate);

	if (str_params != '')
		url += str_params;
	return url;
}

function LocationRelative(obj)
{
	if(typeof(obj) == "undefined")
		obj = location;
	var hr = obj.href;
	if(hr.slice(0, 4) == "http")
		hr = hr.slice(hr.indexOf('/', 10));
	if(hr.indexOf('#') != -1)
		hr = hr.slice(0, hr.indexOf('#'));
	return hr;
}


function FillFromJSON(json)
{
	if(typeof $("yell_container") != "undefined")
	{
		if(json.places.length < 4)
			$("yell_container").show();
		else
			$("yell_container").hide();
	}

	var str = '';
	for (var i = 0; i < json.places.length; i++) {
			var tmp = $('divPlaceTPL').innerHTML;

		if (i == 0)
			tmp = tmp.replace(/%ad_zone_left_middle%/g, json.ad_zone_left_middle);
		else
			tmp = tmp.replace(/%ad_zone_left_middle%/g, '');

		if (i == 4)
			tmp = tmp.replace(/%ad_zone_left_middle2%/g, json.ad_zone_left_middle2);
		else
			tmp = tmp.replace(/%ad_zone_left_middle2%/g, '');

		// sponsored
		if (json.places[i].sponsored_listing != null && json.places[i].sponsored_listing != '')
		{
			sponsored_class = 'sponsored';
			sponsored_title = '<div class="item_rating sponsored_title">'
								+'<strong><i>Sponsored listing</i></strong>'
								+'</div>';
			place_link 		= '/places/sponsoredlisting/'+json.places[i].sponsored_listing;
		}
		else
		{
			sponsored_title = '';
			sponsored_class = '';
			place_link = json.places[i].place_link
		}
		tmp = tmp.replace(/%sponsored_listing%/g, sponsored_class);
		tmp = tmp.replace(/%sponsored_title%/g, sponsored_title);
		tmp = tmp.replace(/_place_link_/g, place_link);


			tmp = tmp.replace(/%place_name%/g, json.places[i].name);
			tmp = tmp.replace(/%img_src%/g, json.places[i].img_src);
			tmp = tmp.replace(/%img_title%/g, json.places[i]._img_title_);
			tmp = tmp.replace(/666/g, json.places[i].avg_rating);
			tmp = tmp.replace(/%total_reviews%/g, json.places[i].total_reviews);
			tmp = tmp.replace(/%review%/g, json.places[i].review);
			tmp = tmp.replace(/%phone%/g, json.places[i].phone);
			tmp = tmp.replace(/%place_areacity_link%/g, json.places[i].place_areacity_link);
			tmp = tmp.replace(/%place_category_link%/g, json.places[i].place_category_link);
			tmp = tmp.replace(/%place_tags%/g, json.places[i].place_tags);
			tmp = tmp.replace(/%place_address%/g, json.places[i].place_address);
			if (json.places[i].author == null)
				json.places[i].author = '';
			tmp = tmp.replace(/%author%/g, json.places[i].author);
			tmp = tmp.replace(/%map_icon%/g, json.places[i].map_icon);
			str = str + tmp;
		}

		if (json.places.length == 0) {
			str = json.prev_link;
			json.sortby = '';
			$('divMapContainer').style.display = 'none';
		}
		else
			$('divMapContainer').style.display = '';

		$('divPlaceList').innerHTML 	= str;
		$('divPagination2').innerHTML 	= json.pagination;
		$('divSortBy1').innerHTML 		= json.sortby;

		if (json.categories.trim() != '') {
			$('divCategories').innerHTML = json.categories;
			$('divCategoriesContainer').show();
		}
		else {
			$('divCategoriesContainer').hide();
		}
	$('breadcrumbs').innerHTML = json.breadcrumbs;
	if ($('search_input1') != null) {
		var search = decodeURIComponent(StateJSON.search).replace(/\\"/g, '"');
		$('search_input1').value = decodeURIComponent(search);
    }

		$('localexperts').innerHTML 	= json.localexperts;

		if (json.area_info != null)
		{
			$('hrefEditInfo').href 		= '/places/areawiki?country='+json.area_info.country+'&city='+json.area_info.city+'&area='+json.area_info.area;
		}

		//$('divAreasContainer')
		if (json.wiki != '')
		{
			$('divAreaWiki').innerHTML 		= json.wiki;
			$('divWikiContainer').show();
		}
		else
			$('divWikiContainer').hide();

		if (json.wiki_long != '')
		{
			$('divAreaWiki').innerHTML += "<span class=\"likehref\" onclick=\"Element.toggle('divAreaWiki');Element.toggle('divAreaWikiLong');\">More</span>";
			$('divAreaWikiLong').innerHTML	= json.wiki_long + "<br />	<span class=\"likehref\" onclick=\"Element.toggle('divAreaWiki');Element.toggle('divAreaWikiLong');\">Less</span>";
		}
		$('h2AreaName').innerHTML 		= json.wiki_title;

		str = ''
		for (var i = 0; i < json.wiki_links.length; i++)
		{
			str += '<li><a rel="nofollow" href="'+json.wiki_links[i].url+'" target="_blank">'+json.wiki_links[i].name+'</a></li>';
		}

		if (str != '')
		{
			$('ulWikiLinks').innerHTML = str;
			$('divLinksContainer').show();
		}
		else
			$('divLinksContainer').hide();

	str = '';
	str += '<h2>' + json.xlinks.title + '</h2>';
	for (var i = 0; i < json.xlinks.sections.length; i++)
	{
		section = json.xlinks.sections[i];
		str += '<ul><li><h3>' + section.title + '</h3></li>';
		for (var bi = 0; bi < section.items.length; bi++)
		{
			str += '<li><a class="plain" href="' + section.items[bi].link+'" class="brhist">'+section.items[bi].text+'</a></li>';
		}
		str += '</ul>';
	}
	str += '<div class="clearboth"></div>';
	for (var i = 0; i < json.xlinks.sections2.length; i++)
	{
		section = json.xlinks.sections2[i];
		str += '<ul><li><h3>' + section.title + '</h3></li>';
		for (var bi = 0; bi < section.items.length; bi++)
		{
			str += '<li><a class="plain" href="' + section.items[bi].link+'" class="brhist">'+section.items[bi].text+'</a></li>';
		}
		str += '</ul>';
	}

	$('ulXlinks').innerHTML = str;

		geos = json.geos;
//		initPlaces();

		if (json.browse_areas != null && json.browse_areas.trim() != '')
		{
			$('divAreas').innerHTML = json.browse_areas;
			$('divAreasContainer').show();
		}
		else
		{
			$('divAreasContainer').hide();
		}

		//browse title
		$('h1Title').innerHTML = json.browse_title;

		//map
		if (json.is_mapsmall) {
		BuildMap(json.mapsmall);
		}
		else {
			$('divMapContainer').hide();
		}

		//rss
		var rss_links = document.getElementsByTagName('link');
		for (var k = 0; k < rss_links.length; k++)
		{
			if (rss_links[k].type == 'application/rss+xml')
			{
				rss_links[k].title 	= json.page_title;
				rss_links[k].href	= json.rss_link;
			}
		}
		$('hrefRssLink').href = json.rss_link;

		//kml
		$('hrefBigMap').href 	= json.bigmap_link;
		$('search_where').value = json.search_where;

		document.title = json.page_title;
}

function AddToHistory(json)
{
//	if (json_history.length < json_history_maxlength)
//		json_history.push(json);
//	else
//	{
//		json_history.shift();
//		json_history.push(json)
//	}
	if (json_history.length >= json_history_maxlength)
		json_history.shift();

	json_history[BuildURL()] = json;
}

function GetFromHistory(url)
{
	return json_history[url];
}

function FillFromHistoryCache(json) {
	FillFromJSON(json);
	$('divMain').show();
	$('divLoading').hide();
}

function AddAreaWikiLink()
{
	tAreaWikiLinkCount = $("#useful_links").get(0).childNodes.length;
	t_id = "useful_link_" + tAreaWikiLinkCount;

    var newDiv = document.createElement("div");
	newDiv.innerHTML +=
		"<div id='" + t_id + "'>" +
		"Name: <input type='text' name='link_name[]' size='20' /><br/> " +
		"URL:  <input type='text' name='link_url[]'  size='30' /> " +
		"<button onclick=\"RemoveAreaWikiLink('" + t_id + "')\">x</button>" +
		"</div>";
    $("#useful_links").get(0).appendChild(newDiv);

}

function RemoveAreaWikiLink(id)
{
	$('#'+id).html('');
}

function MapToolTip()
{
	return toolTip2.tipOver($('previewmap'));
}

function BuildMap(img_url)
{
	var imgMap = document.createElement('img');
	imgMap.setAttribute('src', img_url);
	imgMap.setAttribute('width', 300);
	imgMap.setAttribute('height', 372);
	imgMap.setAttribute('id', 'previewmap');
	$('mapsmall').innerHTML = '';
	$('mapsmall').appendChild(imgMap);
}

function SetQuickRate()
{
	if (StateJSON.quickrate == 1 && $('hiddenQuickRate') != null)
		$('hiddenQuickRate').value = 1;
}

