/*
 * Copyright 2008, 2009 Xavier Le Bourdon, Christoph Böhme, Mitja Kleider
 *
 * This file is part of Openstreetbugs.
 *
 * Openstreetbugs is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Openstreetbugs is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Openstreetbugs.  If not, see <http://www.gnu.org/licenses/>.
 */


/*
 * This file implements the client-side of openstreetbugs. To use it in an
 * application simply add this file and call init_openstreetmap with a map
 * object and the path of the server-side scripts.
 *
 * Please have a look at osb-example.html to see how to add openstreetbugs
 * to your website.
 */

/* The meaning of the "osb_state" values
	1 - open popup for existing bugs
	2 - add new bug popup
	3 - add comment popup
	4 - mark bug as fixed popup
	5 - mark bug as invalid popup
	6 - reopen bug (my bug if the user is autentificated and the bug is invalid)
*/

/*
 * Some utility functions
 */

/* Strip leading and trailing whitespace from str.
 */
function strip(str)
{
	return str.replace(/^\s+|\s+$/g, "");
}

/* Escape html special characters in str.
 */
function escape_html(str)
{
	if(!(str instanceof String))
		str = str.toString();

	str = str.replace(/&/g, "&amp;");
	str = str.replace(/"/g, "&quot;");
	str = str.replace(/</g, "&lt;");
	str = str.replace(/>/g, "&gt;");
	str = str.replace(/'/g, "&#146;");
	return str;
}

/* Save value in a session cookie named "name".
 */
function set_cookie(name, value)
{
	var expires = (new Date((new Date()).getTime() + 604800000)).toGMTString(); // one week from now
	document.cookie = name+"="+escape(value)+";expires="+expires+";";
}

/* Retrieve the value of cookie "name".
 */
function get_cookie(name)
{
	if (document.cookie)
	{
		var cookies = document.cookie.split(";");
		for (var i in cookies)
		{
			if(i*1 != i) continue;
			c = cookies[i].split("=");
			if (strip(c[0]) == name){
				return decodeURIComponent(strip(c[1]));
			}
		}
	}
	return null;
}

/* These functions do some coordinate transformations
 */
function plusfacteur(a) { return a * (20037508.34 / 180); }
function moinsfacteur(a) { return a / (20037508.34 / 180); }
function y2lat(a) { return 180/Math.PI * (2 * Math.atan(Math.exp(moinsfacteur(a)*Math.PI/180)) - Math.PI/2); }
function lat2y(a) { return plusfacteur(180/Math.PI * Math.log(Math.tan(Math.PI/4+a*(Math.PI/180)/2))); }
function x2lon(a) { return moinsfacteur(a); }
function lon2x(a) { return plusfacteur(a); }
function lonLatToMercator(ll) { return new OpenLayers.LonLat(lon2x(ll.lon), lat2y(ll.lat)); }

/*###############################################################*/
var TEMPLATE_SYNTAX = /(^|.|\r|\n)(#\[\[\s*(\w+)\s*\]\])/; //matches symbols like '#[[ field ]]'
/**
 * Html markup for popups showing unresolved bugs.
 */
function popup_open_bug(bug_or_id) {

	bug = bug_or_id instanceof Object ? bug_or_id : get_bug(bug_or_id);
	var data = Object.clone(bug);
	data.top = parseFloat(data.lat)+0.002;
	data.bottom = data.top - 0.004;
	data.left = parseFloat(data.lon-0.003);
	data.right = data.left + 0.006;
	data.classname = 'js_hide_element';
	if(data.numberOfComments > 0){
		data.classname = "";
	}
	data.text = escape_html(data.text);

	var bugTemplate = new Template($('osmbugs_unresolved').innerHTML, TEMPLATE_SYNTAX);
	return bugTemplate.evaluate(data);

}

/**
 * Html markup for popups showing fixed bugs.
 */
function popup_closed_bug(bug_or_id) {
	bug = bug_or_id instanceof Object ? bug_or_id : get_bug(bug_or_id);
	var data = Object.clone(bug);
	if(data.numberOfComments > 0){
		data.classname = "";
	}
	data.text = escape_html(data.text);

	if(data.status == 'INVALID'){
		var bugTemplate = new Template($('osmbugs_invalid').innerHTML, TEMPLATE_SYNTAX);
		if(data.reopen_bug == 1 )
		{
			var reopenLink = new Template($('osmbugs_reopen_link').innerHTML, TEMPLATE_SYNTAX);
			data.reopenLink = reopenLink.evaluate(data);
		}
		else
		{
			data.reopenLink = "";
		}

	} else{
		var bugTemplate = new Template($('osmbugs_closed').innerHTML, TEMPLATE_SYNTAX);

		if(data.reopen_bug == 1 )
		{
			var reopenLink = new Template($('osmbugs_reopen_link').innerHTML, TEMPLATE_SYNTAX);
			data.reopenLink = reopenLink.evaluate(data);
		}
		else
		{
			data.reopenLink = "";
		}

	}	
	return bugTemplate.evaluate(data);
}

/**
 * Html markup for popups for new bug reports.
 */
function popup_add_bug(x, y, nickname, description) {
	var _TEMPLATE_SYNTAX = /(^|.|\r|\n)(#\s\[\[\s*(\w+)\s*\]\])/; //matches symbols like '# [[ field ]]'
	var bug = {
		x2lon: x2lon(x),
		y2lat: y2lat(y),
		nickname: escape_html(nickname),
		description: escape_html(description)
	}
	var bugTemplate = new Template($('osmbugs_add').innerHTML, _TEMPLATE_SYNTAX);
	return bugTemplate.evaluate(bug);
}


/**
 * Html markup which is shown in the popup when a new bug is being submitted.
 */
function popup_add_bug_wait() {
	var bugTemplate = new Template($('osmbugs_wait').innerHTML, TEMPLATE_SYNTAX);
	return bugTemplate.evaluate({});
}

/*###############################################################*/

/*
 * Openstreetbugs main functions
 */

/* base url for images used by openstreetbugs:
 */
var osb_img_path = "js/lib/osm_bugs/";

/* Map object to which openstreetbugs has been added:
 */
var osb_map = null;

/* Feature layer for openstreetbugs:
 */
var osb_layer = null;

/* List of downloaded bugs:
 */
var osb_bugs = new Array();

/* Current state of the user interface. This is used
 * to keep track which popups are displayed. */
var osb_state = 0;
var osb_current_feature = null;

/* Stores the last used filters */
var osb_filters = {bugTypes: new Array(), bugStatuses: new Array(), defaultDescription: 0, minR:0, maxR:17};
var clear_map = false;

/* Call this method to activate openstreetbugs on the map.
 * The argument map must refer to an Openlayers.Map object. The
 * second argument defines the path on the server which contains
 * the openstreetbugs server side scripts.
 */
function init_openstreetbugs(map, server_path)
{
	osb_map = map;

	document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "crosshair";

	osb_layer = new OpenLayers.Layer.Markers("MapDust");

	osb_map.addLayer(osb_layer);

	osb_map.events.register('moveend', osb_map, refresh_osb);

	var click = new OpenLayers.Control.Click();
	osb_map.addControl(click);
	click.activate();

	init_bug_filter();
	refresh_osb();
}

function init_mybugs(map, lat, lon, server_path){

	map.setCenter(new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()), 14);

	//destroy existing markers
	osb_layer = new OpenLayers.Layer.Markers( "mybugsmarkers" );
    map.addLayer(osb_layer);
	
	var icon = create_bug_icon(skobbler_BUG_TYPE, skobbler_BUG_STATUS);
	
    osb_layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lon2x(lon), lat2y(lat)),icon));
    //markers.addMarker(new OpenLayers.Marker( new OpenLayers.LonLat(lat,lon),icon));

}

