/* 
	GoogleMaps Class
	Dominus Mappae !!
	19-11-2008
*/

var gmap;

function GoogleMaps()
{	
  this.edit = false;
  this.map = null;
  this.geocoder = null;
  this.addresses = null;
  this.ids = null;
  this.n = 0;
  this.bounds = null;
  this.center_map = null;

  /* inizializzazione della classe */
  this.init = function(admin)
  {
    if(admin == true){ edit = true } else {edit = false}
    // Ferrara 44.8378942, 11.6204396
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(0, 0), 16);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.enableScrollWheelZoom();
    geocoder = new GClientGeocoder();
    geocoder.setBaseCountryCode('IT');
    n = 0;
    bounds = new GLatLngBounds();
  };
  
  /* aggiunge un indirizzo alla mappa con geocode */
  this.addAddressToMapGC = function(response)
  {
    map.clearOverlays();
    
    if(!response || response.Status.code != G_GEO_SUCCESS) 
    {
      alert('Impossibile trovare questo indirizzo');
    } 
    else 
    {
      place = response.Placemark[0];
      point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
      
      center_map = point
      
      addMarker(point);
    }
  };

  /* aggiunge un indirizzo alla mappa con lat lng */
  function addAddressToMap(address)
  {
    map.clearOverlays();
    
    point = new GLatLng(address[0], address[1]);
    
    center_map = point
    
    addMarker(point);
  }

  function addMarker(point)
  {
      if (edit) 
      {
	marker = new GMarker(point, {draggable: true });
	
	GEvent.addListener(marker, "dragstart", function()
	{
	  map.closeInfoWindow();
	});
	
	GEvent.addListener(marker, "dragend", function()
	{
          //splitPath = window.location.pathname.split('/');
          //reqPath = '/' + splitPath[1] + '/resources/add_lat_lng_to_resource/' + splitPath[4]
          reqPath = '/admin/web_module/add_lat_lng_to_apartment/' + marker.id

	  marker.openInfoWindowHtml(
		'<strong>Latitudine:</strong> ' + this.getLatLng().lat() + '<br />' + 
		'<strong>Longitudine:</strong> ' + this.getLatLng().lng() + '<br /><br />' + 
		'<form action="/" method="post" ' + 
		'onsubmit="new Ajax.Request(\'' + reqPath + '\', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;">' + 
		'<input type="hidden" name="lat" value="' + this.getLatLng().lat() + '" />' + 
		'<input type="hidden" name="lng" value="' + this.getLatLng().lng() + '" />' +
		'<div id="add_lat_lng_response" align="center"><input name="commit" type="submit" value="Salva la posizione" class="mybutton" /></div>' + 
		'</form>'
		);
	});
      }
      else
      {
	marker = new GMarker(point);
      }

      marker.id = ids[n];
      map.addOverlay(marker);
      map.setCenter(point);
      
      GEvent.addListener(marker, 'click', getMapMarker);
  }

  /* aggiunge più indirizzi alla mappa con geocode */
  this.addAddressesToMapGC = function(response)
  {
    if(!response || response.Status.code != G_GEO_SUCCESS) 
    {
      alert('Impossibile trovare questo indirizzo');
    } 
    else 
    {
      place = response.Placemark[0];
      point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);

      addMarkers(point)
    }
  };

  /* aggiunge più indirizzi alla mappa con lat e lng */
  function addAddressesToMap(address)
  {
    point = new GLatLng(address[0], address[1]);

    addMarkers(point);
  }
  
  function addMarkers(point)
  {
    marks = new GMarker(point);
    marks.id = ids[n];
    map.addOverlay(marks);

    GEvent.addListener(marks, 'click', getMapMarker);
      
    bounds.extend(point);

    if(n == (addresses.length - 1))
    {
      map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    }

    n++;
  }

  /* inizializza il posizionamento delle risorse sulla mappa */
  this.showLocation = function(address, id)
  {
    ids = id;
    addresses = address;

    if(is_array(address) && address.length > 1) 
    {
      for(i = 0; i < address.length; i++) 
      {
        if(is_array(address[i]))
        {
          addAddressesToMap(address[i]);
        }
        else
        {
          geocoder.getLocations(address[i], this.addAddressesToMapGC);
        }
      }
    }
    else 
    {
      if(is_array(address[0]))
      {
        addAddressToMap(address[0]);
      }
      else
      {
        geocoder.getLocations(address[0], this.addAddressToMapGC);
      }
    }
  };

  this.description = function(i) 
  {
    return descriptions[i]
  };

  this.address = function(i) 
  {
    return addresses[i]
  };
  
  this.refresh = function()
  {
    map.checkResize();
    
    if(center_map != null)
    {
      map.setCenter(center_map);
    }
    else
    {
      map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    }
  }
  
}

