/**************/
/* INDICATORS */
/**************/

// --- rect ---
var rect_start_x;
var rect_start_y;
var rect_start_w;
var rect_start_h;

// --- ellipse ---
var ellipse_start_x;
var ellipse_start_y;
var ellipse_start_w;
var ellipse_start_h;

// --- flag ---
var flag_start_x;
var flag_start_y;
var flag_start_w;
var flag_start_h;
var flag_pivot_x;
var flag_pivot_y;

// --- arrow ---
var arrow_start_x;
var arrow_start_y;
var arrow_start_w;
var arrow_start_h;
var arrow_pivot_x;
var arrow_pivot_y;

// --- balloon ---
var balloon_start_x;
var balloon_start_y;
var balloon_start_w;
var balloon_start_h;
var balloon_pivot_x;
var balloon_pivot_y;

var balloon_first_edit = true;

var rect_dropped = false;
var ellipse_dropped = false;
var flag_dropped = false;
var arrow_dropped = false;
var balloon_dropped = false;

/*var curr_post_id = null;
var curr_image_id = null;*/

// data structure definition
function indicator_data(id, x, y, w, h, zoom_level, fit_w, fit_h, pivot_x, pivot_y, text)
{
    this.id = id;
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.zoom_level = zoom_level;
    this.fit_w = fit_w;
    this.fit_h = fit_h;
    this.pivot_x = pivot_x;
    this.pivot_y = pivot_y;
    this.text = text;
}

 // define current indicators array object
var indicators_array = [];

// test array used to save the current indicators data (used to be loaded later...)
//var indicators_backup = [];

var ellipse;

var rect_div;
var rect_remover_div;
var rect_handle_div;
var ellipse_div;
var ellipse_remover_div;
var ellipse_handle_div;
var flag_div;
var flag_remover_div;
var arrow_div;
var arrow_remover_div;
var balloon_div;
var balloon_pivot_div;
var balloon_remover_div;
var balloon_handle_div;

var clonedItem;

// indicators effect objects...
var rect_resizable;
var rect_draggable;
var ellipse_resizable;
var ellipse_draggable;
var flag_draggable;
var arrow_draggable;
var balloon_resizable;
var balloon_draggable;
var balloon_editinplace;

var droppable_area;

function switch_indicators_divs_ref(viewonly)
{
	if( viewonly == 1 )
	{
		rect_div = $('ImageViewer_rect_layer');
        ellipse_div = $('ImageViewer_ellipse_layer');
        flag_div = $('ImageViewer_flag_layer');
        arrow_div = $('ImageViewer_arrow_layer');
        balloon_div = $('ImageViewer_balloon_layer');
        balloon_pivot_div = $('ImageViewer_balloon_pivot_layer');
        // set the longer pivot
        balloon_pivot_div.style.backgroundImage = "url('/images/image-editor/b_longer.png')";
    }
    else
    {
	    rect_div = $('ImageEditor_rect_layer');
        rect_remover_div = $('ImageEditor_rect_remover_layer');
        rect_handle_div = $('ImageEditor_rect_se_handle_layer');
        ellipse_div = $('ImageEditor_ellipse_layer');
        ellipse_remover_div = $('ImageEditor_ellipse_remover_layer');
        ellipse_handle_div = $('ImageEditor_ellipse_se_handle_layer');
        flag_div = $('ImageEditor_flag_layer');
        flag_remover_div = $('ImageEditor_flag_remover_layer');
        arrow_div = $('ImageEditor_arrow_layer');
        arrow_remover_div = $('ImageEditor_arrow_remover_layer');
        balloon_div = $('ImageEditor_balloon_layer');
        balloon_pivot_div = $('ImageEditor_balloon_pivot_layer');
        // set the shorter pivot
        balloon_pivot_div.style.backgroundImage = "url('/images/image-editor/b_new.png')";
        balloon_remover_div = $('ImageEditor_balloon_remover_layer');
        balloon_handle_div = $('ImageEditor_balloon_se_handle_layer');
	}
	
	// --- rect ---
    // start position and dimensions (how can I declare these values as I do in c/c++ using #define ??...so I can use the "macro" here and in the CSS file...)
    // must I use CSS classes?
    rect_start_x = rect_div.getStyle('left');
    rect_start_y = rect_div.getStyle('top');
    rect_start_w = rect_div.getStyle('width');
    rect_start_h = rect_div.getStyle('height');
    // rect doesn't have a custom pivot...

    // --- ellipse ---
    // start position and dimensions
    ellipse_start_x = ellipse_div.getStyle('left');
    ellipse_start_y = ellipse_div.getStyle('top');;
    ellipse_start_w = ellipse_div.getStyle('width');
    ellipse_start_h = ellipse_div.getStyle('height');
    // ellipse doesn't have a custom pivot...

    // --- flag ---
    // start position and dimensions
    flag_start_x = flag_div.getStyle('left');
    flag_start_y = flag_div.getStyle('top');
    flag_start_w = flag_div.getStyle('width');
    flag_start_h = flag_div.getStyle('height');
    // pivot
    flag_pivot_x = 5;
    flag_pivot_y = 45;

    // --- arrow ---
    // start position and dimensions
    arrow_start_x = arrow_div.getStyle('left');
    arrow_start_y = arrow_div.getStyle('top');
    arrow_start_w = arrow_div.getStyle('width');
    arrow_start_h = arrow_div.getStyle('height');
    // pivot
    arrow_pivot_x = 7;
    arrow_pivot_y = 0;

    // --- balloon ---
    // start position and dimensions
    balloon_start_x = balloon_div.getStyle('left');
    balloon_start_y = balloon_div.getStyle('top');
    balloon_start_w = balloon_div.getStyle('width');
    balloon_start_h = balloon_div.getStyle('height');
    // pivot
    // balloons are dynamic so these two value refer to the pivot layer...so I must add to them the layer left and top...
    /*balloon_pivot_x = 13;
    balloon_pivot_y = 17;*/
    balloon_pivot_x = 15;
    balloon_pivot_y = 48;
}