function show_bug_on_mybugs(map, lat, lon, server_path){

	map.setCenter(new OpenLayers.LonLat(lon, lat).transform(new OpenLayers.Projection("EPSG:4326"), map.getProjectionObject()), 14);

	/* remove and destroy all markers */
	var marker;
	while( osb_layer.markers.length ) {
		marker = osb_layer.markers[0];
		osb_layer.removeMarker(osb_layer.markers[0]);
		marker.destroy();
		/*marker = null;*/
	}

    var icon = create_bug_icon(skobbler_BUG_TYPE, skobbler_BUG_STATUS);
    osb_layer.addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lon2x(lon), lat2y(lat)),icon));
    //markers.addMarker(new OpenLayers.Marker( new OpenLayers.LonLat(lat,lon),icon));
}

function close_popup() {
	if( osb_state == 0) return;
	if(osb_state == 2) { // new bug popup is opened
		document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "crosshair";
		osb_layer.removeMarker(osb_current_feature.marker);
		osb_map.removePopup(osb_current_feature.popup);
		osb_current_feature.destroy();
		osb_current_feature = null;
		osb_state = 0;
		//refresh_osb();
	} else {//existing bug popup is opened // osb_state == 1 || osb_state == 3 || osb_state == 4 || osb_state == 5
		document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "crosshair";
		osb_map.removePopup(osb_current_feature.popup);
		osb_state = 0;
	}

	removeJOSMHandler();


}

