/** $Id: util.js,v 1.9 2007-11-13 06:30:52 dbc Exp $ **/
function showCalendar(layerName)
{
    byId(layerName,'style.display','block');
}
function hideCalendar(layerName)
{
    byId(layerName,'style.display','none');
}
function byId(q,p){
	if(arguments.length<3)return eval("document."+((document.all)?"all['"+q+"']":"getElementById('"+q+"')")+"."+p);
	else eval("document."+((document.all)?"all['"+q+"']":"getElementById('"+q+"')")+"."+p+"='"+arguments[2]+"'");
}
function aprichiudiLay(idLay,icoName){
//	var idImg = idLay+"img";
//	var srcImg;
    if(byId(idLay,'style.display')=="none"){
//		srcImg = "/ospmi/img/sch_"+icoName+"_off.gif";
		byId(idLay,'style.display','block');
//		byId(idImg,'src',srcImg);
	}else{
//		srcImg = "/ospmi/img/sch_"+icoName+"_on.gif";
		byId(idLay,'style.display','none');
//		byId(idImg,'src',srcImg);
	}
}


// utilizzata con il menu laterale interno
function changeAsset(assetId)
{
    var f = document.getElementById('mainform');
    f.assetId.value = assetId;
    f.submit();
}

// calendario home page

/**
 * verifica ala consistenza delle due tendine con il calendario, il parametro
 * indica quale  la data che  stata cambiata se quella di from o quella di to.
 */
function adjustDate( selectSource)
{
    var dayF = document.getElementById('dayFrom');
    var monthF = document.getElementById('myFrom');
    var hourF = document.getElementById('hourFrom');
    var dayT = document.getElementById('dayTo');
    var monthT = document.getElementById('myTo');
    var hourT = document.getElementById('hourTo');

    var from = getSelectedDate( dayF, monthF, hourT );
    var to = getSelectedDate( dayT, monthT, hourT );

    // correggo eventuali date precedenti a oggi
    var today = new Date();
/*
    if (from < today && selectSource == 'from')
    {
        alert('Data di partenza nel passato non valida.');
    }
    if ( to < today && selectSource == 'to' )
    {
        alert('Data di ritorno nel passato non valida.');
    }
*/
/*
    if ( from < today)
    {
        from.setDate(today.getDate());
    }
    if ( to < today)
    {
        to.setDate(today.getDate()+1);
    }
*/    
    var tomorrow = new Date();
    tomorrow.setTime(from.getTime());
    tomorrow.setDate(tomorrow.getDate()+1);
    // reimposto la data per correggere eventuali errori di data fine mese (tipo 31 giugno)
    if ( selectSource == 'from' ) setSelectedDate( from , dayF, monthF );
    if ( selectSource == 'to' ) setSelectedDate( to , dayT, monthT );
    // correggo eventuale partenza dopo arrivo
    if ( to < tomorrow ) {
        if ( selectSource == 'from' )
        {
            to = tomorrow;
            setSelectedDate( tomorrow , dayT, monthT );
        }
        if ( selectSource == 'to' )
        {
            from = to;
            from.setDate(from.getDate() - 1);
            setSelectedDate( from , dayF, monthF );
        }
    }



}

/**
 * restitusce un oggetto Date avendo come parametri di ingresse due tendine con
 * giorno e mese_anno
 **/
function getSelectedDate( selectDay, selectMonth, selectHour )
{
    var day = selectDay.options[selectDay.selectedIndex].value;
    var m = selectMonth.options[selectMonth.selectedIndex].value;
    var hours = selectHour.options[selectHour.selectedIndex].value;
    var monthYearArray = m.split("_");
    var month = monthYearArray[0];
    var year = monthYearArray[1];

    var d = new Date();
    d.setMonth( month );
    d.setYear( year );
    d.setDate( day );
    d.setHours( hours);

//    alert(day + '/' + month + '/' + year + ':' + hours + '\n' + d);

    // se ho selezionato 31 del mese con 30 giorni torno indietro fino all'ultimo del mese prima
    while (d.getMonth() != month)
    {
        d.setDate(d.getDate() - 1 );
    }

    return d;
}

/**
 * seleziona i valori di due tendine con giorno e mese_anno impostando la data
 * specificata dal parametro d di tipo Date
 */
function setSelectedDate( d , selectDay, selectMonth )
{
    var day = d.getDate();
    var month = d.getMonth();
    var year = d.getFullYear();
    var s = month + '_' + year;

    for ( x=0; x < selectMonth.options.length; x++)
    {
        if (selectMonth.options[x].value == s)
        {
            selectMonth.options[x].selected = true;
            selectMonth.selectedIndex = x;
        }
    }

    for ( x=0; x <= selectDay.options.length; x++)
    {
        if (selectDay.options[x].value == day)
        {
            selectDay.options[x].selected = true;
            selectDay.selectedIndex = x;
            return;
        }
    }

}

