// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

function viewmap(v) {
	var show = false;
	if(v>0) show = true;
	var box = document.getElementById('mapbox');
	if(show) {
		box.style.visibility = "visible";
		box.style.display = "block";
	} else {
		box.style.visibility = "hidden";
		box.style.display = "none";		
	}
}

function change_selection(obj) {
	if(obj.className!='F' && obj.className!='P') {
		obj.className='P';
	} else {
		if(obj.className=='F'){
			obj.className='P';
		} else {
			obj.className='F';
		}
	}
}

function set_totals() {
	document.getElementById('reservation_prezzo_tot_listino').value = document.getElementById('ptotlist').value;
	document.getElementById('reservation_prezzo_tot').value = document.getElementById('ptot').value;
	document.getElementById('txt_prezzo').innerHTML = document.getElementById('ptotlist').value;
}

/*
function change_for_edit() {
	var argv = change_for_edit.arguments
	
	var selected = document.getElementsByName('P')
	for(var i=0; i<selected.length; i++) {
		selected[i].name = 'F';
		selected[i].style.backgroundColor='#fff';
	}

	for(var i=0; i<argv.length; i++) {
		try {
			var obj = document.getElementById('p_'+argv[i])
				obj.name='P';
				obj.style.backgroundColor='#ff0';
				obj.innerHTML = 'edit'
		} catch (e) {;} 		
	}
}
*/


startList = function() {
if (document.all&&document.getElementById) {
navRoot = document.getElementById("nav");
for (i=0; i<navRoot.childNodes.length; i++) {
node = navRoot.childNodes[i];
if (node.nodeName=="LI") {
node.onmouseover=function() {
this.className+=" over";
  }
  node.onmouseout=function() {
  this.className=this.className.replace(" over", "");
   }
   }
  }
 }
}

window.onload=startList;

/*
	Autocompleter - - - - - - - - - - >>
*/

function disableEnable(element, element_to_disable_name)
{
  if(element.value == '')
  {
    document.getElementById(element_to_disable_name).disabled = true;
  }
  else
  {
    document.getElementById(element_to_disable_name).disabled = false;
  }
}

function getAuthenticityToken(form_name)
{
  return document.getElementById(form_name).authenticity_token.value;
}

/* 
	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
		}
	}
}

/*
	FCKEDITOR ...
*/

var FCKeditorAPI  // need to declare it in order to test it
var intFCKCheck   // our setTimeout pointer
var oFCKeditor    // used for our FCKEditor objects

function doOnLoad() // called from the body onload event
{
  // set the FCK polling timeout
  intFCKCheck = window.setInterval('checkFCKisReady()', 300)

  // create the first editor object to kick off the FCK core code
  oFCKeditor = new FCKeditor('data_node_description_' + langs[0])
  oFCKeditor.BasePath = '/fckeditor/'
  oFCKeditor.ToolbarSet = 'Default'
  oFCKeditor.ReplaceTextarea()
}

function checkFCKisReady()  // this is the polling function
{
  if(typeof(FCKeditorAPI) != 'undefined') // it's available now!
  {
    // stop checking already
    window.clearInterval(intFCKCheck)

    // crea FCKEditor a partire dalla seconda lingua
	for(i = 1; i < langs.length; i++)
	{
		oFCKeditor = new FCKeditor('data_node_description_' + langs[i])
		oFCKeditor.BasePath = '/fckeditor/'
		oFCKeditor.ToolbarSet = 'Default'
		oFCKeditor.ReplaceTextarea()
	}
  }
}

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();
    }
}