/*
 * Bug management
 */

/* Downloads new bugs from the server.
 */
function refresh_osb()
{
	if (refresh_osb.call_count == undefined){
		refresh_osb.call_count = 0;
	}
	else{
		++refresh_osb.call_count;
	}

	bounds = osb_map.getExtent().toArray();
	b = shorter_coord(y2lat(bounds[1]));
	t = shorter_coord(y2lat(bounds[3]));
	l = shorter_coord(x2lon(bounds[0]));
	r = shorter_coord(x2lon(bounds[2]));

	var params = {
		"b": b, "t": t, "l": l, "r": r,
		"ucid": refresh_osb.call_count,
		"ft": osb_filters.bugTypes.join(','),
		"fs": osb_filters.bugStatuses.join(','),
		"fd": osb_filters.defaultDescription,
		"minR" : osb_filters.minR,
		"maxR" : osb_filters.maxR
	};
	
	// updating RSS feed links
	document.getElementById("rssFeed").href = skobbler_FEED_URL+"&b="+b+"&t="+t+"&l="+l+"&r="+r+"&ft="+params.ft+"&fd="+params.fd+"&minR=" + params.minR + "&maxR=" + params.maxR ;
	
	get_bugs(params);
	get_bugs_statistics(params);

	if(jQuery.browser.opera){
		getMapSettings();
	}

	//osb_state = 0;
}

/* shorten coordinate to 5 digits in decimal fraction */
function shorter_coord(coord)
{
	return Math.round(coord*100000)/100000;
}

/* Check if a bug has been downloaded already.
 */
function bug_exist(id)
{
	for (var i in osb_bugs)
	{
		if (osb_bugs[i].id == id) {
			return true;
		}
	}
	return false;
}

/* Return a bug description from the list of downloaded bugs.
 */
function get_bug(id)
{
	for (var i in osb_bugs)
	{
		if (osb_bugs[i].id == id) {
			return osb_bugs[i];
		}
	}
	return '';
}

/* This function creates a feature and adds a corresponding
 * marker to the map.
 */
 
function create_feature(x, y, popup_content, status, bug_type)
{
	var icon = create_bug_icon(bug_type, status);
	var feature = new OpenLayers.Feature(osb_layer, new OpenLayers.LonLat(x, y), {icon: icon});
	// TODO closeBox should be true, but not closing bugs by clicking the marker leads to buggy behaviour
	feature.closeBox = false;
	//feature.popupClass = OpenLayers.Class(Skobbler.Popup); /* for popup arrow fix */
	feature.popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud); /* for popup arrow fix */

	feature.data.popupContentHTML = popup_content;

	create_marker(feature);
	return feature;
}

function create_marker(feature)
{
	var marker = feature.createMarker();
	var marker_click = function (ev)
	{
		if(osb_current_feature != this && (osb_state == 1 || osb_state == 2)) {
			close_popup();
		}
		if (osb_state == 0)
		{
			this.createPopup(this.closeBox);
			osb_map.addPopup(this.popup);
			osb_state = 1;
			osb_current_feature = this;
			addJOSMHandler();
		}
		else if (osb_state == 1 && osb_current_feature == this)
		{
			osb_map.removePopup(this.popup)
			osb_state = 0;
			osb_current_feature = null;
		}
		document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "pointer";
		OpenLayers.Event.stop(ev);
	};
	feature.autoclick = marker_click; // used for auto-popuping after bug search
	var marker_mouseover = function (ev)
	{
		if (osb_state == 0)
		{
			document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "pointer";
			this.createPopup(this.closeBox);
			osb_map.addPopup(this.popup);

		}

		// if on bug detail popup: show pointer over all other bug icons
		if (osb_state == 1){
			document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "pointer";
		}

		OpenLayers.Event.stop(ev);
	};
	var marker_mouseout = function (ev)
	{
		if (osb_state == 0)
		{
			document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "crosshair";
			osb_map.removePopup(this.popup);
		}
		else
			document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "default";
		OpenLayers.Event.stop(ev);
	};
	/* marker_click must be registered as click and not as mousedown!
	 * Otherwise a click event will be propagated to the click control
	 * of the map under certain conditions.
	 */
	marker.events.register("click", feature, marker_click);
	marker.events.register("mouseover", feature, marker_mouseover);
	marker.events.register("mouseout", feature, marker_mouseout);

	osb_layer.addMarker(marker);
}


