function change_img(id){
    if ($("#"+id).attr('src')=='/default/images/icon_view_less'){
        $("#"+id).attr('src', '/default/images/icon_view_more');
    }
    else {
        $("#"+id).attr('src', '/default/images/icon_view_less');
    }
}

function toggleComments(){
    $("#comments").toggle();
    // change the icon.
    change_img("img_comment");
}

function showComments(){
  $("#comments").addClass("show")
  changeDisplay("#hide_comments", "#show_comments");
}

function hideComments() {
  $("#comments").addClass("hide");
  $("#comments").removeClass("show")
  changeDisplay("#show_comments", "#hide_comments");
}

function validateComment(){
if (($("#c_email").val()) && ($("#c_author").val()) )
    {
       return true;
    }

alert('All fields are required in this form.');
return false;
}

/**
function showMap(){
    $("#map_widget").css("display","block");
    $("#location_widget").css("display","none");
    $("#map_link_hide").css("display","block");
    $("#map_link_show").css("display","none");
}

function hideMap(){
    $("#map_widget").css("display","none");
    $("#location_widget").css("display","block");
    $("#map_link_hide").css("display","none");
    $("#map_link_show").css("display","block");

    // remove the value on lat long.
    $("#latitude").val("");
    $("#longitude").val("");
}
**/

function getLocationStr(point){
    s = '<table><tr><td COLSPAN=2>'
    s += 'Do you want to use this marker as the <b>new location</b>?</td></tr>'
    s +='<tr><td><a href=# onclick="addLoc('+point.y+','+point.x+');">Yes</a></td><td><a href=# onclick="noLoc();">No</a></td></tr>'
    s +='</table>'
    MARKER.openInfoWindowHtml(s)
}
function addLoc(x,y){
    MAP.closeInfoWindow(); 
    reverseGeo(x,y);
    showLocationTools();
}

function noLoc(){
    // remove the marker to original position
    lat=$("#latitude").val();
    lon=$("#longitude").val();
    if (lat && lon){
       addMarker(lat, lon);
    }
    MAP.closeInfoWindow(); 
}


/** 
    Do reverse geocoding.
    First check on the google reverse geo.
    If no results check geonames (if no results we just use the lat long). 
**/
function update_location(response){
   if (!response || response.Status.code != 200){
     // try Geonames
     geonameReverse($("#latitude").val(), $("#longitude").val());
   } else{
     town = '';
     var place = response.Placemark[0];
     var country = place.AddressDetails.Country.CountryNameCode;
     country = getCountry(country, 1);
     if  (place.address){
          town = place.address;      
     } 
     else if (!place.AddressDetails.Country.AdministrativeArea.Locality 
          || response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName){
         town = response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
     }
     else {
         town = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
     } 
     var title = country;
     if (town){
         title +=','+town
      } 

      $("#mtgt_ekit").attr('title', title)
      $("#country").val(country);
      $("#user_place").val(town);
      $("#place").val(town);
   }
   
}

function calculate_distance(lat, lon){
    var latest = $("#latitude").val()
    var lotest = $("#longitude").val()
    var glatlng1 = new GLatLng(lat, lon);
		var glatlng2 = new GLatLng(latest, lotest);
		var meterdistance = glatlng1.distanceFrom(glatlng2);
		var kmdistance = (meterdistance / 1000).toFixed(1);
    return kmdistance
 }

function reverseGeo(lat, lon){
    // And have funn.... if we do have the tower....
    if ($("#tower")){
//        alert('get the tower')
        test_street_view(lat, lon);
     }

// try to use the other js stuff..
    // XXX 19/02/2009
    // NOw we can do reverse geocoding with GClientGeocoder.getLocations()
    var reversegeocoder = new GClientGeocoder();
    if (calculate_distance(lat, lon)<6){
        $("#keepweather").val(1)
    }
    else {
        $("#keepweather").val(0)
    }

    $("#latitude").val(lat);
    $("#longitude").val(lon);    
    reversegeocoder.getLocations(new GLatLng(lat, lon), update_location);
/**
    GEvent.addListener(reversegeocoder, "error",  function() {
        // let's try geonames.  
        geonameReverse(lat, lon);
    }
    );
    GEvent.addListener(reversegeocoder, "load",
          function(placemark) {
            var town = reversegeocoder.getPlacemarkProperty(placemark,"LocalityName"); 
            $("#user_place").val(town);
            $("#place").val(town);
            var country = reversegeocoder.getPlacemarkProperty(placemark,"CountryNameCode");
            // some mapping need to be done with country
            country = getCountry(country, 1);
            var title = country;

            if (town){
                title +=','+town
            } 

            $("#mtgt_ekit").attr('title', title)
            $("#country").val(country);
            $("#latitude").val(lat);
            $("#longitude").val(lon);

          }
        );
    reversegeocoder.reverseGeocode(new GLatLng(lat, lon));
**/ 
}