function init_indicators(viewonly)
{	
	rect_dropped = false;
	ellipse_dropped = false;
	flag_dropped = false;
	arrow_dropped = false;
	balloon_dropped = false;
	
	switch_indicators_divs_ref(viewonly);
	
	// draw the ellipse graphic plane
    ellipse = new jsGraphics(ellipse_div.id);
	
    drawEllipse();
    
	if( viewonly == 1 )
	{
		// since we added the viewer own divs we don't need to destroy and hide editor divs anymore...
		// That was needed because indicators divs (and some others) were shared...
		
		// Here now is empty...but if you want you can insert some viewer-indicators initialization code...
    }
	else
	{	
        // RECT
        rect_resizable = new Resizable('ImageEditor_rect_layer', {handle: 'ImageEditor_rect_se_handle_layer', onEnd: saveItemPos});
        rect_draggable = new Draggable('ImageEditor_rect_layer', { revert: 'failure', reverteffect: revertIndicator, ghosting: true, onEnd: saveItemPos, onStart: showRealIndicator });
        //rect_draggable = new Draggable('ImageEditor_rect_layer', { revert: 'failure', ghosting: true, onStart: cloneItem, onEnd: saveItemPos });
    
        // ELLIPSE
        //drawEllipse();
        ellipse_resizable = new Resizable('ImageEditor_ellipse_layer', {handle: 'ImageEditor_ellipse_se_handle_layer', onResize: drawEllipse, onEnd: saveItemPos});
        ellipse_draggable = new Draggable('ImageEditor_ellipse_layer', { revert: 'failure', reverteffect: revertIndicator, ghosting: true, onEnd: saveItemPos, onStart: showRealIndicator }); // <--
        //new Resizable('ImageEditor_ellipse_layer', {handle: 'ImageEditor_ellipse_se_handle_layer', onEnd: saveItemPos});
        //new Draggable('ImageEditor_ellipse_layer', { revert: 'failure', ghosting: true, onStart: cloneItem, onEnd: saveItemPos });
        //new Resizable('ImageEditor_ellipse_layer', {handle: 'ImageEditor_ellipse_se_handle_layer', onResize: drawEllipse, onEnd: saveItemPos});

        // FLAG
        flag_draggable = new Draggable('ImageEditor_flag_layer', { revert: 'failure', reverteffect: revertIndicator, ghosting: true, onEnd: saveItemPos, onStart: showRealIndicator });
        //new Draggable('ImageEditor_flag_layer', { revert: 'failure', ghosting: true, onStart: cloneItem, onEnd: saveItemPos });

        // ARROW
        arrow_draggable = new Draggable('ImageEditor_arrow_layer', { revert: 'failure', reverteffect: revertIndicator, ghosting: true, onEnd: saveItemPos, onStart: showRealIndicator });
        //new Draggable('ImageEditor_arrow_layer', { revert: 'failure', ghosting: true, onStart: cloneItem, onEnd: saveItemPos });

        // BALLOON
        balloon_resizable = new Resizable('ImageEditor_balloon_layer', {handle: 'ImageEditor_balloon_se_handle_layer', onEnd: saveItemPos});
        balloon_draggable = new Draggable('ImageEditor_balloon_layer', { revert: 'failure', reverteffect: revertIndicator, ghosting: true, onEnd: saveItemPos, onStart: showRealIndicator });
        balloon_editinplace = addEditInPlace('ImageEditor_balloon_layer', 'ImageEditor_balloon_text_layer', true);
        //new Draggable('ImageEditor_balloon_layer', { revert: 'failure', ghosting: true, onStart: cloneItem, onEnd: saveItemPos });
        
        // droppable area (needed only for editor)
        droppable_area = Droppables.add('ImageEditor_image_layer', { accept: "ImageEditor_draggable", onDrop: moveItem } );
                
        // indicators removers observers
        Event.observe('ImageEditor_rect_remover_layer', 'click', remove_indicator_from_remover);
        Event.observe('ImageEditor_ellipse_remover_layer', 'click', remove_indicator_from_remover);
        Event.observe('ImageEditor_flag_remover_layer', 'click', remove_indicator_from_remover);
        Event.observe('ImageEditor_arrow_remover_layer', 'click', remove_indicator_from_remover);
        Event.observe('ImageEditor_balloon_remover_layer', 'click', remove_indicator_from_remover);
    }
}	

