$jQuery(document).ready(function () {
	var messageList = $jQuery(".comment");
	var thisid = $jQuery("#thisid").attr("value");
	
	$jQuery('#dialog_1_close_btn').click(function(){
			$jQuery( ".dialog, .dialog_overlay").hide();return false;
			});
	$jQuery('#dialog_2_close_btn').click(function(){
			$jQuery( ".dialog, .dialog_overlay").hide();return false;
			});
	$jQuery('#dialog_3_close_btn').click(function(){
			$jQuery( ".dialog, .dialog_overlay").hide();return false;
			});
	$jQuery('#dialog_4_close_btn').click(function(){
			$jQuery( ".dialog, .dialog_overlay").hide();return false;
			});
	$jQuery('#dialog_5_close_btn').click(function(){
			updateShoutbox();
			$jQuery( ".dialog, .dialog_overlay").hide();return false;
			});
	$jQuery('#dialog_6_close_btn').click(function(){
			updateShoutbox();
			$jQuery( ".dialog, .dialog_overlay").hide();return false;
			});



	$jQuery('#dialog_2_action_btn').click(function(){

			var f = document.getElementById('send_to_friend_form');

				// a t on au moins un ami de coché ?
			var friends = f.elements['friends[]'];
			var hasCheckedFriends = false;
			
			if(friends){
				for(var n = 0; n < friends.length; n++){
					if (friends[n].checked){
						hasCheckedFriends = true;
						break;
					}
				}
			}

			var email =  f.elements['email'].value;
			
			if((false == hasCheckedFriends) && (0 == email.length) ){
					alert('No Selection');
					return false;
			}


			var form_data = $jQuery("#send_to_friend_form").serialize();

			// exépdition du mail via ajax :

			//$jQuery.post("/ajax/send-to-friend/", form_data);

			
			$jQuery.ajax( {
				type : "POST",
				url : "/ajax/send-to-friend/", 
				data : form_data,
				error : function(XMLHttpRequest, textStatus, errorThrown){/*alert(textStatus + ' : ' + errorThrown);*/},
			  success :function(data){/*alert(data.message);*/},
				dataType : 'json'

			}  );
							


			cham_showDialog({'name' : 'dialog_3', 'hasOverlay' : false});
			$jQuery( '#dialog_2' ).hide();
			return false;

			});
		
		
		$jQuery('#dialog_5_action_btn').click(function(){
	
			var f = document.getElementById('send_cmt_form');
	
			var avis =  f.elements['avis'].value;
			if(0 == avis.length){
					alert('Veuillez Entrer un commentaire pour valider');
					return false;
			}
			
			
			var form_data = $jQuery("#send_cmt_form").serialize();
			$jQuery.ajax( {
				type : "POST",
				url : "/comment/add-comment/",
				data : form_data,
				error : function(XMLHttpRequest, textStatus, errorThrown){/*alert(textStatus + ' : ' + errorThrown);*/},
				success : function(data){/*alert(data.message);*/},
				dataType : 'json'
			} );
				
			
			
			cham_showDialog({'name' : 'dialog_6', 'hasOverlay' : false});
			$jQuery( '#dialog_5' ).hide();
			updateShoutbox();
			return false;
					
		});

		$jQuery(window).resize(function(){

				var objPageSize = ___getPageSize();
				var objPageScroll = ___getPageScroll();

				$jQuery(".dialog").css({
							top:	objPageScroll._y + (objPageSize.windowHeight / 3),
							left:	objPageScroll._x + (objPageSize.windowWidth/2)
							});

				});
				
	updateShoutbox(); 

});

	function updateShoutbox(){
	var messageList = $jQuery(".comment");
	var thisid = $jQuery("#thisid").attr("value");
		//send the post to shoutbox.php
		$jQuery.ajax({
			type: "POST", 
			url: "/comment/display-comment/", 
			data: "b="+thisid,
			error : function(XMLHttpRequest, textStatus, errorThrown){/*alert(textStatus + ' : ' + errorThrown);*/},
			success :function(data){/*alert("success");*/},
			complete :function(data){ messageList.html(data.responseText)},
			dataType : 'html'
		});
	};
