
var selectedmarker;
var DATA_TYPE = 'POINT';
var polyline = new Array();
//var all_items = new Array();



/***************************************
Cleans Blanks from any input	
****************************************/
function cleanBlanks(source){
	temp_string = source;
	source = (temp_string.replace(/^\W+/,'')).replace(/\W+$/,'');
	alert('fun cleanBlanks');
	return source
}

/**************************
Fills the needed field in the form, when posting
***************************/

function fill_id_coords() {
// this is the function who fill the coords in POST process    
    if (DATA_TYPE=='POINT'){
        lon = selectedmarker.getPoint().lng();
        lat = selectedmarker.getPoint().lat();
        full_value = '('+lon+", "+lat+')';
    }
    else {
        full_value = '';
        for (var i=0; i<polyline.length; i++){           
            point = polyline[i];
            full_value += '('+ point.lng() + ', ' + point.lat() + ')';
            if (i<(polyline.length-1)){
            full_value += ', ';            
            } 
        }
    }
    
    $("#id_coords").val(full_value);

}

/***************************************
Creates a draggable marker and updates the needed fields
Used in post, but it doesn't work
****************************************/
function markerdraggable(lat,lon, options, icon) {
    var thismarker;
    /* ########################################### */
    if (icon != null)
    {
        new_icon_url = media_url + "img/placemarkers/"+ icon +".png";
    } 
    else
    {
        new_icon_url = media_url + "img/placemarkers/default.png";/* "http://tagzania2.cs/st/img/placemarkers/ */
    }
    
    var func_icon = new GIcon();
    func_icon.image = new_icon_url;
    func_icon.iconSize = new GSize(27, 34);
    func_icon.shadowSize = new GSize(47, 46);
    func_icon.iconAnchor = new GPoint(12, 33);
    var options = {};
    options.icon = func_icon;
    options.draggable = true;
    /* ########################################### */    
    thismarker = new GMarker(new GLatLng(lat,lon), options );
    
    GEvent.addListener(thismarker, "dragstart", function() {
       selectedmarker = thismarker;
    });
    GEvent.addListener(thismarker, "dragend", function() {
       fill_id_coords();
       //marker.openInfoWindowHtml(document.getElementById('form2').innerHTML);
    });
    markerdraggable_listener = GEvent.addListener(map, "click", function() 
    {
       fill_id_coords();
       //marker.openInfoWindowHtml(document.getElementById('form2').innerHTML);
    });
	return thismarker;  
}