// This is the original revert code from the scriptaculous library (see dragdrop.js)
// I need to redefine this to make the indicator smaller when it reverts...
function revertIndicator(element, top_offset, left_offset)
{
    var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
    new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur, queue: {scope:'_draggable', position:'end'} });
    
    if( element.id == rect_div.id )
	{
	    element.style.border = "1px dashed #0000FF";
	    element.setStyle({ width: rect_start_w, height: rect_start_h});
	}
	else if( element.id == ellipse_div.id )
	{
		element.setStyle({ width: ellipse_start_w, height: ellipse_start_h});
	    drawEllipse();
	}
	else if( element.id == flag_div.id )
	{
		element.setStyle({ width: flag_start_w, height: flag_start_h});
		element.style.backgroundImage = "url('/images/image-editor/flag_smaller.png')";
	}
	else if( element.id == arrow_div.id )
	{
		element.setStyle({ width: arrow_start_w, height: arrow_start_h});
		element.style.backgroundImage = "url('/images/image-editor/arrow_smaller_new.png')";
	}
	else if( element.id == balloon_div.id )
	{
		balloon_pivot_div.style.backgroundImage = "url('/images/image-editor/b_new.png')";
		element.setStyle({ width: balloon_start_w, height: balloon_start_h});
		setBalloonText(""); // empty the balloon...
	}
}

// this should be used only for the editor...
function showRealIndicator(dragObj, event)
{			
	if( dragObj.element.id == rect_div.id && rect_dropped == false )
	{
	    dragObj.element.style.border = "2px dashed #0000FF";
	    dragObj.element.setStyle({ width: '70px', height: '50px'});
	}
	else if( dragObj.element.id == ellipse_div.id && ellipse_dropped == false )
	{
		dragObj.element.setStyle({ width: '70px', height: '50px'});
	    drawEllipse();
	}
	else if( dragObj.element.id == flag_div.id && flag_dropped == false )
	{
		dragObj.element.setStyle({ width: '35px', height: '50px'});
	    dragObj.element.style.backgroundImage = "url('/images/image-editor/flag_small.png')";
	}
	else if( dragObj.element.id == arrow_div.id && arrow_dropped == false )
	{
		dragObj.element.setStyle({ width: '70px', height: '50px'});
	    dragObj.element.style.backgroundImage = "url('/images/image-editor/arrow_small_new.png')";
	}
	else if( dragObj.element.id == balloon_div.id && balloon_dropped == false )
	{
		balloon_pivot_div.style.backgroundImage = "url('/images/image-editor/b_longer.png')";
		dragObj.element.setStyle({ width: '180px', height: '120px'});
		setBalloonText("Double click to edit");
	}
}

