var Ctrl = new function()
{
  var options;
  
  this.initPage = function(opt)
  {
    Ctrl.options = opt;
    
    Ctrl.init($(document));
  }
  
  this.init = function($dom)
  {
    $.facebox.settings.close_image = Ctrl.options.base_url+'images/btFermerIntersticiel.jpg';
    $.facebox.settings.opacity = 0.2;
    if ($('a.facebox').length) {
      $('a.facebox').facebox().trigger("click");
      setTimeout(function(){
      if($.browser.msie)
       $("#facebox").css("left", '0');
        $("#facebox").css("overflow-y", "auto");
      }, 800);
    }
    
    $("ul.accordion_me", $dom).accordion({
      header: 'a.acc_header',
      autoHeight: false,
      alwaysOpen: false,
      animated:   false,
      active:     '#aucun',
      navigation: true,
      navigationFilter: function() {
        return $(this).hasClass("current_parent");
      }
    });
    
    if ($("div.dms_gmap_custom", $dom).length)
    {
      Ctrl.launchGmap($("div.dms_gmap_custom", $dom));
    }
    
    if($(".main_page .gd_me_little", $dom).length)
    {
      $(".main_page .gd_me_little", $dom).each(function()
      {
        var texte = $(this).find('span').html();
  
        $(this).html(
          $("<img>")
            .attr("src", Util.action2href("dms/main/fakeTitre/img/little/titre/"+texte))
            .attr("alt", texte.replace( "+", "__PLUS__" )
            )
          );
      });
    }
    
    if ($("#visio_anim").length)
    {
      var metas = $("#visio_anim").metadata();
      var soVisio = new SWFObject(Ctrl.options.relative_url_root+"sfPropelActAsVisioBehaviorPlugin/swf/Visio.swf", "visio", "520", "280", "9", "#FFFFFF");
      soVisio.addVariable("gateWayUrl",Ctrl.options.relative_url_root+"index.php/dms/dmsTools/amf?fromFlash=1");
      soVisio.addParam("wmode", "opaque");
      //soVisio.addVariable("debug", metas.debug);
      soVisio.addVariable("idVisio", metas.idVisio);
      if (metas.visioFrom)
        soVisio.addVariable("fromVisio", metas.visioFrom);
      soVisio.addVariable("template", metas.template);
      soVisio.write("visio_anim");
    }
    if($(".gd_me_acces_2", $dom).length)
    {
      $(".gd_me_acces_2", $dom).each(function()
      {
        var texte = $(this).find('span').html();
  
        $(this).html(
          $("<img>")
            .attr("src", Util.action2href("dms/main/fakeTitre/img/acces_2/titre/"+texte))
            .attr("alt", texte.replace( "+", "__PLUS__" )
            )
          );
      });
    }
    if($(".gd_me", $dom).length)
    {
      var background = "";
      if($(".module_enseigne.action_detail .gd_me").length)
      {
        background = "magasin";
      }
      else if($(".module_promo .gd_me").length)
      {
        background = "magasin";
      }
      else if($(".module_promoLoisir .gd_me").length)
      {
        background = "magasin";
      }
      else if($(".module_promoCinema .gd_me").length)
      {
        background = "magasin";
      }
      else if($(".module_loisir.action_detail .gd_me").length)
      {
        background = "loisir";
      }
      else if($(".module_cinema.action_detail .gd_me").length)
      {
        background = "loisir";
      }
      else if($(".module_cinema.action_programme .gd_me").length)
      {
        background = "loisir";
      }
      else if($(".module_service.action_detail .gd_me").length)
      {
        background = "service";
      }
      else if($(".module_emploi .gd_me").length)
      {
        background = "emploi";
      }
      else if($(".action_planDAcces .gd_me").length)
      {
        background = "normal";
      }
      else
      {
        background = "normal";
      }
      $(".gd_me", $dom).each(function()
      {
        var texte = $(this).find('span').html();
  
        $(this).html(
          $("<img>")
            .attr("src", Util.action2href("dms/main/fakeTitre/img/"+background+"/titre/"+texte))
            .attr("alt", texte.replace( "+", "__PLUS__" )
            )
          );
      });
    }
    
    if($('.big .onglet_visio_image').length)
    {
      $('.contenu_right', $dom).each(function(){
        
        $('.affiche_visio').rebind('click', function(){
          $('.affiche_visio').addClass('current_onglet');
          $('.affiche_image').removeClass('current_onglet');
          $('#visioBody').show();
          $('div.img_mag').hide();
        });
        
        $('.affiche_image').rebind('click', function(){
          $('.affiche_image').addClass('current_onglet');
          $('.affiche_visio').removeClass('current_onglet');
          $('#visioBody').hide();
          $('div.img_mag').show();
        });
      });
    }
    
    $("a.facebox").each(function(){
      $(this).rebind("click", function(){
        $.facebox.loading();
        $.get($(this).attr("href"), function(data){
          $.facebox(data);
          $("#facebox").bgiframe();
          $("#facebox form.validate_me").validate();
        });
        return false;
      });
    });
    
    $("form.validate_me", $dom).each(function(){
      $(this).validate();
    });
    
    $("input#date").datepicker({
      speed: 0,
      firstDay: 1
    });
    
  };
  
  this.launchGmap = function($elem)
  {
    if (!$.fn.jmap)
    {
      $elem.html(Dms.alertMsg("Rechargez la page pour activer l'API GoogleMap"));
      return;
    }
    
    $("input#depart").one("click", function(){$(this).val("");});
    
    var metas = $elem.metadata();
    
    $elem.jmap('init', {
      // Initial type of map to display
      language: "fr",
      // Options: "map", "sat", "hybrid"
      mapType: metas.map_type,
      // Initial map center
      mapCenter: [55.958858,-3.162302],
      // Initial zoom level
      mapZoom: parseInt(metas.zoom),
      // Initial map control size
      // Options: "large", "small", "none"
      mapControlSize: "small",
      // Initialise type of map control
      mapEnableType: false,
      // Initialise small map overview
      mapEnableOverview: false,
      // Enable map dragging when left button held down
      mapEnableDragging: true,
      // Enable map info windows
      mapEnableInfoWindows: true,
      // Enable double click zooming
      mapEnableDoubleClickZoom: false,
      // Enable zooming with scroll wheel
      mapEnableScrollZoom: false,
      // Enable smooth zoom
      mapEnableSmoothZoom: false,
      // Enable Google Bar
      mapEnableGoogleBar: false,
      // Enables scale bar
      mapEnableScaleControl: false,
      // Enable the jMap icon
      mapShowjMapIcon: false,
      //Debug Mode
      debugMode: false
    });
    
    $elem.jmap('SearchAddress', {
      'query': metas.address,
      'returnType': 'getLocations'
    }, function(result, options)
    {
      var valid = Mapifies.SearchCode(result.Status.code);
      if (valid.success) {
        $.each(result.Placemark, function(i, point){
          $elem.jmap('AddMarker', {
            'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
            'pointHTML':point.address
          });
          $elem.jmap('MoveTo', {mapCenter: [point.Point.coordinates[1], point.Point.coordinates[0]]});
        });
      } else {
        $elem.html(Dms.alertMsg("L'adresse "+metas.address+" n'a pas été trouvée !<br />"+valid.message));
      }
    });
    
    $("form.direction").submit(function(){
      $elem.jmap('SearchDirections', {
          'query': "from: "+$("form.direction input#depart").val()+" to: "+metas.address+", france",
          'panel': '#itineraire',
          'locale': 'fr_FR'
      }, function(result, options) {
        var valid = Mapifies.SearchCode(result.getStatus());
        if (valid.success) {
         $("form.direction p.erreur").html("");
         $.each(result.Placemark, function(i, point){
           $elem.jmap('AddMarker',{
             'pointLatLng':[point.Point.coordinates[1], point.Point.coordinates[0]],
             'pointHTML':point.address
           });
         });
       } else {
         $("form.direction p.erreur").html("Cette adresse n'a pas pu être trouvée. Essayez de l'écrire autrement.");
       }
     });
      return false;
    });
  };
  
};

$(function(){Ctrl.initPage(page_options);});