var videos=[];

var initFunc = function() {
   // Composant carte
   $('.eziweb_rollingmap .cpnt-body map area').hover(
      function(){
         var main_img = $(this).parent().parent().find('img').eq(0);
         if ( main_img.get(0).main_src == undefined ) {
            main_img.get(0).main_src = main_img.attr('src');
         }
         var area_title = $(this).attr('title').replace( / /g, '_' );
         var alt_src = $(this).parents('.vertical').find(".area_list div[id="+area_title+"] img").attr('src');
         if ( alt_src != undefined )
            main_img.attr('src', alt_src);
      },
      function(){
         var main_img = $(this).parent().parent().find('img').eq(0);
         main_img.attr('src', main_img.get(0).main_src);
      }
   );

   $('.eziweb_rollingmap select').change(function () {
      if ($(this).val() != '') {
         document.location.href = $(this).val();
      }
   });
   
   // Ajout dynamique du div layer
   $('body').append(
      '<div class="basic-overlay" id="node-full-overlay"><div class="embed-layer"></div></div>');

   // Gestion des vues en layer
   var overlayParams = {
      expose: {
         color: '#406080',
         loadSpeed: 200,
         opacity: 0.8
      },
      onBeforeLoad: function() {
         var url = this.getTrigger().attr("href");
          
         var layout_url = "";
         if ( accessparams.accesstype_method == "2" ){ // siteaccess in href (ex : http://wwz.ifremer.fr/euro_argo/...)
            var index = url.indexOf('/', 1);
            layout_url = url.substring(0,index) + '/layout/set/layer' + url.substring(index);
         }else{ // ex : http://www.euro-argo.eu/...
            layout_url = '/layout/set/layer' + url;
         }
         
         var close = this.getContent().find(".close");
         close.hide();
         var layer = this.getContent().find(".embed-layer");
         layer.html("<div class='ajax_loader'></div>");
         layer.load(
            layout_url,function(){close.show();}
         );
      }
   };
   $("a[rel^='#']").filter(function(i){return $("map",this).length==0;}).overlay(overlayParams);
   $( '.embed-layer form[name="loginform"]' ).live( "submit", function(e) {
      var $this = $(this);
      var layer = $(this).parents(".embed-layer").get(0);
      $.post(
         $this.attr('action'),
         $this.serialize(),
         function(data, res, xhr) {
            $(layer).html( data );
         });
      return false;
   });
   // Filtrage des noeuds enfants
   $('.sns_content .view-node-full .children a.item').click(function(e) {
      var link = $(this).attr('href');
      var select = $(this).parent().find('select.theme');
      if ( select.length ) {
         if (select.val()!='non specifie') {
            link += '/(theme)/' + encodeURIComponent(select.val());
         }
         select = $(this).parent().find("select.category");
         if (select.val()!='non specifie') {
            link += '/(category)/' + encodeURIComponent(select.val());
         }
         select = $(this).parent().find("select.area");
         if (select.val()!='non specifie') {
            link += '/(area)/' + encodeURIComponent(select.val());
         }
         select = $(this).parent().find("select.unit");
         if (select.val()!='non specifie') {
            link += '/(unit)/' + encodeURIComponent(select.val());
         }
         link += '#filter';
         e.preventDefault();
         if (link != document.location.pathname) {
            document.location.href = link;
         }
      }
   });
   
   $('form.img-request-form').live( "submit", function(e) {
      var current_line = $(this).parent();
      $.ajax({
         url:eziwebp_module+'/ajax_img_request/' + $( 'input[name="node"]', this ).val() + '/' + $( '.input_text[name="email"]', this ).val(),
         success:function(data,textStatus,XMLHttpRequest) {
            current_line.html( '<div class="img-request-answer ' + ( $( 'error', data ).text() == 'true' ? 'failure' : 'success' )  + '">' + $( 'message', data ).text() + '</div>' );
         },
         cache:false,
         dataType: 'xml'
      });
      return false;
   });
   
   // Switch CSS en fonction de la résolution écran
   /*if ( $(window).width() >= 1280 ) {
      version = 1280;
   }
   else {
      version = 1024;
   }
   $('#sns_mainpagecontent').addClass("screen_" + version);*/

   // Boutons FAQ
   $('.question .switchlink').click(function(e) {
      e.preventDefault();
      var question = $(this).parents(".question");
      question.toggleClass('expanded');
      if (question.is('.expanded'))
         question.find('.answer').slideDown();
      else
         question.find('.answer').slideUp();
   });
   $('.class-faq_folder .view-body>.content>.questions .view-node-line').each(function() {
      if ('#' + $(this).attr('id') == window.location.hash) {
         $(this).find('.question .switchlink').click();
      }
   });
   $('.subfolder .switchlink').live("click", function() {
      var subfolder = $(this).parents(".subfolder").eq(0);
      if (subfolder.is('.expanded')) {
         subfolder.removeClass('expanded').addClass('collapsed');
      }
      else {
         subfolder.removeClass('collapsed').addClass('expanded');
      }
      if (subfolder.find('> .children > .ajax_loader').length == 1) {
         $.ajax({
            url:eziwebp_module+'/ajax_faq/' + subfolder.attr('id').substr(10),
            success:function(data,textStatus,XMLHttpRequest) {
            subfolder.children('.children')
               .append($('ezresult', data).text())
               .children('.ajax_loader').remove();
            },
            cache:false,
            dataType: 'xml'
         });
      }
      return false;
   });

   // Boutons dans le menu de gauche
   $('.mnu_level_2 .foldlink').live("click", function() {
      var menuitem = $(this).parent().parent();
      if (menuitem.children('ul').length == 0) {
         menuitem.append('<div class="loader"></div>');
         $.ajax({
            url:eziwebp_module+'/ajax_menu/' + menuitem.attr('id').substr(9) + '/' + $(this).closest('.component').attr('id'),
            success:function(data,textStatus,XMLHttpRequest) {
               menuitem.find('.loader').remove();
               menuitem.append($('ezresult', data).text());
            },
            cache:false,
            dataType: 'xml'
         });
      }
      if (menuitem.hasClass('expanded')) {
         menuitem
            .removeClass('expanded')
            .addClass('collapsed');
      }
      else {
         menuitem
            .removeClass('collapsed')
            .addClass('expanded');
      }
      return false;
   });

   if (document.location.hash.substr(1, 8) == "question") {
      var anchor = document.location.hash.substr(1);
      $('a[name|=' + anchor + '] + div .question').toggleClass('expanded');
   }

   // Listes dépliables
   $('.view-node-listitem-ext .expandlink a')
      .click(function(e) {
         $(this).parent()
            .hide()
            .parent()
               .find('.collapselink')
                  .show()
                  .end()
               .parent().find('.summary')
                  .slideDown('fast');
         e.preventDefault();
      });
   $('.view-node-listitem-ext .collapselink a')
      .click(function(e) {
         $(this).parent()
            .hide()
            .parent()
               .find('.expandlink')
                  .show()
                  .end()
               .parent().find('.summary')
                  .slideUp('fast');
         e.preventDefault();
      });
   
   // Zones de saisie avec message
   $('input.withmessage')
      .attr( 'message', function() {
         return this.value;
      })
      .focus(function() {
         if ( $(this).val() == $(this).attr( 'message' ) ) {
            $(this).val( '' );
         }
      })
      .blur(function() {
         if ( $(this).val() == '' ) {
            $(this).val( $(this).attr( 'message' ) );
         }
      });
   
   // Boutons submit
   $('a.submit').click(function() {
      var form=$(this).parents('form');
      var id=$(this).attr('id');
      if (id) {
         form.append('<input type="hidden" name="' + id + '" value="true" />');
      }
      form.submit();
   });
   
   // Visionneuse
   $('.eziweb_viewer .scrollable .view-node, .list_gallery .scrollable .view-node')
      .click(function(e) {
         if ($("map",this).length==0)
            e.preventDefault();
         $this = $(this);
         var viewer = $this.parents('.viewer');
         var scrollable = viewer.find('.scrollable');
         if (scrollable.length) {
            scrollable.scrollable().play(true);
         }
         var screen = viewer.find('.screen');
         var clone = $this.find('.content').clone();
         screen.find('.content').fadeOut(150, function() {
            clone.appendTo( screen.empty() ).fadeIn( 150 );
            screen.find("a[rel^='#']").filter(function(i){return $("map",this).length==0;}).overlay(overlayParams);
         });
      });
   $('.eziweb_viewer .screen')
      .hover(
         function() {
            var scrollable = $(this).parents('.viewer').find('.scrollable');
            if (scrollable.length) {
               scrollable.scrollable().pause();
            }
         },
         function() {
            if( $(this).find( 'object' ).length == 0 )
            {
               var scrollable = $(this).parents('.viewer').find('.scrollable');
               if (scrollable.length) {
                  scrollable.scrollable().play();
               }
            }
         }
      );
   var hoverTimer;
   $('.eziweb_viewer .scrolllink, .list_gallery .viewer .scrolllink')
      .hover(
         function() {
            var viewer = $(this).parents('.viewer');
            var scrollable = viewer.find('.scrollable').scrollable();
            var steps = 1;
            if($(this).is(".left")) 
               steps = -1;
            hoverTimer = setInterval(
               function() {
                  scrollable.move(steps);
               }, 
               400);
         },
         function() {
            clearInterval(hoverTimer);
         }
      );
   $('.eziweb_viewer .mode_list .title a').add( '.eziweb_viewer .mode_list .catcher a' )
      .click(function(e) {
         e.preventDefault();
         $this = $(this);
         var viewer = $this.parents('.viewer');
         var screen = viewer.find('.screen');
         var clone = $this.parents('.class').find('.content').clone();
         screen.find('.content').fadeOut(150, function() {
            clone.appendTo( screen.empty() ).fadeIn( 150 );
            screen.find("a[rel^='#']").filter(function(i){return $("map",this).length==0;}).overlay(overlayParams);
         });
      })
      .eq(0).click();
   $('.scrollable')
      .scrollable({
         size: 7,
         item: '.view-node',
         hoverClass: 'hovered',
         loop: true
      })
      //.circular()
      .mousewheel(250)
      .autoplay()
      .focus();
   $('.scrollable-viewer').each(function(){
      var max_height = 0;
      var clientWidth = $(this).width();
      var nodes = $(this).find('.view-node');
      nodes.each(function() {
         var elt_height = $(this).outerHeight();
         if ( elt_height > max_height)
            max_height = elt_height;
         var elt_margins = $(this).outerWidth(true) - $(this).width();
         $(this).width(clientWidth - elt_margins);
      });
      $(this).find('.items')
         .width((clientWidth+1) * nodes.length)
         .height(max_height);
      $(this).height(max_height + 25);
   });
   
   $('.scrollable-viewer')
      .scrollable({
         size:1,
         item: '.view-node',
         loop: true
      });
   
//   function displayVideo(trigger, target, size)
//   {
//      var movie_url = $(trigger).parent().attr('href');
//
//      var movie_type = "default";
//      var known_types = ["youtube", "dailymotion"];
//      for (var type in known_types) {
//         if (movie_url.indexOf(known_types[type]) != -1) {
//            movie_type = known_types[type];
//            break;
//         }
//      }
//      if (movie_type == "default") {
//         embedInternalVideo(target, movie_url, videos[ $(trigger).attr('id').substring(6) ], size);
//      }
//      else {
//         embedExternalVideo(target, movie_url);
//      }
//      target.fadeIn( 400 );
//   }
//   $('.class-video .content-media .videomask,.class-external_video .content-media .videomask')
//      .live('click', function(e) {
//         e.preventDefault();
//         if ($(this).parent().attr('href')) {
//            var content = $(this).parent().parent();
//            content.css('width', content.find('.image img').css('width') );
//            content.css('height', content.find('.image img').css('height'));
//            var size = {
//               'width' : content.find('.image img').outerWidth( true ),
//               'height' : content.find('.image img').outerHeight( true )
//            };
//            content.html('');
//            displayVideo( this, content, size );
//         }
//      });
   
//   $('.viewer .screen .videomask')
//      .live('click', function(e) {
//         e.preventDefault();
//         if ($(this).parent().attr('href')) {
//            var viewer = $(this).parents('.viewer');
//            var content = viewer.find('.screen')
//               .html('<div class="content" />')
//               .find('.content');
//            displayVideo( this, content );
//            viewer.find('.scrollable')
//               .scrollable()
//                  .stop();
//         }
//      });
   // Déactivation du clic sur le titre lorsqu'il s'agit d'une video ou d'une vidéo externe
   $('.viewer .screen .videomask ~ .caption-mask, .class-video .content-media .videomask ~ .caption-mask,.class-external_video .content-media .videomask ~ .caption-mask').live( 'click', function(e){
	   e.preventDefault();
   });
   
};