// draw the ellipse inside the ImageEditor_ellipse_layer div...  
function drawEllipse()
{
    if( ellipse )
    {	    
        ellipse.clear();
        
        // possible memory leak?? ellipse.clear clears everything also observer and resizable properties!!!
        if( ellipse_handle_div != null )
            ellipse_resizable = new Resizable(ellipse_div.id, {handle: ellipse_handle_div.id, onResize: drawEllipse, onEnd: saveItemPos});
        
        if( ellipse_remover_div != null )
            Event.observe(ellipse_remover_div.id, 'click', remove_indicator_from_remover);
            
        //myresize.activate();
        ellipse.setColor("#0000FF");
        ellipse.setStroke(Stroke.DOTTED);
        //ellipse.setStroke(2);

        // get current dimensions            
        dim = ellipse_div.getDimensions();
        ellipse.drawEllipse(0, 0, dim.width - 2, dim.height - 2);
        ellipse.paint();
    }
}
        
function restoreIndicators(viewonly)
{
	remove_indicator(rect_div);
	remove_indicator(ellipse_div);
	remove_indicator(flag_div);
	remove_indicator(arrow_div);
	remove_indicator(balloon_div);
	
	if( viewonly == 1 )
	{
		// if viewer mode then hide again the indicators
		rect_div.setStyle({ visibility: 'hidden' });
		ellipse_div.setStyle({ visibility: 'hidden' });
		flag_div.setStyle({ visibility: 'hidden' });
		arrow_div.setStyle({ visibility: 'hidden' });
		balloon_div.setStyle({ visibility: 'hidden' });
	}	
}
    
function updateIndicatorsPositionAndSize(ind)
{
	var ind_zoom_vpw; // indicator zoom viewport width
	var ind_zoom_vph; // indicator zoom viewport height
	var zoom_vph; // zoom viewport width
	var zoom_vph; // zoom viewport height
	
	// TOBEFIXED : This code must be improved!
	for(var i=0;i<ind.length;i++)
	{		
		// 07102008 : I added a new condition to this 'if'.... "|| zoom == -1"...
		// This is needed because the fit level is not a fixed dimension...it's variable and it depends on the viewport size...
		// So if zoom == -1 (that is the fit level) we MUST recalculate the indicators position and size!
		if( ind[i].zoom_level != zoom || zoom == -1 )
		{	
			// "normal" zoom level...
			//if( ind[i].zoom_level > -1 || ( innerdiv_fit_w == -1 || innerdiv_fit_h == -1 ) )
			if( ind[i].zoom_level > -1 )
			{				
			    ind_zoom_vpw = stripPx(zoomSizes[ind[i].zoom_level][0]);
			    ind_zoom_vph = stripPx(zoomSizes[ind[i].zoom_level][1]);
			}
			// here I must consider the special case that is the fit level...(indicator saved when using the fit level in the editor)
			else
			{				
				ind_zoom_vpw = ind[i].fit_w;
			    ind_zoom_vph = ind[i].fit_h;
			    
			    // now the fit for indicators is the viewer one!
			    ind[i].fit_w = innerdiv_fit_w;
			    ind[i].fit_h = innerdiv_fit_h;
			}	
			
			if( zoom > -1 || ( innerdiv_fit_w == -1 || innerdiv_fit_h == -1 ) )
			{				
			    zoom_vpw = stripPx(zoomSizes[zoom][0]);
			    zoom_vph = stripPx(zoomSizes[zoom][1]);
			}
			// here I must consider the special case that is the fit level...
			else
			{				
				zoom_vpw = innerdiv_fit_w;
			    zoom_vph = innerdiv_fit_h;
			    
			    // now the fit for indicators is the viewer one!
			    ind[i].fit_w = innerdiv_fit_w;
			    ind[i].fit_h = innerdiv_fit_h;
			}
			
		    // if the indicator is a rect or an ellipse calculate also the new width and height...
		    if( ind[i].id == rect_div.id || ind[i].id == ellipse_div.id )
		    {
			    new_w = (ind[i].w * zoom_vpw) / ind_zoom_vpw;
			    new_h = (ind[i].h * zoom_vph) / ind_zoom_vph;
			    
			    // update w and h
			    ind[i].w = parseInt(new_w);
			    ind[i].h = parseInt(new_h);
			}       
		 
			 // recalculate the new position
		    new_x = ((ind[i].x) * zoom_vpw) / ind_zoom_vpw;
		    new_y = ((ind[i].y) * zoom_vph) / ind_zoom_vph;
			   
		    // update pos and zoom level
		    ind[i].x = parseInt(new_x);
		    ind[i].y = parseInt(new_y);
		    ind[i].zoom_level = zoom;
		    
		    // move the element to the new calculated position and size
		    $(ind[i].id).setStyle({ left: (ind[i].x - ind[i].pivot_x) + 'px', top: (ind[i].y - ind[i].pivot_y) + 'px', width: ind[i].w + 'px', height: ind[i].h + 'px'});
		    
		    // if it's an ellipse I must redraw it...
		    if( ind[i].id == ellipse_div.id )
		        drawEllipse();
	    }
	}
}	

