var baseurl = "http://www.bombe.tv/";
//var baseurl = "http://localhost/BombeTv/";

var preroll_active = false;
var body_loaded = 10;
//changeTabs
function changeTabs(elemName, newImg, newStyle){
	document.getElementById("img-"+elemName).src = newImg;
	document.getElementById("div-"+elemName).style.display = newStyle;
}

function goto(url){
	window.location.href=url;
}

//validate email address
function isValidEmail(str) {
		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
		   return false
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return false
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return false
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return false
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return false
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return false
		 }
		
		 if (str.indexOf(" ")!=-1){
		    return false
		 }

 		 return true					
	}

//contest
 function validateConcours(){
	error = "";
	if (document.getElementById('fname').value == "")		error += "Prénom est vide\n";
	if (document.getElementById('lname').value == "")		error += "Nom est vide\n";
	if (document.getElementById('email').value == "")		error += "Email est vide\n";
	else if(isValidEmail(document.getElementById('email').value)==false)		error += "Email n'est pas valide\n";

	if (error == "") return true;
	else{
		alert("SVP corrigé les erreurs suivant \n" + error);
		return false;
	}
}
	
//login to comment
function validateLogin(){
	loginname = document.getElementById('loginname').value;
	password = document.getElementById('password').value;
	textDiv = document.getElementById('divBadLogin');
	badLoginTxt = "<p><strong>Connexion : Nom d'utilisateur et mot de passe invalide</strong></p>";
	
	if (loginname == "" || password == "") alert("Nom d'utilisateur/ Mot de passe est vide");
	else{
		textDiv.innerHTML = "<p>V&#233;rification en cours...</p>";

		new Ajax.Request(baseurl+'prototype/login.ajax.php',
  	{
    	method:'post',
			parameters:{ 'username':loginname, 'password':password },
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response != "login-error-occur"){
	
					hideMe('signup');	
					showMe('divAllowToAddComment');
					
					rebuildUserInfo(); // UNCOMMENT THIS
					
					/*
					document.getElementById("divUserProfil").innerHTML = "Salut, " + response;
					document.getElementById("divUserProfil").href = "http://www.bombe.tv/mon_profil";
							
					document.getElementById("divUserLogin").innerHTML = "D&#233;connexion";
					document.getElementById("divUserLogin").href = "http://www.bombe.tv/logout.php";
					*/
				}else{
					textDiv.innerHTML = badLoginTxt;
				}
			},
			onFailure: function(){ textDiv.innerHTML = badLoginTxt; }
		});
	}

}
function rebuildUserInfo(){
jQuery('#menu_user').load(baseurl + 'prototype/userInfo.ajax.php', { 'username':loginname });
return false;
}
function writeComment(commentType){
	hideMe("comment_div_" + document.getElementById('commentType').value);
	document.getElementById('commentType').value = commentType;
	showMe("comment_div_" + commentType);
}
function publishComment(elemId, elemType, currentCount){
	comment_type=document.getElementById('commentType').value;
	error = 0;
	comment_text = "";
	comment_link = "";
	textDiv = document.getElementById('divAllowToAddComment');
	badTxt = 'Could not post your comment, please try again later';
	
	if (comment_type == "text"){
		comment_value = (htmlentities( document.getElementById('txtComments').value, 'ENT_NOQUOTES', 'ISO8859-15'));
		comment_text = document.getElementById('txtComments').value;
	}else if (comment_type == "image"){
		comment_link=document.getElementById('imageUrl').value;
		comment_text=document.getElementById('imageDesc').value
		//img_width = getImgSize(document.getElementById('imageUrl').value);
		//if (img_width > 340)	img_width = '340';

		if (!checkUrl(document.getElementById('imageUrl')))		error = 3;
		else if (comment_link=='' || comment_text =='')		error = 1;
		else{
			//comment_value = '<img src="' +comment_link + '" width="' + img_width +'" /><br>' + (htmlentities( comment_text, 'ENT_NOQUOTES', 'ISO8859-15'));
		}

	}else if (comment_type == "link"){
		comment_link=document.getElementById('lienUrl').value;
		comment_text=document.getElementById('lienDesc').value
		
		if (!checkUrl(document.getElementById('lienUrl')))		error = 3;
		else if (comment_link=='' || comment_text =='')		error = 1;		
		//else	comment_value = '<a href="' +comment_link + '" target="_blank" />'+comment_link+'</a><br>' + (htmlentities( comment_text, 'ENT_NOQUOTES', 'ISO8859-15'));

	}else if (comment_type == "video"){
		comment_link=str_replace('youtube.com/watch?v=' , 'youtube.com/v/' , document.getElementById('videoUrl').value)
		comment_text=document.getElementById('videoDesc').value
		if (comment_link=='' || comment_text =='')		error = 1;
		else if (comment_link == document.getElementById('videoUrl').value)	error = 2;	
	}

	if(comment_text=='' || trim(comment_text) == "" || trim(strip_tags(comment_text))=="")		error = 1;

	if (error == 1)		alert('Le commentaire est vide!!');
	else if (error == 2)		alert("Video YouTube Invalide");
	else if (error == 3)		alert("Lien invalide");
	else{
		comment_text = addslashes(htmlentities( comment_text, 'ENT_NOQUOTES', 'ISO8859-15'));
		new Ajax.Request(baseurl+'prototype/comment.ajax.php',
  	{
    	method:'get',
			parameters:{ 'comment':comment_text, 'comment_type':comment_type, 'comment_link':comment_link, 'elem_id':elemId, 'elem_type': elemType },
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response != "error-occur"){
					hideMe('divAllowToAddComment');	
							
					document.getElementById("newComment").innerHTML = response;
					document.getElementById('currentCommentCounter').innerHTML = currentCount+1;
				}else{
					textDiv.innerHTML = badTxt;
				}
			},
			onFailure: function(){ textDiv.innerHTML = badTxt; }
		});



	}
}
function publishCommentFB(elemId, elemType, currentCount){
	comment_type=document.getElementById('commentType').value;
	error = 0;
	comment_text = "";
	comment_link = "";
	textDiv = document.getElementById('divAllowToAddComment');
	badTxt = 'Could not post your comment, please try again later';
	
	if (comment_type == "text"){
		comment_value = (htmlentities( document.getElementById('txtComments').value, 'ENT_NOQUOTES', 'ISO8859-15'));
		comment_text = document.getElementById('txtComments').value;
	}else if (comment_type == "image"){
		comment_link=document.getElementById('imageUrl').value;
		comment_text=document.getElementById('imageDesc').value
		//img_width = getImgSize(document.getElementById('imageUrl').value);
		//if (img_width > 340)	img_width = '340';

		if (!checkUrl(document.getElementById('imageUrl')))		error = 3;
		else if (comment_link=='' || comment_text =='')		error = 1;
		else{
			//comment_value = '<img src="' +comment_link + '" width="' + img_width +'" /><br>' + (htmlentities( comment_text, 'ENT_NOQUOTES', 'ISO8859-15'));
		}

	}else if (comment_type == "link"){
		comment_link=document.getElementById('lienUrl').value;
		comment_text=document.getElementById('lienDesc').value
		
		if (!checkUrl(document.getElementById('lienUrl')))		error = 3;
		else if (comment_link=='' || comment_text =='')		error = 1;		
		//else	comment_value = '<a href="' +comment_link + '" target="_blank" />'+comment_link+'</a><br>' + (htmlentities( comment_text, 'ENT_NOQUOTES', 'ISO8859-15'));

	}else if (comment_type == "video"){
		comment_link=str_replace('youtube.com/watch?v=' , 'youtube.com/v/' , document.getElementById('videoUrl').value)
		comment_text=document.getElementById('videoDesc').value
		if (comment_link=='' || comment_text =='')		error = 1;
		else if (comment_link == document.getElementById('videoUrl').value)	error = 2;	
	}

	if(comment_text=='')		error = 1;

	if (error == 1)		alert('Le commentaire est vide!!');
	else if (error == 2)		alert("Video YouTube Invalide");
	else if (error == 3)		alert("Lien invalide");
	else{
		comment_text = addslashes(htmlentities( comment_text, 'ENT_NOQUOTES', 'ISO8859-15'));
		new Ajax.Request(baseurl+'prototype/commentFB.ajax.php',
  	{
    	method:'get',
			parameters:{ 'comment':comment_text, 'comment_type':comment_type, 'comment_link':comment_link, 'elem_id':elemId, 'elem_type': elemType, 'fb_publish' : document.getElementById('fb_comment').checked },
			onSuccess: function(transport){
				var response = transport.responseText;
				if (response != "error-occur"){
					hideMe('divAllowToAddComment');	
							
					document.getElementById("newComment").innerHTML = response;
					document.getElementById('currentCommentCounter').innerHTML = currentCount+1;
				}else{
					textDiv.innerHTML = badTxt;
				}
			},
			onFailure: function(){ textDiv.innerHTML = badTxt; }
		});

	}
}

