// ---------------------------------------------------------------------------------------------------------------
// 
// 
// 
//                                                                           site mix, realisation glazfab 2008
// 
// ---------------------------------------------------------------------------------------------------------------

// ---------------------------------------------------------------------------------------------------------------
//    INITIALISATION
// ---------------------------------------------------------------------------------------------------------------

// browser identification
ns4 = (document.layers);
ns6 = (!document.all && document.getElementById);
ie4 = (document.all && !document.getElementById && !window.opera);
ie5 = (document.all && !document.fireEvent && !window.opera);
op7 = (window.opera && document.createComment) ;
w3dom = (document.getElementById || op7);
//alert("ns4: "+(ns4!=null)+", ns6: "+(ns6!=null)+", ie4: "+(ie4!=null)+", ie5: "+(ie5!=null)+", op7: "+(op7!=null)+", w3dom: "+(w3dom!=null));
rootpath = window.location.protocol + "//" + window.location.hostname + window.location.pathname;
rootpath = rootpath.substr(0,rootpath.length-9);
//alert("path: " + rootpath);
var dumpw = null;

// query string management
var qsParm = new Array();
qsParm['type'] = null;
qsParm['page'] = null;
qs();
var actionqueue = "";


// scrolling and mouse wheel inti
var scrolling = false;
var scrolling_speed = 3;
var scroll_timer = null;
var wheelling_speed = 15;
if (window.addEventListener) window.addEventListener('DOMMouseScroll', wheel, false); // (Mozilla)
window.onmousewheel = document.onmousewheel = wheel; // IE and Opera


// ref database objects
var catalogue_loaded = false;
var catalogue = {
	nbproperties: 9,
	titles: new Array(),
	authors: new Array(),
	collindex: [new Array(), new Array(), new Array()],
	addauthor: function (acode,afirstname,aname) {
		this.authors.push({code:acode,firstname:afirstname,name:aname,idxtitles:new Array()});
		},
	addtitle: function(tisbn,ttitleformat,ttitle,tcodeaut,tmonth,tyear,tcoll,tpages,tprice) {
		this.titles.push({isbn:tisbn,titlef:ttitleformat,title:ttitle,aidx:new Array(),month:tmonth,year:tyear,coll:tcoll,pages:tpages,price:tprice});
		this.collindex[tcoll].push(this.titles.length-1);
		var auttable = tcodeaut.split(",");
		for (i=0;i<auttable.length;i++) {
			found = false;
			for (j=0;j<this.authors.length;j++) {
				if (auttable[i]==this.authors[j].code) {
					this.titles[this.titles.length-1].aidx.push(j);
					this.authors[j].idxtitles.push(this.titles.length-1);
					found = true;
					break;
				}
			}
		}
		if (!found)  {alert("author not found");this.titles[this.titles.length-1].aidx.push(0);this.authors[0].idxtitles.push(this.titles.length-1)}
		},
	resetall: function() {
		this.titles = new Array();
		this.authors = new Array();
		this.collindex = [new Array(), new Array(), new Array()]; 
		},
	listauthors: function(titleidx, format) {
		var current_author = this.authors[this.titles[titleidx].aidx[0]];
		var current_author_firstname = (format=="long"?current_author.firstname:shortenFirstname(current_author.firstname));
		var authorlist = (current_author_firstname==""?current_author.name:current_author_firstname+(format=="long"?" ":"")+current_author.name);
		for (a=1;a<this.titles[titleidx].aidx.length;a++) {
			current_author = this.authors[this.titles[titleidx].aidx[a]]
			var current_author_firstname = (format=="long"?current_author.firstname:shortenFirstname(current_author.firstname));
			authorlist += (format=="long"?", ":"+") + (current_author_firstname==""?current_author.name:current_author_firstname+(format=="long"?" ":"")+current_author.name);
		}
		return authorlist;
		},
	findref: function(risbn) {		
		var sisbn = risbn.substr(6,risbn.length);
		var tidx = -1;
		for (i=0;i<this.titles.length;i++) {
			if (this.titles[i].isbn == sisbn) {
				tidx = i;
				break;
			}
		}
		return tidx;
		},
	computerisbn: function(titleidx) {
		return this.titles[titleidx].coll+"-"+this.authors[this.titles[titleidx].aidx[0]].code+"-"+this.titles[titleidx].isbn;
		}
};


// ref and shopping cart variables
var current_ref = "";
var first_buy = true;
var cart = {
	items: new Array(),
	nbitems: 0,
	pricetotal: 0.0,
	additem: function(iref,iname,iprice) {
		var cprice = iprice.replace(",",".");
		this.items.unshift({name:iname,ref:iref,quant:1,price:parseFloat(cprice)});
		this.pricetotal += parseFloat(cprice);
		this.nbitems += 1;
		},
	delitem: function(idx) {
		var p = this.items[idx].price, q = this.items[idx].quant;
		this.items.splice(idx,1);
		this.pricetotal -= p;
		this.nbitems -= q;
		},
	findref: function(sref) {
		var found = -1;
		for (i=0; i<this.items.length; i++) { if (this.items[i].ref == sref) { found =i ; break; } }
		return found;
		}
};
var compte_paypal = "collectifmix@hotmail.com";


// ---------------------------------------------------------------------------------------------------------------
//    BASIC ROUTINES
// ---------------------------------------------------------------------------------------------------------------

// content access and cross-browser functions
function MM_reloadPage(init) {  //reloads the window if Nav4 resized
  if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
    document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
  else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}
MM_reloadPage(true);

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function findObj(id) {
// locate an HTML object in current document
	if(ns4) {
		obj = document[id].document;
	} else if(ie4 || ie5) {
		obj = document.all[id];
	} else if(w3dom) {
		obj = document.getElementById(id);
	}
	return obj;
}

