//patch for IE6,IE7
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
        fun.call(thisp, this[i], i, this);
    }
  };
}
//end of patch

function comma2dot(s)
{
  s=s.toString();
  var r, re;
  re = /,/g;
  r = s.replace(re, ".");
  return(r);
}

var clickHandler;
var map;
var lat;
var lng;
var locations;
var bounds;
var MapsAvailable=false;
var mymarker;

$(document).ready(function() {
    try {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("fcs_map"));
        //map.setMapType();
        //-map.addControl(new GLargeMapControl());
        //-map.addControl(new GMapTypeControl());
        //map.setCenter(new GLatLng(0,0), 13, G_SATELLITE_MAP); //ROMA!
        map.setCenter(new GLatLng(41.8941,12.480469), 6, G_SATELLITE_MAP); //ROMA!
        map.enableDoubleClickZoom();
        map.enableScrollWheelZoom();
        map.setZoom(4);
        MapsAvailable=true;
	map.setMapType(G_HYBRID_MAP);

	//creates the only and one MARKER!
        mymarker = new GMarker(new GLatLng(42.8941,13.480469), {title: 'location'});
        //done by setting latlng later---setTimeout(  "map.addOverlay(mymarker);", 500);
        //GEvent.addListener(marker, 'click', function() {
        //    fcs_maps_article_show(index); //lastindex!
        //});

    }
        }
        catch(e) {
           //alert(e + " : Maps services not available.");		// Return error message.
        }
    if (!MapsAvailable) {
           $('div#fcs_info').html( '<A HREF=javascript:; onClick="$(\'div#fcs_info\').hide(\'slow\');" >' +
            e + ': maps services are not available, showyourmusic apologizes for any inconvenience' +
            '&nbsp;[x]</A>' );
           $('div#fcs_info').show('fast');
           setTimeout("$('div#fcs_info').hide('slow');",2000);

           //$('div#fcs_info').html( e + ': maps services are not available, showyourmusic apologizes for any inconvenience' );
           //$('div#fcs_info').append( '<A HREF=# onClick="$(\'div#fcs_info\').hide(\'slow\');" > [x]</A>' );
           $('div#fcs_info').show('slow');
          $.post('/web/bla/gmaps_srv.asp', fcs_maps_getLocations_complete );

    }
    
});

//$(window).unload( function () { if(MapsAvailable) {alert('unloading...'; GUnload();} } );
//$(document).unload( function () { {alert('unloading document...'; GUnload();} } );
//$(window).unload( function () { alert("Bye now!"); } );

var fcs_maps_user_index;

function fcs_maps_article_show(index) {


  var loadingmsg='loading data for <B>'+locations[index].name+'</B>...<img border=0 src=images/sym_wait.gif /><br />';

  $('#fcs_product_out').html(loadingmsg);
  article_show_more( locations[index].userid );

  if (MapsAvailable) {
	mymarker.setLatLng(new GLatLng(locations[index].latitude, locations[index].longitude));
	//alert(locations[index].latitude +','+ locations[index].longitude);
	map.addOverlay(mymarker);
	//mymarker.show();
	//alert(locations[index].latitude +','+ locations[index].longitude);
  }

 if(false){
  if (MapsAvailable) {
    //---xxx---map.panTo(new GLatLng(locations[index].latitude, locations[index].longitude));
    (locations[index].marker).openInfoWindowHtml(loadingmsg);
  } else {
    (locations[index].marker).openInfoWindowHtml(loadingmsg);
  }
	//alert(locations[index].userid);
        fcs_maps_user_index=index;
        $.post('/web/bla/all_srv.asp',
               { type: 'article_getinfo',
                 format: '',
            lang: $('#fcs_lang').get(0).value,
                 sid: $('input#sid').get(0).value,
                 id: locations[index].userid
               }, 
               fcs_maps_article_show_complete );        
 }//if(false)

  return false;
}

function fcs_maps_article_show_complete(res) {
  var index=fcs_maps_user_index;
  if (MapsAvailable) {
    (locations[index].marker).openInfoWindowHtml(res);
  } else {
    (locations[index].marker).openInfoWindowHtml(res);
  }
  window.status=locations[index].name;
}

