/**
 JS functions for public site
 depends on JQuery
*/ 

function log(str){
	try{
		console.log("LOG: "+str);
	}catch(ex){
		
	}
}

jQuery.fn.tabs = function() { 
  	//containing div=
	contDiv=this.parent();
  
	//initialize vars: first
	//turn off every tab except one
	//and disable first tab
	this.find('a').each(function(i){
		if(i==0){
			this.tabEnable=false;
			$(this).css('cursor','default');
			//disable
		}else{
			this.tabEnable=true;
			$(this).parent().toggleClass('tab-off',true);
		}
	});
	//hide every tab except first
	contDiv.find('.tabPane').each(function(i){
		if(i>0){
			//console.log('hide  tab ' + this.id);
	 		$(this).toggle();
	 	}
	}); 
    //now assign handlers
  	this.find('a').each(function(i){
  	//add click handler
  	
  		$('#'+this.id).click(function(e){ 
			if(!this.tabEnable){
				//console.log('tab is disabled!! '+this.id);
	    		return false;
	    	}     	
	    	$(this).css('cursor','default');
	   
	    	//gray out tab...
	    	currentTabId=this.id;
	    	currentTabIdx=0;
	    	contDiv.find('.tabs   a').each(function(i){  
	    		if(currentTabId ==  this.id){ 
	    			currentTabIdx=i;
	    			this.tabEnable=false;
	    			$(this).css('cursor','default'); 
	    			//show tab
	    			$(this).removeClass('tab-off');
	    			
	    		}else{
	    			this.tabEnable=true;
	    			$(this).css('cursor','pointer'); 
	    			//hide tab
	    			$(this).addClass('tab-off');
	    		}
	    		 
	    	}); 
    	
	    	//toggle every child pane
	    	contDiv.find('.tabPane').each(function(i){
	    		if(i==currentTabIdx){
	    			$(this).show( ); //show 
	    			//check if there is a map.. 
	    			$(this).find('.public-map').each(function(i){
	    				
	    				//console.log('asa='+this.id); 
	    				var ob=$(this).data('mappaSemplice'); 
	    				ob.correctMap(); 
	    				ob.correctMap(); 
	    				ob.correctMap(); 
	    				ob.autoFit();
	    			});
	    		}else{ 
	    			$(this).hide( );
	    		}
	    	});    
    		$(this).blur();
	
    		return false;
    	}); 
  	});
  	return this;
}; 