function printIndicatorsData(ind)
{
	for(var i=0;i<ind.length;i++)
	    alert("indicator["+i+"] = id:" + ind[i].id + " x:" + ind[i].x + " y:" + ind[i].y + " w:" + ind[i].w + " h:" + ind[i].h + " z:" + ind[i].zoom_level);
}

function get_indicator_index(ind_array, id)
{
    for(var i=0;i<ind_array.length;i++)
    {
	    if( ind_array[i].id == id )
	    {
	        /*indicator_id_found = true;
	        break;*/
	        return i;
	    }    
	}
	
	return -1;
}

function saveItemPos(dragObj, event)
{
	//var curr_zoom;
	var i = 0;
	var indicator_id_found = false;
	var indicator_text = '';
	    
    // identify the pivot coordinates for the current element...(rect and ellipse have pivot_x and pivot_y = 0...
    var pivot_x_tmp = 0;
	var pivot_y_tmp = 0;
		
    // this should be only executed from the editor...not the viewer...however I use the variables!
	if( dragObj.element.id == flag_div.id )
	{
		pivot_x_tmp = flag_pivot_x;
		pivot_y_tmp = flag_pivot_y;
	}
	else if( dragObj.element.id == arrow_div.id )
	{
		pivot_x_tmp = arrow_pivot_x;
		pivot_y_tmp = arrow_pivot_y;
	}
	else if( dragObj.element.id == balloon_div.id )
	{        
        pivot_x_tmp = stripPx(balloon_pivot_div.getStyle('left')) + balloon_pivot_x;
        
        // I get this value using height and not top because I had problems in Safari!
        /*pivot_y_tmp = stripPx(balloon_div.getStyle('height')) - 20 + balloon_pivot_y;*/
        pivot_y_tmp = stripPx(balloon_div.getStyle('height')) - 51 + balloon_pivot_y;
                
        // for balloon update indicator text
        indicator_text = getBalloonText();
	}
    
	i = get_indicator_index(indicators_array, dragObj.element.id);
	    
	if( i != -1 )
	{
		indicators_array[i].id = dragObj.element.id;
		indicators_array[i].x = stripPx($(dragObj.element).getStyle('left')) + pivot_x_tmp;
		indicators_array[i].y = stripPx($(dragObj.element).getStyle('top')) + pivot_y_tmp;
		indicators_array[i].w = stripPx($(dragObj.element).getStyle('width'));
		indicators_array[i].h = stripPx($(dragObj.element).getStyle('height'));
		// update also pivots (this is needed for the balloon!)
		indicators_array[i].pivot_x = pivot_x_tmp;
		indicators_array[i].pivot_y = pivot_y_tmp;
		// this is used to know the current zoom level...
		indicators_array[i].zoom_level = zoom;
		indicators_array[i].fit_w = innerdiv_fit_w;
		indicators_array[i].fit_h = innerdiv_fit_h;
		// maybe this is not needed...
		indicators_array[i].text = indicator_text;
	}
	else
	{	
		end = indicators_array.length;
		
		indicators_array[end] = new indicator_data(dragObj.element.id,
		    stripPx($(dragObj.element).getStyle('left')) + pivot_x_tmp, stripPx($(dragObj.element).getStyle('top')) + pivot_y_tmp,
		    stripPx($(dragObj.element).getStyle('width')), stripPx($(dragObj.element).getStyle('height')),
		    zoom, innerdiv_fit_w, innerdiv_fit_h, pivot_x_tmp, pivot_y_tmp, indicator_text);
	}
	
	// test 060808
	// in this way we save the current indicators every time an indicator is dropped or moved...
	indicators_backup = indicators_array.clone();
}

