// JScript File
/* getMouse :
	Recupere les coordonnees de la souris et les met dans les variables globales
		window.mouseX
	et	window.mouseY,
		il faut passer event en parametre sur les evenements
	ex :
		function fun(param1, param2, e) {
			getMouse(e);
			sourisX = window.mouseX;
			sourisY = window.mouseY
		}
		fun("foo", "bar", event);

*/
/* getMouse :  */
function getMouse(e){
	var x,y; var elt = (navigator.userAgent.indexOf("MSIE 5")!=-1) ? document.body : document.documentElement;
	if ( document.captureEvents ) {
		x = e.pageX;
		y = e.pageY;
	} else if ( window.event.clientX ) {
		x = window.event.clientX+elt.scrollLeft;
		y = window.event.clientY+elt.scrollTop;
	}
	window.mouseX = x;
	window.mouseY = y;
}
/* findPos :
	recupere la position X,Y d'un objet dans une page
	ex :
		var pos = findPos(elm);

*/
function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function GetElementId(id)
{
	return document.getElementById(id);
} 
 
function activateLink(prefix,prid){
    var e = getElement(prefix + 'Link');
    var cible = $('#hiddenLink_'+prid).val();

    if ( e != null )
        e.innerHTML = '<a href="' + cible + '">Ajouter&nbsp;un&nbsp;avis</a>';
}

function desactivateLink(prefix){
    var e = getElement(prefix + 'Link');
   
    if ( e != null )
        e.innerHTML = 'Ajouter&nbsp;un&nbsp;avis';
}

