/* An InfoBox is like an info window, but it displays
* under the marker, opens quicker, and has flexible styling.
* @param {GLatLng} latlng Point to place bar at
* @param {Map} map The map on which to display this InfoBox.
* @param {Object} opts Passes configuration options - content,
*   offsetVertical, offsetHorizontal, className, height, width
*/
function InfoBox(opts)
{
	 google.maps.OverlayView.call(this);
	 this.latlng_ = opts.latlng;
	 this.map_ = opts.map;
	 this.valueObject_ = opts.valueObject;
	 this.stationName_ = opts.stationName;
	 this.labelOffset_ = opts.label_offset;
	 this.labelPosition_ = opts.label_position;
	 this.divXOffset_ = opts.div_x_offset;
	 this.divYOffset_ = opts.div_y_offset;
	 this.idInfospot_ = opts.idInfospot;
	 
	 this.div_ = null;
	 
	 // Once the properties of this OverlayView are initialized, set its map so
	 // that we can display it.  This will trigger calls to panes_changed and
	 // draw.
	 this.setMap(this.map_);
	 
	 this.currentIndex_ = 40;
	 
}

/*
* 
* InfoBox extends GOverlay class from the Google Maps API
* 
*/
InfoBox.prototype = new google.maps.OverlayView();

/* Creates the DIV representing this InfoBox
*/
InfoBox.prototype.remove = function() {
 if (this.div_) {
   this.div_.parentNode.removeChild(this.div_);
   this.div_ = null;
 }
};

/* Redraw the Bar based on the current projection and zoom level
*/
InfoBox.prototype.draw = function()
{
	div = this.div_;
	 
	// Calculate the DIV coordinates of two opposite corners of our bounds to
	// get the size and position of our Bar
	var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
	if (!pixPosition) return;
	
	// Now position our DIV based on the DIV coordinates of our bounds
	div.style.position = 'absolute';
	div.style.display = 'block';
	
	/**
	 * posiziono il div in base alla proprietà label_position
	 * pixPosition.x è l'origine x del marker
	 * pixPosition.x è l'origine y del marker
	 */
        
	switch(this.labelPosition_)
	{
            /**
             * label top
             */
	   case	'T':
		   div.style.left = (pixPosition.x - 31) + "px";
		   div.style.top = (+ pixPosition.y - div.offsetHeight) + "px";
		   break;
		   
	   // label left
	   case	'L':
		   div.style.left = (pixPosition.x - div.offsetWidth) + "px";
		   div.style.top = (pixPosition.y - 8) + "px";
		   break;
		   
	   // label bottom
	   case	'B':
		   div.style.left = (pixPosition.x - Math.floor(div.offsetWidth / 2)) + "px";
		   div.style.top = (this.divYOffset_ + pixPosition.y) + "px";
		   break;
		   
		// label right
	   case	'R':
		   div.style.left = (this.divYOffset_ + pixPosition.x) + "px";
		   div.style.top = (pixPosition.y - 8) + "px";
		   break;
	} 

};