/**
 Callback function for geonames
**/
var processJsonGeo = function (json){
if (json != null && json.postalCodes != null && json.postalCodes.length >0){
    $("#user_place").val(json.postalCodes[0].placeName);
    $("#place").val(json.postalCodes[0].placeName);
    $("#country").val(getCountry(json.postalCodes[0].countryCode, 1));
}
else {
        /** bad luck no reverse geo for it.
            we keep the lat long...
            erasamus mmight be able to reverse it  
        **/

        s = 'We were unable to get your country and city.<br>'
        s += 'The marker will be use as the position. <br>'  
        s += 'You <b>can change the city and country name</b>. <br>'  
        // the city and country field need to be reset to null.
        $("#place").val('');
        $("#user_place").val(''); 
        $("#country").val('');
        MARKER.openInfoWindowHtml(s);  
}
}


function geonameReverse(lat, lon){
      /**
         We do this way as AJAX and security browser...
         First remove the element.
         Add new element in the DOM and voila, if the service let us  
         query for JSON format and specify a callback function no more security probs.
      **/
      var s = document.getElementById('jsonScript');
      if (s != null) {
         s.parentNode.removeChild(s);
      }      
      src = 'http://ws.geonames.org/findNearbyPostalCodesJSON?callback=processJsonGeo&lat=' + lat  + '&lng=' + lon 
      var head = document.getElementsByTagName("head");
      var s = document.createElement("script");
      s.setAttribute('type', 'text/javascript');
      s.setAttribute('id', 'jsonScript');
      s.src = src
      head[0].appendChild(s);
}


/** 
    GEOCODING 
**/
function getAllMatchingAddress(){
    geocoder = new GClientGeocoder();
    var country=$("#country").val();
    var city=$("#user_place").val();
    var address = country+','+city;
    geocoder.getLocations(address, function (addresses){
    // Show all the adress matching the given address. 
    var content = '';
    for (var i=0; i<addresses.Placemark.length; i++){
        var place = addresses.Placemark[i].address.replace("'", "\\'");
        // somehow we don't have the country sometime.
        if (addresses.Placemark[i].AddressDetails.Country==undefined){
            var geo_country = getCountry(country);
        }
        else {
            var geo_country = addresses.Placemark[i].AddressDetails.Country.CountryNameCode
        }
        content +='<tr><td><a href=# onclick="replace_place(\''+place+'\'); changeCountry(\''+geo_country+'\'); addMarker('+addresses.Placemark[i].Point.coordinates[1]+','+addresses.Placemark[i].Point.coordinates[0]+')" class="anchor_tag">';
        content +=addresses.Placemark[i].address;
        content +='</a></td></tr>'
    }
    $("#place_results").css("display","block");
    $("#addresses_table").html(content); 
    $("#addresses_table").css("display","block");
 }
);
}

function changeCountry(val){
    var country = getCountry(val, 1);
    $("#country").val(country);
}
function geo(){
    getAllMatchingAddress();

}
function addMarkerGallery(lat, lon, title){
    if (!title){
        title=''
    }
    // Add the new coor in the fields.
    $("#latitude").val(lat);
    $("#longitude").val(lon);

    // Move the marker
    var coor = new GLatLng(lat, lon);
    if (!MARKER){
        var icon = new GIcon();
        icon.image = "/default/images/icon_map_past_location"
        icon.shadowSize = new GSize(28, 19);
        icon.iconAnchor = new GPoint(0, 30);
        icon.infoWindowAnchor = new GPoint(10, 4);
        MARKER = new GMarker(coor, {icon:icon, title:''});
        // init the marker
        MAP.addOverlay(MARKER);
    }
    MARKER.setPoint(coor)
    MAP.setCenter(coor,5);
}
function addMarker(lat, lon, title){
    if (!title){
        title=''
    }
    // Add the new coor in the fields.
    $("#latitude").val(lat);
    $("#longitude").val(lon);

    // Move the marker
    var coor = new GLatLng(lat, lon);
    if (!MARKER){
        var icon = new GIcon();
        icon.image = "/default/images/icon_map_past_location"
        icon.shadowSize = new GSize(22, 20);
        icon.iconAnchor = new GPoint(0, 30);
        icon.infoWindowAnchor = new GPoint(10, 4);
        MARKER = new GMarker(coor, {icon:icon, title:'', draggable: true, dragCrossMove: true});
        // init the marker
        GEvent.addListener(MARKER, 'dragend', function() {
        MARKER = this;
        var point = MARKER.getLatLng()
        getLocationStr(point);
        })
        MAP.addOverlay(MARKER);
    }
    MARKER.setPoint(coor)
    MAP.setCenter(coor,5);
}

