//
// Hue NewsLetter
function hueNewsLetterOnClick(txNewsletter) {
	if ( validateEmail(document.getElementById(txNewsletter).value) ){
		callWS("/index.php/site/ws_newsletter", 'nl_id=1&email='+escape(document.getElementById(txNewsletter).value), hueNewsLetterWSCallBack);
		if(document.getElementById('eb').src.indexOf('_on') != -1){
			callWS("/index.php/site/ws_newsletter", 'nl_id=2&email='+escape(document.getElementById(txNewsletter).value), hueNewsLetterWSCallBack);
		}
	}else{
		alert('Veuillez entrer un courriel valide');
	}
}

function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   return reg.test(email);
}

function hueNewsLetterWSCallBack() {
	if (XMLHttp.readyState == 4 && XMLHttp.status == 200)
	{
		var sStatus = new String(XMLHttp.responseText);
		var aStatus = sStatus.split(':');

		if ( aStatus[0] != "huenewsletter" ) {
			alert("Web Service Problem: "+sStatus);
			return;
		}

		switch(aStatus[1] )
		{
			case "already_registred":
				try {document.getElementById('divNewsletter').innerHTML = "<br><br><div>Vous &#234;tes d&#233;j&#224; inscrit.</div>";}catch(err){}
				try {document.getElementById('divNewsletterFooter').innerHTML = "<br><br><div>Vous &#234;tes d&#233;j&#224; inscrit.</div>";}catch(err){}
				break;
			case "registred":
				try {document.getElementById('divNewsletter').innerHTML = "<br><br><div>Vous &#234;tes maintenant inscrit.</div>";}catch(err){}
				try {document.getElementById('divNewsletterFooter').innerHTML = "<br><br><div>Vous &#234;tes maintenant inscrit.</div>";}catch(err){}
				break;
			default:
				alert('Web Service Problem : '+sStatus);
				break;
		}
	}
}

//
// Hue Like
var like_ope = true;

$(document).ready(function(){
	$('#like').click( function() {
		var y_timer;
		if(like_ope) {
			invisible('like_btn_close');
			show('like_open');
			$('#like,#aHueLikeSideAnchor').mouseover( function() {
				clearTimeout(y_timer);
			});
			$('#like,#aHueLikeSideAnchor').mouseout( function() {
				y_timer = setTimeout("closeLike();displayPlus();", 2000);
			});
		}
	});
});

function hueLikeWS(sData, oCallBackFct) {
	callWS("/index.php/site/ws_coup_coeur", sData, oCallBackFct);
}

function getHueLikeStatus(entryID, oCallBackFct) {
	hueLikeWS("entry_id="+entryID+"&fct=status", oCallBackFct);
}

function doHueLike(entryID, oCallBackFct) {
	hueLikeWS("entry_id="+entryID+"&fct=like", oCallBackFct);
}

function setAnchor(sFld, sText, sHref, sClass) {
	if ( document.getElementById(sFld) ) {
		oFld = document.getElementById(sFld);
		oFld.innerHTML = sText;
		oFld.href = sHref;
		if(sClass){
			oFld.className = sClass;
		}
	}
}

// Web Service Callback to handle response and update content
function hueLikeWSCallBack() {


	if(XMLHttp.readyState == 4 && XMLHttp.status == 200) {
		var sStatus = new String(XMLHttp.responseText);
		var aStatus = sStatus.split(':');

		if( aStatus[0] != "huelike" ) {
			alert("Web Service Problem: "+sStatus);
			return;
		}
		
		
		switch(aStatus[1]) {
			case "can_vote":
				setAnchor("aHueLikeOptionsAnchor", "COUP DE COEUR", "javascript:hueLikeOnClick();");
				$('#aHueLikeSideAnchor').html('COUP DE COEUR').bind('click', function() { hueLikeOnClick() } ).css('cursor', 'pointer');
				break;
			case "already_voted":
				setAnchor("aHueLikeOptionsAnchor", "VOTRE COUP DE COEUR A D&#201;J&#192; &#201;T&#201; AJOUT&#201;", "javascript:void(0);", "coeur noHover");
				like_ope = false;
				$('#like_btn_close').removeAttr('onclick');
				$('#like_btn_close').css('visibility', 'hidden');
				break;
			/*case "not_loggued":
				setAnchor("aHueLikeOptionsAnchor", "COUP DE COEUR", "javascript:parent.openLightbox('/member/login/', 647, 275);");
				$('#aHueLikeSideAnchor').html('COUP DE COEUR').attr('onclick', "javascript:parent.openLightbox('/member/login/', 647, 275);").css('cursor', 'pointer');
				break;*/
			case "accepted":
				setAnchor("aHueLikeOptionsAnchor", "MERCI!", "javascript:void(0);", "coeur noHover");
				$('#aHueLikeSideAnchor').html('MERCI!').attr('onclick', 'javascript:void(0);').css('cursor', 'default');
				$('#like_btn_close').removeAttr('onclick');
				like_ope = false;
				setTimeout("closeLike();$('#like_btn_close').css('visibility', 'hidden');", 2000);
				if(document.getElementById('divHueLikeCount')){
					document.getElementById('divHueLikeCount').innerHTML = aStatus[2];
				}
				break;
			default:
				alert('Web Service Problem : '+sStatus);
				break;
		}
	}
}