function MappaSemplice(mapId,startLat,startLng,zoom,type){
 
	this.lineColor='#FF0000';
	this.lineWeight=3;
	this.opacity=0.5;
	this.fillColor='#FFFF00';
	this.mainFillColor='#FF0000';
	this.polygonDepth=1;
	this.type=type; //if city, than displays cities, if building, than holds a collection
	//of buildings
	this.counter = 0;
	this.actualCenter=null; //accumulate center of added markers..
	//this.actualCenterMarker=null;
    this.marker=null;
    this.address=null; 
    this.map = new GMap2(document.getElementById(mapId),{googleBarOptions: {
    	showOnLoad: true
    }}); 
    //for emulated tooltips
    this.mapId=mapId;
    //
    var o=$('#'+mapId);
    $(o).data('mappaSemplice',this);
    
    this.origDivTitle=$('#'+mapId).attr('title'); 
    
    //for autofit
    this.pointArray=[];
    
    this.center=new GLatLng(37.4419, -122.1419);
    this.zoom=zoom;
    if(this.zoom==null)
    	this.zoom=7;
    if(startLat != null && startLng!=null){
    	this.center=new GLatLng(startLat,startLng);
    }
    
    this.map.setCenter(this.center, zoom);
   	//this.map.enableGoogleBar();
    this.map.enableScrollWheelZoom();
    this.map.addControl(new GSmallZoomControl());
    this.map.checkResize();
    /*
    GEvent.addListener(this.map, "click", function(marker) {
  		//alert(marker.url);
  		document.location=marker.url;
	});
	*/
  	this.correctMap=function(){
  	 	this.map.setCenter(this.center,this.zoom);
  	 	this.map.panTo(this.center);
  		this.map.checkResize();
  		// alert('fatto');
  	};
  	
  	this.correctMap2=function(){
  	 	//this.map.setCenter(this.actualCenter,this.zoom);
  	 	this.map.checkResize();
  	  this.map.panTo(this.center);
		// alert('fatto');
  	};
  	
  	this.addItemMarker=function(name,image,extraText,lat,lng,url,isMain){
  		 
  		// Create our "tiny" marker icon
		//var itemIcon = new GIcon(G_DEFAULT_ICON);
		var itemIcon = new GIcon();
		//,"http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png");
		if(this.type=='city'){
			//itemIcon.size=new GSize(21,44);
			//itemIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
			 	
			itemIcon.image =  "/css/cc/ICO_City_01.png";// "/css/imgs/casetta_blu.png";
			 itemIcon.size=new GSize(37,37);
			 itemIcon.iconAnchor = new GPoint(18,18);
			 itemIcon.infoWindowAnchor = new GPoint(18, 7);		
			 
		}else if(this.type=='building'){
			if(isMain)
				itemIcon.image = "/css/cc/building-ON.png";//"/css/imgs/main-building-icon.png";
			else
				itemIcon.image = "/css/cc/building.png";// "/css/imgs/menubar-building-icon.png"; 
			
			 itemIcon.size=new GSize(24,24);
			 itemIcon.iconAnchor = new GPoint(12,23);
			 itemIcon.infoWindowAnchor = new GPoint(12, 4);
			  
		}
                
		// Set up our GMarkerOptions object
		markerOptions = {title:name, icon:itemIcon };
  		
  		var itemMarker = new GMarker(new GLatLng(lat, lng),markerOptions);
  		itemMarker.url=url;
  		
  		//add info window
  		//costruisce Indirizzo
		var div=  "<div class=\"gmaps-popup\"><img src=\""+image+
			"\" /><div class=\"popup-info\"><a href=\""+url+"\">"+name+"</a><br />"+
		extraText+ "</div>"+
		"</div>";
         
		var opts = {maxWidth:250}; 
 		itemMarker.bindInfoWindowHtml(div,opts);
  		
    	this.map.addOverlay(itemMarker);
    	//for autofit
    	var ll=new GLatLng(lat, lng);
    	this.pointArray.push(ll);
    	//
    	if(this.actualCenter==null)
    		this.actualCenter=ll;
    	else{
    		var accumLat=this.actualCenter.lat();
    		var accumLng=this.actualCenter.lng();
    		log("Accumulated so far: "+accumLat+","+accumLng+" for "+(this.pointArray.length-1));
    		//multiply by number of points accumulated so far (minus the very last one)
    		accumLat *= this.pointArray.length -1;
    		accumLng *= this.pointArray.length -1;
    		//add last point
    		accumLat += ll.lat();
    		accumLng += ll.lng();
    		//divide by number of points accumulated so far
    		accumLat /= this.pointArray.length;
    		accumLng /= this.pointArray.length;
    		this.actualCenter=new GLatLng(accumLat, accumLng);
    		log("Accumulated so far: "+accumLat+","+accumLng);
    	}
    	/*
    	 if(this.actualCenterMarker==null){
    		this.actualCenterMarker=new GMarker(this.actualCenter);
    		this.map.addOverlay(this.actualCenterMarker);
    	}else{
    		//move
    		this.actualCenterMarker.setLatLng(this.actualCenter);
    	}*/
  	};
  	
  	this.addAreaMarker=function(){
  		name=arguments[0];
  		isMain=arguments[1];
  		image=arguments[2];
  		url=arguments[3];
  		poly=[];
  		l=(arguments.length-4)/2;
  		for(i=0;i<l;i++){
  			lat=arguments[4+i*2];
  			lng=arguments[5+i*2];
  			
  			latlng=new GLatLng(lat,lng,false);
    		poly.push(latlng);
    		//for autofit
    		this.pointArray.push(latlng);
  		}   
  		color= isMain? this.mainFillColor : this.fillColor;
  		
  		polyShape = new GPolygon(poly,this.lineColor,this.lineWeight,
				this.opacity,color,this.opacity); 
		polyShape.map=this;
		polyShape.tooltip=name;
		polyShape.url=url;
		
	  	GEvent.bind(polyShape, "mouseover", polyShape, function(latlng) {
	  		this.map.showTooltip(this.tooltip);
	  	}); 
	  	GEvent.bind(polyShape, "mouseout", this, function(latlng) {
	  		this.clearTooltip();
	  	}); 
  		this.map.clearOverlays();
  		this.map.addOverlay(polyShape); 
  		// 
  		extraText="";
  		var div=  "<div class=\"gmaps-popup\"><img src=\""+image+
			"\" /><div class=\"popup-info\"><a href=\""+url+"\">"+name+"</a><br />"+
		extraText+ "</div>"+
		"</div>";
		
		
        GEvent.bind(polyShape, "click", this, function(latlng) {
	  		var opts = {maxWidth:250}; 
 			this.map.openInfoWindowHtml(latlng,div,opts);
	  	});  
		 
  	};
  	
  	this.showTooltip=function(tooltip){ 
  		$('#'+this.mapId).attr('title',tooltip) ; 
  	};
  	this.clearTooltip=function(){
  		$('#'+this.mapId).attr('title',this.origDivTitle) ; 
  	};
  	
  	this.autoFit=function(){ 
  		if( this.pointArray.length <=1){
  			return;
  		}
   		var bounds = new GLatLngBounds();
		for (var i=0; i< this.pointArray.length; i++) {
		   bounds.extend(this.pointArray[i]);
		   //alert(this.pointArray[i].lat()+'N '+this.pointArray[i].lng()+'E');
		}
		//extend by 5% around border of extended map
		var /* GLatLng*/ sw=bounds.getSouthWest();
		var /* GLatLng*/ ne=bounds.getNorthEast();  
		var /* GLatLng*/ span=bounds.toSpan();
		//get 5% 
		var spanLat=span.lat();
		var spanLng=span.lng();
		var extension=0.1;
		spanLat=extension * spanLat;
		spanLng=extension * spanLng;
		/*                 --+
			             NE  | lat  +, lng +
			+-----------+
			|           |
			|           |
			|           |
			+-----------+
		 | SW
		 +--	
		*/
		//now increment SW by the given amount
		sw=new GLatLng(sw.lat()-spanLat, sw.lng()-spanLng);
		//and decrement NE by the given amount
		ne=new GLatLng(ne.lat()+spanLat, ne.lng()+spanLng);
		//ne=new GLatLng(52.23, 21.01);
		//sw=new GLatLng(52.23, 21.01);
		
		//now extend
		bounds.extend(sw);
		bounds.extend(ne);
		//done extending by 5%
		
		this.map.setZoom(this.map.getBoundsZoomLevel(bounds));
		this.map.setCenter(bounds.getCenter());
  	}
  	
  	this.getGoogleMap=function(){
  		return this.map;
  	}
  	 
}
 