// calendarietti in home page
function showHomeCalendar(sourceSelect)
{
  // todo impostare la data leggendola dalle tendine
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);

    // uncomment the following line to hide the week numbers
    cal.weekNumbers = false;
    cal.showsTime = false;
    cal.showsOtherMonths = true;

    _dynarch_popupCalendar = cal;                  // remember it in the global var
    // todo impostare la regola dei sei mesi
    cal.setRange(2008, 2010);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat('%d/%m/%Y');    // set the specified date format

  if (sourceSelect == 'homeTo')
  {
    var dayT = document.getElementById('dayTo');
    var monthT = document.getElementById('myTo');
    var hourT = document.getElementById('hourTo');
    var to = getSelectedDate( dayT, monthT, hourT );
    _dynarch_popupCalendar.setDate(to);
    _dynarch_popupCalendar.sel = sourceSelect;                 // inform it what input field we use

  } else if (sourceSelect == 'homeFrom') {
    var dayF = document.getElementById('dayFrom');
    var monthF = document.getElementById('myFrom');
    var hourF = document.getElementById('hourFrom');
    var from = getSelectedDate( dayF, monthF, hourF );
    _dynarch_popupCalendar.setDate(from);
    _dynarch_popupCalendar.sel = sourceSelect;                 // inform it what input field we use
  }

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  if (sourceSelect == 'homeFrom')
  {
      var el = document.getElementById('buttonfrom');
      _dynarch_popupCalendar.showAtElement(el, "br");        // show the calendar
  } else if (sourceSelect == 'homeTo') {
      var el = document.getElementById('buttonto');
      _dynarch_popupCalendar.showAtElement(el, "br");        // show the calendar
  }

  return false;
}

function showCalendar( field , button)
{
  // todo impostare la data leggendola dalle tendine
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);

    // uncomment the following line to hide the week numbers
    cal.weekNumbers = false;
    cal.showsTime = false;
    cal.showsOtherMonths = true;

    _dynarch_popupCalendar = cal;                  // remember it in the global var
    // todo impostare la regola dei sei mesi
    cal.setRange(2009, 2011);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat('%d/%m/%Y');    // set the specified date format

  var el = document.getElementById(field);
  _dynarch_popupCalendar.parseDate(el.value);
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  var btn = document.getElementById(button);
  _dynarch_popupCalendar.showAtElement(btn, "br");        // show the calendar

  return false;
}

function selected(cal, date) {

    if (cal.sel == 'homeTo')
    {
        var dayT = document.getElementById('dayTo');
        var monthT = document.getElementById('myTo');
        setSelectedDate( cal.date , dayT, monthT );
        adjustDate('to');

    } else if (cal.sel == 'homeFrom'){
        var dayF = document.getElementById('dayFrom');
        var monthF = document.getElementById('myFrom');
        setSelectedDate( cal.date , dayF, monthF );
        adjustDate('from');
    } else {
        cal.sel.value = date;
    }

    // chiusura con singolo click
    if (cal.dateClicked) cal.callCloseHandler();
}

// And this gets called when the end-user clicks on the _selected_ date,
// or clicks on the "Close" button.  It just hides the calendar without
// destroying it.
function closeHandler(cal) {
  cal.hide();
  _dynarch_popupCalendar = null;
}

/** Restaurant's Calendar **/

    function place( div, w , h , e)
	{
		var mX = 0;
		var mY = 0;

		if (document.all) { // grab the x-y pos.s if browser is IE
		    mX = event.clientX + document.body.scrollLeft
		    mY = event.clientY + document.body.scrollTop
	    } else {  // grab the x-y pos.s if browser is NS
	    		mX = e.pageX
	    		mY = e.pageY
		}
 		// catch possible negative values in NS4
		if (mX < 0){mX = 0}
		if (mY < 0){mY = 0}

		var x = mX-w-35;
		if (x < 5) x= mx+5;

		var y = mY + 10;
		if (y < 5) y = mY -10;
		if (y < 5) y = mY - 5;
		if (y < 5) y = mY;
		if (y < 5) y = mY + 5;

		div.style.top=y+"px";
		div.style.left=x+"px";
	}

    function placeconf(e)
	{
		var div = document.getElementById("detailsconf");
		var w = 280;
		var h=220;
		place(div, w, h, e)
	}

    function placeres(e)
	{
		var div = document.getElementById("detailsres");
		var w = 280;
		var h=320;
		place(div, w, h, e)
	}

	function showreservations( date , time )
	{
		closeconf();
		var theDiv = document.getElementById("detailsres");
		theDiv.style.visibility="visible";
		theDiv.style.display="block";
		//place( theDiv , 280 , 320 );

	}

	function showconf(date, time)
	{
		closereservations();
		var theDiv = document.getElementById("detailsconf");
		theDiv.style.visibility="visible";
		theDiv.style.display="block";
		//place( theDiv , 280 , 220 );
	}
	function closereservations()
	{
		var theDiv = document.getElementById("detailsres");
		theDiv.style.visibility="hidden";
		theDiv.style.display="none";
	}
	function closeconf()
	{
		var theDiv = document.getElementById("detailsconf");
		theDiv.style.visibility="hidden";
		theDiv.style.display="none";
	}



