// JavaScript Document
var $j = jQuery.noConflict();

//center map Almere
var center_lat = '52.0808';
var center_lng = '4.3045';
var activeInfoWindow;
var markersArray = [];
var showMarker;

var CMMAP = {
  bounds: null,
  map: null
}
CMMAP.init = function(selector, latLng, zoom) {
  var myOptions = {
    zoom:zoom,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  this.map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  this.bounds = new google.maps.LatLngBounds();
}

$j(document).ready(function(){
  var bVersion = getInternetExplorerVersion();
  //if((bVersion > 0) && (bVersion  < 7)){
    //use sucker fish
    //$('#menuTop ul.nav').superfish();
  //}

  if( $j('.play-img').length >0 ){
    $j('.play-img').playMovie();
  }
  
  //date picker
  if( $j('input[name="tx_pbsurvey_pi1[1][0][0]"]' ).length > 0) {
    $j('input[name="tx_pbsurvey_pi1[1][0][0]"]').datepicker();
    $j('.date_icon').click(function(){
       $j('input[name="tx_pbsurvey_pi1[1][0][0]"]').trigger('focus');
    });  
  }
  
  //map_icon animation
  if( (bVersion < 1 ) || (bVersion  >= 8 )){
    if ($j('#menuTop li li.selected').length >0){
    
      $j('#map').addClass('noie7');
      
      $j('#map a').append('<img id="temp" src="fileadmin/cm/images/map-btn-hover.jpg" width="108" height="145" style="position:absolute;top:0; left:0;display:none" />');
      $j('#map a img#temp').fadeIn('slow').delay(500).fadeOut('slow');
    }
  }
  
  //google map
  if( $j('#map_canvas').length > 0 ){
    var myLatLng = new google.maps.LatLng(center_lat, center_lng);    
    CMMAP.init('#map_canvas', myLatLng, 4);
    CMMAP.placeMarkers( $j('#nav li[data-lat!=0]') );
  }
  
  //map menu
  $j('.mapMenu li').toggleMarkers();
  
  //save page for google map marker
  $j('#content ul#one a, #menuTop .snd li a').click(function(){
      var elId = $j(this).parent().attr('id');

      if (elId == 'one')
          elId = $j('li', this).data('id');

      //save previous page
      $j('body').userEventStorage()
      .data('ues')
      .saveLocal({
        'href': $j(this).attr('href'),
        'id': elId,
        'title': $j(this).text()
      });
  });
});

(function($){
   var UserEventStorage = function(element) {
       var elem = $(element);
       var obj = this;

       var defaults = {}
       
       this.init = function (){ }
       
       // Public method
       this.saveLocal = function(options) {
         
         // Merge options with defaults
         var config = $.extend(defaults, options || {});
         
         for(i in config){
           if (Modernizr.localstorage) {
             localStorage.setItem(i, config[i]);
           } else {
             //alert(i +', '+ config[i]);
             $.cookie(i, null);
             //alert($.cookie(i));
             $.cookie(i, config[i], { path: '/', expires: 1 });
           }
         }
       };
       
       // Public method
       this.getLocal = function(target) {
         if (Modernizr.localstorage) {        
           return localStorage.getItem(target);
         } else {
           //alert($.cookie(target));
           return $.cookie(target);
         }
       };
   };

   $.fn.userEventStorage = function() {
       return this.each(function() {
           var element = $(this);
          
           // Return early if this element already has a plugin instance
           if (element.data('ues')) return;

           var ues = new UserEventStorage(this);

           ues.init();
           
           // Store plugin object in this element's data
           element.data('ues', ues);
       });
   };
})(jQuery);

(function($) {
 $.fn.playMovie = function() {
    
  Shadowbox.init({
    handleOversize: "drag",
    modal: true
  });
  Shadowbox.setup("a.play-img", {
    gallery:        "City Mondial",
    continuous:     true,
    counterType:    "skip"
  });  
 }
})(jQuery);  
  
(function($) {
 $.fn.toggleMarkers = function() {
   
   //update menu with corresponding id
   $('#nav li[data=L0]').each(function(i){
     var liId = $(this).attr('id');
     $('.mapMenu li').eq(i).attr('data-options', liId);
   });
   
   $(this).click(function(){
     //clear markers
     if( $(this).hasClass('selected') ){
       $(this).removeClass('selected');
       clearOverlays($(this).data('options'));
     } else {
       $(this).addClass('selected');
     
       //target
       var liId = $(this).data("options");

       //load related markers
       CMMAP.placeMarkers( $('li#'+ liId +' li[data-lat!=0]') );
     }
   });
 }
})(jQuery);  
    
CMMAP.placeMarkers = function( target ) {
  var relGroupIdPrev = '';
  showMarker = undefined;
  
  //trigger click event to open infowindow
  var localStorageId = $j('#menu').userEventStorage()
      .data('ues')
      .getLocal('id');
  
  //localStorageId = 'li1718';
  
  target.each(function(){
    var lat = $j(this).data('lat');
    
    if( lat > 0){
//console.log(lat);
      // create a new LatLng point for the marker
      var lat = $j(this).data('lat');
      var lng = $j(this).data('lng');
     
      var elLI = $j(this);
      
      var elGroup = $j(this).parent().parent();
      if( $j(this).data('level') == 'L2' ){
        elGroup = $j(this).parent().parent().parent().parent();
      }
      
      var name = $j('a', elLI).text();
//console.log(name);
      var html = '<div class="markerTitle"><h2>' +name+'</h2></div>';
      html += '<div class="catTitle">categorie: <i>' + $j('a:first', elGroup).text() +'</i></div>';
      html += '<div class="address">'+$j(this).data('street')+' '+$j(this).data('streetnr')+'<br>'+ $j(this).data('zip') + ' '+ $j(this).data('city') +'</div>';
      html += '<div class="pageLink"><a href="' +  $j('a', elLI).attr('href') + '" title="'+name+'">klik hier voor meer info</a></div>';
    
      var point = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
      
      // extend the bounds to include the new point
      //CMMAP.bounds.extend(point);
      
      var relGroupId = elGroup.attr('id');
//console.log(relGroupId, "relGroupIdPrev "+relGroupIdPrev);
     
      if( (relGroupIdPrev == '') || (relGroupIdPrev != relGroupId) ){
            markersArray[relGroupId] = new Array();
            //console.log(relId + ' ' +name);
      }
      
      //get parent to match with group icon
      switch(relGroupId){
          case 'li1580':
              iconPath = 'mapHotspots.png';
              break;
          case 'li1590':
              iconPath = 'mapTours.png';
              break;
          case 'li1591':
              iconPath = 'mapBakje.png';
              break;
          case 'li1592':
              iconPath = 'mapHand.png';
              break;
          case 'li1605':
              iconPath = 'mapSleep.png';
              break;
      }
      
      var marker = createMarker(point, name, html, '/fileadmin/cm/images/'+iconPath);
      markersArray[relGroupId].push( marker );

      if(localStorageId == elLI.attr('id')) {
        showMarker = marker;
      }
      
      relGroupIdPrev = relGroupId;
    }
    //CMMAP.map.fitBounds(CMMAP.bounds);
  });
   
  if(showMarker != undefined) {
    google.maps.event.trigger( showMarker , 'click');
  }
  // Fit the map around the markers we added:
  //CMMAP.map.fitBounds(CMMAP.bounds);
  CMMAP.map.setZoom(14);
}

function createMarker(posn, title, html, iconPath) {
    defIcon = "http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    iconPath = (typeof iconPath == 'undefined') ? defIcon : iconPath;

    var mkr = new google.maps.Marker({ position: posn, title: title, draggable: false, map: CMMAP.map, icon: iconPath });
    mkr['infowindow'] = new google.maps.InfoWindow({ content: html });

    //infoWindows.push(marker['infowindow']);
    google.maps.event.addListener(mkr, "click", function () {
        if ( activeInfoWindow == this['infowindow'] ) {
            return;
        }
        if ( activeInfoWindow ) {
            activeInfoWindow.close();
        }

        this['infowindow'].open(CMMAP.map, this);
        activeInfoWindow = this['infowindow'];
    });
    
    return mkr;
}  
  
function clearOverlays(relId) {

  if (markersArray[relId]) {
    for (i in markersArray[relId]) {
      
      if (typeof markersArray[relId][i] == 'object') {
        markersArray[relId][i].setMap(null);
      }
      
    }
  }
}

jQuery.cookie = function (key, value, options) {
    
    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }
        
        value = String(value);
        
        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};