/* 
/********************************************
posts an point with a single click on the map
*********************************************
function post_point(){
    GEvent.clearListeners(map, "click");
	GEvent.addListener (map, "click", function(overlay, point){
		map.clearOverlays();
		marker = markerdraggable(point.lat(), point.lng(),{draggable:true});
		map.addOverlay(marker);
		selectedmarker=marker;
    	//marker.openInfoWindowHtml(document.getElementById('form2').innerHTML);
		fill_id_coords();
	});
}

/*******************************************
posts a polyline, defining points with a single click
********************************************
function post_polyline_BACKUP(){
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.image = "/static/img/tz_point.png";
	//blueIcon.size = new GSize(32,32);
	if (polyline.length < 1){
	    polyline.push(new GLatLng(lastlat, lastlon));
	}
	GEvent.clearListeners(map,  "click");
	GEvent.addListener (map, "click", function(overlay, point){
		map.clearOverlays();
		polyline.push(new GLatLng(point.lat(), point.lng()));
		line = new GPolyline(polyline);
		map.addOverlay(line);
		start_marker = markerdraggable(polyline[0].lat(), polyline[0].lng(),{draggable:true});
		map.addOverlay(start_marker);
		plength = polyline.length;
		if (polyline.length > 1){
			end_marker = markerdraggable(polyline[plength-1].lat(), polyline[plength-1].lng(),{draggable:true});
		    map.addOverlay(end_marker);
		}
		fill_id_coords();
	});	
	
}

function post_polyline(){
 
  var line = new GPolyline([], "#ff6600");
  startDrawing(line, "Line " + (++lineCounter_), function() { }, "#ff6600");
  
}
/*******************************************
posts a polygon, defining points with a single click
********************************************
function post_polygon(){
	var yellowIcon = new GIcon(G_DEFAULT_ICON);
	yellowIcon.image = "/static/img/tz_point.png";
	//blueIcon.size = new GSize(32,32);
	//disable double click zoom
	if (polyline.length < 1){
	    polyline.push(new GLatLng(lastlat, lastlon));
	}
	GEvent.clearListeners(map,  "click");
    GEvent.addListener (map, "click", function(overlay, point){
		map.clearOverlays();
		polyline.push(new GLatLng(point.lat(), point.lng()));
		polygon_draw = new GPolyline(polyline);
		map.addOverlay(polygon_draw);
		fill_id_coords();		
	});

	map.disableDoubleClickZoom();
	GEvent.addListener (map, "dblclick", function(overlay, point){
	    alert('-1');
		map.clearOverlays();
		alert('0');
		polyline.push(new GLatLng(point.lat(), point.lng()));
		alert('1');
		polyline.push(polyline[0]);
		alert('2');
		//GLog.write(	polyline[polyline.length-2] + ' ' +polyline[polyline.length-1] + ' ' + polygon[0]);
		polygon_draw = new GPolygon(polyline,fillColor="BC8F8F");
		map.addOverlay(polygon_draw);
		alert('Honaino bai?');
		if (polyline.length > 1){
		    polyline.push(new GLatLng(polyline[0].lat(), polyline[0].lng()));
		    fill_id_coords();			
		}			
	});	
	

}



/********************************************
START DRAWING POINTS / LINES / SHAPES
*********************************************
function startDrawing(poly, name, onUpdate, color) {
  map.addOverlay(poly);
  poly.enableDrawing(options);
  poly.enableEditing({onEvent: "mouseover"});
  poly.disableEditing({onEvent: "mouseout"});
  GEvent.addListener(poly, "endline", function() {
      alert("ADDLISTENER AMAITUIK");
    //select("hand_b");
    var cells = addFeatureEntry(name, color);
    //detailInfo_.innerHTML = "endline";
    GEvent.bind(poly, "lineupdated", cells.desc, onUpdate);
    GEvent.addListener(poly, "click", function(latlng, index) {
      //detailInfo_.innerHTML = "latlng = " + latlng + ", index = " + index;
      if (typeof index == "number") {
        poly.deleteVertex(index);
      } else {
        var newColor = getColor(false);
        cells.color.style.backgroundColor = newColor
        poly.setStrokeStyle({color: newColor, weight: 4});
      }
    });
    fill_id_coords();  
  });
}

function addFeatureEntry(name, color) {
  currentRow_ = document.createElement("tr");
  var colorCell = document.createElement("td");
  currentRow_.appendChild(colorCell);
  colorCell.style.backgroundColor = color;
  colorCell.style.width = "1em";
  var nameCell = document.createElement("td");
  currentRow_.appendChild(nameCell);
  nameCell.innerHTML = name;
  var descriptionCell = document.createElement("td");
  currentRow_.appendChild(descriptionCell);
  featureTable_.appendChild(currentRow_);
  return {desc: descriptionCell, color: colorCell};
}

/******************************************
resets values in the form and in the javascript variables
*******************************************/
function resetCoords(){
	map.clearOverlays();
	//clear variables of polyline and polygon
	polyline = new Array();
	polygon = new Array();
	multipoint = new Array();
	setInputType();
	fill_id_coords();
	alert('fun resetCoords');
}


/*********************************************************
Checks and sets the data type that is going to be posted
**********************************************************/
function setInputType(){
	if (document.getElementById('id_item_type_1').checked){
		DATA_TYPE = 'POLYLINE';	
	}else 
		if (document.getElementById('id_item_type_2').checked){
			DATA_TYPE = 'POLYGON';
		}else{
			DATA_TYPE = 'POINT';}
}

/*************************
Deletes last point
***************************/
function delete_last(){
		if (DATA_TYPE == 'POLYLINE'){
			polyline.pop();
			map.clearOverlays();
			line = new GPolyline(polyline);
			map.addOverlay(line);	
		}else if (DATA_TYPE == 'POLYGON'){
			polyline.pop();
			map.clearOverlays();
			line = new GPolygon(polyline);
			map.addOverlay(line);
		}
		fill_id_coords();
}
/************************************
gets the data in coords_id box and creates a list of GLatLng
**************************************/

function parseCoordsField(coords){
	result = new Array();
	for (i = 0; i< coords.length/2;i++){
		coords[i*2+1]= coords[i*2+1].replace(/,/,'');
		result.push(new GLatLng(coords[i*2+1], coords[i*2]));
	}
	alert('fun parseCoordsField');
	return result;
}

/*Loads the point for editing*/
function loadForEdit(item){
	//read coords
	map.clearOverlays();
	coords = document.getElementById('id_coords').value;
	coords = coords.split(' ');
	marker = markerdraggable(coords[1], coords[0],{draggable:true})
	map.addOverlay(marker);
	selectedmarker=marker;
	//createTzmarker
	alert('fun loadForEdit');
}