function qs() {
// parse query string and return param values
	var query = window.location.search.substring(1);
	var parms = query.split('&');
	for (var i=0; i<parms.length; i++) {
		 var pos = parms[i].indexOf('=');
		 if (pos > 0) {
			 var key = parms[i].substring(0,pos);
		  var val = parms[i].substring(pos+1);
		  qsParm[key] = val;
      }
   }
}

function fileRequest(file_url, success_act, fail_act, post_act) {
// perform an AJAX request
	var request = null;
	if(window.XMLHttpRequest) // Firefox   
    	request = new XMLHttpRequest();   
 	else if(window.ActiveXObject) // Internet Explorer   
    	request = new ActiveXObject("Microsoft.XMLHTTP");   
 	else { // XMLHttpRequest non supporté par le navigateur   
    	alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...\n\nCe site ne pourra pas fonctionner.");
    	return;
	}
	request.open("GET", file_url, true);
	request.onreadystatechange = function() {
		if(request.readyState == 4) {
			if((request.status == 200) || (request.status == 0)){
				//alert("file received ok");
				//alert("executing succes: " + success_act);
				eval(success_act);
			} else {
				//alert("file missing");
				//alert("executing fail: " + fail_act);
				eval(fail_act)
			}
			//alert("executing post: " + post_act);
			eval(post_act);
		}
	}
	request.send(null);
}

function shortenFirstname(fn) {
// return appropriate abbreviation for a given author's firstname
	var shortfirst =fn.substr(0,1);
	for (sep=1;sep<fn.length;sep++) {
		if ((fn[sep]=="-")||(fn[sep]==".")) {
			shortfirst += (sep==(fn.length-1)?"":".") + (fn[sep]=="-"?"-":"") + (sep==(fn.length-1)?"":fn[sep+1]);
			sep++;
		}
	}
	return shortfirst + ".";
}

function std_ize(str) {
// replace ponctuation by standard characters
	var p_rchar = [["\'"," "],["\"",""],["…","..."]];

	var std_str = str;
	for (c=0;c<p_rchar.length;c++) {
		std_str = std_str.replace(p_rchar[c][0],p_rchar[c][1]);
	}
	return std_str;
}

// ---------------------------------------------------------------------------------------------------------------
//    INTERFACE ROUTINES
// ---------------------------------------------------------------------------------------------------------------

function swapIcon(icon_name,img_name) {
// swap an icon image
	var ic = findObj(icon_name);
	ic.src = ic.src.substring(0,ic.src.length-10) + img_name;
}

function showMsg(msg_txt, msg_delay) {
// display a msg in msg box for a given duration
	var msg_div = findObj("msgpane");
	if (msg_txt == "") {
		msg_div.style.visibility = "hidden";
	} else {
		msg_div.innerHTML = "<p class='menutxt'>" + msg_txt + "</p>";
		msg_div.style.visibility = "visible";
		setTimeout("showMsg('',0)", msg_delay);
	}
}

function showDetails(show,titletxt,file,w) {
// display details window with the requested content
	var details_div = findObj("detailspane"), details_header_div = findObj("detailspane_header");
	var details_title_div = findObj("detailspane_title"), details_content_div = findObj("detailspane_content");
	details_content_div.style.width = details_header_div.style.width = details_div.style.width = ((w3dom)?w+"px":w);
	if ((show)&&(details_content_div.innerHTML == "")) {
		details_title_div.innerHTML = titletxt;
		var url = rootpath + "catalogue/titres/" + file;
		//alert("loading details:  " + url);
		details_content_div.innerHTML = "<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p style='text-align:center;'><img src='img/wait_large.gif' width='33' height='15' /></p>";
		var success_action = "findObj('detailspane_content').innerHTML = request.responseText;"; 
		var fail_action = "findObj('detailspane_content').innerHTML = '<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p class=\"erreur\" style=\"text-align:center\"><<strong>erreur: </strong>Fiche d&eacute;tails manquante.></p>'";
		fileRequest(url, success_action, fail_action, "");
		details_div.style.visibility = "visible";
	} else {
		details_div.style.visibility = "hidden";
		details_title_div.innerHTML = "";
		details_content_div.innerHTML = "";
	}
}

// ---------------------------------------------------------------------------------------------------------------
//    PAGE MANAGEMENT
// ---------------------------------------------------------------------------------------------------------------

function divSetup(parent,id,left,top,zindex,visibility) {
// dynamic DIV cross-browser constructor
	if(ns4) {
		this.obj = (parent != null) ? parent.document[id] : document[id];
		this.obj.htm = (parent != null) ? parent.document[id].document : document[id].document;
	} else if(ie4 ||ie5) {
		this.obj = document.all[id].style;
		this.obj.htm = document.all[id];
	} else if(w3dom) {
		this.obj = document.getElementById(id).style;
		this.obj.htm = document.getElementById(id);
	}
	this.obj.left = (w3dom) ? left + "px" : left;
	this.obj.top = (w3dom) ? top +"px" : top;
	this.obj.zIndex = zindex;
	this.obj.visibility = visibility;	
	return this.obj;
}

function init() {
// prepare variables for page management
	var par = findObj("extframe");
	content = new divSetup(par,"page",24,90,7,"visible");
	content.top = (w3dom) ? 0 +"px" : 0;
	content.left = (w3dom) ? 0 +"px" : 0;
//load database files
	loadCatalogue();
}