// This method is not used for now but will be useful when we will want to implement the multiple indicators feature...
// I suggest to look at the dragdrop scriptaculous methods (in particular the "ghosting" feature) to have some suggestion to implement
// a good clone method...
/*function cloneItem(dragObj, event)
{	    
    clonedItem = dragObj.element.cloneNode(true);
    dragObj.element.parentNode.appendChild(clonedItem);
}*/
    
function moveItem(draggable, droparea)
{       
    draggableleft = Position.page(draggable)[0];
    draggabletop = Position.page(draggable)[1];
    innerleft = Position.page(inner_div)[0];
    innertop = Position.page(inner_div)[1];
     
    // append to the inner_div
    inner_div.appendChild(draggable);
     	
    if( draggable.id == rect_div.id )
	{
	    rect_dropped = true;
	}
	else if( draggable.id == ellipse_div.id )
	{
		ellipse_dropped = true;
		drawEllipse(); // I must call it here again because I need to reinitialize also the handle and the remover...ouch! :-(
	}
	else if( draggable.id == flag_div.id )
	{
		flag_dropped = true;
	}
	else if( draggable.id == arrow_div.id )
	{
		arrow_dropped = true;
	}
	else if( draggable.id == balloon_div.id )
	{
		balloon_dropped = true;
	}
           
    // normalize item position
    draggable.setStyle({ left: (draggableleft - innerleft) + 'px', top: (draggabletop - innertop) + 'px' });
        
    //draggable.options.revert = false;
}

function setBalloonText(btext)
{
    var text_layer = balloon_div.getElementsByTagName('div');
    var text_layerView = text_layer[0].getElementsByTagName('div');            
    text_layerView[0].innerHTML = btext;
}

function getBalloonText()
{
	var text_layer = balloon_div.getElementsByTagName('div');
    var text_layerView = text_layer[0].getElementsByTagName('div');
    return text_layerView[0].innerHTML;
}

function remove_indicator(item_to_remove)
{
	var new_x, new_y, new_w, new_h;

	if( item_to_remove.parentNode == inner_div )
	{
	    if( item_to_remove.id == rect_div.id )
	    {
		    new_x = rect_start_x;
		    new_y = rect_start_y;
		    new_w = rect_start_w;
		    new_h = rect_start_h;
		    rect_dropped = false;
	    }
	    else if( item_to_remove.id == ellipse_div.id )
	    {
		    new_x = ellipse_start_x;
		    new_y = ellipse_start_y;
		    new_w = ellipse_start_w;
		    new_h = ellipse_start_h;
		    ellipse_dropped = false;
	    }
	    else if( item_to_remove.id == flag_div.id )
	    {
		    new_x = flag_start_x;
		    new_y = flag_start_y;
		    new_w = flag_start_w;
		    new_h = flag_start_h;
		    flag_dropped = false;
	    }
	    else if( item_to_remove.id == arrow_div.id )
	    {
		    new_x = arrow_start_x;
		    new_y = arrow_start_y;
		    new_w = arrow_start_w;
		    new_h = arrow_start_h;
		    arrow_dropped = false;
	    }
	    else if( item_to_remove.id == balloon_div.id )
	    {
		    new_x = balloon_start_x;
		    new_y = balloon_start_y;
		    new_w = balloon_start_w;
		    new_h = balloon_start_h;
		    balloon_dropped = false;
	    }
	
	    inner_div.removeChild(item_to_remove);
	
	    // restore the old start position...
	    item_to_remove.setStyle({ left: new_x, top: new_y, width: new_w, height: new_h });
	
	    main_div.appendChild(item_to_remove);
	
	    // adjustments...
	    if( item_to_remove.id == ellipse_div.id ) // redraw the ellipse on its original position... 
	        drawEllipse();
	    else if( item_to_remove.id == rect_div.id ) // for the rect set the original thin border...
	        item_to_remove.style.border = "1px dashed #0000FF";
	    else if( item_to_remove.id == flag_div.id )
	        item_to_remove.style.backgroundImage = "url('/images/image-editor/flag_smaller.png')";
	    else if( item_to_remove.id == arrow_div.id )
	        item_to_remove.style.backgroundImage = "url('/images/image-editor/arrow_smaller_new.png')";
	    else if( item_to_remove.id == balloon_div.id )
	    {
		    balloon_pivot_div.style.backgroundImage = "url('/images/image-editor/b_new.png')";
	        balloon_first_edit = true;
	        balloon_editinplace.editor.blur();
	        setBalloonText("");
	    }
	    
	    // remove the element also from the array...
	    i = get_indicator_index(indicators_array, item_to_remove.id);
	    indicators_array.splice(i, 1);
    }
}

