/* NOTICE OF LICENSE
 *
 * This source file is subject to a commercial license from SARL SMC
 * Use, copy, modification or distribution of this source file without written
 * license agreement from the SARL SMC is strictly forbidden.
 * In order to obtain a license, please contact us: olivier@smartmarseille.com
 * ...........................................................................
 * INFORMATION SUR LA LICENCE D'UTILISATION
 *
 * L'utilisation de ce fichier source est soumise a une licence commerciale
 * concedee par la societe SMC
 * Toute utilisation, reproduction, modification ou distribution du present
 * fichier source sans contrat de licence ecrit de la part de la SARL SMC est 
 * expressement interdite.
 * Pour obtenir une licence, veuillez contacter la SARL SMC a l'adresse: olivier@smartmarseille.com
 * ...........................................................................
 * @package    SO COLISSIMO
 * @copyright  Copyright (c) 2010-2011 S.A.R.L SMC (http://www.smartmarseille.com)
 * @author     Olivier B.
 * @license    Commercial license
 * Support by mail :  olivier@smartmarseille.com
 * Support on form : Olivier B > A.K.A delete 
 * Skype : delete13_fr 
 */
 

 $(document).ready(function() {
  

  // Div qui contiendra la fenetre & overlay pour le fond
  //
  $('body').prepend('<div id="soverlay">&nbsp;</div>') ;
  $('#form').prepend('<div id="socowindow">&nbsp;</div>') ;

  // Input Radio du module Socolissimo
  //
  soCoCarrierId = parseInt( $('#soliberte-carrier').val() ) ;
  soCoModule = $('#id_carrier' + soCoCarrierId) ;
  
  soCoModule.attr('checked', false) ;
  soCoModule.removeAttr('checked') ;
    
  var geocoder ;
  var map;
   
  // On geolocalise toutes les entrees du carnet d'addresse 
  //
  var mainlocation = 0 ;
  var mapfailed = 0 ; 
  
  function geocode(fulladdress, latitem, lngitem, defaut)
  {
      // Starting GeoCoding
      //
      try {
            var geocoder = new google.maps.Geocoder() ;
          }
      catch (e) {
          mapfailed ++ ; 
          return(false) ;
      }

      geocoder.geocode( { 'address': fulladdress}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK ) {
             
            $('input[name="' + latitem + '"]').val( results[0].geometry.location.lat() ) ;
            $('input[name="' + lngitem + '"]').val( results[0].geometry.location.lng() ) ;

            if ( defaut )
            {
              $('#geolat').val( results[0].geometry.location.lat() ) ;
              $('#geolng').val( results[0].geometry.location.lng() ) ;            
            }
            $('input[name=geolocated]').val('1') ; // Au moins une entree du carnet d'addresse a ete geolocalisee
        }
      });
      
  }
  //
  // Geocoding de tout le carnet d'adresse dès l'affichage de la page
  // ca laisse le temps a la requete asynchrone de récuperer les points GPS
  //
  $('input[name$="-address1"]').each(function() {

    point = $(this).attr('name').match('-([0-9]*)-') ;
    point = point[1] ; 
  
  
      address1 = $('input[name="ab-' + point + '-address1"]').val() ;
      address2 = $('input[name="ab-' + point + '-address2"]').val() ;
      city = $('input[name="ab-' + point + '-city"]').val() ;
      country = $('input[name="ab-' + point + '-country"]').val() ;
      latitem = 'ab-' + point + '-lat' ; 
      lngitem = 'ab-' + point + '-lng' ;
            
      fulladdress = (address1.length ? address1 + ', ' : '') +
                    (address2.length ? address2 + ', ' : '') +
                    (city.length ? city + ', ' : '') +
                    (country.length ? country : '') ;
      defaut = parseInt($('input[name="ab-' + point + '-abdefault"]').val()) ;
      
     geocode(fulladdress, latitem, lngitem, defaut) ;
  });
  
  //
  // Affichage du module dans la page order
  //   
  $(soCoModule).click(function() {
    
    // On invalide tout
    //
    $('input:radio[name="id_carrier"]').attr("checked", false);
    $("input:radio").removeAttr("checked");
    
    $('tr[class$=_item]').click(function() 
    {
      soCoModule.attr('checked', false) ;
    });
           
    // Container pour afficher les infos sur le module
    //
    if ( $('#table-sodesc').length )    $('#table-sodesc').remove() ;
    
    $(this).parent().parent().parent().parent().append('<tr id="table-sodesc"><td colspan="4"></td></tr>') ;

    //
    // Affichage du menu evolué SoColissimo
    //
    
    $('#table-sodesc td').load( $('#description_url').val(), function() {

      $('.soco-choose').click(function() {
          //
          // Affichage de la fenetre principale soColissimo (avec Carto)
          //
          $.ajax({
              type: 'POST',
              url: $('#window_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#soverlay').show(); 
                    $('#socowindow').html(data).fadeIn() ,
                    soCoInit(),
                    $('#address-loader').fadeOut() ;             
                  }
              });    
          return(false) ;
      });
      
      //
      // Livraison a Domicile 
      //
      $('#soco-choose-dom').click(function() 
      {
        $('#soverlay').hide();
        $('#table-sodesc').remove() ;
           
        soCoModule.parent().parent().parent().parent().append('<tr id="table-sodesc"><td colspan="4"></td></tr>') ;
                
        $('#table-sodesc td').load( $('#validation_url').val() + '?dom=dom') ;
        
        return(false) ;
      });
      
      //
      // Livraison sur Rendez Vous (PARIS)  
      //
      $('#soco-choose-rdv').click(function() 
      {
        if ( $('input[name=paris]').val().match('disabled') ) 
        {
          alert('Livraison sur RDV uniquement sur Paris') ;
          return(false) ;
        }

        $('#soverlay').hide();
        $('#table-sodesc').remove() ;
           
        soCoModule.parent().parent().parent().parent().append('<tr id="table-sodesc"><td colspan="4"></td></tr>') ;
                
        $('#table-sodesc td').load( $('#validation_url').val() + '?dom=rdv') ;
        
        return(false) ;
      });
            
    }) ;
     
    return(true) ;
           
  });

  
  //
  // Main functions
  //
  function soCoInit()
  {
      // Pas de geoloc ou googlemap pas encore chargé, on affiche par code postal
      //
      if ( ! parseInt($('#geolocated').val()) == 1 )
      {
         $('#address-loader').fadeIn() ;
         
         mainpostcode = $('input[name="ab-0-postcode"]').val() ;
         $('input[name="postcode"]').val(mainpostcode) ;
    
         // Echec de geoloc on positionne google map sur la france
         //
         $('#geolat').val('47.227638') ;
         $('#geolng').val('2.213749'); //france
         $('#geozoom').val('5'); 
         
         $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;
                    $('#address-loader').fadeOut() ;              
                  }
          });        
          $('#address-loader').fadeOut() ;     
      }
      else
      {
           $('#geozoom').val('14');
            
          // Affichage du initial plan 
          //
          $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;
                  }
          });    
      }
      
      // Recherche d'une addresse 
      //
      $('input[name=valid]').click(function() {
          fulladdress = '' ;
    
          if ( ! $('input[name=city]').val().length && ! $('input[name=postcode]').val().length )
          {
            alert('Champ ville ou Code Postal requis !') ;
            return(false) ;
          } 
          
          if ( $('input[name=address]').val().length ) 
            fulladdress += $('input[name=address]').val() + ', ' ;
    
          fulladdress += $('input[name=postcode]').val() + ' ' ;       
          fulladdress += $('input[name=city]').val() + ', ' ;
          fulladdress += $('input[name=country]').val() ;
    
          $('#points').scrollTop(0);
          $('#address-loader').fadeIn() ;       
    
          var geocoder;
          var map;
    
           try {
              var geocoder = new google.maps.Geocoder() ;
           }
           catch(e) {
            return(false) ;
           }  
          
          geocoder.geocode( { 'address': fulladdress}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK ) {
 
              $('#geozoom').val('15');
               
              $('#latlng').val( results[0].geometry.location ) ; 
              $('#geolat').val( results[0].geometry.location.lat() ) ;
              $('#geolng').val( results[0].geometry.location.lng() ) ;
              $('#lookup').val(1) ;
               
              $.ajax({
                  type: 'POST',
                  url: $('#parser_url').val(),
                  data: $('#form').serialize(),
                  success: function(data) {
                        $('#points').html(data) ;
                        $('#address-loader').fadeOut() ;               
                      }
                  });    
            } else {
            
              $('#geozoom').val('5');
              $('#geolat').val('47.227638') ;
              $('#geolng').val('2.213749'); //france              

              alert(fulladdress + ' : Adresse introuvable') ;      
            }
          });             
        $('#lookup').val(0) ; 
    
        return(false) ;
      });
         
      // Limitation a n kilometres
      //
      $('#limiter').change(function() {
           
           $('#points').scrollTop(0);
           $('#address-loader').fadeIn() ;     
            
          // Zoom en fonction de la distance des points (ca c bo ca !)
          //
          switch( parseInt($('#limiter').val()) )
          {
            case 0 :
              $('#geozoom').val('16');
              break ;
            case 1 :
              $('#geozoom').val('15');
              break ;
            case 5 :
              $('#geozoom').val('13');
              break ;
            case 10 :
              $('#geozoom').val('12');
              break ;
            case 30 :
              $('#geozoom').val('11');
              break ;
            case 100 :
              $('#geozoom').val('8');
              break ;
            default:
            $('#geozoom').val('15');
              break ;
          }
            
           $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;
                    $('#address-loader').fadeOut() ;              
                  }
              }); 
      });
      // Limitation a n Points de retrait
      //
      $('#maxpts').change(function() {
           
           $('#points').scrollTop(0);
           $('#address-loader').fadeIn() ;     
         
           $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;
                    $('#address-loader').fadeOut() ;              
                  }
              }); 
      });
        
      // On recupere la ville pour le code postal
      //
      $('input[name=postcode]').blur(function() {
        soCityQuery( $(this) ) ;
      });

      $('input[name=postcode]').mouseout(function() {
        soCityQuery( $(this) ) ;
      });
     
      // JSON Query pour obtenir la ville
      //
      function soCityQuery(obj)
      {
          if ( ! parseInt(obj.val()) )  return ;
          if ( ! $('#cityservices_url').val().length ) return ;
           
          $('#address-loader').fadeIn() ;      
          
          $.ajax({
              type: 'GET',
              url: $('#cityservices_url').val(),
              timeout: 750, // 750 ms de timeout, + ca sert plus a rien !
              data: obj.serialize(),
              dataType: 'json',
              success: function(data) {
                    //if ( ! $('#soli-ci').val().length )
                    $('#soli-ci').val(data.city),       
                    $('#address-loader').fadeOut() ;       
                  }
          });
          $('#address-loader').fadeOut() ;    
      }
      
      // On Choisit le Domicile
      //
      $('.home-selector').click(function() {
          
          $('#points').scrollTop(0);
          $('#address-loader').fadeIn() ;
      
          $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;       
                    $('#address-loader').fadeOut() ;       
                  }
          });    
      });
      
      // On selectionne un Point de Retrait SoColissimo
      //  
      $('.type-selector').click(function() {
      
          $('#points').scrollTop(0);
          $('#address-loader').fadeIn() ;
              
          $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;
                    $('#address-loader').fadeOut() ;              
                  }
              });    
      });  
    
      // testing purpose only
      $('#generate').click(function() {
          $.ajax({
              type: 'POST',
              url: $('#parser_url').val(),
              data: $('#form').serialize(),
              success: function(data) {
                    $('#points').html(data) ;              
                  }
              });    
      });

      // Fermeture de la fenetre soco
      //
      function closeSoCo()
      {
        $('#table-sodesc').remove() ;
        $('#soverlay').hide();
        $('#socowindow').fadeOut() ;
        $('#socowindow').html('') ;        
        
        soCoModule.attr('disabled', false) ;  
        soCoModule.attr('checked', false) ;
        soCoModule.removeAttr('checked') ;     
      }
      
      $('#sowindow-close').click(function() {
        closeSoCo() ;
        
        return(false) ;   
      });      
      $('#sowindow-closeX').click(function() {
        closeSoCo() ;
        
        return(false) ;   
      });      
 
  }
    
  


  
  
});