var connector = new function() {
	//var gai=this; //permet d'accéder aux attribut publiques de l'objet depuis la fonction via un simple gai.monattribut

	/*** Variables  de paramétrage du GAI ***/
	this.XMLUrl = ""; //url du XML paramétrable dans la page

	/* attributs privés */
	var XML = null; //variable qui contient le résultat de la requête XHR qui a été faite. cet objet est privé et ne peux être utilisé que par des méthodes du GAI
    var initiated = false;
	this.init = function() {
	    	    
        try {
	        if ( !initiated )
	        XML = getXHR();
	        initiated = true;
	    }
	    catch(ex){}
	};
 
	this.putValuation = function(valuation, prefix) {
	    
	    /*
	    this.init();
		var UrlToCall = this.XMLUrl;
		// Method
		UrlToCall += 'PutValuation?'
		// Parameters
		UrlToCall += 'ArticleId=' + articleId + '&UserId=' + userId + '&Valuation=' + valuation
		
		XML.open("GET", UrlToCall, true); 
		XML.send(null);
		*/
		
		getElement(prefix + "ref").value = valuation;
	};	
	this.putRelation = function(articleId, userId, relationId) {
	    
		var action;
		if(document.getElementById('action')!=null)
		action =document.getElementById('action').value;
		
		/* 				
	    this.init();
		var UrlToCall = this.XMLUrl;
		// Method
		UrlToCall += 'PutRelation?'
		// Parameters
		UrlToCall += 'ArticleId=' + articleId + '&UserId=' + userId + '&RelationId=' + relationId
		XML.open("GET", UrlToCall, true); 
		XML.send(null);
		XML.onreadystatechange = function()
		    {  		          
	            if (this.readyState == 4) { // 4 : état "complete"  
                if (this.status == 200) {// 200 : code HTTP pour OK
                //debugger
                if(document.getElementById('NodeParent')!=null)
                {
                    var NodeParent = document.getElementById('NodeParent').value;  
			        RefreshMenu(NodeParent, userId,action);
			    }
               } else {
		            alert("Une erreur est survenue")};
               }
            }
		if(document.getElementById('NodeParent')!=null)
		{
			var NodeParent = document.getElementById('NodeParent').value;  
			RefreshMenu(NodeParent, userId,action);
		}         
         */
	};	
	this.putInterestRelation = function(nodeId, userId, relationId,control) {	   
		if(control.checked)
	 	{   
		    var action;
		    if(document.getElementById('action')!=null)
		    action =document.getElementById('action').value;
		    
		    /* 				
	        this.init();	    
		    var UrlToCall = this.XMLUrl;
		    
		    // Method
		    UrlToCall += 'PutInterestRelation?'
		    // Parameters
		    UrlToCall += 'NodeId=' + nodeId + '&UserId=' + userId + '&RelationId=' + relationId
		    XML.open("GET", UrlToCall, true);		
		    XML.send(null);
		   // debugger	
		    XML.onreadystatechange = function()
		    {  		          
	            if (XML.readyState == 4) { // 4 : état "complete"
                if (XML.status == 200) { // 200 : code HTTP pour OK
                //debugger
                 if(document.getElementById('NodeParent')!=null)
                {
                    var NodeParent = document.getElementById('NodeParent').value;  
			        RefreshMenu(NodeParent, userId,action);
			    }
               } else {
		            alert("Une erreur est survenue")};
               }
            }
			if(document.getElementById('NodeParent')!=null)
			{
				var NodeParent = document.getElementById('NodeParent').value;  
				RefreshMenu(NodeParent, userId,action);
			}         
            */
        }	
	};
}
/*
function RefreshMenu(nodeId, userId,action)
	{    
	    httpRequest = getXHR();	   
		var UrlToCall = document.getElementById('MenuRender').value;
		var menuType = document.getElementById('MenuRenderParam').value;
		waitingMsg.show();
        waitingMsg.setHideTimer(); 
        var laps = new Date();     	
		// Parameters		
		UrlToCall += '?MenuType=' + menuType + '&NodeId=' + nodeId + '&UserId=' + userId + "&action=" + action + "&date=" + laps 
		httpRequest.open("GET", UrlToCall, true);		
		httpRequest.send(null);	
		
		httpRequest.onreadystatechange = function()
        { 
           // debugger        
            if(httpRequest.readyState==4 || httpRequest.readyState=="complete")
             {
                  waitingMsg.hide();
                  if(document.getElementById('MenuRenderContent')!=null)
                  {
                  x = document.getElementById('MenuRenderContent')                  
                  if(httpRequest.status  == 200) 
                     x.innerHTML = httpRequest.responseText;
                  }                               
             }
        }        
	};
*/
function getXHR() {
	function xmlpref() {
		if (xmlpref.prefix) return xmlpref.prefix;
		var prefixes=['MSXML2','Microsoft','MSXML','MSXML3'];
		for (var i=0;i<prefixes.length;i++) {
			try {
				return xmlpref.prefix=prefixes[i];
			}
			catch(ex){}
		}
	}
	if (window.XMLHttpRequest){
		return new XMLHttpRequest();
	}
	if(window.ActiveXObject){
		return new ActiveXObject(xmlpref()+'.XmlHttp');
	}
	return null;
}


/* Opinion Functions*/
function HightLight ( prefix , index , pathImg) {
    for (var i=1 ; i <= 5 ; i++ ) {
        if ( i <= index )
            getElement(prefix+'StarL'+i).src=pathImg+'starIn.png';
        else
            getElement(prefix+'StarL'+i).src=pathImg+'starOut.png';
    }
}

function getStartPos(prefix, pathImg){
    var initPos = getElement(prefix+'ref').value;
    for (var i=1 ; i <= 5 ; i++ ) {
        if ( i <= initPos ) {
            getElement(prefix + 'StarL' + i).src=pathImg+'starIn.png';
        }else{
            getElement(prefix + 'StarL' + i).src=pathImg+'starOut.png';
        }
    }
}

function putRelation( Relation, Checkbox, SisterCheckbox, pathImg){
    var returnvalue = 0;
    if ( Checkbox.src.substr(Checkbox.src.length-6, 12) == 'on.gif' ){
        Checkbox.src = pathImg+'caseoff.gif';
        returnvalue = -1 * parseInt(Relation.substr(1,1));
    }
    else
    {
        returnvalue = parseInt(Relation.substr(1,1));
        Checkbox.src = pathImg+'caseon.gif';
        if (SisterCheckbox)
            SisterCheckbox.src = pathImg+'caseoff.gif';
    }
       
   return returnvalue;
}