/* inizializzazione della classe */
function getMapMarker()
{
  mark = this;
  
  splitPath = window.location.pathname.split('/');
  //reqPath = '/' + splitPath[1] + '/resources/json_resource/' + this.id;
  reqPath = '/admin/web_module/json_apartment/' + this.id;
  
  new Ajax.Request(reqPath, {asynchronous:true, evalScripts:true, 
    onSuccess:function(resp)
    {
      resource = JSON.parse(resp.responseText);

      image = (resource['image'] != null) ? '<td width="60"><img src="' + resource['image'] + '" width="50" height="50" /></td>' : '';

      html = '<table width="210"><tr>' + image + '<td valign="top">' + 
        '<b>' + resource['title_it'] + '</b><br />' + 
        resource['address'] + '<br />' + resource['town'] + ', ' + resource['district'] + 
        '</td></tr></table>';
        
      mark.openInfoWindowHtml(html);
    }, 
    onFailure:function()
    {
      //
    }
  });
}

function is_array(input)
{
  return typeof(input)=='object'&&(input instanceof Array);
}

/* Period Table Fragmentation */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

function PeriodTableFragmentation()
{
	this.prev = null;
	this.next = null;
	this.table = null;
	this.tot = 0;
	this.cols = 0;
	this.frags = 0;
	this.selected = 0;
	this.pre_cols = 0;
	this.tmpThStyles = null;
	this.tmpTdStyles = null;

	this.init = function(tab, img_prev, img_next, total, columns, off_set)
	{
		prev = document.getElementById(img_prev);
		next = document.getElementById(img_next);
		table = document.getElementById(tab);
		setFragments(total, columns, off_set);
		tmpThStyles = new Array();
		tmpTdStyles = new Array();
		setNavigation();
		setTempStyles();
		setTableState();
		table.style.display = '';
	}
	
	function setFragments(total, columns, off_set)
	{
		tot = total;
		cols = columns;
		frags = Math.ceil(tot / cols);
		selected = 1;
		pre_cols = off_set;
		
		//alert('TOT: ' + tot + "\n" + 'COLS: ' + cols + "\n" + 'FRAGS: ' + frags + "\n" + 'SELECTED: ' + selected + "\n" + 'PRECOLS: ' + pre_cols);
	}
	
	function setNavigation()
	{
		next.onclick = nextOp;
		prev.onclick = prevOp;
		
		if (frags == 1) 
		{
			prev.style.display = 'none';
			next.style.display = 'none';
		}
		if (frags >= 2 && selected == 1) 
		{
			prev.style.display = 'none';
			next.style.display = '';
		}
		if (frags >= 2 && selected == frags) 
		{
			prev.style.display = '';
			next.style.display = 'none';
		}
		if (frags > 2 && (selected > 1 && selected < frags)) 
		{
			prev.style.display = '';
			next.style.display = '';
		}
	}
	
	function setTempStyles()
	{
		var trs = table.getElementsByTagName('tr');
		
		for (j = 0; j < trs.length; j++) 
		{
			var ths = trs[j].getElementsByTagName('th');
			var tds = trs[j].getElementsByTagName('td');
			tmpThStyles[j] = new Array()
			tmpTdStyles[j] = new Array()
			
			for (i = 0; i < ths.length; i++) 
			{
				tmpThStyles[j][i] = ths[i].className;
			}
			
			for (i = 0; i < tds.length; i++) 
			{
				tmpTdStyles[j][i] = tds[i].className;
			}
		}
		
		//alert(tmpThStyles)
		//alert(tmpTdStyles)
	}
	
	function nextOp()
	{
		selected++;

		//alert('TOT: ' + tot + "\n" + 'COLS: ' + cols + "\n" + 'FRAGS: ' + frags + "\n" + 'SELECTED: ' + selected + "\n" + 'PRECOLS: ' + pre_cols);

		setNavigation();
		setTableState();
	}
	
	function prevOp()
	{
		selected--;

		//alert('TOT: ' + tot + "\n" + 'COLS: ' + cols + "\n" + 'FRAGS: ' + frags + "\n" + 'SELECTED: ' + selected + "\n" + 'PRECOLS: ' + pre_cols);

		setNavigation();
		setTableState();
	}
	
	function setTableState()
	{
		var trs = table.getElementsByTagName('tr');
		start = pre_cols + ((selected - 1) * cols);
		end = pre_cols + (selected * cols);
		
		//alert('START: ' + start + "\n" + 'END: ' + end + "\n");
		
		for (j = 0; j < trs.length; j++) 
		{
			var ths = trs[j].getElementsByTagName('th');
			var tds = trs[j].getElementsByTagName('td');
			
			for (i = 0; i < ths.length; i++) 
			{
				if ((i <= pre_cols) || (i > start && i <= end) || i == ths.length - 1) 
				{
					ths[i].className = tmpThStyles[j][i];
				}
				else
				{
					ths[i].className = 'hidden';
				}
			}
			
			for (i = 0; i < tds.length; i++) 
			{
				if ((i <= pre_cols) || (i > start && i <= end) || i == tds.length - 1) 
				{
					tds[i].className = tmpTdStyles[j][i];
				}
				else
				{
					tds[i].className = 'hidden';
				}
			}
		}
	}
}

