// Code sous Copyright (c) 2009 Pronosoft - Nadim Noureddine. Toute réutilisation, copie ou copie partielle interdite

var currentPronoId=-1;

$(document).ready
(
	function()
	{
		InitAll();
	}
);

function InitAll()
{
	currentPronoId = GetCouponId($('#pronoId').text());
}

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function GetCouponId(pronoId)
{
	return 'id_'+pronoId;
}

function GetErrorMessage(msg)
{
	return '<p id="errormsg" class="center"><img src="http://www.pronosoft.com/img/css/images/puce_avert.gif" alt="" width="16" height="16"> '+msg+'</p>';
}


function submitCouponError(response)
{
	mErrorMessage=GetErrorMessage('Une erreur de communication avec le serveur est survenue.');
//	alert(response.responseText);
	$('#html_ajax').html(mErrorMessage);
}

function getSessionURL(url)
{
	var sid = gup('sid');
	if (sid!='')
		url+='?sid='+sid;
	else
		url+='?';
	// anti-cache
	var timestamp=new Date().getTime();
	url+='&nocache='+timestamp;

	return url;
}

function submitCouponCallback(response) 
{ 
    mUserName = $(response).find('name').text();
	mNetAmount = $(response).find('net').text();
	mListNetAmount = $(response).find('listnet').text();

	mErrorValidation = $(response).find('error').text();
	if (mErrorValidation=='')
	{
		// add the html section
		$(response).find('coupon').each(function()
		{
			var html=$(this).find('html').text();
			$('#html_ajax').html(html);
//alert(html);

			$('#'+currentPronoId).removeClass("courant")
			
			// set the coupon to current
			currentPronoId=GetCouponId($(this).find('id').text());
			$('#'+currentPronoId).addClass("courant");
		}
		);
	}
	else
	{
		mErrorMessage=mErrorValidation;
	}
}

function submitAjaxCoupon(dayId, userId) // on form submission
{
	// check that the coupon is not the current one
	var pronoId = GetCouponId(dayId+'_'+userId);
	if (pronoId!=currentPronoId)
	{
		// build the data
		var data='mode=pronos&param=view&journee='+dayId+'&userId='+userId;
		if (gup('mode')=='pronos') // displayBuddy only in Pronos
		{
			data+='&displayBuddy=true';
		}
//		alert(data);

		var url = getSessionURL('/fr/concours/concours_scores.php');

		$.ajax
		({
			type: 'POST',
			url: url,
			data: data,
			dataType: 'xml',
			success: submitCouponCallback,
			error: submitCouponError
		});
	}
}

function UpdateText(id, newText)
{
	var old = document.getElementById(id).firstChild;
	var txt = document.createTextNode(newText);
	document.getElementById(id).replaceChild(txt, old);
}