function autoLoad() {
// open page  requested by query string
	if (catalogue_loaded) {
		var typ = qsParm['type'];
		var pg = qsParm['page'];
		//alert("autoOpen: type=" + typ + ", page=" + pg);
		switch(typ) {
			case "page":
				loadPage(pg);
				break;
			case "ref":
				loadPage("catalogue");
				var idx = catalogue.findref(pg);
				if (idx != -1) displayRef("", idx);
				break;
			case "buy":
				loadPage("catalogue");
				switch(pg) {
					case "paid":
						findObj("bookref").innerHTML = "<p class='msg' style='text-align:center'>Merci !<br/ >Votre paiement a bien &eacute;t&eacute; pris en compte.</p><p class='msg' style='text-align:center'>Vous recevrez sous peu un email de confirmation<br/ >et la commande vous sera envoy&eacute;e.</p><p class='msg' style='text-align:center'>Pour toute demande sp&eacute;cifique, contacter :<br/ ><a href='mailto:info@editionsmix.org'>info@editionsmix.org</a>.</p></span>";
						findObj("bookref").style.display = "block";
						findObj("basketbtn").innerHTML = "<img src='img/blank.gif' width='91' height='5' /><b><a href='javascript:;' onclick='closeRef();findObj(&quot;basketbtn&quot;).style.visibility = &quot;hidden&quot;'>continuer</a></b>";
						findObj("basketbtn").style.visibility = "visible";
						break;
					case "cancelled":
						findObj("bookref").innerHTML = "<p class='msg' style='text-align:center'>Votre commande a &eacute;t&eacute; annul&eacute;e,<br/ >aucun paiement n\'a &eacute;t&eacute; effectu&eacute;.</p><p class='msg' style='text-align:center'>Recommencez une nouvelle commande<br/ >quand vous le souhaitez.</p></span>";
						findObj("bookref").style.display = "block";
						findObj("basketbtn").innerHTML = "<img src='img/blank.gif' width='91' height='5' /><b><a href='javascript:;' onclick='closeRef();findObj(&quot;basketbtn&quot;).style.visibility = &quot;hidden&quot;'>continuer</a></b>";
						findObj("basketbtn").style.visibility = "visible";
						break;
				}
				break;
			case "debug":
				loadPage("catalogue");
				dumpw = window.open("pages/dump.html","dumpwindow","scrollbars=yes,resizable=yes,width=600,height=600");
			break
		}
	}
}

function loadPage(pname) {
// load a page into main iframe
	findObj("tag").style.visibility = "hidden";
	content.htm.innerHTML = "<img src='img/wait_large.gif' width='33' height='15' />";
	var ifr = findObj("pageframe");
	ifr.src = rootpath + "pages/" + pname + ".html";
}

function changePage() {
// standard tasks for page swapping
	showDetails(false);
	closeRef();
}

function initPage(pnb) {
// copy content from iframe to page container and perform several init tasks for the newly loaded page
	if (content.htm) {
		setTag(pnb);
		if(ie4) {
			content.htm.innerHTML = document.frames['pageframe'].document.body.innerHTML;
		} else if(w3dom) {
			content.htm.innerHTML = window.frames.pageframe.document.getElementById('body').innerHTML;
		}
		content.top = (w3dom) ? 0 +"px" : 0;
		setScrollBtns();
		if (pnb==3) fillCollections();
		var typ = qsParm['type'];
		var pg = qsParm['page'];
		if ((typ=="ref")&&pg) {
			var coll = pg.substr(0,1);
			if (coll) {
				var collname = (coll=="0")?"noirs":((coll=="1")?"gris":(coll=="2")?"blancs":null);
				var notice_id = "not_" + coll + "_" + pg.substr(2,3) + "_" + pg.substr(6,pg.length);
				if (collname) {
					toggleCollection(collname);
					toggleNotice(notice_id);
				}
			} 
		}
	}
}

function setTag(menu_id) {
// set tag position above menu items
	var m = findObj("menu"+menu_id);
	var t = findObj("tag");
	t.style.left = parseInt(m.style.left)+parseInt(m.style.width)/2-2+"px";
	t.style.visibility = "visible";
	return false;
}

// ---------------------------------------------------------------------------------------------------------------
//    SCROLLING FUNCTIONS
// ---------------------------------------------------------------------------------------------------------------

function setScrollBtns() {
// test overflow/scrolling state of page content and display or hide scrolling buttons accordingly
	var cont = findObj("page_container");
	var top_offset = parseInt(content.top);
	var down_offset = content.htm.offsetHeight + top_offset - cont.clientHeight;
	var btn_scroll_up = findObj("btnscrollup");
	var btn_scroll_dn = findObj("btnscrolldown");
	//alert("cont height: " + cont.clientHeight + "\n" + "page height: " + content.htm.offsetHeight);
	//alert("top offset: " + top_offset + "\n" + "down offset: " + down_offset);
	if (top_offset < 0) {
		btn_scroll_up.style.display = "block";
	} else {
		btn_scroll_up.style.display = "none";
	}
	if (down_offset > 0) {
		btn_scroll_dn.style.display = "block";
	} else {
		btn_scroll_dn.style.display = "none";
	}
}

function scrollPageTo(position) {
// scroll page content to chosen position
	//alert("scrolling to: " + position);
	content.top = (w3dom) ? position +"px" : position;
	setScrollBtns();
}

function scrollDown() {
// scroll down page content
	var cont = findObj("page_container");
	if (scrolling) {
		var newtop = parseInt(content.top) - scrolling_speed;
		scrollPageTo(newtop);
		if (newtop <  (cont.clientHeight - content.htm.offsetHeight)) { 
			scrollToBottom();
			scrolling = false;
		}
		scroll_timer = setTimeout(scrollDown,0);
	}
}

function scrollUp() {
// scroll up page content
	var cont = findObj("page_container");
	if (scrolling) {
		var newtop = parseInt(content.top) + scrolling_speed;
		scrollPageTo(newtop);
		if (newtop >  0) { 
			scrollToTop();
			scrolling = false;
		}
		scroll_timer = setTimeout(scrollUp,0);
	}
}