/* ACL */

function checkActions(select){
	
	var div = document.getElementById('acl_options');
	var acls = div.getElementsByTagName('input');
	
	for (i = 0; i < acls.length; i++) {

		if (select == 'all') 
		{
			(acls[i].value.indexOf(select) > 0) ? acls[i].checked = true : acls[i].checked = false
		}
		
		if (select != 'all' && select != 'remove') 
		{
			if (acls[i].value.indexOf(select) > 0) 
			{
				acls[i].checked = true
			}
		}		
		if(select == 'remove')
		{
			acls[i].checked = false
		}
	}
}



function hide_and_show(show)
{
    //hide = ['display_price_list', 'display_images', 'display_googlemaps', 'display_email'];
    hide = ['display_googlemaps', 'display_email', 'display_features'];
    
    for(i = 0; i < hide.length; i++)
    {
        if(hide[i] != show)
        {
            $(hide[i]).hide();
        }
        else
        {
            if($(hide[i]).style.display != 'none')
            {
                $(hide[i]).hide();
            }
            else
            {
                $(hide[i]).show();

                if(hide[i] == 'display_googlemaps')
                {
                    gmap.refresh();
                }
            }
        }
    }
}

function focusLog()
{
    if($('login'))
    {
        $('login').focus();
    }
}

/* progress bar */

/*
var progress_bar = null;

function start_progress()
{
  progress_bar.reset();
  progress_bar.poll('/admin/uploader/progress', 0.15);
  progress_bar.start();
}
*/

