//-----------------------------------------------------------------------------------------------
var ImageHover = {
		
  init: function(elements, divImg, divA){
    $(elements).hover(
      function() {
        if($(this).attr('rel') != 'undefined')
          ImageHover.changeImage(divImg, $(this).attr('rel'), $(this).text());
        if($(this).attr('url') != 'undefined')
          ImageHover.changeLienImage(divA, $(this).attr('url'));
      },
      function() { }
      );
  },
	
  initBg: function(elements, divImg){
    $(elements).each(function() {
			
      if($(this).attr('rel') != 'undefined')
        $(this).hover(function() {
          ImageHover.changeImageBg(divImg,$(this).attr('rel'));
        }, function() {});
    });
  },
	
  changeImage: function(el, imgpath, imgalt){
    $(el).attr({
      'src': imgpath
    });
  },
	
  changeLienImage: function(el, url){
    $(el).attr({
      'href': url
    });
  },
	
  changeImageBg: function(el, imgpath){
    $(el).attr('style','background-image:url('+imgpath+');');
  //console.log($(el));
  }
	
};
//-----------------------------------------------------------------------------------------------
var Pagination = {		
  init: function(selectboxes,submitBtns){
    $(selectboxes).bind("change",function(e){
      $(this).parent("form").get(0).submit();
    });
    $(submitBtns).css("display","none");
  }
};

//-----------------------------------------------------------------------------------------------

var Product = {		

	
  initCrosselling: function(){
    $('#similar_products > a').click(function(e){
						
      e.preventDefault();
      Loading.on();
						
      $.get($(e.target).attr('rel'), function(data){
        $('.col3 .inner').html(data);
        Product.initCrosselling();
        Loading.off();
      });
    });
  },
	
  initProductUpdate: function(container, selectBoxes, BtnUpdate, zoneProductStock, zoneProductPrice) {
    //recup des urls sur l'attribut rel du bouton
    var initdata =new Array();
		
    $(container).each(function(i,el) {
      var c = this;
				
      initdata[i] = new Array();
      initdata[i]["stock"] = $(zoneProductStock,c).html();
      initdata[i]["price"] = $(zoneProductPrice,c).html();


      var ajaxUrl = $(BtnUpdate,this).attr('rel');
      if (!ajaxUrl) return false;
      var ajaxUrlArray = ajaxUrl.split('|');
				
      //ajout des evenements sur les select boxes
      $(selectBoxes,this).change(function(e) {
        if($(selectBoxes,c).eq(1).val() != "" && $(selectBoxes,c).eq(0).val() != "")
        {
          Loading.on();
          $(selectBoxes,c).attr('disabled',true);
						
          $.get(ajaxUrlArray[0], {
            color: $(selectBoxes,c).eq(1).val(),
            size: $(selectBoxes,c).eq(0).val()
          }, function(data) {
            $(zoneProductStock,c).html(data);
            $.get(ajaxUrlArray[1], {
              color: $(selectBoxes,c).eq(1).val(),
              size: $(selectBoxes,c).eq(0).val()
            }, function(data) {
              $(zoneProductPrice,c).html(data);
              Loading.off();
              $(selectBoxes,c).removeAttr('disabled');
              Panier.initSubmit('.formbuy', '#ajaxajout');
              Product.initPlusMoins('.plus','.moins');
            });
          });
        } else {
          $(zoneProductStock,c).html(initdata[i]["stock"]);
          $(zoneProductPrice,c).html(initdata[i]["price"]);
							
							
        }
      });
      $(BtnUpdate,this).css('display','none');
    });
		
  },
	
  initPlusMoins: function(selPlus,selMoins) {
		
    $(selPlus).each(function(){
      $(this).css({
        visibility: "visible"
      });
      $('img',this).click(function(e){
        e.preventDefault();
        var quantity = $('input', $(e.target).parent().parent());
        if(quantity.val() <=  0)
          quantity.val(1);
        else if(quantity.val() < 99) 
          quantity.val(parseInt(quantity.val())+1);
				
      });
    });
		
    $(selMoins).each(function(){
      $(this).css({
        visibility:"visible"
      });
      $('img', this).click(function(e) {
        e.preventDefault();
        var quantity = $('input', $(e.target).parent().parent());
        if(quantity.val() >= 1)
          quantity.val(parseInt(quantity.val())-1);
        else if(quantity.val() < 0)
          quantity.val(1);
      });
    });
  }
};

//-----------------------------------------------------------------------------------------------

var Loading = {		
  init: function() {
    $('body').append('<div id="loading">chargement</div>');
  },
  on: function(){
    $('#loading').addClass('on');
  },
  off: function(){
    $('#loading').removeClass('on');
  }
};

//-----------------------------------------------------------------------------------------------

var Popup = {
  initSharePopup: function() {
		
		
  }
};

