// Set the width and height arrows to the actual
// values of the given image.
// We make them 15px shorter than the image to make them look "tighter".

function adapt_arrow_size_to_product() {
	var img_height = $('center-stage').getHeight();
	$('height').style.height = (img_height - 15) + 'px';
	$('width').style.width = ($('center-stage').getWidth() - 15) + 'px';
	$('height').style.top = Math.floor((img_height - $('height').getHeight()) / 2) + 'px';
}

// Vertically center the product pictos.
// The only way I can see how to do this in CSS is with a table :(
function vertically_center_pictos() {
	$('pictos').style.top = Math.floor(($('center-stage').getHeight() - $('pictos').getHeight()) / 2) + 'px';
}
function SD_GetLove() {
	return iLove;
}
function SD_SetLove(n, prefix) {
	iLove = n;
	if(prefix == 'B')
	{

	$('user_rating_B').value=iLove;

	}else{

	$('user_rating').value=iLove;
	
	}
	for (i=1; i<=5; i++) {$(prefix+'star'+i).src="/images/imgsite/product/picto_star_off.gif";}
	for (i=1; i<=n; i++) {$(prefix+'star'+i).src="/images/imgsite/product/picto_star_on.gif";}
}

var is_currently_toggling = false;

function start_toggle() {
	is_currently_toggling = true;
}
function end_toggle() {
	is_currently_toggling = false;
}

function ie_start_fix() {
	if (Prototype.Browser.IE) {
		$$('table.mobile-list tr.pic-row td div').each(function(el){
			$(el).setStyle({position:'static'});
		})	
	}
}

function ie_end_fix() {
	if (Prototype.Browser.IE) {
		$$('table.mobile-list tr.pic-row td div').each(function(el){
			$(el).setStyle({position:'relative'});
		})	
		$$('table.mobile-list tr.pic-row td div.reducPng').each(function(el){
			$(el).setStyle({position:'absolute'});
		})
	}
}

function pageNumberingProduct(page){
	$('loadingProduct').show();
	new Ajax.Updater({ success: 'tab4'},'/ajax/product.ajax.php?page='+page,
	{
		method: 'get',
		onComplete: function(){
			$('loadingProduct').hide();
			if (Prototype.Browser.IE){
			    $$('a.select').each(function(el){
					Event.observe(el, 'click', function(ev){
					    Event.stop(ev);
					     cartAddMobile(el);
					   });
				    });
			 }else{
			     
			     if(page == 1){
				    $$('a.select').each(function(el){
				        Event.observe(el, 'click', function(ev){
					    Event.stop(ev);
					    cartAddMobile(el);
					   });
				     });
				}else{
				    $$('a.select').each(function(el){
					Event.observe(el, 'click', function(ev){
					    Event.stop(ev);
					     cartAddMobile(el);
					     
					});
				    });
				}
                         }	
			if (Prototype.Browser.IE && parseInt(navigator.appVersion.match( /msie (\d+)/i )[1]) == 6) {
				 $$('a.compare').each(function(el){
					Event.observe(el, 'click', function(ev){
					    Event.stop(ev);
					    add_to_session_store(el);
					});
				 });

				
			}else{
				 $$('a.compare[rel]').each(function(el){
				    Event.observe(el, 'click', drawer.compare_button_handler.bindAsEventListener(drawer));
				});
			
			}	
			
		}
	});
}


function pageNumberingComment(pageComment){
	$('loading').show();
	new Ajax.Updater({ success: 'comments'},'/ajax/comment.ajax.php?pageComment='+pageComment,
	{
		method: 'get',
		onComplete: function(){
			$('loading').hide();
		}
	});
}
function MessageAlert(){

	$('alert').update('Votre commentaire a bien été enregistré. Il sera mis en ligne, sous réserve de modération.').setStyle({ color: '#000' });

}