function fire_click(element)
{
//  var el = document.getElementById(element);
//
//  if(document.createEventObject)
//  {
//    var evt = document.createEventObject();
//    el.fireEvent('onclick',evt);
//  }
//  else
//  {
//    var event = document.createEvent("MouseEvents");
//    event.initMouseEvent("click", true, true, document.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
//    el.dispatchEvent(event);
//  }

  $(element).simulate('click');
}

function climage(n)
{
  fire_click('prima' + n);
}


function apartment_show_hide(show, el)
{
  ids = ['htmlareas_table', 'co_im', 'ca_im', 'gm_im', 'me_im', 'se_im', 'in_im'];
  
  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);
    
    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function structural_show_hide(show, el)
{
  ids = ['htmlareas_table', 'in_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function information_show_hide(show, el)
{
  ids = ['htmlareas_table', 'dt_im', 'me_im', 'se_im', 'in_im', 'ca_im', 'pr_im', 'gm_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function restricted_show_hide(show, el)
{
  ids = ['la_im', 'us_im', 'ub_im', 'in_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function rwr_show_hide(show, el)
{
  ids = ['htmlareas_table', 'sr_im', 'me_im', 'se_im', 'in_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function poll_show_hide(show, el)
{
  ids = ['dm_im', 'rs_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function calendar_item_show_hide(show, el)
{
  ids = ['htmlareas_table', 'dt_im', 'cl_im', 'me_im', 'se_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

function generator_show_hide(show, el)
{
  ids = ['htmlareas_table', 'type_im', 'in_im'];

  for(i = 0; i < ids.length; i++)
  {
    h = $(ids[i]);

    if(h)
    {
      h.hide();
    }
  }

  $(show).show();

  as = $('globalnav').getElementsByTagName('a')

  for(i = 0; i < as.length; i++)
  {
    if(as[i].className != 'save' && as[i].className != 'annulla')
    {
      as[i].className = '';
    }
  }

  $(el).className = 'here';
}

/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */


/* SETUP - - - - - - - - - - - -  - - - - - - - - -  - - - - - - -  - - - - - - - -  - - - -  - - - - - - - - - - */

var Apartment = ['title', 'subtitle','description','description2','note','pricelist_note','reference','sale','sale_price','rent','features','price_list','address','town','district','images','videos'];
var InformationNode = ['title','subtitle','description','description2','note','pricelist_note','images','files','videos','visual_dates','features','price','code','googlemaps'];
var Structural = ['title'];
var RestrictedArea = ['title'];
var ReWebResearch = ['title','images'];
var Calendar = ['title'];
var Poll = ['title'];
var Generator = ['title'];
var Store = ['title','subtitle','description','features','googlemaps'];
var Product = ['title','subtitle','description','images','files','videos','visual_dates','features','price','code','googlemaps'];

var Apartment_EX = ['Immobile', 'resource.png'];
var InformationNode_EX = ['Info', 'information.png'];
var Structural_EX = ['Struttura', 'structural.png'];
var RestrictedArea_EX = ['Area Riservata', 'restricted_area.png'];
var ReWebResearch_EX = ['Ricerca ReWeb', 'reweb_research.png'];
var Calendar_EX = ['Calendario', 'calendar.png'];
var Poll_EX = ['Sondaggi', 'poll.png'];
var Generator_EX = ['Generatore', 'generator.png'];
var Store_EX = ['Store', 'store.png'];
var Product_EX = ['Product', 'product.png'];

var id = 0;       // id numerico
var nsel = null;  // nodo selezionato
var dp = 0;       // profondità
var dump = '';    // dump yaml
var deep = 0;     // profondità yaml

/* CREAZIONE ALBERO - - - - - - - - - - - - - -  - - - - - - -  - - - - - - - -  - - - -  - - - - - - - - - - - - */

function AddN(nome)
{
  id++;

  if(nsel==null)  // se non è stato selezionato alcun nodo
  {
    nsel = document.getElementById('node-1');
  }
  else
  {
    nsel = document.getElementById(nsel.getAttribute('id') + '-childs');
  }

  var is_new = true;
  var c = nsel.firstChild
  
  while(c != null)
  {
    var ln = document.getElementById(c.getAttribute('id') + '-label');
    var label = ln.firstChild.nodeValue;

    if(label == nome)
    {
      is_new = false;
      break;
    }
    c = c.nextSibling
  }

  if(is_new == true)
  {
    nsel.innerHTML += '<div style="background-color:orange;margin-left:' + dp + 'px;" id="node-'+id+'" dp="' + dp + '">' +
                        '<a href="javascript:void(0);" onclick="SelectN(this);" id="node-'+id+'-label">' + nome + '</a>' + '&nbsp;' +
                        '<a href="javascript:void(0);" onclick="RemoveN(this);">x</a> ' +
                        '<a href="javascript:void(0);" onclick="ReloadAllFields(\'node-'+id+'\', \''+nome+'\');">-fs-</a> ' +
                        '<div id="node-'+id+'-fields"></div>' +
                        '<div id="node-'+id+'-extra"></div>' +
                        '<div id="node-'+id+'-childs"></div>' +
                      '</div>';

    var html = ''
    var fields = eval(nome)

    for(var i = 0; i < fields.length; i++)
    {
      html += '<div style="background-color:yellow;margin-left:' + (dp+5) + 'px;">' + fields[i]

      if(fields[i] != 'title')
      {
        html += ' <a href="javascript:void(0);" onclick="RemoveN(this);">x</a>';
      }

      html += '</div>';
    }

    document.getElementById('node-'+id+'-fields').innerHTML = html;

    var extra = eval(nome + '_EX')

    html = '';
    html += '<div style="background-color:gold;margin-left:' + (dp+5) + 'px;">';
    html += '  Name:<input type="text" id="c_name" value="' + extra[0] + '" size="15" />';
    html += '</div>';
    html += '<div style="background-color:gold;margin-left:' + (dp+5) + 'px;">';
    html += '  Icon:&nbsp;&nbsp;<input type="text" id="c_icon" value="' + extra[1] + '" size="15" />';
    html += '</div>';

    document.getElementById('node-'+id+'-extra').innerHTML = html;
  }

  SelectN(nsel);
}

function AddRoot(nome)
{
  id = 1;
  dp = 0;

  nsel = document.getElementById('vincles');

  nsel.innerHTML += '<div style="background-color:red;margin-left:' + dp + 'px;" id="node-'+id+'" dp="' + dp + '">' +
                      '<a href="javascript:void(0);" onclick="SelectN(this);" id="node-'+id+'-label">' + nome + '</a>' + '&nbsp;' +
                      '<a href="javascript:void(0);">&nbsp;</a>' +
                      '<div id="node-'+id+'-fields"></div>' +
                      '<div id="node-'+id+'-extra"></div>' +
                      '<div id="node-'+id+'-childs"></div>' +
                    '</div>';

  var l = document.getElementById('node-'+id+'-label');
  SelectN(l);
}

function SelectN(el)
{
  nsel = el.parentNode;                                 // imposta il nodo selezionato
  dp = parseInt(el.parentNode.getAttribute('dp')) + 5;  // imposta la profondità
}

String.prototype.repeat = function(l){
	return new Array(l+1).join(this);
};

function Spaces()
{
  return ' '.repeat(deep)
}

function SetMaxId(mId)
{
  id = mId;
}

/* DUMP YAML DELL'ALBERO - - - - - - - - - - - - - -  - - - - - - -  - - - - - - - -  - - - -  - - - - - - - - - -*/

function DumpVincles(n)
{
  if(n == null)
  {
    dump = '';
    //dp = 0;
    n = document.getElementById('vincles').firstChild

    if(n == null)
    {
      document.getElementById('current_node_constraints').value = '';
      return;
    }
  }

  while(n != null)
  {
    DumpNode(n);
    DumpFields(n);
    DumpExtra(n);
    DumpChildrens(n);
    n = n.nextSibling;
  }

  document.getElementById('current_node_constraints').value = dump;

//  if(dump.length > 0)
//  {
//    document.getElementById('current_node_fixed').checked = true;
//  }
}

function DumpNode(n)
{
  var id = n.getAttribute('id');
  var label = document.getElementById(id + '-label');

  if(label != null)
  {
    dump += Spaces() + "type: " + label.firstChild.nodeValue + "\n";
  }
}

function DumpFields(n)
{
  var id = n.getAttribute('id');
  var field = document.getElementById(id + '-fields').firstChild;

  dump += Spaces() + "disallowed_fields:\n";

  if(field != null)
  {
    while(field != null)
    {
      dump += Spaces() + "- " + field.firstChild.nodeValue + "\n";
      field = field.nextSibling
    }
  }
  else
  {
    dump += Spaces() + "-\n";
  }
}

function DumpExtra(n)
{
  var id = n.getAttribute('id');
  var extra = document.getElementById(id + '-extra').firstChild;
  
  if(extra != null)
  {
    var name = extra.firstChild.nextSibling.value;
    dump += Spaces() + "name: " + name + "\n";
    var icon = extra.nextSibling.firstChild.nextSibling.value;
    dump += Spaces() + "icon: " + icon + "\n";
  }
  else
  {
    dump += Spaces() + "name:\n";
    dump += Spaces() + "icon:\n";
  }
}

function DumpChildrens(n)
{
  var id = n.getAttribute('id');
  var c = document.getElementById(id + '-childs').firstChild;

  dump += Spaces() + "childrens:\n";
  dump += Spaces() + "-\n";
  deep += 2;

  while(c != null)
  {
    DumpNode(c);
    DumpFields(c);
    DumpExtra(c);
    DumpChildrens(c);

    c = c.nextSibling;

    if(c != null)
    {
      deep -= 2;
      dump += Spaces() + "-\n";
      deep += 2;
    }
  }
  deep -= 2;
}

function RemoveN(el)
{
  el.parentNode.parentNode.removeChild(el.parentNode);

  if(document.getElementById('node-1-childs').firstChild == null)
  {
    var l = document.getElementById('node-1-label');
    SelectN(l);
  }
}

/* DISALLOWED FIELDS */

function DisallowedAPI(nome)
{
  var dis = document.getElementById('disallowed_fields');

  dis.innerHTML = '<div style="background-color:orange;margin-left:0px;" id="dis-1" dp="0">' +
                     '<a href="javascript:void(0);" id="dis-1-label">' + nome + '</a>' + '&nbsp;' +
                     '<a href="javascript:void(0);" onclick="ReloadAllFields(\'dis-1\', \'' + nome + '\');">-fs-</a> ' +
                     '<div id="dis-1-fields"></div>' +
                     '<div id="dis-1-extra"></div>' +
                   '</div>';

  var html = ''
  var fields = eval(nome)

  for(var i = 0; i < fields.length; i++)
  {
    html += '<div style="background-color:yellow;margin-left:5px;">' + fields[i]
    
    if(fields[i] != 'title')
    {
      html += ' <a href="javascript:void(0);" onclick="RemoveN(this);">x</a>';
    }

    html += '</div>';
  }

  document.getElementById('dis-1-fields').innerHTML = html;

  var extra = eval(nome + '_EX')

  html = '';
  html += '<div style="background-color:gold;margin-left:5px;">';
  html += '  Name:<input type="text" id="c_name" value="' + extra[0] + '" size="15" />';
  html += '</div>';
  html += '<div style="background-color:gold;margin-left:5px;">';
  html += '  Icon:&nbsp;&nbsp;<input type="text" id="c_icon" value="' + extra[1] + '" size="15" />';
  html += '</div>';

  document.getElementById('dis-1-extra').innerHTML = html;
}

function DumpDisallowedFields()
{
  var field = document.getElementById('dis-1-fields').firstChild;
  var yaml = '';

  yaml += "disallowed_fields:\n"

  if(field != null)
  {
    while(field != null)
    {
      yaml += "  - " + field.firstChild.nodeValue + "\n";
      field = field.nextSibling;
    }
  }
  else
  {
    yaml += "  -\n";
  }

  var extra = document.getElementById('dis-1-extra');
  var name = extra.firstChild.firstChild.nextSibling.value;
  yaml += "name: " + name + "\n";
  var icon = extra.firstChild.nextSibling.firstChild.nextSibling.value;
  yaml += "icon: " + icon + "\n";

  document.getElementById('current_node_disallowed_fields').value = yaml;
}

function DumpAllVincles()
{
  if(document.getElementById('current_node_fixed'))
  {
    if(document.getElementById('current_node_fixed').checked == true)
    {
      if(document.getElementById('current_node_constraints'))
      {
        DumpVincles(null);
      }

      if(document.getElementById('current_node_disallowed_fields'))
      {
        DumpDisallowedFields();
      }
    }
    else
    {
      document.getElementById('current_node_constraints').value = '';
      document.getElementById('current_node_disallowed_fields').value = '';
    }
  }
}

function ReloadAllFields(id, nome)
{
    var html = ''
    var fields = eval(nome)

    for(var i = 0; i < fields.length; i++)
    {
      html += '<div style="background-color:yellow;margin-left:' + (dp+5) + 'px;">' + fields[i]

      if(fields[i] != 'title')
      {
        html += ' <a href="javascript:void(0);" onclick="RemoveN(this);">x</a>';
      }

      html += '</div>';
    }

    document.getElementById(id+'-fields').innerHTML = html;
}

function div_up(n)
{
  var cont = $('imgs_ord');
  var divs = cont.getElementsByTagName('div');
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id == 'picture_'+n)
    {
      break;
    }
  }
  if(i != 0)
  {
    var my_div = divs[i];
    var other_div = divs[i-1];
    cont.insertBefore(my_div, other_div);
  }

  divs = cont.getElementsByTagName('div');
  var imgs = [];
  var order = [];
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id.match(/^picture/) != null)
    {
      imgs = divs[i].getElementsByTagName('img');
      order.push(imgs[3].src.split('/').last().replace('_small', ''));
    }

  }

  set_hode_show_admin_image_arrows();

  var vjson = JSON.stringify(order);
  new Ajax.Request('/admin/web_module/reorder_image_session?vjson='+vjson, {asynchronous:true, evalScripts:true});
}

function div_down(n)
{
  var cont = $('imgs_ord');
  var divs = cont.getElementsByTagName('div');
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id == 'picture_'+n)
    {
      break;
    }
  }
  if(i != divs.length-2)
  {
    var my_div = divs[i];
    var other_div = divs[i+1];
    cont.insertBefore(other_div, my_div);
  }
  
  divs = cont.getElementsByTagName('div');
  var imgs = [];
  var order = [];
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id.match(/^picture/) != null)
    {
      imgs = divs[i].getElementsByTagName('img');
      order.push(imgs[3].src.split('/').last().replace('_small', ''));
    }

  }

  set_hode_show_admin_image_arrows();

  var vjson = JSON.stringify(order);
  new Ajax.Request('/admin/web_module/reorder_image_session?vjson='+vjson, {asynchronous:true, evalScripts:true});
}

function update_label(element)
{
  new Ajax.Request('/admin/web_module/update_labels_session', {asynchronous:true, evalScripts:true, parameters:Form.serialize(element)});
}

function update_file_label(element)
{
  new Ajax.Request('/admin/web_module/update_files_labels_session', {asynchronous:true, evalScripts:true, parameters:Form.serialize(element)});
}

function set_hode_show_admin_image_arrows()
{
  var cont = $('imgs_ord');
  
  if(cont)
  {
    var divs = cont.getElementsByTagName('div');
    var imgs = [];
    var n_pict = 0;
    for(i = 0; i < divs.length; i++)
    {
      if(divs[i].id.match(/^picture/) != null)
      {
        n_pict = i;
      }
    }
    for(i = 0; i < divs.length; i++)
    {
      if(divs[i].id.match(/^picture/) != null)
      {
        imgs = divs[i].getElementsByTagName('img');

        if(imgs.length > 0)
        {
          imgs[1].style.display = '';
          imgs[2].style.display = '';

          if(i == 0)
          {
            imgs[1].style.display = 'none';
          }
          if(i == (n_pict))
          {
            imgs[2].style.display = 'none';
          }
        }
      }
    }
  }
}

function set_hode_show_admin_file_arrows()
{
  var cont = $('fls_ord');

  if(cont)
  {
    var divs = cont.getElementsByTagName('div');
    var imgs = [];
    var n_pict = 0;
    for(i = 0; i < divs.length; i++)
    {
      if(divs[i].id.match(/^df/) != null)
      {
        n_pict = i;
      }
    }
    for(i = 0; i < divs.length; i++)
    {
      if(divs[i].id.match(/^df/) != null)
      {
        imgs = divs[i].getElementsByTagName('img');

        if(imgs.length > 0)
        {
          imgs[1].style.display = '';
          imgs[2].style.display = '';

          if(i == 0)
          {
            imgs[1].style.display = 'none';
          }
          if(i == (n_pict))
          {
            imgs[2].style.display = 'none';
          }
        }
      }
    }
  }
}

function div_up_file(n)
{
  var cont = $('fls_ord');
  var divs = cont.getElementsByTagName('div');
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id == 'df_'+n)
    {
      break;
    }
  }
  if(i != 0)
  {
    var my_div = divs[i];
    var other_div = divs[i-1];
    cont.insertBefore(my_div, other_div);
  }

  divs = cont.getElementsByTagName('div');
  var fls = [];
  var order = [];
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id.match(/^df/) != null)
    {
      fls = divs[i].getElementsByTagName('a');
      order.push(fls[1].innerHTML);
    }

  }

  set_hode_show_admin_file_arrows();

  var vjson = JSON.stringify(order);
  new Ajax.Request('/admin/web_module/reorder_file_session?vjson='+vjson, {asynchronous:true, evalScripts:true});
}