function zoomOnCountry(country){
    // Get the bound for the given country
    for (var i=0; i<boundaries.length; i++){
        if (boundaries[i][0]==country){
            var bounds = new GLatLngBounds();
            bounds.extend(new GLatLng(boundaries[i][2],boundaries[i][1]));
            bounds.extend(new GLatLng(boundaries[i][4],boundaries[i][3]));
            MAP.setZoom(MAP.getBoundsZoomLevel(bounds));
            MAP.setCenter(bounds.getCenter());
        }
    }
    // set the lat long to nothing
    $("#latitude").val('');
    $("#longitude").val('');
    $("#place_results").css("display","none");
    $("#addresses_table").css("display","none");
}

function showLocationTools(){
    // display all the elements to be able to change the location.
    $("#loc_place").css("display","block");
    $("#loc_country").css("display","block");
    $("#place_search").css("display","block");
    $("#tr_show_loc").css("display","none");
}

function cancel_location(){
    $("#loc_place").css("display","none");
    $("#loc_country").css("display","none");
    $("#place_search").css("display","none");
    $("#tr_show_loc").css("display","block");
    $("#place_results").css("display","none");
    $("#addresses_table").css("display","none");
    // and return to the original location.
    do_original_loc();
}

function replace_place(place){
    $("#place").val(place);
}

function do_original_loc(){
    // we need to reset the country, city, lat, lon, marker.
    $("#country").val(original_country);
    $("#user_place").val(original_place);
    $("#place").val(original_place);
    $("#latitude").val(original_lat);
    $("#longitude").val(original_lon);

    // Re zoom to the original country.
    zoomOnCountry(original_country.toLowerCase());

    // Move the marker as well.   
    MARKER.setLatLng(new GLatLng(original_lat, original_lon));
}

function apply_loc(){
    // apply the current location as the caption for the location.
    s = $("#place").val()//+', '+$("#country").val()
    s.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
    $("#location_label").val(s);
}


//function geo1(){
//geocoder = new GClientGeocoder();
//country=$("#country").val()
//city=$("#town").val()
//address = country+','+city;
//geocoder.getLatLng(address, 
//function (point){
//    MARKER.setLatLng(point);
//    $("#mtgt_ekit").attr('title', address)
//    MAP.setCenter(point, 4);
//   $("#latitude").val(point.lat());
//    $("#longitude").val(point.lng());
//}
//);
//}

/** 
   ejob
**/

function getCurrentTime(job_id){
  jQuery.get(TJURL+'/getTime', {'job_id':job_id}, function(json){
      // add content to id  current_time 
      if(json) {
          content = 'Time at last know location is <b>'+json+'</b>'
          $("#current_time").html(content);  
          $("#current_time_icon").show();
      }
  })
}

function getCurrentWeather(job_id){
  jQuery.getJSON(TJURL+'/getCurrentWeatherLastKnowLocation', {'job_id':job_id}, function(json){
      // add content to id  current_time 
      if(json) {
          s = 'Current weather'
          s+='<br><a href="http://weather.weatherbug.com/"><img src="'+json.img+'"></a>'+ json.description 
          s+='<br>Min: '+json.min+'<span style="white-space: nowrap">&deg;'+json.sym+'</span> Max: '+json.max+'<span style="white-space: nowrap">&deg;'+json.sym+'</span>'
          
          $("#temp").html(s);  
      }
//      else {
//          alert('no result');
//      } 
  })
}


// used by the gallery.
function initMap(id){
google.load("maps","v=2.55");
google.setOnLoadCallback(function() {
   MAP = new google.maps.Map2(document.getElementById(id));
   // might want to get the lat lon for first img
   var coor = new GLatLng(37.4419, -122.1419);
   MAP.setCenter(coor, 1);
   MAP.setMapType(G_NORMAL_MAP);
   MAP.addControl(new GSmallMapControl());
});

}