function addCommentProduct() {

 var bParamCheckOK = true;
  var reEmail = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;

   	if(!reEmail.test(trim($F('email'))) || trim($F('email')) == ""){

           $("email").addClassName('error');
	   $('errCommentEmail').innerHTML = "Vous y êtes presque ! Il ne vous reste qu'à renseigner votre email !";
	   $('errCommentEmail').show();
	   bParamCheckOK = false;

	 } else {
	   
	   $('email').removeClassName('error');
	   $('errCommentEmail').hide();
	 
	 }
        
	if(isNaN($F('user_rating')) || (trim($F('user_rating')) == "")){
	     
	    $('errCommentRating').innerHTML = "N'oubliez pas de donner une note à votre petit camarade !";
	    $('errCommentRating').show();
	    bParamCheckOK = false;
	 
	 } else {

	      $('errCommentRating').hide();
	 }

	if((trim($F('nom')) == "")){

	   $("nom").addClassName('error');
	   $('errCommentName').innerHTML = "Et bah alors ? On ne veut pas renseigner son nom ?";
	   $('errCommentName').show();
	   bParamCheckOK = false;
	
	}else{
          
	  $('nom').removeClassName('error');
	  $('errCommentName').hide();
	
	}
	
	 if((trim($F('captcha')) == "")){
	
	   $("captcha").addClassName('error');
	   $('errCommentCaptcha').innerHTML = "Vous devez correctement recopier le code ci-contre.";
	   $('errCommentCaptcha').show();
	   bParamCheckOK = false;
        
	}else{
        
	   var params = 'captcha='+(trim($F('captcha')));
	
	   new Ajax.Request('/ajax/checkCap.ajax.php?action=captcha',
	   {  
	    	asynchronous:true,
		method: 'post',
		parameters: params,

		onSuccess: function(t){

		      if(t.responseText == 'true'){
			  
			    $('captcha').removeClassName('error');
			    $('errCommentCaptcha').hide();
			  
                      }else{
			  
			   $("captcha").addClassName('error');
			   $('errCommentCaptcha').innerHTML = "Vous devez correctement recopier le code ci-contre.";
			   $('errCommentCaptcha').show();
			   bParamCheckOK = false;
			  
                      }
		}
	   });

	}

    if(bParamCheckOK != false && $F('user_rating') != "" && $F('nom') != "" && $F('email') != "" && $F('comment') != "" && $F('captcha') != "") {

	var params = $('formCommentTop').serialize();
      
	new Ajax.Request('/ajax/comment.ajax.php?action=insertComment',
	{  
	    asynchronous:true,
	    method: 'post',
	    parameters: params,
	    
	    onSuccess: function(){

		  Form.reset('formCommentTop');
 		  $$('#specs form').each(Element.hide);
		  MessageAlert();


	    },
	   
	    onFailure: function(){

		   alert("Error !");

		}	
       })
    }
}