function vScroll(direction) {
// control scrolling start and stop
	switch (direction) {
		case "up":
			scrolling = true;
			scrollUp();
			break;
		case "down":
			scrolling = true;
			scrollDown();
			break;
		case "stop":
			scrolling = false;
			clearTimeout(scroll_timer);
			break;
	}
}

function scrollToBottom() {
// scroll page content dirctly to bottom of page
	var cont = findObj("page_container");
	scrollPageTo(cont.clientHeight - content.htm.offsetHeight);	
}

function scrollToTop() {
// scroll page content directly to page top
	content.top = (w3dom) ? 0 +"px" : 0;
}

function handleWheel(delta) {
// scroll page up or down according to mouse wheel movement
	var cont = findObj("page_container");
	if (delta < 0) {
		var newtop = parseInt(content.top) - wheelling_speed;
		if (newtop <  (cont.clientHeight - content.htm.offsetHeight)) {
			scrollToBottom(); 
		} else {
			scrollPageTo(newtop);
		}
	} else {
		var newtop = parseInt(content.top) + wheelling_speed;
		if (newtop >  0) {
			scrollToTop();
		} else {
			scrollPageTo(newtop);
		}
	}
}

function wheel(event){
// catch mouse wheel event and send movement to handleWhell
	var delta = 0;
	if (!event) /* For IE. */
		event = window.event;
	if (event.wheelDelta) { /* IE/Opera. */
		//alert(event.wheelDelta);
		delta = event.wheelDelta/120; 
	} else if (event.detail) { /** Mozilla case : sign of delta is different than in IE. Also, delta is multiple of 3. */
		//alert(event.detail);
		delta = -event.detail/3;
	}
	//alert(delta);
    if (delta) handleWheel(delta);
    if (event.preventDefault) event.preventDefault();
	event.returnValue = false;
}

// ---------------------------------------------------------------------------------------------------------------
//    INDEX MANAGEMENT
// ---------------------------------------------------------------------------------------------------------------

function loadCatalogue() {
// load index files and initiate treatment
	var url = rootpath + "catalogue/index_auteurs.txt";
	fileRequest(url, "parseAuthors(request.responseText)", "content.htm.innerHTML = '<p class=\"erreur\"><<strong>erreur: </strong>catalogue g&eacute;n&eacute;ral auteurs manquant.>'", "");
}

function parseAuthors(rawtext) {
// parse rawtext to build authors index
	var allauthors = rawtext.split("\n");
	//alert("Authors: " + allauthors.length + " lignes read");
	catalogue.resetall();
	for (a=0;a<allauthors.length;a++) {
		adetails = allauthors[a].split("\t");
		if (adetails.length == 3) {
			catalogue.addauthor(adetails[0],adetails[1],adetails[2]);
		}
	}
	//alert(catalogue.authors.length + " authors added.");
	var url = rootpath + "catalogue/index_titres.txt";
	fileRequest(url, "parseTitles(request.responseText)", "content.htm.innerHTML = '<p class=\"erreur\"><<strong>erreur: </strong>catalogue g&eacute;n&eacute;ral titres manquant.>'", "");
}

function parseTitles(rawtext) {
// parse rawtext to build titles index
	var alltitles = rawtext.split("\n");
	//alert(alltitles.length + " lignes read");
	for (t=0;t<alltitles.length;t++) {
		tdetails = alltitles[t].split("\t");
		if (tdetails.length == catalogue.nbproperties) {
			addstring = "catalogue.addtitle(";
			for (p=0;p<catalogue.nbproperties;p++) {
				addstring += "tdetails[" + p + "],";
			}
			addstring = addstring.substr(0,addstring.length-1) + ")";
			eval(addstring);
		}
	}
	//alert(catalogue.titles.length + " titles added (noirs: " + catalogue.collindex[0].length + ", gris: " + catalogue.collindex[1].length + ", blancs: " + catalogue.collindex[2].length + ")");
	if (catalogue.titles.length > 0) {
		catalogue_loaded = true;
		// auto load if needed else load default page
		var typ = qsParm['type'];
		var pg = qsParm['page'];
		if ((typ)&&(pg)) {
			autoLoad();
		} else {
			loadPage("actu");
		}
	}
}