function load_posting_gmap(){
   // post form. Loads gmap. needs to be moved to mapstraction

if (GBrowserIsCompatible()) {
    var mapTypes = [];
 // You can define map types 
 
    mapTypes.push(G_NORMAL_MAP);
    //mapTypes.push(G_MOON_VISIBLE_MAP);
    //mapTypes.push(G_PHYSICAL_MAP);
    mapTypes.push(G_SATELLITE_MAP);
    mapTypes.push(G_HYBRID_MAP);
    //mapTypes.push(G_SATELLITE_3D_MAP);
    
    map = new GMap2(document.getElementById("map"),{mapTypes:mapTypes});
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    if (selectedmarker==null) {  
        lat = 0;
        lon = 0;
    }
    else {
        lon = selectedmarker.getPoint().lng();
        lat = selectedmarker.getPoint().lat();
    }
    map.setCenter(new GLatLng(lat,lon),1);
  }else {
    alert("Sorry, the Google Maps API is not compatible with this browser.");
  }
}


/*
	This function parses the HTML created By django for adding points into the google map
*/

//Removes the parenthesis from the item HTML
function ParseItem(item){
	data = item.split(' ');
	data[1] = data[1].substring(1, data[1].length);
	lastone = data[data.length-1];
	lastone = lastone.substring(0,lastone.length-2);
	data[data.length-1] = lastone;
	return data;
    alert('fun ParseItem');
	
}


function createTzMarker(i){
	coords = document.getElementById('coords_'+i).innerHTML;
	coords = cleanBlanks(coords)
	loadItem = ParseItem(coords);
	type = loadItem[0];
	data = loadItem.slice(1,data.length );
	switch (type){
		case 'POINT':
			temp = new GMarker(new GLatLng(data[1],data[0]));break;
			
			GEvent.addListener(temp, "click", function() {
				html = document.getElementById('tzitem_'+ i).innerHTML;
   			temp.openInfoWindowHtml(html);
   		    });
		case 'LINESTRING':
			var points =parseCoordsField(data);
			temp = new GPolyline(points);
			break;
			 
		case 'POLYLINE':
			var points = parseCoordsField(data);
			temp = new GPolygon(points);
	}
   alert('fun createTzMarker');
   return temp
}

function addPoint(point){
    GEvent.addListener(point, "click", function() {
    	html = document.getElementById('tzitem_'+ i).innerHTML;
		temp.openInfoWindowHtml(html);
    });
    return temp;
    alert('fun addPoint');
}

function addPolyline(line){
    GEvent.addListener(line, "click", function() {
    	html = document.getElementById('tzitem_'+ i).innerHTML;
		temp.openInfoWindowHtml(html);
    });
    return temp;
    alert('fun addPolyline');
}

function load_map(){
    var mapTypes = [];
     
 // You can define map types 
  
    mapTypes.push(G_NORMAL_MAP);
    //mapTypes.push(G_MOON_VISIBLE_MAP);
    mapTypes.push(G_PHYSICAL_MAP);
    mapTypes.push(G_HYBRID_MAP);
    mapTypes.push(G_SATELLITE_3D_MAP);
  
    map_div = document.getElementById('map');
    map = new GMap2(map_div, {mapTypes:mapTypes});
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(0,0));
    map.setZoom(1);
    alert('fun load_map');
}

/*
	Displays the items of an HTML document into the google map
*/

function load_items(){
    load_map();
    length = all_items.length;
	for (i=0; i< length;i++){
		temp = all_items.pop();
		map.addOverlay(temp);
		/*if (temp instanceof GMarker){
		    GLog.write('marker');
			map.addOverlay(addPoint(temp));
		}else if (temp instanceof GPolyline){
			map.addOverlay(addPolyline(temp));
			GLog.write('line');
		}*/
	}
	alert('fun load_items');
}



function roundOff(num,decimalplaces){
        var decimalfactor = Math.pow(10,decimalplaces);
        var roundedValue = Math.round(num*decimalfactor)/decimalfactor;
        return roundedValue;
        
}


/******************************************
/* POST form
/* gotop traditional coordinates conversion
/******************************************/