/** 
   Gallery 
**/

function showInfoGallery(url, caption, label, country, lat, lon){
     // We want to show the last icon in a different color.
    s = '<b>Caption:</b>'+caption
    $("#caption").html(s);  
    if (lat !=''){
        // add the marker.
        addMarkerGallery(lat, lon, country+' '+label);  
    }

   // and open a popup window.
//   window.open(url, 'images','height=600,width=600,scrollbars=yes');
}

// Function to change the display of the given id.
function changeDisplay(id1, id2){
    // hide first element an dshow the second element
    show(id1);
    hide(id2);
}

function show_p(id, id2){
    // just do a normal toggle of the divs.
    $("#"+id).toggle();
    $("#"+id2).toggle();
    // empty the fields.
    $("#attachment_url").val('');
    $("#attachment_caption").val('');
}

function show_first(id, id2, id3){
    // show the element with the first given id.
    // add the others.
    // empty the fields.
    $("#"+id2).hide();
    $("#"+id3).hide();   
    $("#attachment_url").val('');
    $("#attachment_caption").val('');
    $("#"+id).show();
    if (id=='divgallerycontent'){
        $("#feedb").html('');
        $("#c_img").hide();
    }
    else {
        $("#c_img").show();
    }
}

function show(id){
    $(id).toggle();
}

function hide(id){
    $(id).toggle();
 }

function openWindow(href){
    window.open(href, 'Travel Links','height=600,width=900,scrollbars=yes');    
    return false;
}


/**
Function to validate forms in the Travel Journal.
tj_entry
 title 100
 location_label 700

tj_comment
  title 100

tj_entry_attachment
  caption 400
  

tj_location
  country 100
  place 700  
**/

function validateTJForms(){
  // we build the message on the fly.
  error_msg = ''
  if ($("#title_entry") && $("#title_entry").val().length > 100){
    error_msg += 'The title is too big.'
  }

  if ($("#location_label")&& $("#location_label").val().length > 700){
    error_msg += 'The label for the location is too big.'
  }

  if ($("#attachment_caption").length > 0 && $("#attachment_caption").val().length > 400){
    error_msg += 'The caption for the attachment is too big.'  }

  if ($("#country") && $("#country").val().length > 100){
    error_msg += 'The country name is too big.'  }
  if ($("#place") && $("#place").val().length > 700){
    error_msg += 'The place is too big.'
  }
  if (error_msg.length){
    // add element error value stuff
    // Make sure it is in red.

    $("#error").html('<strong class="error">'+error_msg+'</strong>')
    $("#error").css("display","block");
    return false;
  }

  // propagate
  return true;
}

// Simple function to show 'la tour d'e'
function test_street_view(lat, lon){
    var myPano = new GStreetviewPanorama(document.getElementById("tower"));

//    fenwayPark = new GLatLng(42.345573,-71.098326);
    fenwayPark = new GLatLng(lat,lon);
    myPOV = {yaw:370.64659986187695,pitch:-20};
    myPano.setLocationAndPOV(fenwayPark, myPOV);
//    alert('yop street view! '+lat+' and '+lon);
//    // make sure it is empty...
//    var fenwayPark = new GLatLng(lat,lon);
//    panoramaOptions = { latlng:fenwayPark };
//     var my_tower = new GStreetviewPanorama(document.getElementById("tower"), panoramaOptions);
}

function process_zoom(current_zoom){
    // Change the hidden field zoom value 
    $("#map_zoom").val(current_zoom);
    $("#map_zoom").trigger('onblur');
}


