var APP = {
  isLoading: true,

  showContent: function() {
    if ($.support.opacity) {
      $('#xhr-content')
        .css({opacity: 0})
        .animate({opacity: 1, left: 0}, {duration: 1250, queue: false, complete: function() { APP.isLoading = false; }});
    }
    else {
      $('#xhr-content')
        .animate({left: 0}, {duration: 1250, queue: false, complete: function() { APP.isLoading = false; }});
    }
  },

  hideContent: function() {
    APP.isLoading = true;

    if ($.support.opacity) {
      $('#xhr-content').animate({opacity: 0, left:1000}, {duration:1250, queue:false});
    }
    else {
      $('#xhr-content').animate({left:1000}, {duration:1250, queue:false});
    }
  },

  refreshCountdown: function() {
    //$('.xhr-countdown').load(APP.BASE_URL + '/index/countdown', {lang: APP.LANG});
    $('.xhr-countdown').load(APP.BASE_URL + '/live/countdown', {lang: APP.LANG});
  },

  contestForm: function() {
    $('.contest-box form').submit(function(event) {
      event.preventDefault();

      var form = $(this);
      var data = {};

      // CLEAN ERRORS FIELDS
      form.find('.error').removeClass('error');
      form.find('.errors').hide();

      form.find(':input').each(function() {
        var input = $(this);
        var val = input.val();

        // CLEAN POST DATA FROM DEFAULT VALUE
        if (input.attr('default') && input.val() == input.attr('default')) {
          val = '';
        }

        // SEND ONLY TEXT / CHECKED / SELECTED / HIDDEN VALUE
        if (input.is('input:checked, input:text, select, textarea, input[type=hidden]')) {
          data[input.attr('name')] = val;
        }
      });

      $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        dataType: 'json',
        data: data,
        success: function(response) {
          if (!response) {
            $(form).find('.step').hide().filter(':last').show();
          }
          else {
            $.each(response, function() {
              form.find('input:text[name="' + this + '"]:visible').addClass('error');
              form.find('label[for=' + this + ']').addClass('error');
              form.find('.errors').show();
            });
          }
          APP.scrollPane();
        }
      });
    });
  },

  guestForm: function() {
    $('.guest-box form').submit(function(event) {
      event.preventDefault();

      var form = $(this);
      var data = {};
      if(!form.find('.form-php').is(':visible'))
      {
        return false;
      }

      // CLEAN ERRORS FIELDS
      form.find('.error').removeClass('error');
      form.find('.errors').hide();

      form.find(':input').each(function() {
        var input = $(this);
        var val = input.val();

        // CLEAN POST DATA FROM DEFAULT VALUE
        if (input.attr('default') && input.val() == input.attr('default')) {
          val = '';
        }

        // SEND ONLY TEXT / CHECKED / SELECTED / HIDDEN VALUE
        if (input.is('input:checked, input:text, select, textarea, input[type=hidden]')) {
          data[input.attr('name')] = val;
        }
      });

      $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        dataType: 'json',
        data: data,
        success: function(response) {
          if (!response) {
            $(form).find('input:text[name="from_name"], input:text[name="from_email"], input:text[name="to_name"], input:text[name="to_email"]').val('');
            $(form).find('input:text[name="from_name"], input:text[name="from_email"], input:text[name="to_name"], input:text[name="to_email"]').blur();
            $(form).find('.step').hide().filter(':last').show();
            setTimeout(function(){
              $(form).find('.step:last').fadeOut(1000, function () {
                $(form).find('.share').fadeIn(1000, function(){ APP.scrollPane(); });
              });
            }, 5000);
          }
          else {
            $.each(response, function() {
              form.find('input:text[name="' + this + '"]:visible').addClass('error');
              form.find('.errors').show();
            });
          }
          APP.scrollPane();
        }
      });
    });
  },

  pressForm: function() {
    $('.press-box form').submit(function(event) {
      event.preventDefault();
      var form = $(this);

      $.ajax({
        url: form.attr('action'),
        type: form.attr('method'),
        dataType: 'json',
        data: {password: form.find('#password').val()},
        success: function(response) {
          if (!response) {
            $(form).find('.step').hide().filter(':last').show();
          }
          else {
            $(form).find('.errors').show();
          }
          APP.scrollPane();
        }
      });
    });
  },

  galleryLegend: function()
  {
    $('.box .gallery .photo .legend').each(function() {
      var width = $(this).prev('a').find('img:first').width() - 20;

      $(this).css({
        left: Math.floor((202 - width) / 2) + 'px',
        width: width + 'px'
      });
    });

    $('.box .gallery .photo').hover(function() {
      $(this).find('.legend:hidden').slideDown();
    }, function() {
      $(this).find('.legend:visible').slideUp();
    });
  },

  newsHref: function()
  {
    $('.entry img').each(function() {

      if(!$(this).closest('a').length)
      {
        var href = $(this).attr('rel');
        var cssClass = $(this).attr('class') ? $(this).attr('class') : 'lightbox';
        var matches = $(this).closest('div[class*="entry"]').attr('class').match(/entry-(\d+)/);
        var articleId = matches[1];

        if(!href)
        {
          var href = $(this).attr('src').replace(/\/width\/(\d)*\//, '').replace(/\/height\/(\d)*\//, '');
        }

        if(cssClass == 'simple-modal')
        {
          $(this).load(function(){
            $(this).before('<a href="'+href+'" class="simple-modal play" style="width:'+$(this).width()+'px !important;height:'+$(this).height()+'px !important;border:none;text-decoration: none !important"></a>');
          });
        }
        
        var alt = $(this).attr('alt').replace(/"/g, '&quot;');
        $(this).wrap('<a href="'+ href +'" class="'+cssClass+'" rel="group'+articleId+'" title="'+ alt +'" style="border:none;text-decoration: none !important"></a>');
      }

    });
  },

  cufon: function() {
    Cufon.replace('.helvetica-neue-ultralight');
  },

  scrollPane: function() {
    $('.scrollpane').jScrollPane({
      scrollbarWidth: 10,
      scrollbarMargin: 20
    });
  },

  lightbox: function()
  {
    $('a.lightbox').each(function() {
      var legend = $(this).next('.legend');

      if (legend.length) {
        $(this).attr('title', legend.html());
      }
    }).slimbox({
      overlayOpacity: 0.7,
      counterText: 'Image {x} sur {y}'
    });
  },

  defaultValue: function()
  {
    $(':input[default]').each(function() {
      var text = $(this);
      text.defaultValue(text.attr('default'));
    });
  },

  swfPlayer: function(options)
  {
    var options = options ? options : {};
    $('.swf-player').each(function(){
      var file = $(this).html();
      $(this).html('');
      $(this).flash({swf: '/swf/player.swf', width: 550, height: 308, hasVersion: 9, params:{scale: 'noborder', wmode: 'transparent', menu: 'false', flashvars: {file: file, autostart: options.autostart}}});
    });
  },

  swfPlayerCustom: function(options)
  {
    var options = options ? options : {};
    $('.swf-player-custom').each(function(){
      var file = $(this).html();
      $(this).html('');
      var date = new Date();
      $(this).flash({swf: '/swf/guest_custom.swf?_='+date.getTime(), width: 570, height: 320, hasVersion: 9, params:{scale: 'noborder', wmode: 'transparent', menu: 'false', flashvars: {autostart: options.autostart, message: options.message}}});
    });
  },
  
  liveGallery: function(){

		$("#gallery-live li a.lien img").mouseover(
		    function () {
		      var numPhoto = $("ul#gallery-live li a.lien img").index(this);
		      var marginHaute = "-=35px";
		      if(numPhoto==0) {
		        var marginGauche = 0;
		      }
		      else if(numPhoto==3) {
		        var marginGauche = "-=70px";
		      }
		      else {
		        var marginGauche = "-=35px";
		      }
		    
		      $(this).stop();
		      $(this).parent().next("p.legende").stop();
		      $(this).css({'z-index' : 100,'width' : 170, 'height' : 200, marginTop: 0, marginLeft: 0}).animate({
		          marginTop: "-=35px",
		          marginLeft: marginGauche,
		          height: 273,
		          width: 232,
		      }, 'fast',function() {
		                              $(this).parent().next("p.legende").children(".sous-legende").animate({'opacity': '1'},100);
		                            })
		      .parent().next('p.legende').css({marginTop: 0, marginLeft: 0, width: 170}).animate({
		          marginTop: "+=35px",
		          marginLeft: marginGauche,
		          width: 233,
		      }, 'fast');
		    }
		  ).mouseout(
		    function () {
		      $("#gallery-live li .sous-legende").animate({'opacity': '0'},100);
		      $(this).stop();
		      $(this).parent().next('p.legende').stop();
		      $(this).animate({
		          marginTop: 0,
		          marginLeft: 0,
		          height: 200,
		          width: 170,
		      }, 'fast', function() {
		                              $(this).css({'z-index' : 0, marginTop: 0, marginLeft: 0});
		                            }
		      );
		      
		      $(this).parent().next('p.legende').animate({
		          marginTop: 0,
		          marginLeft: 0,
		          width: 170,
		      }, 'fast', function() {
		                              $(this).css({marginTop: 0, marginLeft: 0, width: 170});
		                            }
		      );
		    }
		  );
  
  }

  
}

$(document).ready(function()
{

  // Page accueil et Live 
  //$("ul#gallery-live li img").css({'border': '1px solid #777575'});
  //$("ul#gallery-live li .sous-legende").css({'opacity': '0'}); 

  // INIT CUFON
  Cufon.now();
  APP.cufon();
  $('#menu a').hover(function() { setTimeout(APP.cufon, 5); }, function() { setTimeout(APP.cufon, 5); });

  $('#l8n a').hover(function(){
  	$('#flag').css('background-position', '0 -13px');
  },
  function(){
  	$('#flag').css('background-position', '0 0');
  });

  $.ajaxSetup({
    cache: false,
    type: 'POST',
    async: true
  });

  // simple modal
  $('a.simple-modal').live('click', function(event) {
    event.preventDefault();
    var a = this;
    $.modal('Chargement...', {
      onShow: function (dialog) {
        dialog.data.load($(a).attr('href'));
      },
      overlayClose: true,
      opacity: 70,
      minWidth: 550,
      minHeight: 308
    });
  });

  // INIT MENU CLICK HANDLER
  $('#menu a, a.xhr-load-content').live('click', function(event) {
    event.preventDefault();

    if (APP.isLoading) {
      return false;
    }

    var url = $(this).attr('href');
    var rel = $(this).attr('rel') ? $(this).attr('rel') : url;

    $('#menu a').removeClass('selected');
    $('#menu a[href="' + rel + '"]').addClass('selected');

    APP.cufon();

    APP.hideContent();

    setTimeout(function() {
      $('#xhr-content').load(url, function() {
        APP.cufon();
        APP.scrollPane();
        APP.defaultValue();
        APP.newsHref();
        APP.lightbox();
        APP.galleryLegend();
        APP.contestForm();
        APP.guestForm();
        APP.pressForm();
        APP.liveGallery();

        $('img').load(APP.scrollPane);

        APP.showContent();
      });
    }, 1500);

    pageTracker._trackPageview(url);
  });

  // INIT NEWS CATEGORIES ET TITLE CLICK HANDLER
  $('a.news-category-box, a.xhr-load-news-content').live('click', function(event) {
    event.preventDefault();

    var url = $(this).attr('href');
    var rel = $(this).hasClass('.news-category-box') ? url : $(this).attr('rel');

    $('a.news-category-box').removeClass('selected');
    $('a.news-category-box[href="' + rel + '"]').addClass('selected');

    $('#xhr-news-content').load(url + ' #xhr-news-content .news-box', {}, function() {
      APP.cufon();
      APP.scrollPane();
      APP.newsHref();
      APP.lightbox();
      APP.swfPlayer();

      $('img').load(APP.scrollPane);
    });

    pageTracker._trackPageview(url);
  });

  // INIT FOCUS LEGEND
  $('#focus .photo .legend').each(function() {
    var width = $(this).prev('a').find('img:first').width() - 20;

    $(this).css({
      left: '1px',
      width: width + 'px'
    });
  });

  $('#focus .photo').hover(function() {
    $(this).find('.legend:hidden').slideDown();
  }, function() {
    $(this).find('.legend:visible').slideUp();
  });

  // INIT PHOTOS LEGEND HANDLER
  $('.photo .legend').live('click', function(event) {
    event.preventDefault();

    $(this).prev().click();
  });

  // INIT CONTEST NEXT STEP HANDLER
  $('.contest-box .next-step').live('click', function(event) {
    event.preventDefault();

    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {
      elmt.next().fadeIn(1000, function(){ APP.scrollPane(); });
    });
  });

  $('.next-step-validate1').live('click', function(event){
    event.preventDefault();
    var form = $(this).closest('form');
    var error = false;
    for(var i=1; i<=4; i++)
    {
      form.find('label[for*=question'+i+'-]').removeClass('error');
      if($('input:radio[name="question'+i+'"]:checked').val() == undefined)
      {
        error = true;
        form.find('label[for*=question'+i+'-]').addClass('error');
      }
    }

    if(error)
      return;

    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {
      elmt.next().fadeIn(1000, function(){ APP.scrollPane(); });
    });
  });

  $('.next-step-validate2').live('click', function(event){
    event.preventDefault();
    var form = $(this).closest('form');

    form.find('label.error').removeClass('error');

    if ($('input:checkbox:checked').length == 3)
    {
      var elmt = $(this).closest('.step');

      elmt.fadeOut(1000, function () {
        elmt.next().fadeIn(1000, function(){ APP.scrollPane(); });
      });

      return;
    }

    for (var i=0; i<5; i++) {
      if (!$('input:checkbox[name="answers['+i+']"]:checked').length) {
        form.find('label[for*=answers-'+i+']').addClass('error');
      }
    }
  });

  // INIT GUEST STAR NEXT STEP HANDLER
  $('.guest-box .next-step-1').live('click', function(event) {
    event.preventDefault();

    var form = $(this).closest('form');
    var message = form.find('#message').val();

    form.find('label[for=message]').removeClass('error');
    if(message == '' || message == undefined)
    {
      form.find('input:text[name="message"]:visible').addClass('error');
      form.find('label[for=message]').addClass('error');
      form.find('.errors').show();
      return;
    }

    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {
      elmt.next().fadeIn(1000, function(){ APP.scrollPane(); APP.swfPlayerCustom({message: message, autostart: 1}); });
    });
  });

  $('.guest-box .next-step-2').live('click', function(event) {
    event.preventDefault();

    var form = $(this).closest('form');
    var message = form.find('#message').val();
    var url_custom =  form.find("#url_custom").val()+'/name/';
    form.find("#url_custom").val(url_custom + Base64.encode(encodeURIComponent(message)));
    form.find('#video-custom-twitter').attr('href', 'http://twitter.com/home?status='+  encodeURIComponent('Un invité exceptionnel au défilé @etam_lingerie : ') + url_custom + Base64.encode(encodeURIComponent(message)));
    form.find('#video-custom-facebook').attr('href', 'http://www.facebook.com/share.php?u=' + url_custom + Base64.encode(encodeURIComponent(message)) + '&t='+encodeURIComponent('Un invité exceptionnel au défilé @etam_lingerie'));

    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {
      elmt.next().fadeIn(1000, function(){ APP.scrollPane();$('.swf-player-custom').html('') });
    });
  });

  $('.guest-box .reset-step').live('click', function(event) {
    event.preventDefault();

    var form = $(this).closest('form');
    form.find('#message').val('');
    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {
      $('.step:first').fadeIn(1000, function(){ APP.scrollPane(); });
    });
  });

  $('.guest-box .prev-step-3').live('click', function(event) {
    event.preventDefault();
    var form = $(this).closest('form');
    var message = form.find('#message').val();

    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {

      elmt.prev().fadeIn(1000, function(){ APP.scrollPane();APP.swfPlayerCustom({message: message, autostart: 1}); });
    });
  });

  $('.guest-box .next-step-3').live('click', function(event) {
    event.preventDefault();

    var elmt = $(this).closest('.step');
    elmt.fadeOut(1000, function () {
      elmt.next().fadeIn(1000, function(){ APP.scrollPane(); });
    });
  });

  // ONLOAD CONTENT ANIMATION AND INITS
  setTimeout(function() {
    APP.scrollPane();
    APP.defaultValue();
    APP.newsHref();
    APP.lightbox();
    APP.galleryLegend();
    APP.contestForm();
    APP.guestForm();
    APP.pressForm();
    APP.showContent();
    APP.liveGallery();

    $('img').load(APP.scrollPane);
  }, 3500);

  // INIT COUNTDOWN
  //setInterval(function() { APP.refreshCountdown(); }, 30000);
});