/** my ajax functions UTILITIES **/
function showIt(elementId)
{
        var it = getIt(elementId);
        if (it == undefined)
                return;
        it.style.visibility = 'visible';
        it.style.display = 'block';
}
function hideIt(elementId)
{
        var it = getIt(elementId);
        if (it == undefined)
                return;
        it.style.visibility = 'hidden';
        it.style.display = 'none';
}
function getIt( elementId )
{
        var element = document.getElementById(elementId);
        if (element == undefined)
        {
                alert("Something goes wrong! Cannot recnognize element with id "+elementId);
                return;
        }
        return element;
}
function getValue(elementId)
{
        return getIt(elementId).value;
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttp;
}

/** my ajax functions **/

function addLinkedReference( mr_id_2, distance)
{

     xmlHttpReq=GetXmlHttpObject()

     if (xmlHttpReq==null)
      {
      alert ("Browser does not support HTTP Request")
      return
      }

     // tabella
     var url="add_linked_mr.do"
     url=url+"?mr_id_1="+getValue('id')
     url=url+"&mr_id_2="+mr_id_2
     url=url+"&distance="+distance
     url=url+"&r="+Math.random()

//     alert(url);

     xmlHttpReq.onreadystatechange=showLinkedMr
     xmlHttpReq.open("GET",url,true)
     xmlHttpReq.send(null)

     // todo change image
}


function showLinkedMr()
{
if (xmlHttpReq.readyState==4 || xmlHttpReq.readyState=="complete")
{
    httpDoc=xmlHttpReq.responseText;
    completeChange(httpDoc.replace(/^\s+|\s+$/g, '') );
}
}

function removeLinkedReference( mr_id_2)
{

     xmlHttpReq=GetXmlHttpObject()
     if (xmlHttpReq==null)
      {
      alert ("Browser does not support HTTP Request")
      return
      }

     // tabella
     var url="remove_linked_mr.do"
     url=url+"?mr_id_1="+getValue('id')
     url=url+"&mr_id_2="+mr_id_2
     url=url+"&r="+Math.random()

     xmlHttpReq.onreadystatechange=removeLinkedMr
     xmlHttpReq.open("GET",url,true)
     xmlHttpReq.send(null)

     // todo change image

}


function removeLinkedMr()
{
if (xmlHttpReq.readyState==4 || xmlHttpReq.readyState=="complete")
{
    httpDoc=xmlHttpReq.responseText;
    completeChange(httpDoc.replace(/^\s+|\s+$/g, '') );
}
}


// oggetto per selezione stella
function mr2obj( slave_id , name , selected, d )
{
    this.mr_id= slave_id;
    this.name= name;
    this.selected=selected;
    this.distance=d;
}

function completeChange(id)
{
    var o = mem[id];
    if (o.selected)
    {
        o.selected = false;
        eval('getIt("star'+o.mr_id+'").src="images/empty_star_white.gif"');
        eval('getIt("d_'+o.mr_id+'").innerHTML="0"');
    } else {
        o.selected = true;
        eval('getIt("star'+o.mr_id+'").src="images/full_star_white.gif"');
        eval('getIt("d_'+o.mr_id+'").innerHTML="'+o.distance+'"');

    }

}
var mem = new Array();

function change( obj )
{
    mem[obj.mr_id]=obj;

    if (obj.selected)
    {
        if (!confirm('Vuoi sicuro di voler rimuovere il collegamento con '+obj.name+'?'))
            return;
        removeLinkedReference(obj.mr_id);
        eval('getIt("star'+obj.mr_id+'").src="images/wait20.gif"');
    } else {

        var distance=window.prompt("Inserisci la distanza del riferimento da "+obj.name)
        if (distance == null)
            return;
        if (isNaN(distance))
        {
            alert(distance+"  non e' un valore valido!");
            return;
        }
        addLinkedReference(obj.mr_id, distance);
        obj.distance = distance;
        eval('getIt("star'+obj.mr_id+'").src="images/wait20.gif"');

    }
}