// ----------------------------------
//
//
// ----------------------------------
var bet_send_to_friend = function(rub_id, cat_id, bet_id, boolLoggedIn, excludedEmails){
	
	
	if(!boolLoggedIn){cham_showDialog({'name' : 'dialog_4', 'hasOverlay' : true}); return false;}
	
	var f = document.getElementById('send_to_friend_form');
	f.elements['r'].value  =  rub_id;
	f.elements['c'].value  = cat_id;
	f.elements['b'].value  = bet_id;
	

	if (excludedEmails.length > 0){
		
		var checkboxes =  $jQuery("li > input[type='checkbox']");
		var lim = checkboxes.length;
	
		for(var i=0; i < lim; i++){
		
				// on grise les amis déjà invites ou bien l'auteur du pari
			
				if(-1 != jQuery.inArray( checkboxes[i].value, excludedEmails )){
					
					checkboxes[i].disabled = true;
					checkboxes[i].checked = false;
					checkboxes[i].nextSibling.style.color = "#aaa";
			 
				} else {
				
					checkboxes[i].disabled = false;
					checkboxes[i].nextSibling.style.color = "#000";
				}
			 
		} // fin de for
 }
	
	window.cham_showDialog({'name' : 'dialog_2', 'hasStep' : true, 'hasOverlay' : true });
	
	return false;
}
// ----------------------------------
//
//
// ----------------------------------
var bet_add_to_favorite  = function(bet_id, boolLoggedIn){
	
		
	  if(!boolLoggedIn){cham_showDialog({'name' : 'dialog_4', 'hasOverlay' : true}); return false;}
	
	
		$jQuery.ajax( {type: "POST",
		  						url: "/ajax/add-to-favorite/", 
									data : { 'b' : bet_id },
									error : function(XMLHttpRequest, textStatus, errorThrown){},
									success :  function(data){
		if('ok' == data.message.toLowerCase()){
					
		} else {
			// nothing !
				
		}
		
		;},
									dataType :  "json"} );
		
		// même en cas d'échec, on sort le dialogue pour cohérence :
		window.cham_showDialog({'name' : 'dialog_1', 'hasOverlay' : true});
	
	return false;
}

// ----------------------------------
//
//
// ----------------------------------
var bet_delete_from_favorite = function(bet_id){
	
	$jQuery.ajax( {type: "POST",
	  						url: "/ajax/delete-from-favorite/", 
								data : { 'b' : bet_id },
								error : function(XMLHttpRequest, textStatus, errorThrown){},
								success :  function(data){
	if('ok' == data.message.toLowerCase()){
		
	} else {
		// nothing !
	}
	
	;},
								dataType :  "json"} );
	
	// même en cas d'échec, on sort le dialogue pour cohérence :
	window.cham_showDialog({'name' : 'dialog_1', 'hasOverlay' : true});
	// le dialogue fait un relaod de la page

	return false;	
	
	
}
// ----------------------------------
//
//
// ----------------------------------
var bet_cmt = function(bet_id){

	var f = document.getElementById('send_cmt_form');
	f.elements['b'].value = bet_id;
	
	window.cham_showDialog({'name' : 'dialog_5', 'hasStep' : true, 'hasOverlay' : true });
	
	return false;
}
// ----------------------------------
//
//
// ----------------------------------
function cham_showDialog(oDialog) {
	
	if(oDialog.hasOverlay){
		window.cham_showOverlay();
	}
	
 	var dialog = '#'+ oDialog.name;
	
	// Get page sizes and scroll amount
	var objPageSize = ___getPageSize(); //pageWidth,pageHeight,windowWidth,windowHeight
	var objPageScroll = ___getPageScroll();
 
	 $jQuery(dialog).css({
					top:	objPageScroll._y + (objPageSize.windowHeight / 3),
					left:	objPageScroll._x + (objPageSize.windowWidth/2)
				}).show();
	
							
}
// ----------------------------------
//
//
// ----------------------------------
function cham_showOverlay(){
	
	// Get page sizes
	var objPageSize = ___getPageSize(); //pageWidth,pageHeight,windowWidth,windowHeight
	
	$jQuery(".dialog_overlay").css({"overflow-y":"hidden", 'opacity' : '0', 'height' : objPageSize.pageHeight + 'px'});
	$jQuery(".dialog_overlay").show();
	$jQuery(".dialog_overlay").animate({"opacity":"0.6"}, 200, "linear");
	

	// clic sur le fond :
	$jQuery(".dialog_overlay").click(function(){
		$jQuery(".dialog, .dialog_overlay").hide();
	});

	// si on étire la fenêtre :

		$jQuery(window).resize(function(){

					var objPageSize = ___getPageSize();
					// Style overlay and show it

					$jQuery('.dialog_overlay').css({
						width:		objPageSize.pageWidth,
						height:		objPageSize.pageHeight
						});

			});
				
}
// ----------------------------------
//
//
// ----------------------------------