function remove_indicator_from_remover()
{	
	to_remove = this.parentNode;
	remove_indicator(to_remove);
}

// this should be used only in viewer mode...
function load_indicators_from_data(ind_array)
{    
    //center_innerdiv_after_zoom = true;
    
    for(var i=0;i<ind_array.length;i++)
    {   
	    // Fabian : Qui servirebbe una "conversione" tra id degli indicatori dell'editor e quelli del viewer...
	    // questo pezzo di codice e' qualcosa di temporaneo che deve essere sostituito...
	    ind_array[i].id = ind_array[i].id.replace("Editor", "Viewer");
	    
	    //alert(ind_array[i].id);
	    	    
	    // if the zoom level is different from each indicator in the array this function will do a total mess...
	    // zoom_level should be the same for each indicator in the structure...
	    // however I've added a check in toggleZoom so if the current zoom level is = to zoom_level it does nothing...	    
	    //toggleZoom(ind_array[i].zoom_level);
	    
	    // removed 170908
	    //slider.setValue(ind_array[i].zoom_level);
	    
	    var tmp_left = ind_array[i].x - ind_array[i].pivot_x;
	    var tmp_top = ind_array[i].y - ind_array[i].pivot_y;
	    $(ind_array[i].id).setStyle({ left: tmp_left + 'px', top: tmp_top + 'px', width: ind_array[i].w + 'px', height: ind_array[i].h + 'px' });
	    	    
	    inner_div.appendChild($(ind_array[i].id));
	    	    
	    // show the indicator (should be hidden!)
	    $(ind_array[i].id).setStyle({ visibility: 'visible' });
	    
        // if ellipse then redraw the graphical ellipse
	    if( ind_array[i].id == ellipse_div.id )
	        drawEllipse();
	    
	    // if balloon then update the internal text
	    if( ind_array[i].id == balloon_div.id )
	    {
            setBalloonText(ind_array[i].text);
	    }    
    }

    // added 170908 : This is needed because we go as default to the zoom level 0...ignore for now the ind_array[i].zoom_level value...
    //slider.setValue(0);
    updateIndicatorsPositionAndSize(ind_array);
    
    //center_innerdiv_after_zoom = false;
    
    var myJSONText = JSON.stringify(ind_array, function (key, value){ return value; } );
        
    // a new indicators configuration has been loaded...I save it in the current array...
    indicators_array = ind_array.clone();
}

/*Object.prototype.clone = function () {var o = new Object(); for (var property in this) {o[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return o}
Array.prototype.clone = function () {var a = new Array(); for (var property in this) {a[property] = typeof (this[property]) == 'object' ? this[property].clone() : this[property]} return a}*/

function text_struct(text)
{
    alert("text: "+text);

    tmpstructa = new indicator_data;
    return tmpstructa;
}

