// Popup
var fenetre1visible=false;


//Products
var urlimgs="products.imsgroupe.com";


function fiche(pType, pTitle, pShortDescr, pValidated, pForComm, pPict1, pPict2, pPict3, pPict4, pPict5, pContrainte, pQuant) {
	
	this.Type=pType;
	this.Title=pTitle;
	this.ShortDescr=pShortDescr;
	this.Validated=pValidated;
	this.ForComm=pForComm;
	this.Pict1=pPict1;
	this.Pict2=pPict2;
	this.Pict3=pPict3;
	this.Pict4=pPict4;
	this.Pict5=pPict5;
	this.Contrainte=pContrainte;
	this.Quantite=pQuant;
	
}



function getProduct(id) {
	
	var page="mur/getFiches.php";
	new Ajax.Request(page, {
	    method:	"post",
	    parameters: {fiche: id },
	    onSuccess: function(transport){
	      var xmlinfo = transport.responseText || "no response text";
	      if ( (ifError(xmlinfo))==false) {
		      var products=ProdXmltoArray(xmlinfo);
		      
		      // Memorise in popup list
			  PopupProds=new Array();
			  PopupProds[0]=products[0];
			  selected_activityimg_idx=0;

		  	  showPopup(products[0]);
	      }
	    },
	    onFailure: function(){ alert('Sorry something went wrong on loading of the page '+page ); }
	});
}


function showPopup(pProd) {

	if (!fenetre1visible) {
		fenetre1.show();
		fenetre1.center();

		fenetre1visible=true;
	}
	
	showFicheinPopup(pProd);
}

var actpopupimg=0;

function showImage(link, nid, nimg, effect) {
	
	// Empty queue except last one (to let it terminate smoothly)
	// Effect.Queues.get('popupimg').each(	function(effect,index) { if (index>0) effect.cancel(); 	});
	var uri=link; //encodeURI()
	var imgnode=getNodeRef("popup_img");
	
	// Effect affichage première image
	if (effect=="appear") {
		
		Effect.Queues.get('popupimg').invoke('cancel');
		// si déjà une autre image faire un effet sur lui
		/*if (imgnode.src.indexOf("loading.gif")==-1) {
		//if (imgnode.src!="") {
			Effect.Puff(nid, { duration: 1, queue: { position: 'end', scope:'popupimg'} } );
			Effect.Appear(nid, { duration: 1.5, queue: { position: 'end', scope:'popupimg' }
			});
		}
		else {*/
		
			//Effect.Fade("popup_img", { duration: 0, queue: { position: 'end', scope:'popupimg'}	});
			//$( 'popup_img' ).src=link;
			
			$( 'popup_img2' ).src="";
			$( 'popup_img2' ).setStyle({display:"none"});
			$( 'popup_img' ).setStyle({display:"none"});
			
			// Ca l'air con (de remettre à blanc) mais le temps que la nouvelle image se charge
			// l'ancienne image prend sa role
			$( 'popup_img' ).style.backgroundImage="";
			$( 'popup_img' ).style.backgroundImage="url("+uri+")";
			
			imgnode.src="";
			imgnode.src=uri; // IE<9 ne support pas de dimensionner l'arrière plan
			Effect.Appear("popup_img", {
				duration: 1.2, queue: { position: 'end', scope:'popupimg', limit:1}
			});
			
			// Debug 	setNodeContent("popupimglnk",uri);
		//}
		actpopupimg=1;
	}
	else if (effect=="reverse") {
		
		// Fade out and in
		// var eff_fade=Effect.Fade("popup_img", { duration: 0.5});
		
		$( 'popup_img2' ).src=uri;
		$( 'popup_img2' ).setStyle({display:""});
		//Effect.Opacity('popup_img', { from: 1.0, to:0.2});
		Effect.Shrink('popup_img', { 
			direction:'center',
			queue: { position: 'end', scope:'popupimg', limit:1 },
			afterFinish : function( ) {
				$('popup_img' ).style.backgroundImage="url("+$("popup_img2").src+")";
			  	$("popup_img" ).src=$("popup_img2").src; 
				$("popup_img" ).setStyle({display:""});
			}
		});

		//Effect.Appear('popup_img2', { duration: 0.9,  queue: { position: 'end', scope:'popupimg' }});
		
	}
	// effet decalage images
	else if (effect=="scroll") {
		
		var posstart=0;
		var depl=0;
		var img1="";
		var img2="";
		var nodeid="popup_imgs";
		var imgfade="";
		// mvt <-
		if (nimg>actpopupimg) {
			posstart=0;
			depl=-320;
			img2=uri;
			img1=$("popup_img").src; //stays the same
			imgfade="popup_img";
		}
		// mvt ->
		else {
			posstart=-320;
			depl=320;
			img1=uri;
			img2=$("popup_img2").src;
			imgfade="popup_img2";
		}
		actpopupimg=nimg;
		
		var mveff = new Effect.Move(nodeid, {
			  x:depl, y:0, mode: 'relative',
			  transition: Effect.Transitions.sinoidal,
			  beforeSetup : function( ) {
				  $(nodeid).setStyle({left:posstart+"px"});
				  $("popup_img" ).src=img1; 
				  $("popup_img2").src=img2; 
			  },
			  duration: 0.8 ,
			  queue: { position: 'end', scope:'popupimg'}
		});
		
		//Parallel doestn't work very well : flickers a lot :
		//var hideeff = new Effect.Opacity(imgfade, { from: 1, to: 0 });
		
		/*new Effect.Parallel([mveff,	hideeff ], { 
	     duration: 0.8,
		 queue: { position: 'end', scope:'popupimg'}
		});*/


	
		/*	// In case 2 succeeding effects : first 1 image leaves then another arrives:
 		new Effect.Move(nid, {
			  x: 300, y: 0, mode: 'relative', 
			  transition: Effect.Transitions.sinoidal,
			  duration: 0.8,
			  queue: { position: 'end', scope:'popupimg'},
			  beforeSetup : function( ) {
				$('popup_img').setStyle({ left:0});
			  }
	   		});

		new Effect.Move(nid, {
			  x:-300, y: 0, mode: 'relative',
			  transition: Effect.Transitions.sinoidal,
			  queue: { position: 'end', scope:'popupimg'},
			  beforeSetup : function( ) {
				  $( 'popup_img' ).src=link; 
				  $('popup_img').setStyle({  opacity: 1	});
			  },
			  duration: 0.8
		});
		 */
	}
}