function dumpCatalogue() {
// open a new window to list catalogue database
	var htmlstr = "<p class='msg'>## Contenu du catalogue charg&eacute; :</p><p></p>";
	htmlstr += "<p class='msg'>## AUTEURS - total: " + catalogue.authors.length + "</p>";
	htmlstr += "<table width='370' border='0' cellspacing='0' cellpadding='0' class = 'msg'>";
	htmlstr += "<tr><td width='30' align='right'><b>ID</b></td><td width='38' align='right'><b>CODE</b></td><td width='14' align='right'>&nbsp;</td><td width='170'><b>NOM, PR&Eacute;NOM</b></td><td><b>ID TITRES LI&Eacute;S</b></td></tr>";
	htmlstr += "<tr><td colspan='5'><img src='" + rootpath +"/img/black.gif' width='100%' height='1' /></td></tr>";
	for (a=0;a<catalogue.authors.length;a++) {
		htmlstr += "<tr>";
		htmlstr += "<td align='right'>" + a + "</td><td align='right'>" + catalogue.authors[a].code + "</td><td>&nbsp;</td><td>" + catalogue.authors[a].name + (catalogue.authors[a].firstname==""?"":", "  + catalogue.authors[a].firstname) + "</td><td>";
		var ttls = "";
		for (t=0;t<catalogue.authors[a].idxtitles.length;t++) {
			ttls += catalogue.authors[a].idxtitles[t] + ", ";
		}
		ttls = ttls.substr(0,ttls.length-2);
		htmlstr += (ttls==""?"&nbsp;":ttls);
		htmlstr += "</td></tr>";
	}
	htmlstr += "</table><p></p>";
	htmlstr += "<p class='msg'>## TITRES - total: " + catalogue.titles.length + "</p>";
	htmlstr += "<table width='840' border='0' cellspacing='0' cellpadding='0' class = 'msg'>";
	htmlstr += "<tr><td width='30' align='right'><b>ID</b></td><td width='110' align='right'><b>ISBN</b></td><td width='14'>&nbsp;</td><td width='210'><b>TITRE LONG</b></td><td width='180'><b>TITRE COURT</b></td><td width='80'><b>ID AUTEURS</b></td><td width='95'><b>PARUTION</b></td><td width='43'><b>COLL</b></td><td width='33'><b>PAGES</b></td><td width='45' align='right'><b>PRIX</b></td></tr>";
	htmlstr += "<tr><td colspan='12'><img src='" + rootpath +"/img/black.gif' width='100%' height='1' /></td></tr>";
	for (t=0;t<catalogue.titles.length;t++) {
		htmlstr += (t%2>0?"<tr valign='top' bgcolor='#DDDDDD'":"<tr valign='top'>");
		htmlstr += "<td align='right'>" + t + "</td><td align='right'>" + catalogue.titles[t].isbn + "<td>&nbsp;</td><td>" + catalogue.titles[t].titlef + "</td><td>" + catalogue.titles[t].title + "</td><td>";
		var auts = "";
		for (a=0;a<catalogue.titles[t].aidx.length;a++) {
			auts += catalogue.titles[t].aidx[a] + ", ";
		}
		auts = auts.substr(0,auts.length-2);
		htmlstr += (auts==""?"&nbsp;":auts);
		htmlstr += "</td><td>" + catalogue.titles[t].month + " " + catalogue.titles[t].year + "</td><td>" + catalogue.titles[t].coll + "</td><td>" + catalogue.titles[t].pages + "</td><td align='right'>" + catalogue.titles[t].price + "</td>";
		htmlstr += "</tr>";	
	}
	htmlstr += "</table>";
	dumpw.document.getElementById("dmp").innerHTML = htmlstr;
}

function fillCollections() {
// load all 3 collections
	if (findObj("idx_noirs").innerHTML=="") {
		fillCollection("noirs", "titres");
		fillCollection("gris", "titres");
		fillCollection("blancs", "titres");
	}
}

function fillCollection(coll_name,index_name) {
// format collection index html and write it on catalogue page at coorect location
	var index_div = findObj("idx_"+coll_name); 
	index_div.innerHTML = "<p class='texte'><img src='img/wait_small.gif' width='26' height='10' /></p>";
	setScrollBtns();
	var htmlstr = "";
	var coll_ref = (coll_name=="noirs")?0:((coll_name=="gris")?1:2);
	//alert("loading collection " + coll_name + " as " + index_name);
	switch(index_name) {
		case "titres":
			for (i=0;i<catalogue.collindex[coll_ref].length;i++) {
				var current_title = catalogue.titles[catalogue.collindex[coll_ref][i]];
				var current_author = catalogue.authors[current_title.aidx[0]];
				var notice_id = "not_" + coll_ref + "_" + current_author.code + "_" + current_title.isbn;
				var authorstring = catalogue.listauthors(catalogue.collindex[coll_ref][i],"long");
				htmlstr += "<p class='texte_index_titres'><a href='javascript:;' onclick='toggleNotice(&quot;" + notice_id + "&quot;);setScrollBtns();displayRef(&quot;" + notice_id + "&quot;,&quot;" + catalogue.collindex[coll_ref][i] + "&quot;)'><strong>" + current_title.title + "</strong>, " + authorstring + ", " + current_title.year + "</a></p>";
				htmlstr += "<div id='" + notice_id + "' class='notice' style='display:none;'>";
				htmlstr += "<p class='libel'>l&#39;auteur :</p><div id='bio_" + notice_id + "'></div></div>";
			}
			break;
		case "auteurs":
			for(i=0;i<catalogue.authors.length;i++) {
				var current_author = catalogue.authors[i];
				firsttitle = true;
				for (j=0;j<catalogue.authors[i].idxtitles.length;j++) {
					var atitle = catalogue.titles[current_author.idxtitles[j]];
					if (atitle.coll == coll_ref) {
						var author_ref = current_author.code;
						var author_fullname = (current_author.firstname==""?current_author.name:current_author.firstname+ " " + current_author.name);
						var notice_id = "not_" + coll_ref + "_" + author_ref;
						if (firsttitle) {
							htmlstr +="<p class='texte_index_auteurs'><a href='javascript:;' onclick='toggleNotice(&quot;" + notice_id + "&quot;);setScrollBtns()'>" + current_author.firstname + " <strong>" + current_author.name + "</strong></a></p>";
							htmlstr += "<div id='" + notice_id + "' class='notice' style='display:none;'><div id='bio_" + notice_id + "'></div>";
	      					htmlstr += "<p class='mention'>aux &eacute;ditions mix, dans la collection &laquo; " + coll_name +" &raquo; :</p>";
							firsttitle = false;
						}
						htmlstr += "<p class='auteur-titre'>&bull; <a href='javascript:;' onclick='displayRef(&quot;&quot;,&quot;" + current_author.idxtitles[j] + "&quot;)'>" + atitle.title + ", " + atitle.year + "</a></p>";
					}
				}
				htmlstr += "</div>";
			}
			break;
	}
	index_div.innerHTML = htmlstr;
	setScrollBtns();
}

