jQuery.noConflict();
var jQ = jQuery;

/** GLOBAL VARS **/

cookie_name = 'blogorama_bar';
ie7 = jQ.browser.msie && parseInt(jQ.browser.version) == 7;
ie6 = jQ.browser.msie && parseInt(jQ.browser.version) == 6;

/** UTILITIES **/

/* aspect arrondi sur les canvas (IE only) */
function fillRoundedRect(x, y, w, h, r){
  this.beginPath();
  this.moveTo(x+r, y);
  this.lineTo(x+w-r, y);
  this.quadraticCurveTo(x+w, y, x+w, y+r);
  this.lineTo(x+w, y+h-r);
  this.quadraticCurveTo(x+w, y+h, x+w-r, y+h);
  this.lineTo(x+r, y+h);
  this.quadraticCurveTo(x, y+h, x, y+h-r);
  this.lineTo(x, y+r);
  this.quadraticCurveTo(x, y, x+r, y);
  this.fill();
}

/* conversion rgb en hexadécimal */
function rvb2hex(val){
  if (val.indexOf("rgb") >= 0)  {
    var rgb_string = val.slice(val.indexOf('(') + 1,val.indexOf(')'));
    var rgb_val = rgb_string.split(",");
    val = "#";
    var hexChars = "0123456789ABCDEF";
    for (var i = 0; i < 3; i++)  {
      var v = rgb_val[i].valueOf();
      val += hexChars.charAt(v/16) + hexChars.charAt(v%16);
    }
  }
  return val;
}

/******/

/* infobulle */
function infobulle() {  
  if(jQ('.infobulle').length > 0) {    
    jQ('.infobulle').each(function (i,avatar) {
      avatar = jQ(avatar);
      var infos = jQ.parseJSON(avatar.attr('rel'));
      avatar.mouseover(function() {
        var coord = avatar.offset();
        jQ('#infobulle').css({'top': coord.top + 'px', 'left': coord.left + 5 + avatar.innerWidth() + 'px'});
        jQ('#infobulle span.avat_pseudo').html(infos['pseudo']);
        descr = jQ('#infobulle span.avat_descr');
        descr.html(infos['descr']);
        jQ('#infobulle').show();
      });
      avatar.mouseout(function() {
        jQ('#infobulle').hide();
      });
    });
  }
}

/* survol sur les favoris */
function favoris() {
  jQ('#blogpotes li a').each(function(i,elt) {
    jQ(elt).mouseover(function() {
      jQ(elt).find('span.over').innerHTML = jQ(elt).find('span')[1].innerHTML;
      jQ(elt).find('span.over').css('display','');
    });
    jQ(elt).mouseout(function() {
      jQ(elt).find('span.over').innerHTML = '';
      jQ(elt).find('span.over').css('display','none');
    });
  });
}

/* liens rel=external forcés en target=_blank */
function externalLinks() {
	jQ('a[rel=\'external\']').each(function(i,elt) {
		if( jQ(elt).attr("href")) { jQ(elt).target = "_blank"; }
	});
}

/* affichage des smileys */
function showSmileys() {
  if(jQ('block-smileys').hasClass('shown')) { jQ('block-smileys').removeClass('shown'); }
  else { jQ('block-smileys').addClass('shown'); }  
  jQ('#block-smileys').slideToggle(500);
  return false;
}

/* formulaire d'identification */
function autologin(err) {
	if ( jQ('#loginCompte').val() == '' || jQ('#passwdCompte').val() == '') {
		jQ('#error_login').show();
		return false;
	}
	jQ('#error_login').hide();
	jQ('#loginblog').attr('action',jQ('#siteBlogorama').val());
	return true;
}

/* affichage des pubs */
function display_ads() {
  if(jQ('.boxgoogle_content').length > 0) {
    jQ('.boxgoogle_content').each(function(i,it) {
      jQ(it).css('display','block');
    });
  }
}