var rangeshown=0;

function showFicheinPopup(pProd) {
	
// Prod : Type, Title, ShortDescr, Validated, ForComm Pict1.. 5

// Elements in popup : 
// *popup_ title, nxtbtn, prevbtn, *loadedimgs, nimg, *img, img2, *text, *thumbs

	// clearPopup(); 

	// Title productcategory  
	var nact = getIndFollowingWSType(pProd.Type);
	var title =capitalize(activityNames[nact]);
	fenetre1.setTitle(title);

	// Image
	var imglink="http://"+urlimgs+"/Images/" + pProd.Pict1;
	showImage(imglink, "popup_img", 0, "appear");
	
	// Shortdescr
	var text="<div style='padding:0px 0px 0px 0px'><b><u>Description </u></b></div>";
	text+=pProd.ShortDescr;
	
	// Contrainte & quantité
	if (pProd.Contrainte.length>2)
		text+="<div style='padding:10px 0px 0px 0px'><b><u>Contrainte</u></b></div>"+pProd.Contrainte;
	
	if (pProd.Quantite > 0)
		text+="<div style='padding:10px 0px 0px 0px'><b><u>Quantit&eacute;</u></b></div>"+pProd.Quantite+" ex.";
	
	setNodeContent("popup_text", text );
	
	// Title
	setNodeContent("popup_title", pProd.Title );
	//getNodeRef("popup_prevbtn").style.display = "none";
	//setNodeContent("popup_nimg", ""+(pselected_activityimg_idx+1)+"/"+wall_images.length );
	
	// Thumbs (at least 2 pictures)
	var thumbs="";
	var pictname=pProd.Pict2;
	if (pictname.length>4) {
		for (var i=0; i<4; i++) {
			var jscmd="pictname=pProd.Pict"+(i+1);
			eval(jscmd);
			if (pictname.length>4) {
				var pictlnk="http://"+urlimgs+"/Images/"+encodeURI(pictname);
				var thumb="<div style=\"float:left; height:59px; margin-left:5px \">";
				thumb+="<img src=\""+pictlnk+"\" height=59px onmouseover=\"showpopupthumb('"+ pictlnk +"',"+(i+1)+")\"></img>";
				thumb+="</div>";
				thumbs+=thumb;
			}
		}
	}

	setNodeContent("popup_thumbs", thumbs );

	
	// Navigation 
	// - buttons 
	// Hide prev btn if first image
	// (Show image num)
	ShowActivityinPopup();
	
	// - loadedimgs
	// Determine range of images to show
	if (selected_activityimg_idx < rangeshown) {
		rangeshown=selected_activityimg_idx;
	}
	else if (selected_activityimg_idx>=rangeshown+6) {
		rangeshown=selected_activityimg_idx-5;
	}
	
	var loadedimgs="";
	
	for (var k=0; k<PopupProds.length; k++) {
		if ( (k>=rangeshown) && (k< (rangeshown+6) ) ) {
			if (loadedimgs!="") loadedimgs+=" ";
			var imglink="http://"+urlimgs+"/Images/" + encodeURI(PopupProds[k].Pict5);
			var color= (selected_activityimg_idx==k) ? "2px yellow" : "thin  gray";
			loadedimgs+="<img src="+imglink+" style='width:37px; height:20px; border:solid "+color+"' title='"+PopupProds[k].Title+"' onmouseup='showPopupImg("+k+")'></img>";
		}
	}
	
	loadedimgs="<div style='display:inline; background:#eee; border-radius:2px; padding:2px 2px 0px 2px'>"+loadedimgs+"</div>";
	setNodeContent("popup_loadedimgs", loadedimgs);

}