function toggleCollection(coll_name) {
// expand or close collection display
  //alert("toggling collection: " + coll_name);
  var idx = findObj("idx_"+coll_name);
  var btn = findObj("boutons_"+coll_name);
  var icn = findObj("icon_"+coll_name);
  if (idx) {
 	 if (idx.style.display == "none") {
		icn.style.visibility = "hidden";
  		idx.style.display = "block";
		btn.style.visibility = "visible";
  	} else {
		icn.style.visibility = "visible";
		idx.style.display = "none";
		btn.style.visibility = "hidden";
		closeRef();
  	}
  }
  setScrollBtns();
}

function switchIndex(c_name,i_name) {
// switch index buttons state and reload an indexed collection
	var btn_div = findObj("boutons_" + c_name);
	switch(i_name) {
		case "auteurs":
			btn_div.innerHTML = "<em>auteurs</em>  |  <a href='javascript:;' onclick='switchIndex(&quot;"+c_name+"&quot;,&quot;titres&quot;);'>titres</a>";
			fillCollection(c_name,"auteurs");
			break;
		case "titres":
			btn_div.innerHTML = "<a href='javascript:;' onclick='switchIndex(&quot;"+c_name+"&quot;,&quot;auteurs&quot;);'>auteurs</a>  |  <em>titres</em>";
			fillCollection(c_name,"titres");
			break;
	}
}

function toggleNotice(notice_id) {
// expand or close a notice
	var not = findObj(notice_id);
	//alert("toggling notice: " + notice_id);
	if (not) {
		if (not.style.display == "none") {
			not.style.display = "block";
			loadBio(notice_id.substring(6,9),"bio_"+notice_id);
		} else {
			not.style.display = "none";
			closeRef();
		}
		setScrollBtns();
	}
}

function loadBio(author_ref,biodivnm) {
// loads a bio file and writes the content into the corresponding div
	var bio_dv = findObj(biodivnm);
	if (bio_dv.innerHTML == "") {
		//alert("loading bio: " + author_ref + " into div: " + biodivnm);
		var url = rootpath + "catalogue/auteurs/" + author_ref + ".html";
		//alert("loading bio, at url:" + url);
		bio_dv.innerHTML = "<p class='texte'><img src='img/wait_small.gif' width='26' height='10' /></p>";
		var success_action = "findObj('"+biodivnm+"').innerHTML = request.responseText;"; 
		var failure_action = "findObj('"+biodivnm+"').innerHTML = '<p class=\"erreur\" style=\"margin-left:15px;\"><<strong>erreur: </strong>notice manquante.></p>'";
		var post_action = "setScrollBtns()"
		fileRequest(url, success_action, failure_action, post_action);
	}
}

// ---------------------------------------------------------------------------------------------------------------
//    REF. MANAGEMENT
// ---------------------------------------------------------------------------------------------------------------

function displayRef(divname, refidx) {
// find ref's details in global index and write html accordingly in ref div
	if ((divname == "")||((divname != "")&&(findObj(divname).style.display == "block"))) {
		var book_div = findObj("bookref");
		book_div.innerHTML = "<p>&nbsp;</p><p>&nbsp;</p><p>&nbsp;</p><p style='text-align:center;'><img src='img/wait_book.gif' width='33' height='15' /></p>";
		var ref = catalogue.titles[refidx];
		var risbn=catalogue.computerisbn(refidx);
		var authorstring = catalogue.listauthors(refidx, "long");
		var refpr = (ref.price.indexOf("EP")>-1?"[&Eacute;PUIS&Eacute;]":(ref.price.indexOf("ND")>-1?"[BIENTOT DISPONIBLE...]":ref.price + "  &euro;"));
		var refpgs = (ref.pages==0?"":"<p class='descr'>" + ref.pages + " pages</p>");
		current_ref = refidx;
		htmlstr = "";
		htmlstr += "<div class = 'ref'>";
		htmlstr += "<a href='javascript:;' onclick='MM_openBrWindow(&quot;catalogue/titres/" + risbn + "-large.pdf&quot;,&quot;imgpreview&quot;,&quot;scrollbars=no,resizable=no,width=800,height=590&quot;)'><img src='img/xxx.gif' name='couv' width='230' height='180' border='0' lowsrc='img/xxx.gif' id='couv'/></a><br />";
		htmlstr += "<p class='titre'><span style='font-size: 11px'>" + authorstring +"</span> " + ref.titlef + "</p>";
		htmlstr += "<div class='notice' id='summary'></div>";
		htmlstr += "<p class='descr'>" + ref.month + " " + ref.year + "</p>";
		htmlstr += refpgs;
		htmlstr += "<p class='descr'>ISBN " + ref.isbn + "</p>";
		htmlstr += "<p class='descr'>" + refpr + "</p>";
		htmlstr += "<p class='btns'><a href='javascript:;' onclick='MM_openBrWindow(&quot;catalogue/titres/" + risbn + "-pages.pdf&quot;,&quot;preview&quot;,&quot;scrollbars=yes,resizable=yes,width=800,height=600&quot;)'>premi&egrave;res pages</a><img src='img/blank.gif' width='6' height='5' />|<img src='img/blank.gif' width='6' height='5' />";
		if ((ref.price.indexOf("EP")>-1)||(ref.price.indexOf("ND")>-1)) {
			htmlstr += "<span style='color:#555555'><b><em>acheter en ligne (PayPal)</em></b></span>";
		} else {
			htmlstr += "<a href='javascript:;' onclick='buyRef(&quot;" + refidx + "&quot;)'>acheter en ligne (<em>PayPal</em>)</a>";
		}
		htmlstr += "<img src='img/blank.gif' width='12' height='5' /><a href='javascript:;' onclick='closeRef()' onmouseout='swapIcon(&quot;closeref&quot;,&quot;close0.gif&quot;)' onmouseover='swapIcon(&quot;closeref&quot;,&quot;close1.gif&quot;)'><img src='img/close0.gif' name='closeref' width='11' height='11' border='0' align='absmiddle' id='closeref' /></a></p>";
		htmlstr += "</div>";
		book_div.innerHTML = htmlstr;
		refreshRefImg();
		loadSummary();
	} else {
		closeRef();
	}
}

