/**
*Nokia Maps Wordpress plugin
*Version: 0.5
*Author: Frantic Media
*
*depends on jQuery and some variables set by the plugin before this is script file is loaded
*
**/


var player = null;
//this is inside a try / catch so that it won't kill all javascript if the maps parameters are not present
//try {

nmaps.init = function() {
//doc ready
  jQuery(function() {
    if(!nmaps.loadPlayer) return false;

    nmaps.getPoiJSON();

    player = new nokiaMapLoader.getPlayer({
      playerDomId:'player',
       jsPlugin: "forced",
      token:"e86f90ff620c6cd6d9f3d033e17557cf",
      onInitDone:nmaps.playerLoaded

      });


  });

}

nmaps.binds = function() {
//button binds
  jQuery("a#prevMap").live('click',nmaps.prevMarker).show();
	jQuery("a#nextMap").live('click',nmaps.nextMarker).show();
}




nmaps.prevMarker = function(){

  var pois = nmaps.layer.getMapObjects(false);

  if(nmaps.activeMarker > 0)
    {nmaps.activeMarker--}
  else
    {nmaps.activeMarker = (pois.length-1) }

  jQuery("#currentMap").text( nmaps.activeMarker+1 );
  nmaps.activateMarker( nmaps.activeMarker );
  return false;

}

nmaps.nextMarker = function() {

  var pois = nmaps.layer.getMapObjects(false);
  if(nmaps.activeMarker < (pois.length -1))
    {nmaps.activeMarker++}
  else
    {nmaps.activeMarker= 0}

  jQuery("#currentMap").text( nmaps.activeMarker+1 );
  nmaps.activateMarker( nmaps.activeMarker );
  return false;

}

nmaps.activateMarker = function (x){

  var pois = nmaps.layer.getMapObjects(false);
  for(i=0; i<pois.length; i++){
   pois[ i ].setIcon(nmaps.custompoi_default);
  }

  pois[ x ].setIcon(nmaps.custompoi_active);
  var pos = pois[ x ].getPosition();
  //~ var p1 = player.map.pixelToGeo(1, 1);
  //~ var p2 = player.map.pixelToGeo(375, 330);
  //~ var move = true;
  //~ if( nmaps.isBetween( pos["latitude"], p1["latitude"], p2["latitude"] ) && nmaps.isBetween( pos["longitude"], p1["longitude"], p2["longitude"]) ){
  //~ move = false;
  //~ }
//~
  //~ if( move==true ){
  //~
  //~ }


  linkparams = {id:false};

  for(i in nmaps.namedPois) {
    if(nmaps.namedPois[i].name ==  pois[ x ].getInfoTitle()) {
      linkparams.id = nmaps.namedPois[i].id;
    break;
    }
  }



  //truncate description if neccessary
  var descText = pois[ x ].getInfoDescription();
  descText = nmaps.shortText(descText,50,300);
 // descText = (descText.length > 100 ? descText.substring(0,100) + '...' : descText );
  // add readmore button if poi is from nokia POI DB

  if(!descText) descText = ' ';

  var newBg = "url("+nmaps.pluginurl+"/pfw/images/spices/poiCategories/icons/"+pois[ x ].getCategory()+".png )";


  jQuery("#poiDescription").html( descText );
  jQuery('#poiTitle').css("background-image", newBg ).text( pois[ x ].getInfoTitle() );


  //add buttons
  nmaps.addOviButtons(linkparams);

  player.map.moveTo(
    {
      latitude: pos["latitude"] ,
      longitude: pos["longitude"],
      animationMode: "linear"
    }
  );


}