function generate_indicators(originalRequest)
{	
	// check if the responseText is not an empty struct...
    if( originalRequest.responseText != "[]" )
    {
	    indicators_array = [];
	    a = originalRequest.responseText.split("},");
	
	    for(var key=0;key<a.length;key++)
	    {
		    tmpst = a[key].replace("{","").replace("}","").replace("]","").replace("[","");
		    
		    tmpstructa = new indicator_data;
		    tmparray = tmpst.split(",");
		    		    
		    for(var k=0;k<tmparray.length;k++)
		    {
			    extr = [];

			    extr = tmparray[k].split(":");
			    extr[0] = extr[0].replace(/ /g, "").replace(/\"/g, "");;
			    extr[1] = extr[1].replace(/\"/g, "");

			    if( extr[0] != 'text' )
			    {
			        extr[1] = extr[1].replace(/ /g, "");
			    }
  	   
			    switch(extr[0])
			    {
			        case "id": tmpstructa.id = extr[1]; break;    
			        case "x": tmpstructa.x = parseInt(extr[1]); break;
			        case "y": tmpstructa.y = parseInt(extr[1]); break;    
			        case "w": tmpstructa.w = parseInt(extr[1]); break;    
			        case "h": tmpstructa.h = parseInt(extr[1]); break;    
			        case "zoom_level": tmpstructa.zoom_level = parseInt(extr[1]); break;
			        case "fit_w": tmpstructa.fit_w = parseInt(extr[1]); break;
			        case "fit_h": tmpstructa.fit_h = parseInt(extr[1]); break;
			        case "pivot_x": tmpstructa.pivot_x = parseInt(extr[1]); break;    
			        case "pivot_y": tmpstructa.pivot_y = parseInt(extr[1]); break;
			        case "text": tmpstructa.text = extr[1]; break;			  
			    }
			    
		   }
		    
       indicators_array[key] = tmpstructa;
	    }

	    var indicatorsJSON = JSON.stringify(indicators_array);
	    
	    load_indicators_from_data(indicators_array);
    }

}

function load_indicators(post_id, image_id)
{
    if( image_id == '' )
        image_id = gallery_image_id;
    
    // save post_id e image_id for later loads...
    /*curr_post_id = post_id;
    curr_image_id = image_id;*/
            
    new Ajax.Request('/forum/get_indicators/',
    {
        method: 'post',
        parameters: { post_id: post_id, image_id: image_id },
        onSuccess: function(originalRequest) { generate_indicators(originalRequest); }
    } );
}	

function save_indicators()
{
    indicators_backup = indicators_array.clone();
}

/*
 * pm = true|false private message
 */
function save_topic_image(post_id, pm)
{
    if(pm == null)
        pm = 0;

    var indicatorsJSON = JSON.stringify(indicators_array);
    var status = 0;

    if( gallery_image_id != '' && gallery_image_id != null)
    {
        new Ajax.Request('/forum/save_indicators/', 
        {
            method: 'post',
	        asynchronous: false, // can we change this to speed up ... ? be careful with the location.href at the bottom... 
            parameters: { indicators: indicatorsJSON, idimage: gallery_image_id, post_id: post_id },
            onComplete: function showResponse(originalRequest){ status = originalRequest.responseText; }
        } );
    }
    else
	status=1;

    if(pm)
        location.href = "/mailbox/goto_post/"+post_id;
    else
        location.href = "/forum/goto_post/"+post_id;

    return status;
}

function save_topic_image_without_redirect(form_id)
{
//  alert("save_topic_image_without_redirect("+form_id+")");
  var status = 0;
  var indicatorsJSON = JSON.stringify(indicators_array);
  $("indicators").value = indicatorsJSON;
  $("idimage").value = gallery_image_id;

/*
//  if( gallery_image_id != '' && gallery_image_id != null) {
    var i = new Element('input', { 'name': 'indicators', 'type': 'hidden', 'value': indicatorsJSON });
    $(form_id).insert({top: i});
    var i = new Element('input', { 'name': 'idimage', 'type': 'hidden', 'value': gallery_image_id });
    $(form_id).insert({top: i});
*/    
/*
        new Ajax.Request('/forum/save_indicators/', 
        {
            method: 'post',
	        asynchronous: false, // can we change this to speed up ... ? be careful with the location.href at the bottom... 
            parameters: { indicators: indicatorsJSON, idimage: gallery_image_id, post_id: post_id },
            onComplete: function showResponse(originalRequest){ status = originalRequest.responseText; }
        } );
*/
//  } else {
//  	status = 1;
//	}

  return status;
  
}

/*Event.observe('ImageEditor_rect_remover_layer', 'click', remove_indicator);
Event.observe('ImageEditor_ellipse_remover_layer', 'click', remove_indicator);
Event.observe('ImageEditor_flag_remover_layer', 'click', remove_indicator);
Event.observe('ImageEditor_arrow_remover_layer', 'click', remove_indicator);
Event.observe('ImageEditor_balloon_remover_layer', 'click', remove_indicator);*/

