/*
 * SELECT CART
 */
function prepareSelectCart(){
  $('#select_cart').click(function(event){
    event.preventDefault();
    $('#select_cart_form').show();
    $(this).parent().hide();
  });
}


/*
 * PRODUCT FANCY BOX 
 */

function prepareFancyBox(){
 $(".fancyboxcover").fancybox({'hideOnContentClick': true,
                               'hideOnOverlayClick': true,
                               'zoomSpeedIn':200,
                               'zoomSpeedOut':200,
                               'overlayShow': true,
                               'overlayOpacity':0,
                               'padding':0});
 $(".fancyboxreshelp").fancybox({'hideOnContentClick':false,
                                 'hideOnOverlayClick': true,
                                 'zoomSpeedIn':200,
                                 'zoomSpeedOut':200,
                                 'frameWidth':300,
                                 'frameHeight':250
                                });
}

/*
 * ADVANCED SEARCH
 */

function prepareAdvancedSearch() {
  $('#advanced_search_link').click(function(event){
    $('#advanced_search').show();
    $('#search').hide();
    $('#id_title').focus();
  });
}
/*
 * NEWSLETTER
 */

function postSubscriptionWithEmail(id) {
  $.ajax({url:"/newsletters/subscribe_ajax/",
          type:"POST",
          data:$('#'+ id + ' :input').serializeArray(),
          dataType:"json",
          success:function (data, textStatus) {
            switch(data.status) {
              case "OK":
                $('#'+ id).html("Vous êtes désormais inscrit à la lettre d'information");
                $('#'+ id+'_error').hide();
                break;
              case "EMAIL_ERROR":
                $('#'+ id+'_error').html("Entrez une adresse email valide.");
                $('#'+ id+'_error').show();
                break;
              case "ALREADY_SUBSCRIBED":
                $('#'+ id+'_error').html("Cette adresse est déjà inscrite.");
                $('#'+ id+'_error').show();
                break;
             }
          },
          error:function () {
            alert('Inscription impossible');
          }
          });
}

function prepareSubscriptionWithEmail(id) {
  $('#send_'+id).click(function(event){
    event.preventDefault();
    postSubscriptionWithEmail(id);
  });
  $('#' + id + '_email').click(function(){
    $(this).select();
  });
}

function postUnsubscriptionWithEmail(id) {
  $.ajax({url:"/newsletters/unsubscribe_ajax/",
          type:"POST",
          data:$('#'+ id + ' :input').serializeArray(),
          dataType:"json",
          success:function (data, textStatus) {
            switch(data.status) {
              case "OK":
                $('#'+ id).html("Un email de désinscription vous a été envoyé.");
                $('#'+ id+'_error').hide();
                break;
              case "EMAIL_ERROR":
                $('#'+ id+'_error').html("Entrez une adresse email valide.");
                $('#'+ id+'_error').show();
                break;
              case "ALREADY_UNSUBSCRIBED":
                $('#'+ id+'_error').html("Cette adresse n'est pas inscrite à notre liste.");
                $('#'+ id+'_error').show();
                break;
             }
          },
          error:function () {
            alert('Désinscription impossible');
          }
          });
}

function prepareUnsubscriptionWithEmail(id) {
  $('#send_'+id).click(function(event){
    event.preventDefault();
    postUnsubscriptionWithEmail(id);
  });
  $('#' + id + '_email').click(function(){
    $(this).select();
  });
}

function prepareSubscription() {
  prepareSubscriptionWithEmail('subscription_with_email');
  prepareSubscriptionWithEmail('subscription_with_user');
  prepareUnsubscriptionWithEmail('unsubscription_with_email');
  prepareUnsubscriptionWithEmail('unsubscription_with_user');
  $('#unsubscribe_link').click(function(event){
    event.preventDefault();
    $('#subscription_with_email').hide();
    $('#unsubscription_with_email').show();
  });
  $('#unsubscribe_user_link').click(function(event){
    event.preventDefault();
    $(this).parent().hide();
    $('#unsubscription_with_user').show();
  });
}

/*
 * PROGRESS BAR
 */

function gen_uuid() {
  var uuid = "";
  for (var i = 0; i < 32; i++) {
    uuid += Math.floor(Math.random() * 16).toString(16);
  }
  return uuid;
}

function show_progress(data, filename) {
  if (data) {
    var progress = parseInt(data.received) / parseInt(data.size);
    var width = $('#progress_bar').width();
    var progress_width = Math.floor(width * progress);
    $("#progress_indicator").width(progress_width);
    $("#progress_filename").text('Uploading "' + filename + '": '+ parseInt(progress * 100) + '%');
    if (progress == 1 || data.state == 'done') {
      window.clearInterval(window.ProgressIntervalID);
      $("#progress_filename").text('Upload of "' + filename + '" complete. Processing...');
    }
  }
}

function prepare_progress_for_form(form, buttons, fileinput) {
  form.submit(
    function() {
      buttons.hide();
      var uuid = gen_uuid();
      var filename = fileinput.val().split(/[\/\\]/).pop();
      this.action += (this.action.indexOf('?') == -1 ? '?': '&') + 'X-Progress-ID=' + uuid;
      $("#progress_filename").text('Uploading "' + filename + '"...');
      $("#progress_container").show();
      window.ProgressIntervalID = window.setInterval(function() {
        window.frames.progress.update_progress_info(
          function(data) { show_progress(data, filename); }, uuid);}, 1000);
    }
  );
}

/*
 * GOOGLE BOOK API
 */

var isbn_google_book;

function processDynamicLinksResponse(booksInfo) {
  for (id in booksInfo) {
    isbn_google_book = id;
    if (booksInfo[id] && booksInfo[id]['embeddable']) {
      google.load("books", "0", {"language": "fr"});
      var preview_button=$('#preview_button');
      preview_button.show();

      preview_button.click(function() {
        var preview_block = $("#google_preview");
        if(preview_block.is(':hidden')) {
          preview_block.show();
          var viewer = new google.books.DefaultViewer(document.getElementById('viewerCanvas'), {'showLinkChrome': false});
          viewer.load(isbn_google_book);
        }
        $('html,body').animate({scrollTop: preview_block.offset().top}, 1000);
      });
    }
  }
}

function showGooglePreviewInSearchResults(booksInfo) {
  for (id in booksInfo) {
    if (booksInfo[id] && booksInfo[id]['embeddable']) {
      $('#product_miniview_'+id+' .gbs_preview_sticker').show();
    }
  }
}

/*
 * PRODUCT REVIEW
 */

function prepareProductReview() {
  $('a.body_2_review').live('click', function(event){
    event.preventDefault();
    var link = $(this);
    link.next().show();
    link.hide();
  });
}

/*
 * BANNER
 * cf http://jonraasch.com/blog/a-simple-jquery-slideshow
 */

function slideSwitch() {
  if ($("#banner div").length==1) return;
  var active = $("#banner div.active");
  if (active.length == 0) active = $("#banner div:last");
  var next = active.next().length ? active.next()
          : $('#banner div:first');
  active.addClass('last-active');
  next.css({opacity: 0.0})
      .addClass('active')
      .animate({opacity: 1.0}, 1000, function() {
        active.removeClass('active last-active');});
}

function prepareBanners() {
  setInterval( "slideSwitch()", 10000 );
}