function div_down_file(n)
{
  var cont = $('fls_ord');
  var divs = cont.getElementsByTagName('div');
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id == 'df_'+n)
    {
      break;
    }
  }
  if(i != divs.length-2)
  {
    var my_div = divs[i];
    var other_div = divs[i+1];
    cont.insertBefore(other_div, my_div);
  }

  divs = cont.getElementsByTagName('div');
  var fls = [];
  var order = [];
  for(i = 0; i < divs.length; i++)
  {
    if(divs[i].id.match(/^df/) != null)
    {
      fls = divs[i].getElementsByTagName('a');
      order.push(fls[1].innerHTML);
    }

  }

  set_hode_show_admin_file_arrows();

  var vjson = JSON.stringify(order);
  new Ajax.Request('/admin/web_module/reorder_file_session?vjson='+vjson, {asynchronous:true, evalScripts:true});
}

function sleep(milliseconds)
{
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++)
  {
    if ((new Date().getTime() - start) > milliseconds)
    {
      break;
    }
  }
}

function cart_item_change_quantity(elid)
{
  var qt = $(elid).value;
  new Ajax.Request('/cart/item_change_quantity/'+elid+'/'+qt,{asynchronous:true, evalScripts:true});
}

function add_to_mini_cart(url)
{
  var form = $('features');
  if(form != null)
  {
    new Ajax.Request(url, {asynchronous:true, evalScripts:true, parameters:Form.serialize(form)});
  }
  else
  {
    new Ajax.Request(url,{asynchronous:true, evalScripts:true});
  }
}