/**
Jquery plug in to rotate picture.
**/
jQuery.fn.rotate = function(angle,whence) {
	var p = this.get(0);
	// we store the angle inside the image tag for persistence
	if (!whence) {
		p.angle = ((p.angle==undefined?0:p.angle) + angle) % 360;
	} else {
		p.angle = angle;
	}

	if (p.angle >= 0) {
		var rotation = Math.PI * p.angle / 180;
	} else {
		var rotation = Math.PI * (360+p.angle) / 180;
	}
	var costheta = Math.cos(rotation);
	var sintheta = Math.sin(rotation);

	if (document.all && !window.opera) {
		var canvas = document.createElement('img');
		canvas.src = p.src;
		canvas.height = p.height;
		canvas.width = p.width;
		canvas.style.filter = "progid:DXImageTransform.Microsoft.Matrix(M11="+costheta+",M12="+(-sintheta)+",M21="+sintheta+",M22="+costheta+",SizingMethod='auto expand')";
	} 
	else {
		var canvas = document.createElement('canvas');
		if (!p.oImage) {
		    canvas.oImage = new Image();
                    // XXX Changed as Firefox/caching not happy
                    canvas.oImage.onload = function() {
                    canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height);
                    canvas.style.height = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width);

		    var context = canvas.getContext('2d');
		    context.save();
		    if (rotation <= Math.PI/2) {
			    context.translate(sintheta*canvas.oImage.height,0);
		    } else if (rotation <= Math.PI) {
			    context.translate(canvas.width,-costheta*canvas.oImage.height);
		    } else if (rotation <= 1.5*Math.PI) {
			    context.translate(-costheta*canvas.oImage.width,canvas.height);
		    } else {
			    context.translate(0,-sintheta*canvas.oImage.width);
		    }
		    context.rotate(rotation);
		    context.drawImage(canvas.oImage, 
		                  0, 
		                  0, 
		                  canvas.oImage.width, 
		                  canvas.oImage.height
		                  );
		    context.restore();
                    } // end onload
			canvas.oImage.src = p.src;
		} 
		else {
	     canvas.oImage = p.oImage;
       if (canvas.oImage.complete){
		      canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height);
		      canvas.style.width = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width);
		      var context = canvas.getContext('2d');
		      context.save();
		      if (rotation <= Math.PI/2) {
			        context.translate(sintheta*canvas.oImage.height,0);
		      } else if (rotation <= Math.PI) {
			        context.translate(canvas.width,-costheta*canvas.oImage.height);
		      } else if (rotation <= 1.5*Math.PI) {
			        context.translate(-costheta*canvas.oImage.width,canvas.height);
		      } else {
			        context.translate(0,-sintheta*canvas.oImage.width);
		      }
		      context.rotate(rotation);
		      context.drawImage(canvas.oImage, 
		                  0, 
		                  0, 
		                  canvas.oImage.width, 
		                  canvas.oImage.height
		                  );
		      context.restore();
      } // end complete
      else{
          canvas.oImage.onload = function() {
		      canvas.style.width = canvas.width = Math.abs(costheta*canvas.oImage.width) + Math.abs(sintheta*canvas.oImage.height);
		      canvas.style.width = canvas.height = Math.abs(costheta*canvas.oImage.height) + Math.abs(sintheta*canvas.oImage.width);
		      var context = canvas.getContext('2d');
		      context.save();
		      if (rotation <= Math.PI/2) {
			        context.translate(sintheta*canvas.oImage.height,0);
		      } else if (rotation <= Math.PI) {
			        context.translate(canvas.width,-costheta*canvas.oImage.height);
		      } else if (rotation <= 1.5*Math.PI) {
			        context.translate(-costheta*canvas.oImage.width,canvas.height);
		      } else {
			        context.translate(0,-sintheta*canvas.oImage.width);
		      }
		      context.rotate(rotation);
		      context.drawImage(canvas.oImage, 
		                  0, 
		                  0, 
		                  canvas.oImage.width, 
		                  canvas.oImage.height
		                  );
		      context.restore();
          } // end onload
      } // end if else 
		}
	}
	canvas.id = p.id;
	canvas.angle = p.angle;
	p.parentNode.replaceChild(canvas, p);
}

jQuery.fn.rotateRight = function(angle) {
	this.rotate(angle==undefined?90:angle);
}

jQuery.fn.rotateLeft = function(angle) {
	this.rotate(angle==undefined?-90:-angle);
}


/**
Function for our gallery to rotate images.
**/

function rotate_img_left(id){
   // Get the element and rotate
   $('#'+id).rotateLeft();
   // we need to keep track of you it is rotated...
   // to save it...
   var angle = parseInt($("#angle").val());
   angle += 90
   if (angle == 360) {
       angle = 0
   
   }
   // set the variable.
   $("#angle").val(angle);
}
function rotate_img_right(id){
   // Get the element and rotate
   $('#'+id).rotateRight();
   // we need to keep track of you it is rotated...
   // to save it...
   var angle = parseInt($("#angle").val());
   angle += 270
   if (angle >= 360) {
       angle -= 360
   
   }
   // set the variable.
   $("#angle").val(angle);
}