function fcs_maps_getLocations_complete(content) {
//    $.unblockUI();
    eval("locations = "+content);
    $('#location_list').html('');

//    $('#location_list').append('<h4 style="display:inline;">'+locations.length+' results found</h4><br />');
    $('#location_list').append('<img src=/web/bla/bladenis_logo.gif width=82 heigth=20 border=0 /><br />'+fcs_lang_text('offers_you')+' '+locations.length+' '+fcs_lang_text('products_of_this')+' <br />');

    locations.forEach(function(element, index, array) {
      element.name=unescape(element.name);
	//corrects ANY problems if lat/lon are empty ("") or null or with commas (12,34)

	element.latitude=comma2dot(element.latitude)
	element.longitude=comma2dot(element.longitude)

	element.latitude=parseFloat(element.latitude)
	element.longitude=parseFloat(element.longitude)

	if(isNaN(element.latitude)) element.latitude=0;
	if(element.latitude>90) element.latitude=90;
	if(element.latitude<-90) element.latitude=-90;

	if(isNaN(element.longitude)) element.longitude=0;
	if(element.longitude>180) element.longitude=180;
	if(element.longitude<-180) element.longitude=-180;


      if (false&&MapsAvailable) {
        var marker = new GMarker(new GLatLng(element.latitude, element.longitude), {title: element.name});

        // saves the marker for future use
        locations[index].marker=marker;

        map.addOverlay(marker);
        GEvent.addListener(marker, 'click', function() {
            fcs_maps_article_show(index);
        });
      } else {
        //ko var marker = new fcs_maps_marker(element.latitude, element.longitude, element.name);
        // saves the marker for future use
        //ko locations[index].marker=marker;
      }

      link = '<a href="javascript:void(0)" onclick="fcs_maps_article_show('+index+')">'+element.name+'</a><br />';
      link = '<a href="javascript:void(0)" onclick="fcs_maps_article_show('+index+')">'+element.name+'</a>';
      link = '<a href="javascript:;" onMouseOver="window.status=0;" onclick="fcs_maps_article_show('+index+')">'+element.name+'</a>';
      link = '<a href="javascript:;" onMouseOver="window.status=0;" onclick="fcs_maps_article_show('+index+')">'+'&gt;'+locations[index][4]+'&lt; '+element.name+'</a>';
//with art.code
      link = '<a href="javascript:;" onclick="fcs_maps_article_show('+index+')">'+'&gt;'+locations[index][4]+'&lt; '+element.name+'</a>';
//without art.code
      link = '<a href="javascript:;" onclick="fcs_maps_article_show('+index+')">'+element.name+'</a>';
//      link = '<a href="javascript:;" onMouseOver="window.status=\''+element.name+'\';" onclick="fcs_maps_article_show('+index+')">'+'&lt;'+locations[index][4]+'&gt; '+element.name+'</a>';
//      link = '<a href="http://'+element.name+'" xonMouseOver="window.status=0;" onclick="fcs_maps_article_show('+index+')">'+'['+locations[index][4]+'] '+element.name+'</a>';
//      link = '<a href="javascript:;" onMouseOver="window.status=\''+element.name+'\';" onclick="fcs_maps_article_show('+index+')">'+'*['+locations[index][4]+']* '+element.name+'</a>';

      $('#location_list').append(link);
    });
    if (MapsAvailable) {
        //---xxx--- zoomShowAll();
    }
    //message if no results
    if (locations.length==0) {
      $('#location_list').append('[no results found]<br />');
    }

}


// --START FCS EXTENSIONS

var indexFrom=0
var nameFrom=""

function setDpoint(index) {
  indexFrom=index;
  nameFrom=locations[index].name;
  alert( ''+nameFrom+' is now the starting location' );
}

function dporcodio(iii) {
  //alert(iii);
  k=quelpiciodifabrizio(indexFrom,iii);
  alert(k);
//  alert( 'distance from '+nameFrom+' = ' + distanceBetween(indexFrom,index) + ' Km' );
}

function aquelpiciodifabrizio(index1,index2) {
 alert( ''+locations[index2].name+' is the destination ' );
}

function quelpiciodifabrizio(index1,index2) {
 var lat1,lat2,lon1,lon2
 lat1=parseFloat(locations[index1].latitude)
 lon1=parseFloat(locations[index1].longitude)
 lat2=parseFloat(locations[index2].latitude)
 lon2=parseFloat(locations[index2].longitude)

 var x
 x=LatLon.distHaversine(lat1,lon1,lat2,lon2);

 return x
}

// --END FCS EXTENSIONS

function zoomShowAll() {
    bounds = new GLatLngBounds();
    map.setCenter(new GLatLng(0,0),0);
    
    locations.forEach(function(elemet, id, array) {
        bounds.extend(new GLatLng(locations[id].latitude, locations[id].longitude));
    });
    if(locations.length>1) {
      map.setZoom(map.getBoundsZoomLevel(bounds));
    } else {
      map.setZoom(3);
    }
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    map.setCenter(new GLatLng(clat,clng));

}