/* Creates the DIV representing this InfoBox in the floatPane.  If the panes
* object, retrieved by calling get_panes, is null, remove the element from the
* DOM.  If the div exists, but its parent is not the floatPane, move the div
* to the new pane.
* Called from within draw.  Alternatively, this can be called specifically on
* a panes_changed event.
*/
InfoBox.prototype.onAdd = function()
{
   var self = this;
   var offsetTop = 0;
   var offsetLeft = 0;
   var data = this.valueObject_;
   // This does not handle changing panes.  You can set the map to be null and
   // then reset the map to move the div.
   div = document.createElement("div");
   div.style.margin = "0";
   //div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackground.gif)";
   div.style.backgroundRepeat = "no-repeat";
   // in base alla posizione della label modifico il padding e la posizione dello sfondo
   switch(this.labelPosition_)
   {
   		// label top
	   case	'T':
		   //alert('Case T: offset '+ this.labelOffset_);
		   div.style.paddingBottom = this.labelOffset_ + "px";
		   div.style.backgroundPosition = "bottom center";
		   break;
		   
	   // label left
	   case	'L':
		   //alert('Case L: offset '+ this.labelOffset_);
		   div.style.paddingRight = this.labelOffset_ + "px";
		   div.style.backgroundPosition = "center right";
                   offsetLeft = parseInt(this.labelOffset_);
		   break;
		   
	   // label bottom
	   case	'B':
		   //alert('Case B: offset '+ this.labelOffset_);
		   div.style.paddingTop = this.labelOffset_ + "px";
		   div.style.backgroundPosition = "top center";
                   offsetTop = parseInt(this.labelOffset_);
		   break;
		   
		// label right
	   case	'R':
		   //alert('Case R: offset '+ this.labelOffset_);
		   div.style.paddingLeft = this.labelOffset_ + "px";
		   div.style.backgroundPosition = "center left";
                   offsetLeft = parseInt(this.labelOffset_);
		   break;
   }
   
   var contentDiv = document.createElement("div");
   
   /**
    * switch dello sfondo della label in base al tipo di dato ricevuto
    */
   switch(data.dataType)
   {
   		case 'RT':
   			contentDiv.style.backgroundImage = "url(/assets/overlayInfoBoxLabelRT.png)";
   			div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackgroundRT.gif)";

   			break;
   			
   		case 'DF':
   			contentDiv.style.backgroundImage = "url(/assets/overlayInfoBoxLabelDF.png)";
   			div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackgroundDF.gif)";
   			break;
   			
   		case 'ND':
   			contentDiv.style.backgroundImage = "url(/assets/overlayInfoBoxLabelND.png)";
   			div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackgroundND.gif)";
   			break;
   			
   }

    contentDiv.style.margin = "0";
    contentDiv.style.padding = "0";
    contentDiv.style.paddingTop = "1px";
    contentDiv.style.width = "62px";
    contentDiv.style.height = "13px";
    contentDiv.style.backgroundPosition = "top center";
    contentDiv.style.backgroundRepeat = "no-repeat";
    contentDiv.style.lineHeight = "10px";
    contentDiv.style.fontFamily = "Verdana";
    contentDiv.style.fontSize = "10px";
    contentDiv.style.color = "#FFFFFF";
    contentDiv.style.whiteSpace = "nowrap";
    contentDiv.style.cursor = "pointer";
    contentDiv.style.textAlign = "center";
   

    contentDiv.innerHTML = data.data.v + " <b>" + this.getDirection(data.data.d) +"</b>";
    contentDiv.style.color = "#FFFFFF";
    
    if(data.dataType == 'ND') contentDiv.style.color = "#333333";
    
    /**
     * link all'infospot
     */
    /**
    * link to infospot
    */
    var infospotLink = document.createElement('div');
    infospotLink.style.margin = "0";
    infospotLink.style.width = "16px";
    infospotLink.style.height = "16px";
    infospotLink.style.backgroundImage = "url(/assets/overlayInfoBoxInfospotLink.png)";
    infospotLink.style.backgroundPosition = "top left";
    infospotLink.style.backgroundRepeat = "no-repeat";
    infospotLink.style.position = "absolute";
    infospotLink.style.top = offsetTop + "px";
    if(this.labelPosition_ == 'L')
        infospotLink.style.left = -16 + "px";
    else
        infospotLink.style.left = (offsetLeft + 64) + "px";
    infospotLink.style.visibility = "hidden";
    infospotLink.style.cursor = "pointer";
   
   google.maps.event.addDomListener(infospotLink, 'click', function()
   {
       document.location.href = jsCommon.baseUrl + '/' + jsCommon.locale + '/meteo/infospots/detail-infospot/id_infospot/' + self.idInfospot_;
   });

    offsetTop = offsetTop + 18;
    /**
    * tooltip body
    */
    tooltipBoxTop = document.createElement("div");
    tooltipBoxTop.style.margin = "0";
    tooltipBoxTop.style.width = "120px";
    tooltipBoxTop.style.backgroundImage = "url(/assets/overlayInfoBoxTooltipBottom.png)";
    tooltipBoxTop.style.backgroundPosition = "bottom center";
    tooltipBoxTop.style.backgroundRepeat = "no-repeat";
    tooltipBoxTop.style.position = "absolute";
    tooltipBoxTop.style.top = offsetTop + "px";
    if(this.labelPosition_ == 'L')
        tooltipBoxTop.style.left = -16 + "px";
    else
        tooltipBoxTop.style.left = offsetLeft + "px";
    tooltipBoxTop.style.visibility = "hidden";

    /**
    * tooltip content
    */
    tooltipBoxContent = document.createElement("div");
    tooltipBoxContent.style.width = "120px";
    tooltipBoxContent.style.margin = "0";
    tooltipBoxContent.style.backgroundImage = "url(/assets/overlayInfoBoxTooltipTop.png)";
    tooltipBoxContent.style.backgroundPosition = "top center";
    tooltipBoxContent.style.backgroundRepeat = "no-repeat";
    tooltipBoxContent.style.display = "block";
    tooltipBoxContent.style.paddingTop = "20px";
    tooltipBoxContent.style.paddingBottom = "5px";
    tooltipBoxContent.style.textAlign = "center";
    tooltipBoxContent.style.fontFamily = "Verdana";
    tooltipBoxContent.style.fontSize = "10px";
    tooltipBoxContent.style.color = "#333333";


    tooltipBoxContent.innerHTML = "<div><b>" + this.stationName_ + "</b></div>" +
                                        "<div>" + this.timestampToDate(data.dataTime)+ "</div>" +
                                            "<div>" + this.timestampToTime(data.dataTime)+ "</div>";

   /**
    * tooltip close image
    */
   tooltipCloseImage = document.createElement('img');
   tooltipCloseImage.src = "/assets/overlayInfoBoxTooltipCloseImage.gif";
   tooltipCloseImage.style.position = "absolute";
   tooltipCloseImage.style.left = "108px";
   tooltipCloseImage.style.cursor = "pointer";
   
   tooltipBoxTop.appendChild(tooltipCloseImage);
   
   tooltipBoxTop.appendChild(tooltipBoxContent);
   
   /**
    * memorizzo l'index del div
    */
   currentIndex = this.currentIndex_;

   google.maps.event.addDomListener(tooltipCloseImage, 'mouseover', function()
   {
	    this.parentNode.parentNode.childNodes[1].style.visibility = "hidden";
	    this.parentNode.parentNode.childNodes[2].style.visibility = "hidden";
	    this.parentNode.parentNode.style.zIndex = 1;
		/**
		 * incremento l'index in modo che il tooltip appaia sempre in primo piano
		 */
		currentIndex --;
   });
   
   var t;
   
   google.maps.event.addDomListener(contentDiv, 'mouseover', function()
   {
       var parNode = this.parentNode;
       t = setTimeout(function()
       {
           if(self.idInfospot_ > 0)
               parNode.childNodes[1].style.visibility = "visible";
           parNode.childNodes[2].style.visibility = "visible";
           parNode.style.zIndex = currentIndex;
            /**
             * incremento l'index in modo che il tooltip appaia sempre in primo piano
             */
            currentIndex ++;
       }, 800);
   });
   
   google.maps.event.addDomListener(contentDiv, 'mouseout', function()
   {
       clearTimeout(t);
   });
   
   google.maps.event.addDomListener(contentDiv, 'click', function(){
	   document.location.href = jsCommon.baseUrl + '/' + jsCommon.locale + '/meteo/stations/detail-station/id_station/' + data.id;
   });
   

   div.appendChild(contentDiv);
   div.appendChild(infospotLink);
   div.appendChild(tooltipBoxTop);
   
   this.div_ = div;
   
   /**
    * recupero il piano su cui inserire gli elementi
    */
   var panes = this.getPanes();
   
   panes.floatPane.appendChild(div);
}