/*
 * Control to handle clicks on the map
 */

OpenLayers.Control.Click = OpenLayers.Class(OpenLayers.Control, {

	initialize: function() {
		OpenLayers.Control.prototype.initialize.apply(this, arguments);
	},

	destroy: function() {
		if (this.handler)
			this.handler.destroy();
		this.handler = null;

		OpenLayers.Control.prototype.destroy.apply(this, arguments);
	},

	draw: function() {
		handlerOptions = {
		'single': true,
		'double': false,
		'pixelTolerance': 0,
		'stopSingle': false,
		'stopDouble': false
		};

		this.handler = new OpenLayers.Handler.Click(this, {'click': this.click}, handlerOptions);
	},

	click: function(ev) {
		if(osb_state == 1 || osb_state == 2) {
			close_popup();
		} else {
			var lonlat = osb_map.getLonLatFromViewPortPx(ev.xy);
			add_bug(lonlat.lon, lonlat.lat, null, '', 'other');
		}
	},

	CLASS_NAME: "OpenLayers.Control.Click"
});


/*
 * Actions
 */

function add_bug(x, y, nickname, description, type)
{
	if(osb_state == 0)
	{
		document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "default";

		osb_state = 2;
		var nn = (nickname != null)? nickname: get_cookie("osb_nickname");
		osb_current_feature = create_feature(x, y, popup_add_bug(x, y, nn, description), 'OPEN', type);

		osb_current_feature.createPopup(osb_current_feature.closeBox);
		osb_map.addPopup(osb_current_feature.popup);

		type_select = document.getElementById('type');
		for(i=0; i<type_select.length; i++){
			if(type_select[i].value == type){
				type_select[i].selected = true;
				break;
			}
		}

		if(testIfHuman)
		{
			refreshCaptcha( captcha_url ,'#add_new_bug');
		}
		document.getElementById('description').focus();
	}
}


function add_bug_completed()
{
	document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "crosshair";

	osb_layer.removeMarker(osb_current_feature.marker);
	osb_map.removePopup(osb_current_feature.popup);
	osb_current_feature.destroy();
	osb_current_feature = null;
	osb_state = 0;
	refresh_osb();
}

function add_bug_cancel()
{
	document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "crosshair";

	osb_layer.removeMarker(osb_current_feature.marker);
	osb_map.removePopup(osb_current_feature.popup);
	osb_current_feature.destroy();
	osb_state = 0;
	osb_current_feature = null;
}




function reset_popup(id)
{
	document.getElementById("OpenLayers.Map_7_OpenLayers_Container").style.cursor = "default";
	osb_current_feature.data.commentsVisibility = false;

	var bug = get_bug(id);
	if (bug.status == 'OPEN')
		bug.feature.popup.setContentHTML(popup_open_bug(id));
	else
		bug.feature.popup.setContentHTML(popup_closed_bug(id));

	osb_state = 1;
	addJOSMHandler();
}

function clear_overlays()
{
	/* remove and destroy all markers */
	var marker;
	while( osb_layer.markers.length ) {
		marker = osb_layer.markers[0];
		osb_layer.removeMarker(osb_layer.markers[0]);
		marker.destroy();
		/*marker = null;*/
	}
	osb_bugs = []; /* markers not present anymore */

	/* remove and destroy all popups */
	var popup;
	while( osb_map.popups.length ) {
		popup = osb_map.popups[0];
		osb_map.removePopup(osb_map.popups[0]);
		popup.destroy();
		/*popup = null;*/
	}
}

/**
 * AJAX functions
 *
 */