var Panier = {
	
  initSubmit: function(formAjout,zoneAjout) {
    $(formAjout).submit(
      function(e) {
        var ajaxUrl = $(e.target).attr('rel');
        var ajaxUrlArray = ajaxUrl.split('|');
        var products_attributes_id = $("#products_attributes_id").val();
        var cart_quantity = $("#cart_quantity").val();
        Loading.on();

        $(e.target).ajaxSubmit({
          url:ajaxUrlArray[0],
          success:function(data){
            $('#ajaxajout').html(data);
            $.get(ajaxUrlArray[1], function(d) {
              $('#shoppingcartcontainer').html(d);Panier.intitSlidingCart();
            });
            hideSelects();
            $('#ajaxajout').fadeIn();
            $('#blackscreen').show();
            $('#blackscreen').fadeTo('normal',0.5);
            Loading.off();
            Panier.initInner('#ajaxajout', '#close');
																																											 
          }
        })
        /*$.post(ajaxUrlArray[0], {'products_attributes_id':products_attributes_id,'cart_quantity':cart_quantity}, function(data) {
					 																																															
								$(zoneAjout).html(data);
								$.post(ajaxUrlArray[1], function(d) {$('#shoppingcartcontainer').html(d);Panier.intitSlidingCart(); });
								hideSelects();
								$(zoneAjout).fadeIn();
								Loading.off();
								Panier.initInner(zoneAjout, '#close');
			});*/
        return false;
																							
      }
      );
		
  /*$(btnAjout).click(function(e) {
			e.preventDefault();
			//e.stopPropagation();
			form = $(e.target).parents('form').get(0);
			
			url = $(form).attr('rel');
			$.post(url, null, function(data) {
								$(zoneAjout).html(data);
								$(zoneAjout).fadeIn();
								Panier.initInner(zoneAjout, '#close');
			});
			
			
		});*/
  },
	
  initPanierPliable: function() {
		
  },
	
  initInner: function(cont,closebtn) {
    $(cont+' '+closebtn).click(function(e) {
      $(cont).fadeOut();
      $('#blackscreen').fadeOut();
      e.preventDefault();
      showSelects();

    });
  },
	
  intitSlidingCart: function() {
    $("#shoppingcartcontainer a.opencart").click(function(e) {
      $("#panierajax").slideToggle();
      e.preventDefault();

    });
		
  }
	
};

//-----------------------------------------------------------------------------------------------

var Galerie = {
  init: function(imgs,bigimg, bigimgA) {
    $(imgs).click(function(e) {
      //console.log($(this).attr('href'));
      $(bigimg).attr({
        'src': $(this).attr('href'),
        'rel': $(this).attr('rel')
      });
      e.preventDefault();
    });
    $(imgs).mouseover(function(e) {
      //console.log($(this).attr('href'));
      $(bigimgA).attr({
        'href': $(this).attr('href'),
        'rel': $(this).attr('rel')
      });
      $(bigimg).attr({
        'src': $(this).attr('href'),
        'rel': $(this).attr('rel')
      });
      e.preventDefault();
    });
     
  },
	
  initZoom : function(zoomlink, bigimg) {
    $(zoomlink).click(function(e) {
      img = ($(bigimg).attr('src'));
      url = 'popup_zoom_image.php?img='+img+'&KeepThis=true&TB_iframe=true&height=500&width=600';
      tb_show('',url,'');
      e.preventDefault();
    });
  }
};

//-----------------------------------------------------------------------------------------------
Tooltips = {
  init: function(classstr) {
    $(classstr).hover(function(e) {
      if($(e.target).is("a"))
        var l = $(e.target)
      else
        var l = $(e.target).parent();
			
      l.tooltip({
        track: true,
        opacity:1,
        bodyHandler: function() {
          //	console.log($(this));
          return $.ajax({
            async:false,
            type: "GET",
            url: $(this).attr('rel')
          }).responseText;
        },
        showURL: false
      });
    }, function(){});
  }
	
};
//-----------------------------------------------------------------------------------------------