/**
 / THIRD FUNCTION
 * getPageSize() by quirksmode.com
 *
 * @return Array Return an array with page width, height and window width, height
 */
function ___getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	objPageSize = {'pageWidth' : pageWidth,
	 									'pageHeight' : pageHeight,
										'windowWidth' : windowWidth,
										'windowHeight' : windowHeight
	};  //new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return objPageSize;
};
// ----------------------------------
//
//
// ----------------------------------
/**
 / THIRD FUNCTION
 * getPageScroll() by quirksmode.com
 *
 * @return Array Return an array with x,y page scroll values.
 */
function ___getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	objPageScroll = {'_x' : xScroll, '_y' : yScroll}; //new Array(xScroll,yScroll);
	return objPageScroll;
};
// ----------------------------------
//
//
// ----------------------------------
var bet_display_answer = function(id_dest, id_checkbox){
	
	var dest = document.getElementById(id_dest);
	var checkBox = document.getElementById(id_checkbox);
	
	var labels = document.getElementsByTagName('label');
	var tmp = null;
	
	for(var n = 0; n < labels.length; n++){
		
		tmp = labels[n];
		if (tmp.getAttribute('for') == id_checkbox){
			
	   dest.innerHTML = tmp.innerHTML;
		}
	}
	return true;
}

// ----------------------------------
//
//
// ----------------------------------
var bet_validate = function(objLien, objForm, width, height){
	
	var partner = objLien.getAttribute('rel');

	if (partner){
		window.open(partner, 'bet_partner_popup', 'width=' + width +',height=' + height + ',status=yes,location=yes,resizable=yes,scrollbars=yes');
	}
	objForm.submit();
	return false;
}

// ----------------------------------
//
//
// ----------------------------------
var bet_unfold = function(idDetail, testnew){
	
	
	
		
		// modif ici jerome@yazo.net janvier 2011
		// cette methode est aussi appellee pour afficher les message 
		// l'insertion ici )	if (testnew)) d'un appel vers progressbet_... 
		//  rendait inoperante la methode sur la page messagerie
		// (NOTA progressbet_.. lance (je suppose) la barre de progression d'affichage des paris 
		// ne peut donc fonctionner que si il y a des paris...
		// je place tout ça dans un try{}catch{} afin qu'un échec ne soit plus fatal
		
		// NOTA : la modification non documentee d'un code n'est pas bienvenue
		
		
		try{
			
			var testnew = (testnew == null) ? true : false;
			if (testnew){
				if($jQuery(idDetail).css("display") == "none"){
				
					var test = "progressbet_"+idDetail.substring(13);
					eval(test + '()');	
				}else{
					var test = "KILLprogressbet_"+idDetail.substring(13);
					eval(test + '()');
				}
			}		
			
			
		} catch(e){
			
			//throw 'Aie ! ' + e;
		
		}finally{
			
			$jQuery(idDetail).toggle("normal");
			 
			
		}
		 

		return false;
}
// ----------------------------------
//
//
// ----------------------------------
var bettop_fadein = function(idDetail){

	$jQuery('#bettop_detail_1'+idDetail).fadeIn();
		var test = "progresstopbet_"+idDetail;
		eval(test + '()');
		
	return false;
}
// ----------------------------------
//
//
// ----------------------------------
var bettop_fadeout = function(idDetail){
	$jQuery('#bettop_detail_1'+idDetail).fadeOut('fast');
		var test = "KILLprogresstopbet_"+idDetail;
		eval(test + '()');
		return false;
}
// ----------------------------------
//
//
// ----------------------------------
var topbet_unfold = function(idDetail, testnew){
		try{
			
			var testnew = (testnew == null) ? true : false;
			if (testnew){
				if($jQuery('#topbet_detail_1'+idDetail).css("display") == "none"){
				
					var test = "progressbet_"+idDetail.substring(13);
					eval(test + '()');	
				}else{
					var test = "KILLprogressbet_"+idDetail.substring(13);
					eval(test + '()');
				}
			}		
			
			
		} catch(e){
			
			//throw 'Aie ! ' + e;
		
		}finally{
			
			$jQuery(idDetail).toggle("normal");
			 
			
		}
		 

		return false;
}