function popValidation(prefix){

    var initPos = getElement(prefix+'StarL1');

	var deja = document.getElementById('valid_rating');
	if(deja){ document.body.removeChild(deja); }
	var pos = findPos(initPos);
	var content = "<p class='gras mrg_no pdg_sm' style='background-color:#fff;border:1px solid #ccc'>";
	content += "Note prise en compte";
	content += "</p>";
	
	var popin = document.createElement("DIV");
	popin.id = "valid_rating";
	popin.className = "valid_rating";
	popin.innerHTML = content;
	document.body.appendChild(popin);
	
	if(popin.style.display != "block") { popin.style.display = "block"; }
	popin.style.position = "absolute";
	popin.style.zIndex = "300";
	if ($.browser.mozilla) {
		popin.style.left = (pos[0]+45)+"px";
	}
	else {
		popin.style.left = (pos[0]-35)+"px";
	}
	popin.style.top = (pos[1]-40)+"px";
	
	setTimeout(function (){
        deja = document.getElementById('valid_rating');
	    if(deja){ document.body.removeChild(deja); }	
	},2000);
	return false;
}
function notationtip(){
 $(document).ready(function(){
  if ($.browser.safari || $.browser.mozilla) {
	$("img[id*='StarL']").hover(function(){
		var note = $(this).attr("alt");
		var objId = $(this).attr("id");
		var notation = document.createElement("DIV");
		notation.id = "notes";
		notation.className = "notationtip";
		notation.innerHTML = note;
		notation.style.display = "block";
		notation.style.position = "absolute";
		notation.style.zIndex = "300";
		notation.style.backgroundColor = "#ffffe1";
		notation.style.padding = "2px";
		notation.style.border = "1px solid #000";
		notation.style.height = "14px";
		notation.style.color = "black";
		notation.style.fontSize = "10px";
		notation.style.left = mouseX+"px";
		notation.style.top = (mouseY+15)+"px";
		notation.style.whiteSpace = "nowrap";
		document.body.appendChild(notation);
	},
	function(){
		var meurs = $("div#notes");
		if(meurs) { meurs.remove(); }
	});
	}
 });
}
function deleteSelection(id)
{
	for(var i in selection)
	{
		if(selection[i] == id)
		{
			selection.splice(i,1);
			break;
		}
	}
}
function deleteAll(table){
	for(var i in selection)
	{
		selection.splice(i, selection.length);
	}
}
function ifAlreadySelected(id)
{
	var drapeau = false;
	for(var i in selection)
	{
		if(selection[i] == id)
		{
			drapeau = true;
			break;
		}
	}
	return drapeau;
}