function add_bug_submit(form) {


//This works on ie 7
//	alert(jQuery(form).children(":first").children('input[name=lon]').val());
	var bug_lon = jQuery(form).children(":first").children('input[name="lon"]').val();
	var bug_lat = jQuery(form).children(":first").children('input[name="lat"]').val();
	var bug_type= jQuery(form).children(":nth-child(2)").children('select[name="type"]').val();
	var bug_descr = jQuery(form).children(":nth-child(4)").children('textarea[name="description"]').val();
	var bug_nick =jQuery(form).children(":nth-child(3)").children('input[name="nickname"]').val(); //(form.nickname.value!="")?form.nickname.value:null;
	var captcha_value = "" ;
	if(testIfHuman)
	{
		captcha_value = jQuery(form).children(":nth-child(5)").children('input[name="captcha_value"]').val();
	}

	bug_descr = strip(bug_descr);
	bug_nick = strip(bug_nick);

	osb_current_feature.popup.setContentHTML(popup_add_bug_wait());
	new Ajax.Request(form.action, {
			evalJSON: true,
			method: 'POST',
			parameters: {
						lon: bug_lon,
						lat: bug_lat,
						type: bug_type,
						description: bug_descr,
						nickname: bug_nick,
						captcha_value:captcha_value
					},
			onSuccess: function(data) {
				var response = data.responseJSON;
				if (response.status == 'SUCCESS') {
					add_bug_completed();
				}
				if (response.status == 'ERROR') {
					add_bug_cancel();
					add_bug(lon2x(bug_lon), lat2y(bug_lat), bug_nick, bug_descr, bug_type);
					var comErr = $(osb_current_feature.id+'_popup').down('.commentErrors');

					var errorTpl = new Template($('osmbugs_comment_error').innerHTML, TEMPLATE_SYNTAX);
					response.data = {};
					response.data.commentsErrors = "";
					for(var i=0; i<response.errors.length; i++) {
						response.data.commentsErrors += errorTpl.evaluate({commentError: response.errors[i]});
					}
					var errorsTpl = new Template($('osmbugs_comments_error').innerHTML, TEMPLATE_SYNTAX);

					comErr.innerHTML = errorsTpl.evaluate(response.data);
					comErr.removeClassName("js_hide_element");

					osb_current_feature.popup.setContentHTML($(osb_current_feature.id+'_popup_contentDiv').innerHTML);
					if(testIfHuman)
					{
						refreshCaptcha( captcha_url ,'#add_new_bug'); 
					}
				}
			}
		});

}

/* This function is called from the scripts that are returned
 * on make_request calls.
 */
function putMarker(bug) {
	if (!bug_exist(bug.id)) {
		//var bug = {id: id, text: text, lat: lat, lon: lon, type: type, status: status, nickname: nickname, dateCreated: dateCreated, numberOfComments: numberOfComments, feature: null};
		bug.feature = null;
		if (bug.status == 'OPEN')
			bug.feature = create_feature(lon2x(bug.lon), lat2y(bug.lat), popup_open_bug(bug), bug.status, bug.type_const, bug.relevanceCategory, bug.relevanceString);
		else
			bug.feature = create_feature(lon2x(bug.lon), lat2y(bug.lat), popup_closed_bug(bug), bug.status, bug.type_const, bug.relevanceCategory, bug.relevanceString);

		osb_bugs.push(bug);
	}
}

function get_bugs(params) {
	new Ajax.Request(skobbler_GET_BUGS_URL, {
			evalJSON: true,
			method: 'POST',
			parameters: params,
			onSuccess: function(data) {
				if(clear_map == true){
					clear_map = false;
					clear_overlays();
				}
				var response = data.responseJSON;
				if (response.status == 'SUCCESS') {
					var bugs = response.data.bugs;

					for(var i=0; i<bugs.length; i++) {
						putMarker(bugs[i]);
					}
					
				}
				if (response.status == 'ERROR') {
				}
				// hiding filter loading progress image
				$('osmbugs_filter_loading').innerHTML = '';
			}
		});
}

function get_bugs_statistics(params) {
	new Ajax.Request(skobbler_GET_BUGS_STATISTICS_URL, {
			evalJSON: true,
			method: 'POST',
			parameters: params,
			onSuccess: function(data) {

				var response = data.responseJSON;
				var statisticsTemplate = new Template($('statistics').innerHTML, TEMPLATE_SYNTAX);
				$('statistics_html').innerHTML =  statisticsTemplate.evaluate(response);
				 
			}
		});
}


/**
 * especially for IE
 * container - id or element
 * content - string
 */
function set_content(container, content) {
	var old_container = $(container);
	var new_container = document.createElement(old_container.tagName);
	new_container.id = old_container.id;
	new_container.className = old_container.className;
	new_container.innerHTML = content;
	old_container.parentNode.replaceChild(new_container, old_container);
}