$(initFunc);

//function embedInternalVideo(target, movie_url, video_config, size)
//{
//   var flashvars = {
//      flv: movie_url,
//      autoplay: video_config['autoplay'] ? 1 : 0,
//      showstop: 1,
//      showvolume: 1,
//      showfullscreen: 1,
//      loop: video_config['loop'] ? 1 : 0,
//      showplayer: video_config['controler'] ? 'always' : 'never',
//      showtime: 1,
//      margin: 0,
//      playercolor: '006BBA',
//      videobgcolor: '006BBA',
//      slidercolor1: '67C3F7',
//      slidercolor2: '044F90',
//      sliderovercolor: '044F90',
//      buttonovercolor: '044F90',
//      showiconplay: 1,
//      iconplaycolor: 'ffffff',
//      iconplaybgcolor: '3969CE',
//      iconplaybgalpha: 50,
//      buffermessage: video_config['bufferingtext'],
//      ondoubleclick: 'fullscreen',
//      loadonstop: 0,
//      buffershowbg: 0,
//      buffercolor: '044F90'
//   };
//   if (typeof(size) != 'undefined') {
//        flashvars['width'] = size.width;
//        flashvars['height'] = size.height;
//   }
//   if ( video_config['width'] != '' && video_config['width'] != '0' ) {
//      flashvars['width'] = video_config['width'];
//   }
//   if ( video_config['height'] != '' && video_config['height'] != '0' ) {
//      flashvars['height']=video_config['height'];
//   }
//   target.flashembed({
//      src: '/extension/spreadnshare/design/sns-standard/images/player_flv_maxi.swf',
//      wmode: 'opaque',
//      allowFullScreen: true
//   }, flashvars);
//}