function clearPopup() {
	
	var nodeimg=getNodeRef("popup_img");
	if (nodeimg!=undefined && nodeimg!=null) {
		getNodeRef("popup_text").innerHTML="";
		getNodeRef("popup_title").innerHTML="";
	}
	fenetre1.setContent(screencontent);

}


function showpopupthumb(pPict, nimg) {
	showImage(pPict, "popup_img", nimg, "reverse");
}


function ProdXmltoArray(xmlinfo) {
	
	var list = new Array();
	
	var fiches=new Array();
	var pos=0;
	var lastpos=0;
	var tag="</Fiche>";
	while ( (pos=xmlinfo.indexOf(tag, (lastpos+tag.length) ))!=-1) {
		fiches[fiches.length]=xmlinfo.substring(lastpos,pos);
		lastpos=pos+tag.length;
	}

	if (fiches!=null) {
		
		var ind=0;
		var xmlnode=fiches[ind]; 
	
		while (	xmlnode!=undefined && xmlnode!=null) {
			list[list.length] = getProductXml(xmlnode);
			xmlnode=fiches[++ind];
		}
	}

	return list;
}


function getProductXml(xmlnode) {
	
    var nodes=["Type", "Titre", "Descr_Partiel", "Validation", "Communication", "Photo1", "Photo2", "Photo3", "Photo4", "Photo5", "contrainte", "quantite"];
	var values=new Array();
	var debuginfo="";
	for (var i=0; i<nodes.length; i++) {
		values[i]=getTagInfo(nodes[i], xmlnode);
	}
	var Prod = new fiche (
		values[0], 	values[1],	values[2],	values[3],
		values[4],	values[5],	values[6],	values[7],
		values[8],	values[9],	values[10],	values[11]
	);
	return Prod; 	
}


// Product popup
var fenetre1 = null;


function loadFenetre(pathtoroot){
	
	var imgspath='mur/popup_aswin/imgs/';
	if (pathtoroot!=undefined && pathtoroot!=null)
		imgspath=pathtoroot+"/"+imgspath;
		
	var options1 = 	{
		title : 'Activity',
		content : screencontent,
		modal : true,
		onclickBgClose: true,
		imgBase : imgspath,
		noEffects : false,
		draggable : false,
		afterclose : function() { fenetre1visible=false;}
	};
					
	fenetre1 = new ASWin(options1);
	//fenetre1.setTitle(''); fenetre1.setContent(screencontent);

}


// Product types 

var activityNames=new Array(); 
activityNames[0]="Merchandising"; // 26
activityNames[1]="Marketing"; //24
activityNames[2]="Prise de vue";
activityNames[3]="Pré-presse";
activityNames[4]="Edition"; //23
activityNames[5]="PLV"; //6
activityNames[6]="Packaging"; //25
activityNames[7]="Logistique";

var type=-1; //-1 for all activities;

var types = new Array(26, 24, 0, 0, 23, 6, 25, 0);

function getIndFollowingWSType(ptype) {
	
	for (var i=0; i<types.length; i++) {
		if (types[i]==ptype) return(i);
	}
	return(-1);
}



// General functions

function capitalize(pstr) { return ( pstr.substr(0,1).toUpperCase() + pstr.substr(1) );}