/**
  Case when we have to rotate thumbnail as well...
  We must rotate the image based on id as the same image might be use multitime.
**/
function rotate_img_left_gallery(id){
   // Get the element and rotate
   $('#'+id).rotateLeft();

   // we need to keep track of you it is rotated...
   // to save it...
   var ang = parseInt($("#angle").val());
   ang += 90
   if (ang == 360) {
       ang = 0
   
   }

   // set the variable.
   $("#angle").val(ang);
   var img_id = $("#post_main_image").val();

   $('#'+img_id).rotateLeft();

   // Keep track of the angle for that thumbnail.
   update_rotation(img_id, ang);

}

function rotate_img_right_gallery(id){
   // Get the element and rotate
   $('#'+id).rotateRight();

   // we need to keep track of you it is rotated...
   // to save it...
   var ang = parseInt($("#angle").val());
   ang += 270
   if (ang >= 360) {
       ang -= 360
   
   }
   // set the variable.
   $("#angle").val(ang);
  
   // Let's do the thumbnail stuff..
   var img_id = $("#post_main_image").val();

   $('#'+img_id).rotateRight();

   // Keep track of the angle for that thumbnail.
   update_rotation(img_id, ang);

}

function calculate_angle(angle1, angle2){
   //var angle = angle1-angle2;
   var angle = angle2-angle1;
   if (angle==0){
       return 0;
   }
   var value = angle/90;
   // if the value is positif the canvas need to be turn to the left.
   if (value>0){
       if (value==1){
            return 3    
       }
       if (value==3){
            return 1
       }
       return value 
   }
   else {
       return Math.abs(value)
   } 
}

function check_delete_canvas_angle(menu, main_image, delete_id){
/**
    User is deleting one of his own image.
    Check if we got a canvas and angle.
       Trigger onclick for the next canvas (per default first next one.).

**/
        var sel = document.getElementById("img_"+main_image);
        // Need to check if we got an img or a canvas.
            // trigger next canvas.
            var div_menu = document.getElementById(menu);
            if (div_menu != undefined) {
                var l = div_menu.getElementsByTagName("LI");
                for (var i=0; i<l.length; i++) {
                    // see whether the image id matches the currently-selected one
                    var img = l[i].getElementsByTagName('img')[0];
                    if (img==undefined){
                        var img = l[i].getElementsByTagName('canvas')[0]  
                    } 
                    if (img.id != delete_id) {
                        l[i].onclick();
                        return true;
                    }
                }
            }
}

function remove_canvas_angle(delete_id){
/**
    Remove the given id to the array
    of angles.
**/
    for (var i=0; i<rotates.length; i++){
        if (rotates[i][0]==delete_id){
            // reset to 0
            //rotates.splice(i,1)
            rotates[i][1]=0;
            return true;
        }
    }
}

function check_canvas_angle(main_id, id1, id2){
/**
   Chech angle for both img and change appropriate...
   We should have both ids.
   New one coming from 
**/

// quick check
// if id1 is not define, the old image must be a deleted one.
// first we get the angle for both ids.
if (id1!=undefined){
    var original_canvas_angle = get_angle(id1);
    var last_img_angle = get_angle(id2);

    // set the angle for this img.
    $("#angle").val(last_img_angle);

    // now let's calculate the number of times we should rotate...
    var rots = calculate_angle(original_canvas_angle, last_img_angle)
    if (rots == 0){
        // quick hack to reload the picture.
        $('#'+main_id).rotateRight();
        $('#'+main_id).rotateLeft();
    }
    else {
        // let's change the angle's canvas...
        while (rots>0){
            $('#'+main_id).rotateRight();
            rots -=1;
        }
    }
 }
/**
else {
    // we had an angle...
    original_canvas_angle = $("#angle").val();
    if (original_canvas_angle!=undefined){
        // set the angle for this img.
        $("#angle").val(0);

        // now let's calculate the number of times we should rotate...
        var rots = calculate_angle(original_canvas_angle, 0)
        if (rots == 0){
            // quick hack to reload the picture.
            $('#'+main_id).rotateRight();
            $('#'+main_id).rotateLeft();
         }
         else {
            // let's change the angle's canvas...
            while (rots>0){
                $('#'+main_id).rotateRight();
                rots -=1;
            }
         }
    }
}
**/

}

function get_angle(id){
    // return the angle for the given id.
    // if there are no entry==0 (some of the picture can't rotate...)
    for (var i=0; i<rotates.length; i++){
        if (rotates[i][0]==id){
            return rotates[i][1];
        }
    }
    return 0;
}

function update_rotation(id, ang){
    // update array for that angle.
    for (var i=0; i<rotates.length; i++){
        if (rotates[i][0]==id){
            rotates[i][1]=ang;
        }
    }
}