function initPosting(){
    // Navigation actions
    $("#li2").click(function() {
          $("#li1 #searchTab").attr('class', 'searchTab');
          $("#li2 #coordsTab").attr('class', 'coordsTab active');
          $("#step1_1").hide ();
          $("#step1_2").show ();
         
          return false;
    });
      // Geocoding trigger    
    $("#li1").click(function() {
           $("#li1 #searchTab").attr('class', 'searchTab active');
           $("#li2 #coordsTab").attr('class', 'coordsTab');
           $("#step1_2").hide ();
           $("#step1_1").show ();
           
          return false;
    });
    
    $("#fid #searchbuttonajax").click(function() {
          launchGeocoding ();
          return false;
    });
    
    $("#gostep1").click(function() {
          $("#step2").hide ();
          $("#tabs").show ();
          $("#tab_panel").show ();
          $("#post_title_1").show();
          $("#post_title_2").hide();
          //$("#step1").show ();
          return false;
    });
    $("#gostep2").click(function() {
          //$("#step1").hide ();
          $("#tab_panel").hide ();
          $("#tabs").hide ();
          $("#step2").show ();
          $("#post_title_1").hide();
          $("#post_title_2").show();
          
           return false;
    });
    // Form triggers
    $("#gotopoint1 input:button").click(function() {
            gotopTraditional();
    });
    $("#gotopoint2 input:button").click(function() {
            gotop($("#golat").val(), $("#golon").val(), 14);
    });
   
    $("#gostep2").click(function() {
        
          if (selectedmarker==null) {
              gotop (0,0,1);
          }
          else {
          lon = selectedmarker.getPoint().lng();
          lat = selectedmarker.getPoint().lat();
          gotop (lat,lon,14);
          }
          return false;
    });
    
    $("#id_item_type_0").attr('checked','checked');
    
}


function initPosting_invalidForm(lat,lon,zoom){
      
      $("#tab_panel").hide ();
      $("#tabs").hide();
      $("#step2").show ();
      $("#post_title_1").hide();
      $("#post_title_2").show(); 
    //addDraggablePoint(lat,lon,zoom); 
    // Navigation actions
    $("#li2").click(function() {
       $("#li1 #searchTab").attr('class', 'searchTab');
       $("#li2 #coordsTab").attr('class', 'coordsTab active');
       $("#step1_1").hide ();
       $("#step1_2").show ();
      return false;
    });
     // Geocoding trigger    
    $("#li1").click(function() {
       $("#li1 #searchTab").attr('class', 'searchTab active');
       $("#li2 #coordsTab").attr('class', 'coordsTab');
       $("#step1_2").hide ();
       $("#step1_1").show ();
      return false;
    });
    
    $("#fid #searchbuttonajax").click(function() {
      launchGeocoding ();
      return false;
    });

    // Form triggers
    $("#gotopoint1 input:button").click(function() {
        gotopTraditional();
    });
    $("#gotopoint2 input:button").click(function() {
        gotop($("#golat").val(), $("#golon").val(), 14);
    });
    
    $("#gostep2").click(function() {
          if (selectedmarker==null) {
              gotop (0,0,1);
          }
          else {
          lon = selectedmarker.getPoint().lng();
          lat = selectedmarker.getPoint().lat();
          gotop (lat,lon,14);
          }
          return false;
    });

    $("#gostep1").click(function() {
          $("#step2").hide ();
          $("#tabs").show ();
          $("#tab_panel").show ();
          $("#step1").show ();
          $("#post_title_1").show();
          $("#post_title_2").hide();
          return false;
    });
    $("#gostep2").click(function() {
          $("#tab_panel").hide ();
          $("#tabs").hide();
          $("#step2").show ();
          $("#post_title_1").hide();
          $("#post_title_2").show();
          return false;
    });
  
    
}

function startPosting() {
   	setInputType();
	switch (DATA_TYPE){
		case 'POINT':
			$("#deletelast").css('visibility','hidden');
			$("#info_for_user").css('visibility','hidden');
			post_point();break;
		case 'POLYLINE':
			$("#deletelast").css('visibility','visible');
			$("#info_for_user").css('visibility','hidden');
			post_polyline();break;
		case 'POLYGON':
			$("#deletelast").css('visibility','visible');
			$("#info_for_user").css('visibility','visible');
			//GLog.write('init_posting POLYGON');
			post_polygon();	
			break;
	}
}

function gotopTraditional () {
        var signal = 1;
        //if ($("#LatPS").checked) {signal=-1;}
        if ($('#LatPS').attr('checked')){ signal=-1;}
        D = ($("#LatH")).val();
        M = ($("#LatM")).val()
        S = ($("#LatS")).val()
        Lat = signal*roundOff(D/1 + (M/60) + (S/3600),6);
        
        signal = 1;
        //if ($("#LongPW").checked) {signal=-1;}
        if ($('#LongPW').attr('checked')){ signal=-1;}
        D = ($("#LongH")).val();
        M = ($("#LongM")).val()
        S = ($("#LongS")).val()
        Lon = signal*roundOff(D/1 + (M/60) + (S/3600),6);
        gotop(Lat, Lon, 14);
        

}