/*
 * set dataObject
 */
InfoBox.prototype.setValueObject = function(valueObject)
{
	this.valueObject_ = valueObject;
	this.update();
}

/*
 * update infoBox content
 */
InfoBox.prototype.update = function()
{
    var data = this.valueObject_;
    var div = this.div_;

    /**
     * switch dello sfondo della label in base al tipo di dato ricevuto
     */
    switch(data.dataType)
    {
        case 'RT':
            div.childNodes[0].style.backgroundImage = "url(/assets/overlayInfoBoxLabelRT.png)";
            div.childNodes[0].style.color = "#FFFFFF";
            div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackgroundRT.gif)";
            break;

        case 'DF':
            div.childNodes[0].style.backgroundImage = "url(/assets/overlayInfoBoxLabelDF.png)";
            div.childNodes[0].style.color = "#FFFFFF";
            div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackgroundDF.gif)";
            break;

        case 'ND':
            div.childNodes[0].style.backgroundImage = "url(/assets/overlayInfoBoxLabelND.png)";
            div.childNodes[0].style.color = "#333333";
            div.style.backgroundImage = "url(/assets/overlayInfoBoxLabelBackgroundND.gif)";
            break;
	   			
    }

    div.childNodes[0].innerHTML = data.data.v + " <b>" + this.getDirection(data.data.d) +"</b>";

    div.childNodes[2].childNodes[1].innerHTML = "<div><b>" + this.stationName_ + "</b></div>" +
                                                    "<div>" + this.timestampToDate(data.dataTime)+ "</div>" +
                                                        "<div>" + this.timestampToTime(data.dataTime)+ "</div>";
	
}