// laurentiu

var globalParis;

function ajax_request_paris() {
	var div_error = document.getElementById('error');
	div_error.innerHTML = "";

	var sport_options = document.getElementById('sport_paris');
	var sport = sport_options.options[sport_options.selectedIndex].value;
	var equipe = document.getElementById('equipe_paris').value;
	if (equipe !== "undefined" && equipe !== null && equipe.length >= 2 && sport !== "undefined" && sport !== null) {
		//alert(sport + " - " + equipe);
		var host = "betreflex.com";
		if (window.location.host) {
			host = window.location.host;
		}
		var url = "http://" + host + "/bet/flux-receive/sport/" + sport + "/equipe/" + equipe;
		$jQuery.get(url, function(data) {
			//alert("Data Loaded: " + data);
			var jsonData = eval('(' + data + ')');
			globalParis = jsonData;
			// populate paris_received
			document.getElementById('paris_information').value = '';
			var select_paris = document.getElementById('paris_received');
			select_paris.options.length = 0;
			for (var i = 0; i < jsonData.paris.length; i++) {
				var selected = false;
				var eq1VSeq2 = jsonData.paris[i].equipe1 + " vs " + jsonData.paris[i].equipe2; 
				if (i == 0) {
					selected = true;
					// populate textarea paris_information
					update_paris_information(sport, jsonData.paris[i].date, jsonData.paris[i].hour, jsonData.paris[i].ligue, jsonData.paris[i].equipe1, jsonData.paris[i].equipe2);
				}
				var pari = eq1VSeq2 + " - " + jsonData.paris[i].date
				select_paris.options[select_paris.length] = new Option(pari, i, selected);
			}
			
			if (jsonData.paris.length == 0) {
				var div_error = document.getElementById('error');
				div_error.innerHTML = "Aucun résultat trouvé";			
			}
		});
	} else {
		var div_error = document.getElementById('error');
		div_error.innerHTML = "Entrer votre équipe";
	}
}

function update_on_select_paris_received() {
	var paris = document.getElementById('paris_received');
	var index = paris.options[paris.selectedIndex].value;
	if (globalParis.paris[index] != undefined) {
		var jsonObj = globalParis.paris[index];
		update_paris_information(jsonObj.sport, jsonObj.date, jsonObj.hour, jsonObj.ligue, jsonObj.equipe1, jsonObj.equipe2);		
	} else {
		update_paris_information(null, null, null, null, null, null);		
	}	
}

function update_paris_information(sport, date, hour, ligue, eq1, eq2) {
	var textarea = document.getElementById('paris_information');
	if (sport !== null && date !== null && hour !== null && ligue !== null && eq1 !== null && eq2 !== null) {
		var data = "*" + sport + " * " + ligue + " - " + eq1 + " vs " + eq2 + " Date cloture : " + date + " " + hour;
		textarea.value = data;	
	} else {
		textarea.value = '';		
	}
}

function createHiddenField(formId, inputFieldName, inputFieldValue) {
	var input = document.createElement("input");
	input.setAttribute("type", "hidden");
	input.setAttribute("name", inputFieldName);
	input.setAttribute("value", inputFieldValue);
	
	document.getElementById(formId).appendChild(input);
}

function createHiddenFieldsOnSubmit() {
	var paris = document.getElementById('paris_received');
	var index = paris.options[paris.selectedIndex].value;
	if (globalParis.paris[index] != undefined) {
		var jsonObj = globalParis.paris[index];
		
		createHiddenField("new_bet_form", "sport", jsonObj.sport);
		createHiddenField("new_bet_form", "date", jsonObj.date);
		createHiddenField("new_bet_form", "hour", jsonObj.hour);
		createHiddenField("new_bet_form", "ligue", jsonObj.ligue);
		createHiddenField("new_bet_form", "equipe1", jsonObj.equipe1);
		createHiddenField("new_bet_form", "equipe2", jsonObj.equipe2);
		
	} else {
		alert("undefined");
	}
}

// laurentiu