/* function addCommentProductBot() {
var bParamCheckOK = true;
 var reEmail = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;

   	if(!reEmail.test(trim($F('emailBot'))) || trim($F('emailBot')) == ""){

           $("emailBot").addClassName('error');
	   $('errCommentEmailBot').innerHTML = "Vous y êtes presque ! Il ne vous reste qu'à renseigner votre email !";
	   $('errCommentEmailBot').show();
	   bParamCheckOK = false;

	 } else {
	   
	   $('emailBot').removeClassName('error');
	   $('errCommentEmailBot').hide();
	 
	 }
        
	if(isNaN($F('user_rating_B')) || (trim($F('user_rating_B')) == "")){
	     
	    $('errCommentRatingBot').innerHTML = "N'oubliez pas de donner une note à votre petit camarade !";
	    $('errCommentRatingBot').show();
	    bParamCheckOK = false;
	 
	 } else {

	      $('errCommentRatingBot').hide();
	 }

	if((trim($F('nomBot')) == "")){

	   $("nomBot").addClassName('error');
	   $('errCommentNameBot').innerHTML = "Et bah alors ? On ne veut pas renseigner son nom ?";
	   $('errCommentNameBot').show();
	   bParamCheckOK = false;
	
	}else{
          
	  $('nomBot').removeClassName('error');
	  $('errCommentNameBot').hide();
	
	}
	
	if((trim($F('captchaBot')) == "")){

	   $("captchaBot").addClassName('error');
	   $('errCommentCaptchaBot').innerHTML = "Vous devez correctement recopier le code ci-contre.";
	   $('errCommentCaptchaBot').show();
	   bParamCheckOK = false;
        
	}else{
          
	   var params = 'captcha='+(trim($F('captchaBot')));
	
	   new Ajax.Request('/ajax/checkCap.ajax.php?action=captcha',
	   {  
	    	asynchronous:true,
		method: 'post',
		parameters: params,

		onSuccess: function(t){

		      if(t.responseText == 'true'){
			  
			    $('captchaBot').removeClassName('error');
			    $('errCommentCaptchaBot').hide();
			  
                      }else{
			  
			   $("captchaBot").addClassName('error');
			   $('errCommentCaptchaBot').innerHTML = "Vous devez correctement recopier le code ci-contre.";
			   $('errCommentCaptchaBot').show();
			   bParamCheckOK = false;
			  
                      }
		      
		}
	   });
	

	}
	
   	if(bParamCheckOK!= false && $F('user_rating_B') != "" && $F('nomBot') != "" && $F('emailBot') != "" && $F('commentBot') != "" && $F('captchaBot') != "") {

	    var params = $('formCommentBot').serialize();

	    new Ajax.Request('/ajax/comment.ajax.php?action=insertComment&type=B',
	    {  
		asynchronous:true,
		method: 'post',
		parameters: params,

		onSuccess: function(){

		     Form.reset('formCommentBot');
		     $$('#specs form').each(Element.hide);
		     MessageAlert();

		    },

		onFailure: function(){
		    alert('ERROR');		    

		    }	
	   })
	}
} */	
	        
        
document.observe('dom:loaded', function(){
        
	adapt_arrow_size_to_product();
	vertically_center_pictos();
	
	$('loadingProduct').hide();
	
	/*Submit Comments
        Event.observe(window, 'load', function() {
            Event.observe('formCommentTop', 'submit', addCommentProduct);
        });
	//Submit Comments Button
        Event.observe(window, 'load', function() {
            Event.observe('formCommentBot', 'submit', addCommentProductBot);
        });
       */
	// Handle the thumbnails
	// When you click on a thumbnail, we display the large image.
	$$('#thumbs a').each(function(el){
		$(el).observe('click', function(ev){
			//console.log(this);
			//Event.stop(ev); return false;
			$('center-stage').src = this.href;
			if ($$('#thumbs a.selected')[0])
				$$('#thumbs a.selected')[0].removeClassName('selected');
			this.addClassName('selected');
			Event.stop(ev);
		})
	})
	
	$('center-stage').observe('load', function(){
		adapt_arrow_size_to_product();
		vertically_center_pictos();
	})
	
	
	// Setup the accordion effects (expandable / collapsable panels).	
	$$('#specs h6 span.arrow').each(function(el){
		$(el).observe('click', function(ev){
			if (Effect.Queues.get('global').size() > 0) {
				return false;
			}
			var displayId = $(el).id.substring(11);
			var displayType = '';
			displayType = $('display-pane-'+displayId).getStyle('display');
			if(displayType == 'none'){
				new Effect.SlideDown('display-pane-'+displayId, {duration: 0.6, queue: 'end'});
				$(this).toggleClassName('open');
			}else{
				new Effect.SlideUp('display-pane-'+displayId, {duration: 0.6, queue: 'end'});
				$(this).toggleClassName('open');
			}
		});
	});
	
	$$('#prix-selon-offre h6 span.arrow').each(function(el){
		$(el).observe('click', function(ev){
			if (Effect.Queues.get('global').size() > 0) {
				return false;
			}
			var displayId = $(el).id.substring(11);
			var displayType = '';
			displayType = $('display-pane-'+displayId).getStyle('display');
			if(displayType == 'none'){
				new Effect.SlideDown('display-pane-'+displayId, {duration: 0.6, queue: 'end', beforeStart:ie_start_fix, afterFinish:ie_end_fix});
				$(this).toggleClassName('open');
			}else{
				new Effect.SlideUp('display-pane-'+displayId, {duration: 0.6, queue: 'end', beforeStart:ie_start_fix, afterFinish:ie_end_fix});
				$(this).toggleClassName('open');
			}
		});
	});
	
	// The panes are closed, except for the first one, that is left open by default.
	['display-pane-excess', 'display-pane-prepaye', 'display-pane-bloque'].each(function(item){
		$(item).hide();
		$('toggle-for-' + item.substring(13)).toggleClassName('open');
	})
	
	
	// Handle specification tabs.
	$$('#specs ul a').each(function(el){
		$(el).observe('click', function(ev){
			var target = this.href.replace(/^[^#]+#(.*)$/, "$1");
			
			$$('#specs .tab-content').each(function(ele){
				$(ele).hide();
			})
			$(target).show()

            if(target == 'tab3'){
                pageNumberingComment(1);
            }else if(target == 'tab4'){
                pageNumberingProduct(1);
            }

            if ($$('#specs li.selected')[0]) {
				$$('#specs li.selected')[0].removeClassName('selected');
			}
			this.up().addClassName('selected');
           
			//console.log(target);
			Event.stop(ev);
		})
	})
	$$('#specs div.tab-content').each(function(ele){
		$(ele).hide();
	})
	// By default, show the selected panel.
	if ($$('#specs li.selected a')) {
		var targ = $$('#specs li.selected a')[0].href.replace(/^[^#]+#(.*)$/, "$1");
		$(targ).show();
         }
	
	
	$$('#specs form').each(Element.hide);
	$('addCommentTop').observe('click',function(ev){
		Event.stop(ev);
		if (Effect.Queues.get('global').size() > 0) {
			return false;
		}
		if ($('formCommentTop').visible()) {
			new Effect.SlideUp('formCommentTop', {duration: 0.6, queue: 'end'});
		} else {
			new Effect.SlideDown('formCommentTop', {duration: 0.6, queue: 'end'});
		}
		
	});
	/* $('addCommentBot').observe('click',function(ev){
		Event.stop(ev);
		if (Effect.Queues.get('global').size() > 0) {
			return false;
		}
		if ($('formCommentBot').visible()) {
			new Effect.SlideUp('formCommentBot', {duration: 0.6, queue: 'end'});
		} else {
			new Effect.SlideDown('formCommentBot', {duration: 0.6, queue: 'end'});
		}
	}); */
	
	// The weight widget/chart thing.
	// Converts a percentage of weight (relatively to the other phones)
	// to a bar graph.
	var weight_ratio = parseInt($$('#weight-widget span')[0].innerHTML);
	var offset = Math.floor((74 / 100) * weight_ratio);
	var pos_x = 74 - offset;
	$$('#weight-widget span')[0].style.backgroundPosition = '-'+ pos_x + 'px 0px';
	
	
	// Display the comments tab first if #tab3 is found in document.location
	var domaine=document.location.toString();
	var extensionComment = "#tab3";
	var nWhere = domaine.indexOf(extensionComment);
	var ongletCommentaires = document.getElementById('ongComment');
	var ongletDescription = document.getElementById('ongDesc');
	var extensionSendFriend= "#sendf";
	var nWhereS = domaine.indexOf(extensionSendFriend);
	var layerSendFriend = document.getElementById('sendFriend');
	var extensionfb= "#fb";
	var nWherefb = domaine.indexOf(extensionfb);
	var layerfb = document.getElementById('display-pane-bloque');
	
	if (nWhere > -1)
	{
		$$('#specs div#tab1').each(Element.hide);
		$$('#specs div#tab3').each(Element.show);
		pageNumberingComment(1);
		$$('#specs li.selected')[0].removeClassName('selected');
		$$('#specs li')[2].addClassName('selected');
		document.location.href=extensionComment;
	}
	else if (nWhereS > -1)
	{
		layerSendFriend.style.display="block";
	}
	
 
	
	else if (nWherefb > 1)
	{
	var layercurseur = document.getElementById('toggle-for-bloque');
	layerfb.style.display="block";

    layercurseur.addClassName('open');
	}
	
	else
	{
		return false;
	}

})