nmaps.addOviButtons = function (linkparams) {
  //clear old buttons
  $('#poiButtons').html('');

  //no id, no buttons
  if(!linkparams.id)
  return false;

  var mapsUrl = 'http://maps.ovi.com/services/place/'+linkparams.id;

  buttons =
  {
    view:jQuery('<a target="_blank" class="button promoButton" id="nmaps_viewInOvimaps" href=""><span>View in OviMaps</span></a>'),

    favourite:jQuery('<a target="_blank" class="button promoButton" id="nmaps_addToFavourites" href=""><span>Add to Favorites</span></a>'),

    route:jQuery('<a target="_blank" class="button promoButton" id="nmaps_addToRoute" href=""><span>Add to Route</span></a>'),

    share:jQuery('<a target="_blank" class="button promoButton" id="nmaps_share" href=""><span>Share</span></a>')

  }

  var readmore = $('<p><a class="readmore" href="'+mapsUrl+'"><span class="green">&raquo;</span> Read more</a></p>');
  //buttons.view.attr('href',linkparams.view);
  //buttons.share.attr('href',linkparams.share);
  //buttons.bookmark.attr('href',linkparams.bookmark);
  //buttons.share.attr('href',linkparams.share);


  //open these buttons to new window
  var _target = function(){
    window.open(this.href);
    return false;
  }

  //all buttons have same link atm
  for(i in buttons) {
    //$('#poiButtons').append(buttons[i] );
    $('#poiButtons').append(buttons[i].attr('href',mapsUrl));
  }

    $('#poiDescription').append(readmore );




}


nmaps.isBetween = function ( val, a, b ){
 var s = null;
 var e = null;
 if( a < b ){ s=a; e=b; } else { s=b; e=a; }
 if( val>=s && val<=e){ return true; }
 else { return false; }
 }



nmaps.getPoiJSON = function() {
nmaps.namedPois = {};

if(nmaps.pois == null || nmaps.pois.length == 0) return false;

  var poiJSONToMarkerData = function(p,poi) {
    //use local POI text if found, else use remote text if found
    var pDesc = poi.description != false ? poi.description : p.place.hasPpoiInformation == true ? p.place.premiumContent.version.content.description : '' ;

    var poiData =
      {
      type:'marker',
      category:'TOURIST_ATTRACTION',
      longitude:p.place.location.geoCoordinates.longitude,
      latitude:p.place.location.geoCoordinates.latitude,
      infoTitle:p.place.names.defaultName.name,
      infoDescription:pDesc,
      poiId:p.place.a_id
      }

    nmaps.namedPois[p.place.names.defaultName.name] = {id:p.place.a_id,name:p.place.names.defaultName.name}
    nmaps.localMarkerData.push(poiData);

  }

  for(i in nmaps.pois) {
      $.ajax({
          type:'GET',
          dataType:'json',
          success:function(data){poiJSONToMarkerData(data,nmaps.pois[ i ])},
          error:function(x,t,e) {
            alert('error loading POI from remote server. ID:'+nmaps.pois[ i ].id);
          },
          url:nmaps.poiproxy + '?type=poi&id='+nmaps.pois[ i ].id,
          async:false,
          cache:false

        });
    }

  //success handler




}

nmaps.showAll = function() {aler
  player.map.moveToPoints({points:nmaps.markers});
}

nmaps.playerLoaded = function () {

//make new layer for pois and add markers there
  nmaps.layer = player.map.createLayer({name: nmaps.sLayerName });

  nmaps.markers = nmaps.layer.addMapObjects(nmaps.localMarkerData,nmaps.sLayerName );

  var setIcon = function(){
    this.setIcon(nmaps.custompoi_default);
  }

  //set marker icons
  jQuery.each(nmaps.markers,setIcon);

  //set active marker
  var test = nmaps.layer.getMapObjects(false);
  jQuery("#totalMaps").text( test.length );


  //player.map.moveToPoints({points:nmaps.markers});
  nmaps.activateMarker( nmaps.activeMarker );

  if(nmaps.zoomlevel != null)
  player.map.setZoomScale(nmaps.zoomlevel);


  //set focus if defined
  //~ if(nmaps.setFocus != null){
    //~ player.map.moveTo({longitude: nmaps.setFocus.longitude, latitude: nmaps.setFocus.latitude});
  //~ }


  nmaps.binds();

}


nmaps.shortText = function (text,lMin, lMax) {
  if(!text) return '';

  if(text.length < lMax) return text;
	var text  = text.substring(0,lMax);

	for(i=text.length;i>lMin;i--){
		if( /[!]|[?]|[.]/.test(text.charAt(i)) )
      return text.substring(0,i+1);
	}

	return text.substring(0,text.lastIndexOf(' '))+'...';

}


 nmaps.init();
//}


//~
//~ catch(e) {
//~
//~ alert('Error loading maps player:'+e);
//~ }