var divOpen = false;
var selection = new Array();
function redraw(param, bId, from){
	
	var attrObj = document.getElementById(bId);
    var fnClick = attrObj.parentNode.attributes["onclick"].nodeValue;
    
	function recupArgs(phrase){
		// fn spécifique à la fn de lRasle
		var rawArgs = phrase.split("(");
		var args = rawArgs[1].split(",");
		return [args[0],args[1]];
	}
	var checkB = $("img#"+bId);
	var checkBsrc = checkB.attr("src");
	var state = checkBsrc.indexOf("caseon.gif",0);
	
	var id = bId;
	var img = checkB.parents("div").siblings("a[@title='En savoir plus']").children("img");
	var title = checkB.parents("div").siblings("h3").text();
	var author = checkB.parents("div").siblings("h4").text();
	var ok = false;
	if(from == "img") 
	{	
		if(state == -1 && param == "oui") 
		{ 
			ok = true;
		}
		else if(state != -1 && param == "oui")
		{
			param = "non";
			ok = true;
		}
		else if(state == -1 && param == "non")
		{
			ok = true;
		} else  if(state != -1 && param == "non") 
		{
			ok = true;
		}
	} else if(from == "label") 
	{
		if(state == -1 && param == "oui") 
		{
			ok = true;
		}
		else if(state != -1 && param == "oui") 
		{
			param = "non";
			ok = true;
		}
		else if(state == -1 && param == "non") 
		{
			ok = true;
			
		}
		else if(state != -1 && param == "non") 
		{
			ok = true;
			
		}
	}
	
	if(param == "oui" && ok == true)
	{
		if(ifAlreadySelected(id))
		{
			return;
		}
		else
		{
			selection.push(id);
	
			if(!divOpen)
			{
				
				$("#collectionAdded").css("display","block");
				divOpen = true;
				
			}
			var html = "<div class='iHave pdg txt_c'><a href='#' title='"+ id +"'></a><img src='"+ img.attr("src") +"' alt='' /><h3>"+ title +"</h3><h4>"+ author +"</h4></div>";
			$("#collectionAdded .content").prepend(html);
			$("#collectionAdded .content .iHave a").ready(function()
			{
				$(".iHave a").click(function()
				{
					var croix = $(this);
					var id = croix.attr("title");
					// ici on supprime le conteneur cible qui contient ce 'a'
					croix.parent("div.iHave").remove();
					deleteSelection(id);
					// on décoche la case dans la colonne gauche
					var arguments = recupArgs(fnClick);
					connector.putRelation(arguments[0],arguments[1],putRelation('r3', document.getElementById(id), getElement(id), globalImgPath));
					if($("#collectionAdded .content div.iHave").length < 1)
					{
						$("#collectionAdded").hide();
						//$("#collectionEmpty").show();
						divOpen = false;
					}
					return false;
				});
			});
		}
	}
	else if(param == "non" && ok == true)
	{
		if(divOpen)
		{
			for(var i in selection)
			{
				if(selection[i] == id)
				{
					selection.splice(i,1);
					$("#collectionAdded .content div.iHave a[@title='"+id+"']").parent("div.iHave").remove();
					
					if($("#collectionAdded .content").children().length < 1)
					{
						$("#collectionAdded").hide();
						//$("#collectionEmpty").show();
						divOpen = false;
					}
				}
			}
		}
		return false;
	}
}

function checkBmanager(){
	$(document).ready(function(){
		$("img[@alt='oui']").click(function(){
				redraw("oui",$(this).attr("id"),"img");
		});
		$("img[@alt='non']").click(function(){
				redraw("non",$(this).parent("li").prev("li").children("img").attr("id"),"img");
		});
		$("label[@class='souligner']").click(function(){
			var prevAlt = $(this).prev().attr("alt");
			if(prevAlt == "non")
			{
					var previous = $(this).parent("li").prev("li").children("img").attr("id");
					redraw(prevAlt,previous,"label");
			}
			else if(prevAlt == "oui")
			{
					var previous = $(this).attr("for");
					redraw(prevAlt,previous,"label");
			}
		});
	});
}

function callLabel(reference,prefix,identity,imgPath,xml)
{
        connector.XMLUrl=xml+"/"
    
	    $("#"+prefix+"choice1").next().click(function(){
			    connector.putRelation(reference,identity,putRelation('r3', getElement(prefix+'choice1'), getElement(prefix+'choice2'),imgPath))
	    });
	    $("#"+prefix+"choice2").next().click(function(){
			    connector.putRelation(reference,identity,putRelation('r3', getElement(prefix+'choice2'), getElement(prefix+'choice1'),imgPath))
	    });
	    
	    /* Ajout du pointeur sur les labels */
        $("#"+prefix+"choice1").next().mouseover(function(){
            $(this).css("cursor","pointer");
        });
        $("#"+prefix+"choice2").next().mouseover(function(){
            $(this).css("cursor","pointer");
        });
}