function getFilters(){
	// bug type
	var checkedTypes = new Array();
	var i = 0;
	$$(".bug_filter_type").each(function(item) {
		if(item.checked){
			checkedTypes[i++] = item.value;
		}
	});

	// bug status
	var checkedStatuses = new Array();
	var i = 0;
	$$(".bug_filter_status").each(function(item) {
		if(item.checked){
			checkedStatuses[i++] = item.value;
		}
	});

	// default description
	var checkedDefaultDescription = $$(".bug_filter_default_description")[0].checked * 1;
	var minR = $("minR").value;
	var maxR = $("maxR").value;

	return {bugTypes: checkedTypes, bugStatuses:checkedStatuses, defaultDescription:checkedDefaultDescription, minR:minR, maxR:maxR};
}

function init_bug_filter(){
	 
	osb_filters = getFilters();
	if($("bug_filter") == null) return;
	$("bug_filter").observe('click', function(ev) {
		ev.stop();

		// getting filters
		var filters = getFilters();

		if(filters.bugTypes.length == 0){
			if(typeof skobbler_OSMBUGS_FILTER_ERROR_TYPE !== "undefined"){
				//alert(skobbler_OSMBUGS_FILTER_ERROR_TYPE);
			}
			return;
		}
		if(filters.bugStatuses.length == 0){
			if(typeof skobbler_OSMBUGS_FILTER_ERROR_STATUS !== "undefined"){
				//alert(skobbler_OSMBUGS_FILTER_ERROR_STATUS);
			}
			return;
		}

		$('osmbugs_filter_loading').innerHTML = $('osmbugs_filters_loading').innerHTML;

		//saving the new filters
		osb_filters = filters;

		clear_map = true;

		refresh_osb();

	});
}

function toggleFilters(){
	$('filterBody').toggle();
	return;
}

function addJOSMHandler() {

	if( hideJOSMDescription == 1 )
	{
		var directJOSM = $(osb_current_feature.id+'_popup').down('.editJOSM');
		if(typeof directJOSM == 'undefined') return;
		Event.observe(directJOSM, "click", onJOSMYesClick);
	}
	else
	{
		if(typeof osb_current_feature == 'undefined') return;
		var josmLink = $(osb_current_feature.id+'_popup').down('.editJOSM');
		if(typeof josmLink == 'undefined') return;
		Event.observe(josmLink, "click", onJOSMClick);
	}
}

function removeJOSMHandler() {
	if(typeof osb_current_feature == 'undefined' ||  $(osb_current_feature.id+'_popup') == null ) return;
	var josmLink = $(osb_current_feature.id+'_popup').down('.editJOSM');
	Event.stopObserving(josmLink, "click", onJOSMClick);
}

function onJOSMClick() {
	if(typeof osb_current_feature == 'undefined') return;
	var pop = $(osb_current_feature.id+'_popup').down('.JOSMCheck');
	pop.show();
	var noEl =  $(osb_current_feature.id+'_popup').down('.JOSMCheck_No');
	var yesEl =  $(osb_current_feature.id+'_popup').down('#JOSMCheck_Yes');
	Event.observe(noEl, "click", onJOSMNoClick);
	Event.observe(yesEl, "click", onJOSMYesClick);
}


function onJOSMNoClick(ev) {
	Event.stop(ev);
	JOSMPopupHide();
	Event.stopObserving(this, "click", onJOSMNoClick);
}

function onJOSMYesClick(ev) {
	Event.stop(ev);
	var form = $('josm_yes');
	form.target = "hiddenIframe";
	form.submit();
	//check if do not show JOSM description is checked
	if( jQuery('#do_not_show_JOSMmsg').attr('checked'))
	{
		setTimeout ( "JOSMDescriptionHideEvent()", 1000 );
	}
	else
	{
		if( !hideJOSMDescription )
		{
			JOSMPopupHide();
			Event.stopObserving(this, "click", onJOSMYesClick);
		}
	}

}

function JOSMDescriptionHideEvent()
{

	jQuery.cookie("cookieJOSMDescriptionHide", 1, {expires:30, path:'/'} );
	location.reload();

}


function JOSMPopupHide() {
	var pop = $(osb_current_feature.id+'_popup').down('.JOSMCheck');
	pop.hide();
}