/* Dutch (UTF-8) initialisation for the jQuery UI date picker plugin. */
/* Written by Mathias Bynens <http://mathiasbynens.be/> */
jQuery(function($){
  $.datepicker.regional['nl'] = {
    closeText: 'Sluiten',
    prevText: '←',
    nextText: '→',
    currentText: 'Vandaag',
    monthNames: ['januari', 'februari', 'maart', 'april', 'mei', 'juni',
    'juli', 'augustus', 'september', 'oktober', 'november', 'december'],
    monthNamesShort: ['jan', 'feb', 'maa', 'apr', 'mei', 'jun',
    'jul', 'aug', 'sep', 'okt', 'nov', 'dec'],
    dayNames: ['zondag', 'maandag', 'dinsdag', 'woensdag', 'donderdag', 'vrijdag', 'zaterdag'],
    dayNamesShort: ['zon', 'maa', 'din', 'woe', 'don', 'vri', 'zat'],
    dayNamesMin: ['zo', 'ma', 'di', 'wo', 'do', 'vr', 'za'],
    weekHeader: 'Wk',
    dateFormat: 'dd-mm-yy',
    firstDay: 1,
    isRTL: false,
    showMonthAfterYear: false,
    yearSuffix: ''};
  $.datepicker.setDefaults($.datepicker.regional['nl']);
});

function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