function gotop(lat,lon,zoom) {
    
    $("#tab_panel").hide ();
    $("#tabs").hide ();
    $("#step2").show ();
    $("#post_title_1").hide();
    $("#post_title_2").show();
    
    addDraggablePoint(lat,lon,zoom); 
    //load_posting_gmap();
   
    //map.clearOverlays();
    //markeradd = markerdraggable(lat,lon,{draggable:true});
    //map.addOverlay(markeradd);
    //selectedmarker = markeradd;
    //lastlat = lat;
    //lastlon = lon;
    //map.setCenter(new GLatLng(lat, lon), zoom);
    //fill_id_coords();
    //post_point();
    return false;     
}

function addDraggablePoint(lat,lon,zoom) {
    load_posting_gmap();
    //resetCoords();
    map.clearOverlays();
    
    markeradd = markerdraggable(lat,lon,{draggable:true});
    map.addOverlay(markeradd);
    selectedmarker = markeradd;
    lastlat = lat;
    lastlon = lon;
    map.setCenter(new GLatLng(lat, lon), zoom);
    fill_id_coords();
    post_point();
    return false;     
}

/* Geocoding used in post form
*/

function geocode_return(geocoded_location) {
    gotop(geocoded_location.point.lat,geocoded_location.point.lon,14);
}

function launchGeocoding() {
    
    $("#searchnavlist").remove();
    $('<ul id="searchnavlist"></ul>').appendTo('#godestination');
    
    var geocoder = new MapstractionGeocoder(geocode_return, 'google');
    var address = new Object();
    address.address = ($("#fid #q")).val();
    
    
    // There is a choice to set every data detail 
    //address.street = 'Bidebarrieta';
    //address.locality = "Eibar";
    //address.region = "Gipuzkoa";
    //address.country = "ES";
    geocoder.geocode(address);
   
}

function launchGeocodingwithaddress(myaddress) {
    
    $("#searchnavlist").remove();
    $('<ul id="searchnavlist"></ul>').appendTo('#godestination');
				     
    ($("#fid #q")).val(myaddress);
   
    var geocoder = new MapstractionGeocoder(geocode_return, 'google');
    var address = new Object();
    address.address = myaddress;
    
    // There is a choice to set every data detail 
    //address.street = 'Bidebarrieta';
    //address.locality = "Eibar";
    //address.region = "Gipuzkoa";
    //address.country = "ES";
    geocoder.geocode(address);
}

function user_submit() {
    var address = new Object();
    address.address = document.getElementById('address').value;
    geocoder.geocode(address);
    alert('fun user_submit');
}

function clickButtonAjax(name){
    launchGeocoding ();
    return false;
    alert('fun clickButtonAjax');
}

/* Item View functions
*/


function toggleTab(name){
   $("#sidebar_content div.tab_visible").attr('class','tab_hidden');
   $("#sidebar_content #"+name +"_cont" ).attr('class','tab_visible');
   $("#sidebar .active_tab_link").attr('class', 'inactive_tab_link');
   $("#sidebar #"+name ).attr('class','active_tab_link');
}

var activated = 0;   
function initItemView() {
   $("#sidebar a").click(function() {
      toggleTab($(this).attr('id'));
      return false;  
   }); 
   $("#open_embed_custom").click(function() {
       if(activated == 0)
       {
           $("#param").show();
           activated = 1;
       }
       else
       {
           $("#param").hide();
           activated = 0;
       }
      return false;
    });
   $("#close_embed_custom").click(function() {
       $("#param").hide();
       activated = 0;
      return false;
    });
}

function enable_comment_limit()
{
  var comment_limit = 1000;
  $("#commentcharleft").text(comment_limit);

  $("#id_comment").keyup(function (){
    var commenttext = $("#id_comment").val();
    if (commenttext.length >= comment_limit) {
        var maxval = commenttext.substring(0, comment_limit);
        $("#id_comment").val(maxval);
        $("#commentcharleft").text('0');
    } else {
        var commenttext = $("#id_comment").val();
        $("#commentcharleft").text(comment_limit - commenttext.length);
    }
  });
}

function iconRadioClick (icon_tag, media_url) {
    new_icon_url = media_url + icon_tag + ".png"; 
    document.getElementById("selectedIcon").src = new_icon_url;
    $("#selectedIconText").text(icon_tag);
    $("#icon").val(icon_tag);
    document.getElementById('screenoverlay').style.visibility='hidden';
	selectedmarker.setImage(new_icon_url); 
}