/*
 * metodo per convertire il timestamp in data
 */
InfoBox.prototype.timestampToDate = function (timestamp)
{
	var localtime = new Date(timestamp * 1000);
	var month = (localtime.getMonth() < 9 ? '0' : '') + (localtime.getMonth() + 1);
	var day = (localtime.getDate() < 10 ? '0' : '') + localtime.getDate();
	return localtime.getFullYear() + '/' + month + '/' + day;

}

/*
 * metodo per convertire il timestamp in tempo
 */
InfoBox.prototype.timestampToTime = function (timestamp)
{
	var localtime = new Date(timestamp * 1000);
	var seconds = (localtime.getSeconds() < 10 ? '0' : '') + localtime.getSeconds();
	var minutes = (localtime.getMinutes() < 10 ? '0' : '') + localtime.getMinutes();
	var hours = (localtime.getHours() < 10 ? '0' : '') + localtime.getHours();
	return hours + ':' + minutes + ':' + seconds;
	
}

/*
 * metodo per convertire la direzione dle vento
 */
InfoBox.prototype.getDirection = function (direzione)
{
    if(direzione != undefined)
    {
            
	if (direzione>=11 && direzione<=33) {
		return "NNE";
	};
	
	if (direzione>=34 && direzione<=56) {
		return "NE";
	};
	
	if (direzione>=57 && direzione<=78) {
		return "ENE";
	};
	
	if (direzione>=79 && direzione<=101) {
		return "E";
	};
	
	if (direzione>=102 && direzione<=123) {
		return "ESE";
	};
	
	if (direzione>=124 && direzione<=146) {
		return "SE";
	};
	
	if (direzione>=147 && direzione<=168) {
		return "SSE";
	};
	
	if (direzione>=169 && direzione<=191) {
		return "S";
	};
	
	if (direzione>=192 && direzione<=213) {
		return "SSO";
	};
	
	if (direzione>=214 && direzione<=236) {
		return "SO";
	};
	
	if (direzione>=237 && direzione<=258) {
		return "OSO";
	};
	
	if (direzione>=259 && direzione<=281) {
		return "O";
	};
	
	if (direzione>=282 && direzione<=303) {
		return "ONO";
	};
	
	if (direzione>=304 && direzione<=326) {
		return "NO";
	};
	
	if (direzione>=327 && direzione<=349) {
		return "NNO";
	};
	
	if (direzione>=350 || direzione<=10) {
		return "N";
	};
    }
    else
    {
        return "N.D.";
    }
}