function relatedClick(type, url){
	new Ajax.Request(baseurl+'prototype/relatedClick.ajax.php',
	{
		method:'get',
		parameters:{ 'type':type },
		onComplete : function(transport){
			goto(url);
		}
	});

}


//validate the url
function checkUrl(theUrl){
  if(theUrl.value.match(/^(http|ftp)\:\/\/\w+([\.\-]\w+)*\.\w{2,4}(\:\d+)*([\/\.\-\?\&\%\#]\w+)*\/?$/i) ||
     theUrl.value.match(/^mailto\:\w+([\.\-]\w+)*\@\w+([\.\-]\w+)*\.\w{2,4}$/i)){
    return true;
  } else {
    theUrl.select();
    theUrl.focus();
    return false;
  }
}

// hide something
function hideMe(myId){
	document.getElementById(myId).style.display="none";
}

// show something
function showMe(myId){
	document.getElementById(myId).style.display="block";
}

//search content (repertoire + ugc)
function contentSearch(action, termId, formId){
	var term = document.getElementById(termId).value;
	document.getElementById(formId).action = action + term;
	return true;
}


//usager_moi.php
function addElementImage() {
	var ni = document.getElementById('myImagesDiv');
	var numi = document.getElementById('num_images');
	var num = (document.getElementById('num_images').value -1)+ 2;
	numi.value = num;
	var newdiv = document.createElement('div');
	var divIdName = 'my'+num+'ImagesDiv';
	newdiv.setAttribute('id',divIdName);
	newdiv.innerHTML = "<label for='userpic_extra["+num+"]'>Photo Extra #"+num+"</label>";
	newdiv.innerHTML += "<input type='file' name='userpic_extra["+num+"]' id='userpic_extra["+num+"]' class='myprofilebrowsefile' /><br><br>";
	ni.appendChild(newdiv);
}


//ugc_inscription
function ugcAddElementImage() {
	var ni = document.getElementById('myImagesDiv');
	var numi = document.getElementById('num_images');
	if (numi.value < 20 ) {		
		var num = (document.getElementById('num_images').value -1)+ 2;
		numi.value = num;
		var newdiv = document.createElement('div');
		var divIdName = 'my'+num+'ImagesDiv';
		newdiv.setAttribute('id',divIdName);
		newdiv.innerHTML = "<label for='ugc_photo["+num+"]'>Photo #"+num+"</label>";
		newdiv.innerHTML += "<input type='file' name='ugc_photo["+num+"]' id='ugc_photo["+num+"]' class='myprofilebrowsefile' /><br><br>";
		ni.appendChild(newdiv);
	}
}

function ugcTypeSelection(type){
	document.getElementById('ugcDIVphoto').style.display = "none";
	document.getElementById('ugcDIVvideo').style.display = "none";
	
	document.getElementById('ugcDIV' + type).style.display = "block";
	document.getElementById('ugc-type').value = type;
}

 /* ADGEAR PLAYER FUNCTIONS */

/** function called when player has been initialized */
function playerReady(obj) {
    player = document.getElementById(obj['id']);
    player.addModelListener('STATE','stateHandler'); //listener

    ADGEAROBOX.fn.playerReady(obj);
} // playerReady() 

function stateHandler(obj) {
	if (obj.newstate == "COMPLETED"){
		if (preroll_active)	preroll_active = false;
		else{
			if (document.getElementById('postroll_id').value != ""){
				startPlayer("POSTROLL", document.getElementById('postroll_id').value, true, false);
			}
		}
	}
}

/** function that displays and aligns companion iframe */
function videoHasCompanion(playerId, companionURL) {
		
	var iframeHTML = '<iframe class="adCompanion" src="'+ companionURL +'" frameborder="0" width="300" height="250" marginheight="0" marginwidth="0" scrolling="no" style="overflow: hidden; position:relative;"></iframe>';
		document.getElementById('obox_bb_primary').innerHTML = iframeHTML;
} //obm_companion
 
/** function called when no preroll is available */
function noRoll() {
//	setTimeout('play()', 200); //AUTOPLAY WHEN NO PREROLL
} //noRoll()

/** common function that sends a play event to the player */
function play() {
	var player = jQuery('#player').get(0);
	player.sendEvent('PLAY');
}

function startPlayer(type, id, autostart, controlbar){
	so = new SWFObject('http://www.bombe.tv/player/player.swf','mpl','620','365','8');
	so.addParam('allowscriptaccess','always');
	so.addParam('allowfullscreen','true');
	so.addParam('wmode','opaque');
	so.addVariable('width','620');
	so.addVariable('height','365');
	so.addVariable('file','http://www.bombe.tv/commercial_xml.php?info='+type+'_'+id+'&fullscreen=true');
	so.addVariable('linkfromdisplay','true');
	so.addVariable('searchbar','false');
	so.addVariable('autostart', autostart);
	so.addVariable('enablejs', 'true');
	so.addVariable('javascriptid', 'mediaplayer');
	if (!controlbar)	so.addVariable('controlbar','none');
	
	so.write('player');
}

 /* end ADGEAR PLAYER FUNCTIONS */

// job voting
function JOBvote(jid){
	
		new Ajax.Request(baseurl+'prototype/jobVote.ajax.php',{
		method:'post',
		parameters:{ 'jid':jid },
		onComplete : function(transport){
			//chaneg image
			document.getElementById('votingDiv').innerHTML = "Merci"
		}
	});
	
}

//fb comment counter
function loadFbComments(id, url){
	var element = '#' + id;
	var comments = 0;
	
	jQuery.getJSON("https://graph.facebook.com/"+url+"&callback=?", function(data) {
		comments = Number(data.shares);
		if (!isNaN(comments)){
			jQuery(element + ' a').html(comments);
			jQuery(element).removeClass('hidden');
		}
	});

	
}

jQuery(document).ready(function(){
	//sidebar twitter
	jQuery(".tweet").tweet({
			username: ["mfleurant","maximestp","bombetv","GeoffroyH","OlivierDuclos", "PellepX3", "camilledg" ],
			join_text: "auto",
			avatar_size: 32,
			count: 10,
			auto_join_text_default: "", 
			auto_join_text_ed: "",
			auto_join_text_ing: "",
			auto_join_text_reply: "",
			auto_join_text_url: "",
			loading_text: "chargement en cours...",
			refresh_interval: 120 //in seconds
	});
	
	if (jQuery.browser.mozilla){
		console.log('MOZILLA');
		top_social_activate();
	}
});

jQuery(window).load(function(){
	if (body_loaded == 0){
		top_social_activate(); 
	}else body_loaded = 5;
});

function top_social_hide(){
		jQuery('#top_social').slideUp();
		return false;
}
function top_social_activate(){													 
console.log("activate ");
	body_loaded=10;
	jQuery('#top_social').slideDown();
}

function header_drop(show){
	if (show){
		if(body_loaded==5)
			top_social_activate();
		else
			body_loaded=0
	}
}