function closeLike() {
	$('#like_open').hide();
}
function displayPlus() {
	if(like_ope) {
		visible('like_btn_close');
	}
}

//
// Works fine, but this should be replaced by the jQuery version...
//
function callWS(sURL, sData, oCallBackFct) {

	if (window.XMLHttpRequest)
	{
		XMLHttp = new XMLHttpRequest();
		XMLHttp.onreadystatechange = oCallBackFct;
		XMLHttp.open("POST", sURL, true);
		XMLHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		XMLHttp.send(sData);
	}
	else if (window.ActiveXObject)
	{
		try
		{
			XMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(g){var unSupported = 'y';}

		if (XMLHttp)
		{
			XMLHttp.onreadystatechange = oCallBackFct;
			XMLHttp.open("POST", sURL, true);
			XMLHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
			XMLHttp.send(sData);
		}
	}
}

/*
	Poll
*/
//var count = 1;
function huePollWS(sData, oCallBackFct) {
	/*setTimeout('callWS("/index.php/site/ws_poll","'+ sData+'",'+ oCallBackFct+')',250*count);
	count++;*/
	callWS("/index.php/site/ws_poll", sData, oCallBackFct); 
}

function getHuePoll(entryID, nombre, oCallBackFct) {
	huePollWS("mode=return&entry="+entryID+"&nombre="+nombre, oCallBackFct);
}

function doHuePoll(question, entryID, title, oCallBackFct) {
	if(question==undefined){
		alert(unescape("Veuillez choisir une r%E9ponse."));
	}else{
		huePollWS("mode=add&question="+question+"&entry="+entryID+"&title="+title, oCallBackFct);
	}
}

function getQuestion(){
	var question = $('form input[name="question"]:checked').val();
	return question;
}

function huePollWSCallBack() {
	if(XMLHttp.readyState == 4 && XMLHttp.status == 200) {
		var sStatus = new String(XMLHttp.responseText);
		var aStatus = sStatus.split(':');
		if( aStatus[0] != "huepoll" ) {
			alert("Web Service Problem: "+sStatus);
			return;
		}
		
		
		switch(aStatus[1]) {
			case "vote_done":
				window.location="/sondage/view/"+aStatus[2];
				setCookie( 'sondage', aStatus[3], 6000, '/');
				break;
			case "return_vote":
				var entry = aStatus[2];
				var nombreQuestions = aStatus[3];
				var arrayPourcents = Array(aStatus[5],aStatus[7]);
				
				$('#'+entry+' .v1').html(aStatus[4]);
				$('#'+entry+' .p1').html(aStatus[5]+'%');
				
				$('#'+entry+' .v2').html(aStatus[6]);
				$('#'+entry+' .p2').html(aStatus[7]+'%');
				
				if(nombreQuestions>2){
					$('#'+entry+' .v3').html(aStatus[8]);
					$('#'+entry+' .p3').html(aStatus[9]+'%');
					arrayPourcents[2] = aStatus[9];
					if(nombreQuestions>3){
						$('#'+entry+' .v4').html(aStatus[10]);
						$('#'+entry+' .p4').html(aStatus[11]+'%');
						arrayPourcents[3] = aStatus[11];
						if(nombreQuestions>4){
							$('#'+entry+' .v5').html(aStatus[12]);
							$('#'+entry+' .p5').html(aStatus[13]+'%');
							arrayPourcents[4] = aStatus[13];
							if(nombreQuestions>5){
								$('#'+entry+' .v6').html(aStatus[14]);
								$('#'+entry+' .p6').html(aStatus[15]+'%');
								arrayPourcents[5] = aStatus[15];
							}
						}
					}
				}
				var highest=arrayPourcents.max();
				
				var highestID=-1;
				for(i=0;i<=(nombreQuestions-1);i++){
					if(arrayPourcents[i]==highest){
						highestID = i;
					}
				}
				$('#'+entry+' .colonneResultat.Mid'+highestID).css('height','181px');
				var newHeight
				for(j=0;j<=(nombreQuestions-1);j++){
					if(j!=highestID){
						newHeight = (arrayPourcents[j]/highest)*181;
						if(newHeight < 30){
							newHeight=30;
						}
						$('#'+entry+' .colonneResultat.Mid'+j).css('height',newHeight);
					}
				}
				
				break;
			case "vote_no_entry":
				
				break;
			default:
				alert('Web Service Problem : '+sStatus);
				break;
		}
	}
}
Array.prototype.max = function(){
    return Math.max.apply( Math, this );
};

function getCookie( name ) {
        var start = document.cookie.indexOf( name + "=" );
        var len = start + name.length + 1;
        if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
               return null;
        }
        if ( start == -1 ) return null;
        var end = document.cookie.indexOf( ';', len );
        if ( end == -1 ) end = document.cookie.length;
        return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		   expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+'='+escape( value ) +
		   ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		   ( ( path ) ? ';path=' + path : '' ) +
		   ( ( domain ) ? ';domain=' + domain : '' ) +
		   ( ( secure ) ? ';secure' : '' );
}

function deleteCookie( name, path, domain ) {
        if ( getCookie( name ) ) document.cookie = name + '=' +
                       ( ( path ) ? ';path=' + path : '') +
                       ( ( domain ) ? ';domain=' + domain : '' ) +
                       ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