//function embedExternalVideo(target, movie_url)
//{
//   target.flashembed({
//      src: movie_url,
//      movie: movie_url,
//      wmode: "opaque"
//   });
//}

//Gestion des cartes Gogol maps

function initMap( div_id, lat, lon, map_type, map_control, display_overview, display_scale, display_map_type_selector, disable_dragging, kml, zoom ){

if (GBrowserIsCompatible()) {
  var mapElt = new GMap2(document.getElementById( div_id  ));
  mapElt.setCenter(new GLatLng(lat, lon), zoom);
  mapElt.setMapType(map_type);
  if (display_overview)          mapElt.addControl(new GOverviewMapControl());
  if (display_scale)             mapElt.addControl(new GScaleControl());
  if (display_map_type_selector) mapElt.addControl(new GMapTypeControl());
  if (map_control)               mapElt.addControl(map_control);
  if (disable_dragging)          mapElt.disableDragging();
  for ( i in kml ){
    geoXml = new GGeoXml( kml[i] );
    mapElt.addOverlay( geoXml );
  }
}

}

function initializemaps(){
   for (i in maps){
     var map = maps[i];
     initMap( map["div_id"], map["lat"], map["lon"], map["map_type"], map["map_control"], map["display_overview"], map["display_scale"], map["display_map_type_selector"], map["disable_dragging"], map["kml"], map["zoom"]);
   }
}

var maps= new Array();
$(initializemaps);