$(document).ready(function(){										 
  Loading.init();
  
  ImageHover.init( "#products_menu li" , "#catlistimg img:first", "#catlistimg a:first" );
  ImageHover.initBg( "#univers li" , "#univers .inner" );
  Pagination.init(".filterpagination form select", ".filterpagination form :submit");

  //fiche produit
  //Product.initCrosselling();
  
  
  Product.initProductUpdate("#product_main", "select", ".btnUpdateProduct", ".zoneProductsStock",".zoneProductsPrice");
  //fiche produit rse
  Product.initProductUpdate(".product_info", "select", ".btnUpdateProduct", ".zoneProductsStock",".zoneProductsPrice");

  Product.initPlusMoins('.plus', '.moins');

  Galerie.init('.product_tns li a, .product_images img:first', '.product_images img:first', '.product_images a:first');
  //Galerie.initZoom('.zoomline a, .product_images img:first','.product_images img:first');

  zoom_toggle = function(){
    $('#viewport').css({'height':($(window).height()-20)+'px','top':($(window).scrollTop()+10)+'px'});
    $('#viewport').show();
    $('#overlay').css ({'height':$('body').height()+'px','width':$('body').width()+'px'});
    $('#overlay').show();
    $('select').hide();
    $('#closeZoom').click(function() {
        $('#viewport').hide();
        $('#viewport').css({'background-image':'none'});
        $('#overlay').hide();
        $('select').show();
        return false;
      });
    return false;
  }
  $('.zoomline, #bigimg').click(function() {
    $('.ul-zoom').zoom({
        divName:'#viewport',
        drag:false,
        loupe:false,
        startEvent: 'mouseover',
        kbControl:true,
        zoomTrack:false,
        loaderImg : 'templates/Afibel/images/common/ajax-loader.gif'
      });
    return zoom_toggle();
    
  });
  $('#overlay').click(function() {
    $('#viewport').hide();
    $('#viewport').css({'background-image':'none'});
    $('#overlay').hide();
    $('select').show();
    return false;
  });

  Tooltips.init('.tooltip');

  //Panier.initInner('#ajaxajout', '#close');
  Panier.intitSlidingCart();
  Panier.initSubmit('.formbuy', '#ajaxajout');
  Assurance.initSubmit('.form_assurance', '#ajaxajout');

  $('#maincontainer').append('<div id="blackscreen" style="z-index:50;position:absolute;background-color:#333;top:0;left:0;"></div>');
  $('#blackscreen').hide();
  $('#blackscreen').fadeTo('normal',0);
  $('#blackscreen').width( $('#maincontainer').width() + $('body').scrollLeft() );
  $('#blackscreen').height( $('body').height() + $('body').scrollTop() );
});

//-----------------------------------------------------------------------------------------------
function affichagevideo(name,text,title) {
  url = 'popup_video_image.php?src='+name+'&text='+text+'&title='+title+'&KeepThis=true&TB_iframe=true&height=160&width=700';
  tb_show('',url,'');
}

function affichagewishlist() {
  url = 'popup_video_image.php?src='+name+'&text='+text+'&title='+title+'&KeepThis=true&TB_iframe=true&height=160&width=700';
  tb_show('',url,'');
} 
function affichagegrandevideo(name) {
  url = 'popup_grande_video_image.php?src='+name+'&KeepThis=true&TB_iframe=true&height=350&width=700';
  tb_show('',url,'');
}



function hideSelects() {

  if($.browser.msie && jQuery.browser.version.substr(0,1) == "6")
    $("select").css({
      visibility: "hidden"
    });
}

function showSelects() {
  if($.browser.msie && jQuery.browser.version.substr(0,1) == "6")
    $("select").css({
      visibility: "visible"
    });
	
}
//debug 

function trace(s) {
//console.log(s);
}

function naviguerTo(lien) { //fonction permettant au flash de faire des liens de medias vers www
  document.location = lien;
}
//-----------------------------------------------------------------------------------------------

var Assurance = {
  initSubmit: function(formAjout,zoneAjout) {
    $(formAjout).submit(

      function(e) {
        var ajaxUrl = $(e.target).attr('rel');
        var ajaxUrlArray = ajaxUrl.split('|');  
        Loading.on();

        $(e.target).ajaxSubmit(
        {
          url:ajaxUrlArray[0],
          success:function(data){
            $('#ajaxajout').html(data);
            $('#ajaxajout').fadeIn();
            $('#blackscreen').show();
            $('#blackscreen').fadeTo('normal',0.5);
            Loading.off();
            return false;
          }
        }
        );
        return false;
      }
      );
  }
};

function only_car(champ)
{
	var chiffres = new RegExp("[a-zA-Z]");
	var verif;
	var points = 0;
	for(x = 0; x < champ.value.length; x++)
	{
    verif = chiffres.test(champ.value.charAt(x));
	  if(champ.value.charAt(x) == "."){points++;}
    if(points > 1){verif = false;points = 1;}
  	if(verif == false){champ.value = champ.value.substr(0,x) + champ.value.substr(x+1,champ.value.length-x+1);x--;}
	}
}
function naviguerTo(lien) {
  document.location = lien;
}

var fonction=(function($){
  $(document).ready(function(){			
    $('#guide1ereVisite').bind('click',function(e){					
      url = 'popup_1ere_visite.php?KeepThis=true&TB_iframe=true&height=540&width=960';
      tb_show('',url,'');	
      return false;					
    });
    $('#fleche_taille').bind('click',function(e){
       $('#taille_filter ul').attr('style', 'display: block;')
      return false;
    });
    $('#fleche_coloris').bind('click',function(e){
      if( $('#coloris_filter ul') )
       $('#coloris_filter ul').attr('style', 'display: block;')
      return false;
    });

  });	
})(jQuery);
