$(document).ready(function($){

	//lien video auto
  if (jQuery.fn.media) {

  	var $videoLinks = jQuery('a[href$=".flv"]');

    jQuery.fn.media.defaults.flvPlayer = '/images/mediaplayer.swf';

    $videoLinks.each(function(i) {
      var $this = jQuery(this)
        , href = $this.attr('href');

      $this
        .after(jQuery('<div style="display:none;"><div id="video_box_' + i + '"><a href="' + href + '">&nbsp;</a></div></div>' ))
        .colorbox({ rel: 'nofollow', close: '<div id="closePopupJeux"></div>', inline: true, href:'#video_box_' + i });

      jQuery('#video_box_' + i + ' a').media({ width: 640, height: 480, autoplay: false });

    });
  }

  //Menu principal dropdown
  $('#menu_principal li').hover(function() {
    $(this)
      .find('ul')
      .stop(true, true)
      .slideDown('fast')
      .end()
      .animate({
        backgroundPositionY: '0'
      }, 'fast');
  }, function() {
    $(this)
      .find('ul')
      .stop(true, true)
      .slideUp('fast')
      .end()
      .animate({
        backgroundPositionY: '17px'
      }, 'fast');
  });

	//Animation menu top
	$("#topnav li").prepend("<span></span>"); //Throws an empty span tag right before the a tag

	$("#topnav li").each(function() { //For each list item...
		var linkText = $(this).find("a").html(); //Find the text inside of the <a> tag
		$(this).find("span").show().html(linkText); //Add the text in the <span> tag
	});

	$("#topnav li").hover(function() {	//On hover...
		$(this).find("span").stop().animate({
			marginTop: "-104" //Find the <span> tag and move it up 40 pixels
		}, 250);
	} , function() { //On hover out...
		$(this).find("span").stop().animate({
			marginTop: "0"  //Move the <span> back to its original state (0px)
		}, 250);
	});

	//Menu Tout en 1 clic
	$('#tout_un_clic_cnt').mouseover(function() {
  	$(this).stop().css({
			height: "100%"
		});
		$(this).next('.menu_clic').slideToggle('fast');
    return false;
	});
	$('#tout_un_clic_cnt').mouseout(function() {
		$(this).stop().animate({
			height: "19px" //Find the <span> tag and move it up 40 pixels
		}, 250, function() {
			$('.menu_clic ul').hide();
		});
	});
	$(".menu_clic").accordion({
      accordion:true,
      speed: 500,
      closedSign: '',
      openedSign: ''
  });

  $('.menu_clic').find('ul').each(function() {
  	var $this = $(this);

  	if (typeof easytoog_admin === 'undefined' && !$this.find('li').length) {
  		$this.remove();
  	}
  });

  //Menu partager cette page
	$('#share_page_cnt').mouseover(function() {
  	$(this).stop().css({
			height: "100%"
		});
		$(this).next('.menu_share').slideToggle('fast');
    return false;
	});
	$('#share_page_cnt').mouseout(function() {
		$(this).stop().animate({
			height: "15px" //Find the <span> tag and move it up 40 pixels
		}, 250, function() {
			$('.menu_share ul').hide();
		});
	});

	//Home CYCLE HOME
	$('#slider_home')
		.before('<div id="prev">Précédent</div>')
		.after('<div id="next">Suivant</div>')
		.cycle({
		    fx:     'fade',
		    speed:  1000,
		    timeout: 10000,
    		next:   '#next',
    		prev:   '#prev'
	});
	//content CYCLE PAGE
	$('.slider_page')
		.before('<div id="prev">Précédent</div>')
		.after('<div id="next">Suivant</div>')
		.cycle({
		    fx:     'scrollHorz',
		    speed:  1000,
		    timeout: 10000,
    		next:   '#next',
    		prev:   '#prev',
        height:  '200px'
	});

	//content CYCLE PRODUIT
	$('#slider_carrousel ul')
		.before('<div id="navtop">Précédent</div>')
		.after('<div id="navbottom">Suivant</div>')
		.cycle({
		    fx:     'scrollVert',
		    speed:  1000,
		    timeout: 10000,
    		next:   '#navtop',
    		prev:   '#navbottom',
    		height:  '160px'
	});

	//content CYCLE PAGE
	$('#slider_right .slider_right')
		.before('<div id="prev_right">Précédent</div>')
		.after('<div id="next_right">Suivant</div>')
		.cycle({
		    fx:     'fade',
		    speed:  1000,
		    timeout: 10000,
    		next:   '#next_right',
    		prev:   '#prev_right'
	});

	//content CYCLE PAGE
	$('#slider_left .slider_left')
		.before('<div id="prev_left">Précédent</div>')
		.after('<div id="next_left">Suivant</div>')
		.cycle({
		    fx:     'fade',
		    speed:  1000,
		    timeout: 10000,
    		next:   '#next_left',
    		prev:   '#prev_left'
	});

	//Colorbox
	$("a[rel='colorboxpopup']").colorbox({
		transition:"fade",
		maxWidth: 800
	});

	//Menu left bar
	$(".left_menu").accordion({
      accordion:true,
      speed: 500,
      closedSign: '',
      openedSign: ''
    });

  //FAQ
	$(".toggle_container").hide();
	$(".trigger").toggle(function(){
	  	$(this).addClass("active");
		}, function () {
			$(this).removeClass("active");
	});
	$(".trigger").click(function(){
		$(this).next(".toggle_container").slideToggle("slow");
	});

	// Lexique | @TODO ne marche pas sur IE7
	if (location.hash.length) {
    var $wordLexique = $('[name="' + location.hash.substr(1) + '"]');
    if ($wordLexique.length) {
      $wordLexique.parent().next().slideToggle("slow");
    }
  }

	//Tooltip
	$('.hastip').tooltipsy({
        className: 'tooltipsy',
        alignTo: '.hastip',
    		offset: [10, 0],
        show: function (e, $el) {
            $el.fadeIn(100);
        },
        hide: function (e, $el) {
            $el.fadeOut(100);
        }
  });

  //Switch tab produits
	$(function () {

    var tabContainers = $('#global_tabs > div');

    $('ul.tabNavigation a').click(function () {
      tabContainers.hide().filter(this.hash).show();

      if (this.hash == '#installation'){
        var self = this;
        $.post('/docatl', {arbo:$(self.hash).attr('rel')}, function(data){
          $(self.hash).empty().html(data);
        });
      }

      $('ul.tabNavigation a').removeClass('active');
      $(this).addClass('active');

      return false;
    });
    $('ul.tabNavigation a[href='+(document.location.hash ? document.location.hash : '#fiche_technique')+']').click();
	});

	//back top
	$('a[href=#top]').click(function(){
		$('html, body').animate({scrollTop:0}, 'slow');
		return false;
	});

	$("input, textarea, select, button").uniform();

  // Faked menu
  $('.minibox_topcenter_2col ol').each(function() {
    $(this).find('li:first').after($('<li style="display:none;position:absolute;"><ul></ul></li>').addClass('list_cnt'));
    $(this).find('li:gt(1)').each(function(i, e){
        $(e).prev('li').find('ul').append($('<li>' + $(e).html() + '</li>'));
        $(e).remove();
    });
    $(this).mouseover(function(ev){
        $(this).find('li:eq(1)').show();
    });
    $(this).mouseout(function(ev){
        $(this).find('li:eq(1)').hide();
    });
  });


  /***************/
  /* Comparateur */
  /***************/


  // Ajout au comparateur
  $('.add_compar, .addCompare, .delCompare').live('click', function(e) {
    e.preventDefault();
    var $this = $(this),
        data;

    if ($this.hasClass('addCompare')) {
        data = { produit_id: $this.data('id'), type: 'add' };
    } else if ($this.hasClass('delCompare')) {
        data = { produit_id: $this.data('id'), type: 'del' };
    } else {
        data = { produit_name: $this.attr('href').substr(1), type: 'add' };
    }

    var data =

    $.post('/manageCompare', data, function(notice) {
      console.log(typeof notice.error)
      if (typeof notice.error == 'undefined' || notice.error) {
          alert(notice.message);
      } else {
          if (confirm(notice.message))
            location.href = page_comparateur;
      }

      // Si sur la page comparateur, on recharge pour affiché le nouveau produit
      if (!notice.error && $this.parents('#popupcompar').length)
        location.reload();

      // Si delete, on cache le produit ou reload
      if ($this.hasClass('delCompare')) {
        var $parents = $this.parents('.compAccRight');
        if ($parents.length) {
          $parents.parent().slideUp();
        } else {
          location.reload();
        }
      }

    }, 'JSON');
  });

  $('.addCompareAll').live('click', function(e) {
    var ids = [];
    $('.acResultComp a').each(function() {
      ids.push($(this).data('id'));
    });

    $.post('/manageCompare', { ids: ids, type: 'replace' }, function(notice) {
      if (confirm(notice))
            location.href = page_comparateur;
    });
  });

  $('.print').live('click', function(e) {
    window.print();
  });



  // Envoyer à un ami
  $('.sharemail').click(function(ev){
    ev.preventDefault();
    if ($('#formsendto').length) $('#formsendto').parent('div').remove();
    var d = $('<div style="display:none;"><form id="formsendto" ><input type="hidden" name="page" value="' + document.location.href + '" />'
        + '<p class="info">Merci de remplir tous les champs de ce formulaire</p>'
        + '<p><label for="s2fnomfrom">Votre nom</label><input id="s2fnomfrom" name="nomfrom" type="text" /></p>'
        + '<p><label for="s2femailfrom">Votre email</label><input id="s2femailfrom" name="emailfrom" type="text" /></p>'
        + '<p><label for="s2fnom">Le nom de votre ami</label><input id="s2fnom" name="nom" type="text" /></p>'
        + '<p><label for="s2femail">L\'email de votre ami(e)</label><input id="s2femail" name="email" type="text" /></p>'
        //+ '<p><label for="s2fmessage">Votre message</label><textarea id="s2fmessage" name="message"></textarea></p>'
        + '<p><input type="submit" value="Envoyer" /></p>'
        + '</form></div>');
    d.appendTo('body');
    $('#formsendto').submit(function(ev){
        ev.preventDefault();

        var errors = 0;
        var emailregexp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        if ($('#s2fnomfrom').val().replace(/^\s+/g,'').replace(/\s+$/g,'') == '') errors++;
        if ($('#s2fnom').val().replace(/^\s+/g,'').replace(/\s+$/g,'') == '') errors++;
        //if ($('#s2fmessage').val().replace(/^\s+/g,'').replace(/\s+$/g,'') == '') errors++;
        if ($('#s2femailfrom').val().replace(/^\s+/g,'').replace(/\s+$/g,'') == '' || !$('#s2femailfrom').val().match(emailregexp)) errors++;
        if ($('#s2femail').val().replace(/^\s+/g,'').replace(/\s+$/g,'') == '' || !$('#s2femail').val().match(emailregexp)) errors++;

        if (errors > 0){
            $('#formsendto p.info').css({color: "red"});
            return;
        }

        $.post('/send2friend', $(this).serialize(), function(data){
            alert('Merci, votre message a été envoyé.');
            $.colorbox.close();
        });
    });
    $.colorbox({
        inline: true,
        href: '#formsendto',
        width: 410,
        height: 320,
        close: 'fermer'
    });
  });

  $('#docsearch').submit(function(ev){
    ev.preventDefault();
    $.post('/docatl', $(this).serialize(), function(data){
      $('#documents').empty().html(data);
    });
  });
});