function popup_basename(path) {
    return path.replace(/\\/g, '/').replace(/.*\//, '');
}

/* affichage popup */
function popup(url,name,width,height) {
    //var basename = popup_basename(url);

    /* /image/rewrite-title.jpg -> /image/timestamp.jpg */ 
    //jQ('a[href$="'+ basename +'"]').each(function(i, it) { 
    //    var pattern = new RegExp("\\/"+ basename.replace(/\..*/g, ''), "g"); 
    //    url = '/image/'+ popup_basename(it.href.replace(pattern, '')).replace(/\./, '-');
    //});

	window.open(url,name,'scrollbars=yes,width='+width+',height='+height+''); 
	return true;
}

/* redimensionnement toutes les images des articles */
function redimAllImagesDescriptif() {
	return redimAllImagesBySize('div.header',740,99999, false);
}	
function redimAllImages() {
	return redimAllImagesBySize('div.text',525,99999, false);
}
function redimAllImages1000() {
	return redimAllImagesBySize('div.text',640,99999, true);
}
function redimAllImagesBySize(name,s1,s2, check) {
  if(check == false) {
  	if (!jQ.browser.msie) 
  		return false;
  }
	jQ(name).find('img').each( function(i,item) {
  		if (jQ(item).attr('src') != '' && jQ(item).attr('src') != undefined ) {
				// si item est une image, on redimensionne
				var currentTime = new Date();
				id = currentTime.getTime();
				jQ(item).attr('id','insertedimage-'+id); 
				redimImage(jQ(item),s1,s2);
			}
	});
	return true;
}
function redimImage(inImg, maxWidth, maxHeight) {
	// ratio
	var dW = 0;
	var dH = 0;
	oImg=inImg;

	if ( !oImg ) return;

  oImg.css({ position: "absolute", visibility: "hidden", display: "block" });
  var dim = {'width': oImg.outerWidth(),'height': oImg.outerHeight()};
  oImg.css({ position: "", visibility: "", display: "" });
	var h = dim.height;
	var w = dim.width;

	// non ie ou non compatible, on quitte
	if ( h == 0 || w == 0 ) return;

	var dW=0;
	var dH=0;
	// Si la largeur ou la hauteur depasse la taille maximale
	if ((h > maxHeight) || (w > maxWidth)) {
		// Si la largeur et la hauteur depasse la taille maximale
		if ((h >= maxHeight) && (w >= maxWidth)) {
			// On cherche la plus grande valeur
			if (h > w) {
				dH = maxHeight;
				// On recalcule la taille proportionnellement
				dW = parseInt((w * dH) / h, 10);
			} else {
				dW = maxWidth;
				// On recalcule la taille proportionnellement
				dH = parseInt((h * dW) / w, 10);
			}
		} else if ((h > maxHeight) && (w < maxWidth)) {
			// Si la hauteur depasse la taille maximale
			dH = maxHeight;
			// On recalcule la taille proportionnellement
			dW = parseInt((w * dH) / h, 10);
		} else if ((h < maxHeight) && (w > maxWidth)) {
			// Si la largeur depasse la taille maximale
			dW = maxWidth;
			// On recalcule la taille proportionnellement
			dH = parseInt((h * dW) / w, 10);
		}
	}
	if ( dW == 0 || dH == 0 ) 
		return;

	// redimensionnement
	oImg[0].width=dW;
	oImg[0].height=dH;
  oImg.show();

	return -1;
}
// appel avec delai
function delayredim(image,inMW,inMH) {
	redimImage(jQ(image),inMW,inMH);
}

/* fonctions relatives au vote */
function starOver(note,text) {
	jQ('#starbul').innerHTML=text;
	starInitJs(note);
}
function starOut() {
	starInitJs('');
	jQ('#starbul').innerHTML='&nbsp;';
}
function starInitJs(forcenote) {
	urlbase = jQ('#vote_urlbase').attr('value');
	if ( forcenote == '') {
		x = jQ('input[name=\'oldnote\']')[0];
		note = x.value;
	}	else {
		note = forcenote;
	}
	for (i=1;i<=5;i++) {
    y = jQ('input.starbtn[name=\'note'+i+'\']');
		if ( note < ( i - 0.6 ) ) {
			val=0;
			noteFinale = i;
		}
		else if ( note >= (i-0.6) && note < (i-0.3) ) {	val=1; }
		else { val=2;	}
		change = "background-image: url(\""+urlbase+val+".gif\");";
		if ( change != 	y.attr('style') ) {
    	jQ(y)[0].style.cssText="background-image: url("+urlbase+val+".gif);";
		}
	}
}

/* */
function replaceVid(id,type) {
	obj = jQ('#flv'+id);
	flv = jQ("#val"+id).val();

	if ( type == 'webcam' ) {
		url = '/webcam/'+flv+'/';
	}
	else {
		url = '/movie/'+flv+'/';
	}
	
  /* Ajax call */
	jQ.ajax({
    type: 'POST',
    processData: true,
    url: url,
    dataType: 'html',
    success: function(data){
      jQ('#flv'+id).html(data);
    }
  });	
}

/* Toggle the basic theme header */
function descToggle() {
	jQ('#infoBlogOFF').toggle();
	jQ('#infoBlogON').toggle();

	// We need to hide the objects because our deer Internet Explorer don't like that when we hide a block
	jQ('#infoblogON object').each(function() {
		this.toggle();
	});
	jQ('#infoblogON embed').each(function() {
		this.toggle();
	});
}

/* évènements sur onglets du formulaire d'ajout de commentaires */
function comment_show(type) {

  if(typeof(type) == 'string') {
  
    if(type == 'texte') {
    
      jQ('#codeCommTxt').show();
      jQ('#codeCommWebcam').hide();
      
      if(!jQ('.comment-tabs-texte').hasClass('selected')) {
        jQ('.comment-tabs-texte').addClass('selected'); 
      }
      if(jQ('.comment-tabs-webcam').hasClass('selected')) {
        jQ('.comment-tabs-webcam').removeClass('selected'); 
      }
      
      /* gabarits 700 */
      jQ('#form-ajout-commentaire div.bt-submit-form-texte').show();
      jQ('#form-ajout-commentaire').css({'height':'auto'});
      jQ('#form-ajout-commentaire p.warning').css({'position':'relative','bottom':0});
      
    } else {
    
      jQ('#codeCommWebcam').show();
      jQ('#codeCommTxt').hide();
      
      if(jQ('.comment-tabs-texte').hasClass('selected')) {
        jQ('.comment-tabs-texte').removeClass('selected'); 
      }
      if(!jQ('.comment-tabs-webcam').hasClass('selected')) {
        jQ('.comment-tabs-webcam').addClass('selected'); 
      }      
      /* gabarits 700 */
      var h = jQ('#codeCommWebcam').height() + jQ('#form-ajout-commentaire p.warning').height();
      jQ('#form-ajout-commentaire div.bt-submit-form-texte').hide();
      jQ('#form-ajout-commentaire').css({'position':'relative','height':h+'px'});
      jQ('#codeCommWebcam').css({'position':'absolute','top':jQ('#form-ajout-commentaire').css('padding-top'),'left':jQ('#form-ajout-commentaire').css('padding-left')});
      jQ('#form-ajout-commentaire p.warning').css({'position':'absolute','bottom':jQ('#form-ajout-commentaire').css('padding-bottom')});

    }
    
  } else {
    return false;
  }
  
}

/* chargement de la fancybox */
function fancyBox() {
  var fancyboxes = jQ('.fancybox');
  fancyboxes.each(function(i,el) {
    var popup_url = jQ(el).attr('href');
    
    if(popup_url.match(/\/fans\/a\//g)) {
      popup_url = popup_url.replace(/\/fans\/a\//g, '/fans/a/popup/');  
    } else {
      popup_url += 'popup/';
    }
    
    jQ(el).fancybox({
  		'width'				: 432,
  		'height'			: 601,
  		'autoScale'			: false,
  		'transitionIn'		: 'none',
  		'transitionOut'		: 'none',
  		'type'				: 'iframe',
  		'centerOnScroll' : true,
  		'overlayColor' : '#000',
  		'href' : popup_url,
  		'titleShow' : true,
  		'titlePosition' : 'inside',
  		'titleFormat' : formatTitle,
  		'padding' : 2
    });
  });
}

/** ÉVÈNEMENTS DOM:READY, ONRESIZE ET ONLOAD **/

jQ(document).ready(function() {
  // redimensionnement des images présentes dans les articles
  if (is_1000 == true) {
	  redimAllImages1000();
  } else {
    redimAllImages();
  }
  
  // on force les liens rel=external en target=_blank
	externalLinks();
	
	// survol des favoris 
  if(is_1000 == true) { favoris(); }
  
  // chargement de la toolbar et de fancybox
  if(!ie7) { 
    loadBar();
    fancyBox();
  }
});

jQ(window).load(function(){
  // infobulles sur avatars
  infobulle();
  
  // chargement de la toolbar pour IE7
  if(ie7) {
    loadBar();
    fancyBox();
  }

  //bugfix on round corners on IE<9 for $('comment_form') type  
  if(jQ.browser.msie && parseInt(jQ.browser.version) < 9) {
    if(jQ('canvas').length > 0 && jQ(jQ('canvas')[0]).css('display') != 'none') {  
      var cf = jQ('#comment_form'); 
      var canvas = jQ('#canvas')[0];
      var canvas_ = jQ('#canvas_')[0];
      var bg = jQ('#end').css('background-color');
      if (canvas.getContext) {
        canvas.height = cf.innerHeight();
        var ctx = canvas.getContext('2d');
        CanvasRenderingContext2D.prototype.fillRoundedRect = fillRoundedRect;
        ctx.fillStyle = bg;
        ctx.fillRoundedRect(0, 0, cf.innerWidth(), cf.innerHeight(), 5);
        var ctx_ = canvas_.getContext('2d');
        ctx_.fillStyle = bg;
        ctx_.fillRoundedRect(0, 0, jQ(canvas_).parent('div').innerWidth(), jQ(canvas_).parent('div').innerHeight(), 5);
        jQ('#comment-tabs li a').click(function() {        
          canvas.height = cf.innerHeight();
          ctx.fillStyle = bg;
          ctx.fillRoundedRect(0, 0, cf.innerWidth(), cf.innerHeight(), 5);        
        });
      }  
  	}
	}

  //bugfix sur ie6
  if(ie6) {
    jQ('.known-user-pswd').css({'display':'block','zoom':'1'});
  }
  
  // affichage des pubs
  display_ads();
});