//-- START FIND EXTENTIONS
var sss;

function sym_find_update(oChangedField,sDBFieldName) {
 //alert('id='+oChangedField.id+' name='+oChangedField.name+' value='+oChangedField.value+' field='+sDBFieldName);
 //Vaffankulo--fcs_find1();
        $('div#fcs_info').html( 'finding a '+sDBFieldName+' '+oChangedField.value+'...' );
        //$('div#fcs_info').append( '<A HREF=# onClick="$(\'div#fcs_info\').hide(\'slow\');" > [x]</A>' );
        $('div#fcs_info').show('slow');
        if (!MapsAvailable) {
        } else {
           map.clearOverlays();
        }
//superspecial string
//            {
//                 type: 'find',
//                 askills: oChangedField.value,
//                 sid: $('input#sid').get(0).value
//            },

sss="myvect={type:'find',"+sDBFieldName+": oChangedField.value, sid: $('input#sid').get(0).value }"
eval(sss);
sss=sss+' name='+oChangedField.name+' value='+oChangedField.value+' sid='+$('input#sid').get(0).value;
        $.post('/web/bla/gmaps_srv.asp',
            myvect,
            function(x) {$('div#fcs_info').hide('slow'); fcs_maps_getLocations_complete(x);}
        );
}

function fcs_find1() {
 var as=document.getElementById('askills').value;
 var pf=document.getElementById('performer').value;
 var ps=document.getElementById('pskills').value;
 var ms=document.getElementById('mskills').value;

/*
 //var as=$('#askills').get(0).value
 //var pf=$('#performer').get(0).value
 var ps=$('#pskills').get(0).value;
 var ms=$('#mskills').get(0).value;
 var as='caz';
 var pf='porkodio';
*/

 alert(as+'::'+pf+'::'+ps+'::'+ms);
 //fcs_rpc_callserver('sym_srv_find.asp?user='+suser+'&askills='+as+'&pskills='+ps+'&bskills='+bs+'&rnd='+Math.random(),'doit1()')
           $('div#fcs_info').html( 'searching...' );
           $('div#fcs_info').append( '<A HREF=javascript:; onClick="$(\'div#fcs_info\').hide(\'slow\');" > [x]</A>' );
           $('div#fcs_info').show('slow');
        if (!MapsAvailable) {
        } else {
           map.clearOverlays();
        }
        $.post('/web/bla/gmaps_srv.asp',
            {
                 type: 'find',
                 askills: as,
                 performer: pf,
                 pskills: ps,
                 mskills: ms,
                 sid: $('input#sid').get(0).value
            },
            function(x) {$('div#fcs_info').hide('slow'); fcs_maps_getLocations_complete(x);}
        );
}

var global_gmaps_query_parms=""
function gmaps_query(sparams) {
        if (sparams!=global_gmaps_query_parms) {
    $('#location_list').html('');
    if (MapsAvailable) { map.clearOverlays(); };
    $('#location_list').append('<IMG src=progress.gif border=0 />Loading...'+sparams);
//    $.blockUI({ message: '<IMG src=progress.gif border=0 />...'+sparams });

var mytype=sparams.toString();
//           $('div#fcs_info').html( 'L O A D I N G   map data...'+sparams );
//           $('div#fcs_info').append( '<A HREF=# onClick="$(\'div#fcs_info\').hide(\'slow\');" > [x]</A>' );
//           $('div#fcs_info').show('slow');
           $.post('/web/bla/gmaps_srv.asp', {
            type: ''+sparams,
            lang: $('#fcs_lang').get(0).value,
                 sid: $('input#sid').get(0).value
            },
               function(x) {$('div#fcs_info').hide('slow'); fcs_maps_getLocations_complete(x);}
           );
	global_gmaps_query_parms=sparams;
        }
}

function filter_add(sfieldvalue,stype) {
        if (true) {
    $('#location_list').html('');
    if (MapsAvailable) { map.clearOverlays(); };
    $('#location_list').append('Loading . . . ');
           $.post('/web/bla/gmaps_srv.asp', {
            type: ''+stype,
            val: ''+sfieldvalue,
            lang: $('#fcs_lang').get(0).value,
                 sid: $('input#sid').get(0).value
            },
               function(x) {$('div#fcs_info').hide('slow'); fcs_maps_getLocations_complete(x);}
           );
        }
}
//-END