function closeRef() {
// close current book ref and other ref relative windows
	findObj("bookref").innerHTML = "";
	findObj("cartcontent").innerHTML = "";
	findObj("cartpane").style.display = "none";
	showDetails(false);
	current_ref = "";
}

function refreshRefImg() {
// load a title img file into buffer image
	var ref_img = findObj("couv"); var ibuf = findObj("imgbuffer");
	//alert("refreshImg: current_ref=" + current_ref + ", img: " + ibuf.src.substring(0,ibuf.src.length-11) + "catalogue/titres/" + current_ref + ".gif");
	ibuf.src = ref_img.src.substring(0,ref_img.src.length-11) + "catalogue/titres/" + catalogue.computerisbn(current_ref) + ".gif";
}

function loadSummary() {
// loads a bio file and writes the content into the corresponding div
	var url = rootpath + "catalogue/titres/" + catalogue.computerisbn(current_ref) + ".html";
	//alert("loading summary at url: " + url);
	findObj('summary').innerHTML = "<p class='texte'>...</p>";
	var success_action = "findObj('summary').innerHTML = request.responseText";
	var failure_action = "findObj('summary').innerHTML = '.'";
	fileRequest(url, success_action, failure_action, "");
}

// ---------------------------------------------------------------------------------------------------------------
//    SHOPPING CART FUNCTIONS
// ---------------------------------------------------------------------------------------------------------------

function buyRef(rfidx) {
// perform paypal order of selected ref
	var risbn = catalogue.computerisbn(rfidx), refprice = catalogue.titles[rfidx].price;
	//alert("buying title ISBN " + risbn + ", price: " + refprice);
	if (refprice) {
		var refname = catalogue.listauthors(rfidx, "short") + ", " + catalogue.titles[rfidx].title;
		var msgtxt = "Ce titre a &eacute;t&eacute; ajout&eacute; &agrave; votre commande.";
		var dl = 1500;
		if (first_buy) {
			msgtxt = msgtxt + "<br>Si vous avez termin&eacute;, affichez le d&eacute;tail puis validez.";
			dl += 4000;
			first_buy = false;
		}
		existing_ref = cart.findref(risbn);
		if ((existing_ref == -1)||(cart.nbitems == 0)) {
			cart.additem(risbn, refname, refprice);
		} else {
			cart.items[existing_ref].quant += 1;
			cart.nbitems += 1;
			cart.pricetotal += parseFloat(cart.items[existing_ref].price);
		}
		showMsg(msgtxt,dl);
		findObj("cartbtns").innerHTML = "<p class='menutxt'><a href='javascript:;' onclick='delCart()'><b>tout effacer</b></a><img src='img/blank.gif' width='25' height='5' /><a href='javascript:;' onclick='sendOrder()'><b>valider et payer (site <em>PayPal</em>)</b></a><img src='img/blank.gif' width='25' height='5' /><a href='javascript:;' onclick='findObj(&quot;cartpane&quot;).style.display = &quot;none&quot;'><b>continuer</b></a></p>";
		orderNotify(true);
	} else {
		alert("Erreur interne catalogue: prix manquant.\n-- Ce titre en sera pas ajouté à la commande.\n\n(Vous pouvez notifier ce genre d'erreur en écrivant à\n info@editionsmix.org.)");
	}
}

function orderNotify(notify) {
	if (notify) {
		findObj("basketbtn").innerHTML = "une commande est en cours: <b><a href='javascript:;' onclick='showOrder()'>afficher le détail</a></b>";
		findObj("basketbtn").style.visibility = "visible";
	} else {
		findObj("basketbtn").innerHTML = "";
		findObj("basketbtn").style.visibility = "hidden";
	}
}

function showOrder() {
// displays cart details in cart pane
	findObj("cartcontent").innerHTML = "";
	findObj("cartpane").style.display = "block";
	refreshCartDetails();
}

function refreshCartDetails() {
// list cart details and computes totals
	cart_div = findObj("cartcontent");
	cart_div.innerHTML = "";
	var htmlstr = "";
	if (cart.items.length > 0) {
		htmlstr += "<table width='350px' border='0' cellspacing='0' cellpadding='0'>";
		for (i=0;i<cart.items.length;i++) {
			htmlstr += "<tr><td width='237'><div style='width:237px;height:15px;overflow:hidden'>" + cart.items[i].name + "</div></td>";
			htmlstr += "<td width='23' align='right'>" + cart.items[i].quant + "</td>";
			htmlstr += "<td width='20' align='right'><span class='menutxt'><a href='javascript:;' onclick='decthisref("+i+")'>&ndash;</a> <a href='javascript:;' onclick='incthisref("+i+")'>+</a></span></td>";
			var pr = new NumberFormat(parseFloat(cart.items[i].price*cart.items[i].quant));
			htmlstr += "<td width='50' align='right'>" + pr.toFormatted() + "</td>";
			htmlstr += "<td width='20' align='right'><a href='javascript:;' onclick='delthisref("+i+")' onmouseout='swapIcon(&quot;dellref_"+i+"&quot;,&quot;close0.gif&quot;)' onmouseover='swapIcon(&quot;dellref_"+i+"&quot;,&quot;close1.gif&quot;)'><img src='img/close0.gif' name='dellref_"+i+"' width='11' height='11' border='0' align='absmiddle' id='dellref_"+i+"'/></a></td></tr>";
		}
		htmlstr += "<tr height='15'><td colspan='5'><img src='img/black.gif' width='350' height='1' border='0' align='absmiddle' /></td></tr>";
		htmlstr += "<tr style'color:#333333'><td width='237'><b>TOTAL</b></td>";
		htmlstr += "<td width='23' align='right'><b>" + cart.nbitems + "</b></td>";
		htmlstr += "<td width='20' align='right'></td>";
		var tpr = new NumberFormat(cart.pricetotal);
		htmlstr += "<td width='50' align='right'><b>" + tpr.toFormatted() + "</b></td>";
		htmlstr += "<td width='20' align='right'></td></tr>";
		htmlstr += "</table>";
	} else {
		htmlstr = "<p></p><p class='texte_standard'>(votre commande est vide)</p>";
	}
	cart_div.innerHTML = htmlstr;
}