function  loadBaseMap(mapDivId,startLat, startLng, zoom, type) {
	try{
	if (GBrowserIsCompatible()) {
		return new MappaSemplice(mapDivId,startLat, startLng,zoom,type);
	} 
	}catch(ex){}
}
 
function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}
jQuery.each(jQuery.browser, function(i) {
  if($.browser.msie){
     window.attachEvent("onload", correctPNG);
  } 
});


/* JQuery Plugin: "EqualHeights"
	 * by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
	 *
	 * Copyright (c) 2008 Filament Group
	 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
	 *
	 * Description: Compares the heights or widths of the top-level children of a provided element 
	 		and sets their min-height to the tallest height (or width to widest width). Sets in em units 
	 		by default if pxToEm() method is available.
	 * Dependencies: jQuery library, pxToEm method	(article: 
			http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)							  
	 * Usage Example: $(element).equalHeights();
	  		Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
	 * Version: 2.0, 08.01.2008
	--------------------------------------------------------------------*/

	$.fn.equalHeights = function(px) {
		$(this).each(function(){
			var currentTallest = 0;
			$(this).children().each(function(i){
				if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
			});
			//if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
			// for ie6, set height since min-height isn't supported
			if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
			$(this).children().css({'min-height': currentTallest}); 
		});
		return this;
	};
 