function delthisref(refidx) {
// delete a ref from cart
	cart.delitem(refidx);
	if (cart.nbitems == 0) {
		findObj("cartbtns").innerHTML = "<p class='menutxt'><img src='img/blank.gif' width='275' height='5' /><a href='javascript:;' onclick='findObj(&quot;cartpane&quot;).style.display = &quot;none&quot;'><b>continuer</b></a></p>";
		findObj("basketbtn").style.visibility = "hidden";
	}
	refreshCartDetails();
}

function incthisref(refidx) {
// increase a ref quantity in cart
	cart.items[refidx].quant += 1;
	cart.nbitems += 1;
	cart.pricetotal += parseFloat(cart.items[refidx].price);
	refreshCartDetails();
}

function decthisref(refidx) {
// decrease a ref quantity in cart
	if (cart.items[refidx].quant > 1) {
		cart.items[refidx].quant -= 1;
		cart.nbitems -= 1;
		cart.pricetotal -= parseFloat(cart.items[refidx].price);
		refreshCartDetails();
	} else {
		delthisref(refidx);
	}
}

function delCart() {
// delete cart content entirely
	cart.items = new Array();
	cart.nbitems = 0;
	cart.pricetotal = 0;
	findObj("cartbtns").innerHTML = "<p class='menutxt'><img src='img/blank.gif' width='275' height='5' /><a href='javascript:;' onclick='findObj(&quot;cartpane&quot;).style.display = &quot;none&quot;'><b>continuer</b></a></p>";
	findObj("basketbtn").style.visibility = "hidden";
	refreshCartDetails();
}

function sendOrder() {
// displays notification before sending cart
	findObj("cartpane").style.display = "none";
	var hstr = "<p class='msg' style='text-align:center'>Vous allez &ecirc;tre redirig&eacute; vers le site <em>PayPal</em><br/ > pour effectuer le paiement en ligne.</p><p class='msg' style='text-align:center'>Vous pourrez utiliser un compte personnel <em>PayPal</em><br/ >(si vous en poss&eacute;dez d&eacute;j&agrave; un), ou bien r&eacute;gler directement la commande avec une carte de cr&eacute;dit.</p><p class='msg' style='text-align:center'>Une fois le paiement termin&eacute;,<br/ >vous pourrez revenir sur ce site.</p></span>";
	findObj("bookref").innerHTML = hstr;
	findObj("bookref").style.display = "block";
	findObj("basketbtn").innerHTML = "<img src='img/blank.gif' width='60' height='5' /><b><a href='javascript:;' onclick='closeRef();orderNotify(true)'>annuler</a></b><img src='img/blank.gif' width='30' height='5' /><b><a href='javascript:;' onclick='findObj(&quot;basketbtn&quot;).style.visibility = &quot;hidden&quot;;postPayPal()'>continuer</a></b>";
	findObj("basketbtn").style.visibility = "visible";
}

function postPayPal() {
// generate cart html and send it to PayPal
	if (cart.nbitems != 0) {
		var cartpack = findObj("cartpack");
		var htmlstring = "";
		htmlstring += "<form id='paypalform' action='https://www.paypal.com/cgi-bin/webscr' method='post'>";
		htmlstring += "<input type='hidden' name='charset' value='ISO-8859-1'>";
		htmlstring += "<input type='hidden' name='cmd' value='_cart'>";
		htmlstring += "<input type='hidden' name='upload' value='1'>";
		htmlstring += "<input type='hidden' name='business' value='" + compte_paypal + "'>";
		for (i=1; i<cart.items.length+1; i++) {
			var stdnm = std_ize(cart.items[i-1].name);
			htmlstring += "<input type='hidden' name='item_number_" + i + "' value='" + cart.items[i-1].ref + "'>";
			htmlstring += "<input type='hidden' name='item_name_" + i + "' value='" + stdnm + "'>";
			htmlstring += "<input type='hidden' name='amount_" + i + "' value='" + cart.items[i-1].price + "'>";
			htmlstring += "<input type='hidden' name='quantity_" + i + "' value='" + cart.items[i-1].quant + "'>";
		}
		htmlstring += "<input type='hidden' name='no_shipping' value='0'>";
		htmlstring += "<input type='hidden' name='return' value='http://www.editionsmix.org/pages/paid.html'>";
		htmlstring += "<input type='hidden' name='cancel_return' value='http://www.editionsmix.org/pages/cancelled.html'>";
		htmlstring += "<input type='hidden' name='shopping_url' value='http://www.editionsmix.org/main.html?type=buy&page=" + cart.items[0].ref +"'>";
		htmlstring += "<input type='hidden' name='no_note' value='1'>";
		htmlstring += "<input type='hidden' name='currency_code' value='EUR'>";
		htmlstring += "<input type='hidden' name='lc' value='FR'>";
		htmlstring += "<input type='hidden' name='bn' value='PP-ShopCartBF'>";
		htmlstring += "</form>";
		cartpack.innerHTML = htmlstring;
		findObj("paypalform").submit();
	}
}


