/////////////////////
////////////////////
/// FUNCTIONS /////
function trim(st) {
	var	str = st.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
};
function $(id) {
	return document.getElementById(id);
};


////////////////////////////////
///////////////////////////////
// CONTACT ///////////////////

//http://www.aquafadas.com/php/contact/contact.php?operation=sendMessage&firstname=elodie&lastname=eee&email=&ter567wx=elodie@aqua.com&title=zzz&statut=editeur&message=%0Asssss
function sendMessage() {
	var isFormOK=checkForm()
	if( isFormOK==true ) { 
		var imgElement = document.getElementById( "imageLoadContact" );
		imgElement.style.display="block";
		// constructs the request:
		var request = "/php/contact/contact.php";
		request+="?operation=sendMessage";
		var form = document.getElementById( "contactForm" );
		var textarea = form.getElementsByTagName("textarea")[0];
		var inputs = form.getElementsByTagName( "input" );
				
		for( var i=0;i<inputs.length;i++ ) {
			var input = inputs[i];
			// firstname 
			if( input.name == "firstname" ) {
				request += "&firstname="+input.value;
			} else
			// lastname 
			if( input.name == "lastname" ) {
				request += "&lastname="+input.value;
			} else
			// EMAIL 
			if( input.name == "email" ) {
				request += "&email="+input.value;
			} else
			// EMAIL 
			if( input.name == "ter567wx" ) {
				request += "&ter567wx="+input.value;
			} else
			// titre 
			if( input.name == "title" ) {
				request += "&title="+input.value;
			} else
			if( input.name == "statut" ) {
					if (input.checked==true){
						request += "&statut="+(input.value);
					}
			}
		} ;
		request += "&message="+encodeURIComponent( textarea.value );
		var req=getHTTPRequest();
		req.onreadystatechange=function(){			
			responseAvailable(req);
		};
		req.open("GET", request, true);
		req.send(null);	
	}
};
function enableForm() {
	var form = document.getElementById( "contactForm" );
	if( form ) {
		var inputs = form.getElementsByTagName( "input" );
		var selects = form.getElementsByTagName( "select" );
		var textarea = document.getElementById("textarea-contact");		
		for( var i=0;i<inputs.length;i++ ) {
			var input = inputs[i];
			if (input.name != "passwordRetype")	{		
				input.disabled = false;
				input.style.backgroundPosition = "center bottom";
				
			} 
		}
		textarea.disabled = false;
		textarea.style.backgroundPosition = "center bottom";
			
			 
		for( var i=0;i<selects.length;i++ ) {
			var select = selects[i];
			select.disabled = false;
			select.style.backgroundColor = "white";		
		}
	}
};
function responseAvailable(req) {
	if (req.readyState == 4) {
		if (req.status == 200) {
			var imgElement = document.getElementById("imageLoadContact");
			imgElement.style.display = "none";
			var respons = req.responseText.split("|");
			if (respons[0] == "OK") {
				var contactEl = document.getElementById("Inscription");
				contactEl.innerHTML = respons[1];
			}
			else {
				var message = null;
				if (respons[0] == "ER") {
					message = respons[1];
				}
				else {
					message = "Une erreur est survenue lors de l'envoi du formulaire";
				}
				var errorEL = document.getElementById("errorContactMessage");
				errorEL.innerHTML = message;
			}
		}
	}
};
function checkForm() {
	var form=$("contactForm");
	if (form) {
		var inputs = form.getElementsByTagName("input");
		var textarea = form.getElementsByTagName("textarea")[0];
		var allFieldsOK = true;
		for (var i = 0; i < inputs.length; i++) {
			var input = inputs[i];
			if (input.className != "submit") {
				if (!checkInput(input)) {
					allFieldsOK = false;
				}
			}
		}
		if (!checkInput(textarea)) {
			allFieldsOK = false;
		}
		return allFieldsOK;
	}
	return false;
};
function checkInput(inputEl) {
	var valid=true;
	if( inputEl.name == "ter567wx" ) {
		valid=checkMail(inputEl.value);
	} else
	if( inputEl.name == "email" ) {
		valid=( inputEl.value=="" );
	} else {
		if( trim(inputEl.value).length == 0 ) {
			valid=false;	
		}
	}
	if( valid == true ) {
		validateInput(inputEl);
	} else {
		invalidateInput(inputEl);
	}
	return valid;
};

function checkTextarea(textareaEl) {
	var valid=true;
	if( textareaEl.name == "message" ) {
		valid=checkMail(textareaEl.value);
	} else
	
	if( valid == true ) {
		validateTextarea(textareaEl);
	} else {
		invalidateTextarea(textareaEl);
	}
	return valid;
};
function invalidateTextarea(inFormElement) {
	var errorColor = "#CC6600";
	inFormElement.style.borderColor=errorColor;
	inFormElement.style.borderStyle="solid";
	var td = inFormElement.parentNode;
	var span=td.getElementsByTagName("span")[0];
	span.style.display="block";
};
function validateTextarea(inFormElement) {
	// restore the default background
	inFormElement.style.borderColor="";
	inFormElement.style.borderStyle="";
	var td = inFormElement.parentNode;
	var span=td.getElementsByTagName("span")[0];
	span.style.display="none";
};
function invalidateInput(inFormElement) {
	if ( inFormElement.name!="email" ){
		var errorColor = "#CC6600";
		inFormElement.style.borderColor=errorColor;
		inFormElement.style.borderStyle="solid";
		var td = inFormElement.parentNode;
		var span=td.getElementsByTagName("span")[0];
		//span.innerHTML=message;
		span.style.display="block";
	}
};
function validateInput(inFormElement) {
	if ( inFormElement.name!="email" ){
		// restore the default background
		inFormElement.style.borderColor="#2f98ce";
		inFormElement.style.borderStyle="solid";
		var td = inFormElement.parentNode;
		var span=td.getElementsByTagName("span")[0];
	
		span.style.display="none";
	}
};
function checkMail(inEmail) {
	var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (filter.test(inEmail)) {
		return true;
	} else {
		return false;
	}
};



///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


var IMAGES_PATH_DIR="/images/avecomics-1.1";
var LANG_SUBPATH="fr";

///////////
// UTILS //
var _utils=new Utils();
function Utils() {
	var _userBoxState=null;
//	this._memberBoxConnected=false;
	this.setMemberBoxConnected=function(connected) {
		//Utils._memberBoxConnected=connected;
		var mb=$("members-box");
		if( !mb.states ) {
			var divs=mb.getElementsByTagName("div");
			mb.states=new Array();
			for( var i=0;i<divs.length;i++ ) {
				if( divs[i].className=="inside-box" ) {
					mb.states.push(divs[i]);
				}
			}
		}
		mb.states[0].style.display=( connected==true )?"none":"block";	
		mb.states[1].style.display=( connected==true )?"block":"none";
		
		if( connected==true )
		{		
			// get back and display the username:
			var name = Cookies.readCookie("AVnickname");
			// TODO Check IE6 length is not defined ??
			if( name && typeof( name.length ) != 'undefined' && name.length>11 ) {
				name=name.substr(0,10)+"...";
			}
			
			var spans=$("profilName").getElementsByTagName("span");
			for( var i=0;i<spans.length;i++ ) {
				spans[i].innerHTML=name;
			}
			
			// load avatar:
			var avElIMG=$("avatar");
			Avatar.setLoading( avElIMG );
			Avatar.getAvatar(60,60,function(){
				var resizingMedia=Avatar.normalize(50,70,this);
				avElIMG.width=resizingMedia.width;
				avElIMG.height=resizingMedia.height;
				avElIMG.src=resizingMedia.src;
			});
			
		}
	};
	/** @param key 'inscription', 'shopping' */
	this.setUserBoxState=function(key) {
		if ( Utils._userBoxState != key ) {
			Utils._userBoxState=key;
			/*
			var ibox = $("inscription-box");
			var sbow = $('shopping-box');
			if (key == "inscription") {
				sbow.style.display = 'none';
			}
			else 
			if (key == "shopping") {
				ibox.style.height = '0px';
				sbow.style.display = 'block';
				if( $("numberOfArticle") == null ){
					sbow.innerHTML = getDivMonPanier(0).innerHTML;
				}
			}
			*/
		}
	};
};
/////////////////////////////
///////////AVATAR///////////
var Avatar={
	DEFAULT_WIDTH:	50,
	DEFAULT_HEIGHT:	71,
	MEDIA_LOAD:		IMAGES_PATH_DIR+"/perso/avatar_loading.gif",
	MEDIA_DEFAULT:	IMAGES_PATH_DIR+"/perso/avatar_default.jpg",
	setLoading:function(imageEl) {
		if( imageEl ) {
			imageEl.src=Avatar.MEDIA_LOAD;
			imageEl.width=16;
			imageEl.height=16;		
		}
	},
	normalize:function(W,H,image) {
		var w=image.width;
		var h=image.height;
		var sc_ratio = W/H; 
		var vp_ratio = w/h;
		var mode=0;
		var zoom =1;
		if( vp_ratio > sc_ratio ) {	zoom = W/w;	} 
		else if( vp_ratio < sc_ratio ) { zoom = H/h; }	
		image.width = Math.round(image.width*zoom);
		image.height = Math.round(image.height*zoom);
		return image;	
	},
	getAvatar:function(maxWidth,maxHeight,updateHandler){
		// try to get the avatar media:
		var avatarFilename=Cookies.readCookie("AVavatar");
		if (avatarFilename) {
			var url = "/friends/avatar/"+avatarFilename;
			var req = getHTTPRequest();
			req.open("GET", url, false);
			req.send(null);
			if (req.status == 404) {
				// give the rescue img:
				url = Avatar.MEDIA_DEFAULT;
			}
		} else {
			url = Avatar.MEDIA_DEFAULT;
		}
		// load image and check aspect ratio:
		var media=new Image();
		media.onload=updateHandler;
		media.src=url;
	}
};
////////////////////////

function smoothScrollToTop() {
	var t=0;
	var to=0;
	//var from=document.documentElement.clientHeight;	
	var from = ( document.documentElement.scrollTop ) || ( window.pageYOffset); 
	var nd=1/from;
	var i=setInterval(
		function() {
			if (t >= 1) {
				clearInterval(i);
			} else {
				from = quad.easeInOut(t,from,to-from,1);
				window.scrollTo(0,from);
				t+=.05;
			}
		},20	
	);
};

////////////
// PAGE ///
//////////
function Page() {
	this.MIN_HEIGHT=871;
	this.DEFAULT_TITLE="Aquafadas - AVE!Comics";
	this.swf=null;
	this.anim=null;
	this.connection=null;
	this.newsletter=null;
	this.nav=null;
	this.req=null;
	this._selectedPageID="p1";
	this._firstload=true;
	this._wdgtStopped=true;
};
Page.prototype = {
	homeHTML:null,
	_wdgt:null,
	init:function(wdgt,isUserConnected){
		//alert("nit page");
		var page=this;
		this.req=getHTTPRequest();
		this.enableAllInputs();	
		
		this.swf=new MainSWFComics("aveComicsSWF");	
		this.homeHTML=$("aveComicsContent").innerHTML;// store the home page content
		
		this.nav=new Navigation(this);
		// connection
		this.connection=new Connection(isUserConnected);
		this.connection.onUserConnected=function( email,password ) {
			_utils.setMemberBoxConnected(true);
			// special case: UNLIBRARY
			if(  _page._selectedPageID=="p1" ) {
				History.add(["library"]);
			} else if( _page._selectedPageID==_notConnectedPageID || _page._selectedPageID==_libraryPageID) {
				History.forceReload();
			}
		};
		this.connection.onUserDeconnected=function() {
			//console.log( "DISCONNECT" );
			_utils.setMemberBoxConnected(false);
			if( _page._selectedPageID==_libraryPageID  ) {
				History.forceReload();
			}
		};		
		
		// newsletter:
		this.newsletter=new Newsletter();
		// widget:
		this._wdgt=wdgt;
		this.anim=new AnimationPhone();
		_page.goToInstinctivePage();
		addSearchField();
		// looking if user is connected:
		var eml=Cookies.readCookie("AVemail");
		if (  eml != null&&eml!="null" ) {
			_utils.setMemberBoxConnected(true);
		} else {
			// deconnection ???
		}
	},
	
	_isPageNameDefined:function(name) {
		// !! special case
		if( name=="details-pending" ){
			return true;
		} else {
			return ( typeof(_NPages[name]) != 'undefined' );
		}
	},
	
	navigate:function(pns) {		
		//console.log(pns[0]+" "+pns.length );
		if(!_dontInterpretNextUpdate)
		{
			switch( pns.length ) {
				case 0:
					this.goToPage("home");
				break;
				case 1:
					this.goToPage(pns[0]);
				break;
				case 2:
					var pa0 = decodeURIComponent(pns[0]);
					var pa1 = decodeURIComponent(pns[1]);
					if( pa0 == "store" ) {
						this.goToPage("store");
					}
				break;
				case 3:
					var pa1 = decodeURIComponent(pns[1]);
					var pa2 = decodeURIComponent(pns[2]);
					if ( this._isPageNameDefined( pns[0] ) == true ) {
						switch (pns[0]) {
							case "library":
								// Special case --> 'all'
								 if( pa1 == "details" ) {
									var bp=_detailsOfBoughtProductID;
									var pp=_detailsOfProductID;
									var hd="$('aveComicsSWF').showDetailOfProduct("+pa2+","+pp+","+pp+","+pp+","+bp+","+bp+","+bp+")";
									this.goToPage("library",hd);
								}
								if (pa2.toLowerCase() == "all" || pa2 == "") {
									//console.log("NAVIGATE>>>"+ hd );
									AFAVENavBox_selectFilter("all", "");
								}
								else {
									var hd = null;
									switch (pa1) {
										case "gender":
											hd = 'searchGenre(\'lib_user_1\', \'' + pa2 + '\');searchGenre(\'lib_user_2\', \'' + pa2 + '\');';
											break;
										case "author":
											hd = 'searchArtist(\'lib_user_1\', \'' + pa2 + '\');searchArtist(\'lib_user_2\', \'' + pa2 + '\');';
											break;
										case "album":
											hd = 'showDetailOfProduct(' + pa2 + ',25,25,25,37,37,37)';
											break;
										case "editor":
											hd = 'searchEditor(\'lib_user_1\', \'' + pa2 + '\');searchEditor(\'lib_user_2\', \'' + pa2 + '\');'
											break;
									}
									
									if (hd) {
										//console.log("NAVIGATE>>>"+ hd );
										AFAVENavBox_selectFilter(pa1, hd);
									}
								}
							break;
							case "store":
								if( pa1=="category" ) {
									this.goToPage("store",'MainSWFComics.secureGoPage("'+getPageNumberForCategorie(pa2)+'")');
								} else if( pa1 == "details" ) {
									var bp=_detailsOfBoughtProductID;
									var pp=_detailsOfProductID;
									var hd="$('aveComicsSWF').showDetailOfProduct("+pa2+","+pp+","+pp+","+pp+","+bp+","+bp+","+bp+")";
									this.goToPage("store",hd);
								}
								// cart
							//	AFAVENavBox_selectFilter("store", "_page.showDetailOfProduct(" + pa2.toLowerCase() + ")");
							break;
						}
					}
				break;
				case 4:
					var pa1 = decodeURIComponent(pns[1]);
					var pa2 = decodeURIComponent(pns[2]);
					var pa3 = decodeURIComponent(pns[3]);
					// SEARCH:
					if( pa1=="result" && pa2=="all" ) {
						if( pns[0]=="library") {
							this.goToPage("library",'$("aveComicsSWF").goSearch("46","'+pa3+'")');
						} else
						if( pns[0]=="store" ){
							this.goToPage("store",'$("aveComicsSWF").goSearch("40", "'+pa3+'")');
						}
					}
				break;			
			}
		}
		_dontInterpretNextUpdate = false;
	},

	_startWidget:function(){
		if( this._wdgtStopped == false ) return;// !! check if widgets are already stopped
		this._wdgtStopped=false;
		if( this._wdgt ) {
			// first reinit the IE Canvas improvement, for the 'etagere' canvas
		/*	
			if( typeof(G_vmlCanvasManager)!='undefined' ) {// IE only
				var cv=document.getElementsByTagName("canvas")[0];
				if( cv ) {// be sure canvas is loaded...
					alert( "G_vmlCanvasManager required !" );
					G_vmlCanvasManager.initElement(cv);
				}
			}
		*/
			this._firstload=false;
			for(var i=0;i<this._wdgt.length;i++ ) {
				var wd=this._wdgt[i];
				try {
					if(wd.play) wd.play();
				} catch(e) {
					
				} 
			}
		}
		if( this.anim.play ) {
			this.anim.play();
		}
	},
	_stopWidget:function() {
		this._wdgtStopped=true;
		if( this._wdgt )
		{
			for(var i=0;i<this._wdgt.length;i++ ) {
				var wd=this._wdgt[i];
				if( wd && wd.stop )	{
					try{wd.stop();}catch(e){}
				}
			}
		}
		if( this.anim.stop ) {
			this.anim.stop();
		}
	},
	/** INPUTS **/
	enableAllInputs:function() {
		var inputs=document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++) {
			var ip=inputs[i];
			if( ip.className!="headerSearchField" ) {			
				ip.validate=function() {
					this.style.backgroundColor="#D3FE67";
					this.style.border="2px inset #D3FE67";
					this.isValid=true;
				};
				ip.invalidate=function() {
					this.style.backgroundColor="#FF8187";
					this.style.border="2px inset #FF8187";
					this.isValid=false;
				};
				this.extendInput(ip);// enhanced 
				ip.disabled = false;
				ip.style.backgroundColor="#FFFFFF";
			}
		}
	},
	disableAllInputs:function() {
		var inputs=document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++) {
			var ip=inputs[i];
			ip.disabled=true;
		}		
	},
	extendInput:function(input) {
		var page=this;
		if( !input.shadowText ) {
			input.shadowText=input.value;
		}
		if( input.id=="realpass"||input.id=="mockpass" ) {
			input.reset=function() {
				this.value = '';
				this.style.backgroundColor="#FFFFFF";
				this.style.border="2px inset #CCC";	
			};			
		} else {
			
			input.reset=function() {
				this.value = this.shadowText||"";
				this.style.color="#888888";
				
				this.style.backgroundColor="#FFFFFF";
				this.style.border="2px inset #CCC";	
			};			
			input.onfocus=function(e) {
				this.style.color="black";
				if (this.value == this.shadowText) {
					this.value = "";
				}
			};
			input.onblur=function(e) {		
				if (this.value == "") {
					var ip=this;
					ip.tmt=setTimeout(
						function() {
							if( ip.reset ) ip.reset();	
						},100
					);					
				}
			};
		}
		input.onkeypress=function(e) {
			if( !e ) e=window.event;
			if( e.keyCode && e.keyCode == 13) {
				if( isParentOf($("members-box"),input) ) {
					page.connection.connect(this);
				}else 
				if( isParentOf($("newsletter-box"),input) ) {
					page.newsletter.subscribe();
				}
			}
		};
		if( isParentOf($("members-box"),input) ) {
			if( input.name=="username" ) {
				input.onkeyup = function() {
					var ip=this;
					ip.to=setTimeout(function() {
						clearTimeout( ip.to );// prevent last check
						if( checkMail( ip.value )==true ){ip.validate();} else {ip.invalidate();}						
					},200);
				}
			} else
			if( input.name=="password" ) {
				input.onkeyup = function(){
					var ip = this;
					ip.to = setTimeout(function(){
						clearTimeout(ip.to);// prevent last check
						if (trim(ip.value).length > 0) {ip.validate();} else {ip.invalidate();}
					}, 200);
				}
			}
		} else 
		if( isParentOf($("newsletter-box"),input ) ) {
			input.onkeyup = function() {
				var ip=this;
				ip.to=setTimeout(function() {
					clearTimeout( ip.to );// prevent last check
					if (checkMail(ip.value) == true) {	ip.validate();}	else {ip.invalidate();}								
				},200);
			}
		}
	},
	_getUrlParameter:function( 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];
	},
	goToInstinctivePage:function() {
		var key=this._getUrlParameter("order_ref");
		if (key != "") {
			this.goToPage("library");
		} else {
			History.addressChangeHandler();// force go to the right place
		}
		/*
		var key=this._getUrlParameter("order_ref");
		if( key != "" ) {
			this.goToPage("library");
		} else {
	        key=this._getUrlParameter("page");
	        if( key!="" ) {
				this.goToPage(key);
	        } else {
				this.goToPage("home");//default page
			}	
		}	onLoadComplete
		*/			
	},	
	goToPage:function(name,evaluate) {
		var thePage=this;
		if ( this._isPageNameDefined(name) == true ) {
			var pageID = _NPages[name].id;
			if (pageID.indexOf("p") == 0) {
				//alert( name );
				if (name == "library") {
					//alert(Cookies.readCookie("AVnickname"));
					if (Cookies.readCookie("AVnickname")) {
						this._goToPage("library");
					}
					else {
						this._goToPage("unlibrary");
					}
				}
				else {
					this._goToPage(name);
				}
			}
		}
	},
	/**
	 * Select menu from HTML Dom if needed 
	 * @param {Integer} pageID
	 */
	setSelectedPage:function(pageID) {
		this._selectedPageID=pageID;
		for( var key in _NPages ) {
			
			if( _NPages[key].id==pageID ) {				
				var m=$(_NPages[key].domId);
				if( m ) this.nav.selectMenu(m);
				this._setDocumentTitleForKey(key);
			} else {
				var key=_NPages[key].domId
				if( _NPages[key]==pageID ) {
					var m=$(_NPages[key].domId);
					if( m ) this.nav.selectMenu(m);
					this._setDocumentTitleForKey(key);
				}
			}
		}
	},	
	_setDocumentTitleForKey:function(key) {
		document.title=this.DEFAULT_TITLE;
		var tl=_NPages[key].title;
		if( tl && tl.length>0 ) {
			document.title+=" - "+tl;
		}
	},
	showDetailOfProduct:function(productID) {
		History.add(["store","details",productID]);
	},
	_goToPage: function(name,evaluate){
	//	console.log( name + " "+_NPages[name] );
		if( this._isPageNameDefined( name ) == false ) {
			return;//block if name does not denote a right page key
		}		
		// _NPages
		var pageID=_NPages[name].id;
		// go to the right place:		
		if( pageID.indexOf("p")==0 ) {
			//$("mobiles").style.display="block";
			
			// load external page
			if( pageID=="p1" || pageID=="p0" ) {
				this._switchDisplay(pageID);
				window._page.setSelectedPage(pageID);
			} else {
				this.loadContent(
					_NPages[name].url, 
					// Result
					function() {
						window._page._switchDisplay("home");
						// SWF does not call function here
						// do it by ourself
						window._page.setSelectedPage(pageID);
					},
					// Error
					function() {
						History.add(["home"]);
					}
				);
			}	
		}		
	},

	_switchDisplay:function(inName)
	{
		var rc=$("right-column");
		var bxs=rc.getElementsByTagName("div");
		//var boxFiltersFound=false;
		
		//hide box-jeunesse and box-manga, display other
		for( var i=0;i<bxs.length;i++ ) {
			if (bxs[i].parentNode == rc) {
				if (bxs[i].id == 'box-jeunesse' || bxs[i].id == 'box-manga') {
					bxs[i].style.display = "none";
				}
				else {
					bxs[i].style.display = "block";
				}
			}
		}
		this.enableAllInputs();
		CatNavLibrary.setVisible(false);
        if($('LeftColClassement')) $('LeftColClassement').style.display="none";
        
		switch(inName)
		{
			case "p0":
				this.swf.setVisible(false);	
				this._stopWidget();
				displayAvePreview();
			break;
			case "p1":
				this.swf.setVisible(false);	
				$("aveComicsLoader").style.display="none";
				$("aveComicsContent").innerHTML=this.homeHTML;
				$("aveComicsContent").style.display="block";
				// reload all the widgets:
				this._startWidget();
				
				
				var so = new SWFObject("/resources/video/home/preview.swf", "main","585", "362", "8", "#000000");
				so.addParam("allowFullScreen", "true");
				so.addVariable("htmlpath", location.href);
				so.addVariable("MediaLink", "media/AVEComics720p.flv");
				so.addVariable("MediaLink2", "media/AVEComics720p.mp4");
				so.addVariable("defaultMedia", "1");
				so.addVariable("image", LANG_SUBPATH+"/images/avecomics-1.1/image-video2.jpg");
				so.addVariable("logo", "");
				so.addVariable("logoLink", "http://www.ave-comics.com");
				so.addVariable("playOnStart", "false");
				so.addVariable("startVolume", "50");
				
				so.addVariable("cuePoints1", "xml/cuepoints1.xml");
				so.addVariable("cuePoints2", "xml/cuepoints2.xml");
				so.addVariable("autoHideOther", "false");
				so.addVariable("autoHideVideoControls", "false");
				so.addVariable("onStartShowControls", "true");
				so.addVariable("fullVideoScale", "false");
				so.addVariable("controlsSideMargin", "0");
				so.addVariable("controlsDownMargin", "0");
				so.addVariable("showPlayButton", "true");
				so.addVariable("script_path", "http://www.as-flash.com/phpscripts/share.php");
				so.write("playerdiv");
			break;
			case "home":
				this.swf.setVisible(false);	
				this._stopWidget();
			break;
			case "store":
				this.swf.setVisible(true);	
				this._loadStorePage();
			break;
			case "library":
				this.swf.setVisible(true);
				CatNavLibrary.setVisible(true);
			break;
			case "other":
				this.swf.setVisible(true);
				CatNavLibrary.setVisible(false);
        		if($('LeftColClassement'))
        			$('LeftColClassement').style.display="none"; 
			break;
		}
	},	
	_loadStorePage:function() {	
		_utils.setUserBoxState("shopping");
		// RIGHT COLUMN:
		var rc=$("right-column");
		var bxs=rc.getElementsByTagName("div");
		var boxFiltersFound=false;
		for( var i=0;i<bxs.length;i++ ) {
			if( bxs[i].parentNode == rc ) {// prevent to modify the content
				if( bxs[i].id == 'box-jeunesse'|| bxs[i].id =='box-manga' ) {
					bxs[i].style.display="block";
					boxFiltersFound=true;
				} else {
					bxs[i].style.display="none";
				}
			}
		}
		
	    $("left-column").className ="";
	    if ( !$('LeftColClassement')  ) { // && CatNavStore.load==false	    	
			//console.log( "Left columns not exist" );
			var html = "<div id='LeftColClassement'><div style='margin-top:118px;' id='box-raccourcis'><div id='top-raccourcis'></div>";
			html += "<div id='middle-raccourcis'></div><div id='bottom-raccourcis'></div><div id='content-raccourcis'><div id='content-raccourcis'>";
			html += "<ul class='white'>";
			html += "<li onclick=\"History.add(['store','manga']);\">Manga</li>";
			html += "<li onclick=\"History.add(['store','comics']);\">Comics</li>";
			html += "<li onclick=\"History.add(['store','humour']);\">Humour</li>";
			html += "<li onclick=\"History.add(['store','aventure']);\">Aventure</li>";
			html += "<li onclick=\"History.add(['store','jeunesse']);\">Jeunesse</li>";
			html += "</ul></div></div></div><div id='box-humour'></div>" + "<div id='box-nouveautes'></div>" + "<div style='width:203px;' id='box-100'></div></div>";
			
			$("left-column").innerHTML += html;
			
			CatNavLibrary.setVisible(false);
			if ($('LeftColClassement')) 
				$('LeftColClassement').style.display = "block";
			if (boxFiltersFound == false) {
				$("right-column").innerHTML += "<div style='margin-top:118px' id='box-jeunesse'></div>" + "<div  id='box-manga'></div>";
			}
			afficheClassement('box-nouveautes', 'top_nouveautes'); //affiche le classement "top_nouveaute" (attribut de la requete php) dans le div dont l'id ='box-nouveautes'              
			afficheClassement('box-jeunesse', 'top_jeunesse');
			afficheClassement('box-humour', 'top_humour');
			afficheClassement('box-manga', 'top_manga');
			afficheClassement('box-100', 'top_100');
			
		} else {
			$('LeftColClassement').style.display = "block";
		}	   
	},
	/** Load external pages */
	loadContent:function(url,resultHandler,errorHandler) {
		$("aveComicsLoader").style.display="block";
		$("aveComicsContent").style.display="none";
		if (url) 
		{
			var req=getHTTPRequest();
			req.onreadystatechange = function(){
				if (req.readyState == 4) {
					if (req.status == 200) {
						setTimeout(function(){
							var avcc = $("aveComicsContent");
							avcc.innerHTML = req.responseText;
							$("aveComicsSWF").style.height = "0px";
							$("aveComicsContent").style.display = "block";
							$("aveComicsLoader").style.display = "none";
							enableForm();
							// call 
							resultHandler();
							
						}, 200);
					} else {
						// error 404 or server issue
						//$("aveComicsLoader").style.display="none";
						//$("aveComicsContent").style.display="block";
						// go to home page
						
						errorHandler();
					}
				}
			}
			req.open("GET", url, true);
			req.send(null);
		}
	}
};
/******************/
/** SWF Handler **/
function MainSWFComics(id) {
	this.HEIGHT=1309;
	this.id=id;
	// private
	var _visible=false;
	var _loaded=false;
	
	this.obj=function() {
		return $(this.id);
	};
	this.setLoaded=function(flag) {
		_loaded=flag;
	};
	this.isLoaded=function() {
		return _loaded;
	};
	this.isVisible=function() {
		return _visible;
	};
	this.setVisible=function(flag) {
		$("aveComicsLoader").style.display="none";
		if( _visible!=flag ) {
			_visible=flag;
			if( flag==true ) {
				_page._stopWidget();
				$(this.id).style.height = this.HEIGHT+"px";
				$("aveComicsContent").style.display = "none";
			} else {
				$("aveComicsContent").style.display = "block";
				$("aveComicsLoader").style.display="none";
				$(this.id).style.height = "0px";
			}
		}
	};
	this.goPage=function(pageID) {
		if (this.isLoaded()) {
			this.setVisible(true);
		//	$("aveComicsSWF").goPage(pageID);
		}// do nothing, called function must be store in some place for a later and appropriate call
	};
};
// direct called:
MainSWFComics.secureGoPage = function(pageID){
	changePage( pageID );
};
/*
MainSWFComics.prototype.secureCall=function(functionName,args) {
	var swf=$(this.id);
	if( swf ) {
		if( typeof swf[functionName] != 'undefined' ) {
			// constructs the call:
			var argsHD="";
			if( args && args.length>0 ) {
				for( var i=0;i<args.length;i++ ) {
					argsHD+="'"+args[i]+"',";
				}
				argsHD.substr(0,argsHD.length-2);// remove the last comma
			}
			var HD="$('"+this.id+"')."+functionName+"("+argsHD+")";
			console.log( HD );
//			eval( HD );
		} 
	}
};
*/
/*************************/
/** Connection Handler **/
function Connection(isUserConnected){
	this.isUserConnected=isUserConnected||false;
	this.onUserConnected=null;
	this.onUserDeconnected=null;
	
	this.CONNECTION_SCRIPT="/ave-comics/core/connection.php";
};
Connection.prototype = {
	connect : function() {
		$("members-logger").innerHTML="Connexion...";
		// get back and check username and password:
		var inputs=$("members-box").getElementsByTagName("input");
		var username=inputs[0];
		var passw=inputs[1];
		// recheck ( external tools copy & paste issue )
		if( checkMail(username.value)==true ){
			username.validate(); 
		} else{
			username.invalidate(); 
		}
		if( trim(passw.value).length>0 ) {
			passw.validate(); 
		} else {
			passw.invalidate(); 
		}
		var allIsOK= ( username.isValid || false ) && ( passw.isValid || false );
		/////////////////////////////////
		if (allIsOK==true) {
			var params="opNEW=connection&username=" + username.value + "&password=" + passw.value;
			var req = getHTTPRequest();
			var conn=this;
			req.onreadystatechange = function() {
				conn._connectionResponseHandler(req);
			};
			req.open("POST", this.CONNECTION_SCRIPT, true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			req.setRequestHeader("Content-length", params.length);
			req.setRequestHeader("Connection", "close");
			req.send(params);
		} else {
			$("members-logger").innerHTML="Mauvais identifiants";
		}
	},	
	deconnect : function() {
		var params="opNEW=deconnection";
		var req = getHTTPRequest();
		req.open("POST", this.CONNECTION_SCRIPT, false);
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", params.length);
		req.setRequestHeader("Connection", "close");
		req.send(params);
		
		// Carefull: Wait for deconnection !
		this.onUserDeconnected();
		this.isUserConnected=false;
		///////////////////////////////////////////
		// MOVE and TODO: some fixed are required !
		// reset account in box
		var inputs=$("members-box").getElementsByTagName("input");
		inputs[0].reset();
		inputs[1].reset();
		$("members-logger").innerHTML="";
	},
	_connectionResponseHandler:function(req) {
		if (req.readyState == 4) {
			if (req.status == 200) {
				var r=req.responseText.split("|");
				if( r[0]=="OK" ) {
					this.isUserConnected=true;
					var inputs=$("members-box").getElementsByTagName("input");
					var username=inputs[0];
					var passw=inputs[1];
					_nickname=r[1];
					this.onUserConnected(username.value,passw.value);
				} else {
					$("members-logger").innerHTML="Mauvais identifiants";
				}
			} else {
				$("members-logger").innerHTML="Erreur indéfinie";
			}
		}
	}
};

function getDivMonPanier(nbArticle){

	var ub=document.createElement("div");
	ub.id="user-box";
	
	var cc=document.createElement('div');
	cc.id="cart-content";
	cc.className="connected";
	var st=document.createElement('p');
	st.className="shadow-text";
	var tx=document.createElement('span');
	tx.className="text";
	tx.innerHTML="ARTICLE AJOUTÉ";
	var tx2=document.createElement('span');
	tx2.className="shadow";
	tx2.innerHTML="ARTICLE AJOUTÉ";
	st.appendChild(tx);
	st.appendChild(tx2);
	
	var st2=document.createElement('p');
	st2.id="numberOfArticle";
	st2.className="shadow-text";
	var tx3=document.createElement('span');
	tx3.className="text";
	if(nbArticle<=1) tx3.innerHTML="contient "+nbArticle+" article";
	else tx3.innerHTML="contient "+nbArticle+" articles";
	
	var tx4=document.createElement('span');
	tx4.className="shadow";
	if(nbArticle<=1) tx4.innerHTML="contient "+nbArticle+" article";
	else tx4.innerHTML="contient "+nbArticle+" articles";
	st2.appendChild(tx3);
	st2.appendChild(tx4);
	
	cc.appendChild(st);
	cc.appendChild(st2);
	
	var bouton=document.createElement("div");
	bouton.id="checkout-cart";
	bouton.className="medium-button";
    bouton.innerHTML='voir les détails';
    //bouton.style.textAlign:'center';
    bouton.style.color="white";
	/*bouton.onclick=function() {
		History.add(["store","cart"]);
	};*/
	cc.appendChild(bouton);
	ub.appendChild(cc);	
	
	bouton.setAttribute('onClick',"History.add( ['store','cart'] );");
	
	
//	return cc;		
	return ub;
};
function Newsletter() {
	this.NEWS_SCRIPT="/ave-comics/core/registration/newsletter.php";
};
Newsletter.prototype={
	subscribe : function() {
		$("news-logger").innerHTML="Demande...";
		// get back and check username and password:
		var inputs=$("newsletter-box").getElementsByTagName("input");
		var email=inputs[0];
		if ( email.isValid && email.isValid==true ) {
			var params="operation=presubscribe&email="+email.value+"&lang=fr";
			var req = getHTTPRequest();
			req.onreadystatechange = function() {
				if ( req.readyState == 4 ) {
					if ( req.status == 200) {
						var r=req.responseText.split("|");
						if( r[0]=="OK" ) {
							var okHTML='<div class="inside-box"><p style="margin:0;font-size:12px;text-align:left">';
							okHTML+='Votre demande a été <br/>enregistrée, un email <br/>pour la confirmation<br/>vous a été envoyé</p></div>';
							$("newsletter-box").innerHTML=okHTML;
						} else {
							$("news-logger").innerHTML="une erreur est survenue...";
						}
					}
				}
			};
			req.open("POST", this.NEWS_SCRIPT, true);
			req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	     	req.setRequestHeader("Content-length", params.length);
	      	req.setRequestHeader("Connection", "close");
			req.send(params);
		} else {
			$("news-logger").innerHTML="Email invalide";
		}
	}
};

///////////////////////////////
/// SLIDE PHONE ANIMATION ////
/////////////////////////////
function AnimationPhone() {
	this.tic=null;
};
AnimationPhone.prototype={
	play:function() {
		var anim=this;
		anim.eff=anim._scrollToRight;
		anim.tic=setInterval(
			function() {
				if(anim.eff()==false) {
					//trace("reverse animation");
					if( anim.eff==anim._scrollToLeft ) {
						anim.eff=anim._scrollToRight;
					} else {
						anim.eff=anim._scrollToLeft;
					}
				}
			},2000
		);	
	},
	stop:function() {
		clearInterval(this.tic);
	},
	_scrollToLeft:function() {
		var sc=$("ip-scroll");
		if( sc ) {// if removed an error is throw
			var from=parseInt( sc.style.left );
			if( isNaN(from) ) from = 0;
			var to=from-(250);
			var scH=sc.clientWidth;
			var srH = $('image-iphone').clientWidth;
			if (from >= (srH - ( scH-252 ) )) {
				this._go(from, to, sc);
				return true;
			}
		}
		return false;
	},
	_scrollToRight:function() {
		var sc=$("ip-scroll");
		if( sc ) {
			var from=parseInt( sc.style.left );
			if( isNaN(from) ) from = 0;
			var to=from+(250);
			if ( to <= 230 ) {
				this._go(from, to, sc);
				return true;
			}
		}
		return false;
	},
	_go:function(from,to,el) {
		if( el.running == true ) return;
		var t=0;
		el.tic=setInterval(
			function() {
				if (t >= 1) {
					clearInterval(el.tic);
					el.running=false;
				} else {
					from = quad.easeInOut(t,from,to-from,1);
					el.style.left=from+"px";
					t+=.05;
					el.running=true;
				}
			},50	
		);
	}
};

/////////////////////
////////////////////
/// FUNCTIONS /////
function trim(st) {
	var	str = st.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
};
function $(id) {
	return document.getElementById(id);
};
function getHTTPRequest(){
	var http;
	if (window.XMLHttpRequest) {
		http = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		http = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return http;
};

function isParentOf(parentEl,el) {
	var pn=el.parentNode;
	while( pn && pn.tagName.toUpperCase()!="BODY" ) {
		if( parentEl == pn ) {
			return true;
		}
		pn=pn.parentNode;
	}
	return false;
};
function displayAvePreview() {
	//window.location.href=LANG_SUBPATH+"/avepreview";
	// use replace instead, remove from history the #avepreview url
	location.replace( LANG_SUBPATH+"/avepreview" );
};
// Easing
var quad = {
	easeIn : function(t,b,c,d) {return c*(t/=d)*t + b;},
	easeOut : function(t,b,c,d) {return -c *(t/=d)*(t-2) + b;},
	easeInOut: function(t, b, c, d){
		if ((t /= d / 2) < 1) 
			return c / 2 * t * t + b;
		return -c / 2 * ((--t) * (t - 2) - 1) + b;
	}
};
var _pageChangeHandler = new changePageFunctions();
//object contenant les function a appeler sur le changePage();
function changePageFunctions(){
    
    this.toDoOnPageChange = function(){
    };
    
	//ajouter les functions a executer sur un changement de page ici. syntaxe:    
	//    this.toDoOnPageChange["test"]=function(){
	//        alert('test');
	//    }
	//ou en dehors de l'objet, syntaxe :
	// _pageChangeHandler.toDoOnPageChange["test2"]=function(){
	//        alert('test2');
	//    }
	
    this.run = function(){
	    for(i in this.toDoOnPageChange){
	        if(i != "prototype") this.toDoOnPageChange[i]();
	    }
    };
};
// SWF Handler functions:
function changePage(pageID,idProduct) {	
	if( typeof(window._page)!='undefined' ) {
		window._page.setSelectedPage(pageID);
	}
	
	switch(pageID)
	{
		case "p0":
			window._page._switchDisplay("p0");
		break;
		case "p1":
			window._page._switchDisplay("p1");
		break;
		default:
			//window._page._switchDisplay("home");
			
			
				if(isUserPage(pageID))
				{
					if(pageID != "37" && pageID != "25")
					{
						window._page._switchDisplay("library");
					}
					if(idProduct != 'undefined' && idProduct != null)
					{
						_dontInterpretNextUpdate = true;
						History.add(["library","details",idProduct])
					}
						
				}
				else
				{
					if(pageID != "37" && pageID != "25")
					{
						window._page._switchDisplay("store");
					}
					if(idProduct != 'undefined' && idProduct != null)
					{
						_dontInterpretNextUpdate = true;
						History.add(["store","details",idProduct])
					}
				}
			
		break;
	}
	
	_pageChangeHandler.run();
    //then reset the list of things to do.
    _pageChangeHandler.toDoOnPageChange = function(){};
};

function updateCart(nbArticle){
	// TODO:
	// only update the text, not the entire box !
	//if ( !isNaN(parseInt(nbArticle)) ) {
		var nbaEl = $("numberOfArticle");
		if (nbaEl) {
			trace(">>>>>>>>updateCart - Article number:"+nbArticle);
			nbaEl.innerHTML = '<span class="text">contient ' + nbArticle + ' article</span><span class="shadow">contient ' + nbArticle + ' article</span>';
		} else {
			
			// create the component:
			$("shopping-box").innerHTML = getDivMonPanier(nbArticle).innerHTML; 
		}
	//}
};

function cartLoaded()
{
	var el=document.createElement("div");
	el.id = "cart-update";
	// add buttons:
	var btn1=document.createElement("div");
	btn1.id="close-popup";
	
	el.appendChild(btn1);
	btn1.onclick=cleanPopup;
	showPopup(el,255,125);
};

function cartAddProduct(inName)
{
	if( _page._selectedPageID==_cartPageID ) return;
	//does not display popup when view is on cart
	var el=document.createElement("div");
	el.id = "add-product";
	// add buttons:
	var product=document.createElement("div");
	product.className="productName";
	product.innerHTML=inName;
	var btn1=document.createElement("div");
	btn1.className="medium-button";
	btn1.innerHTML="Voir les détails";
	var btn2=document.createElement("div");
	btn2.className="big-button";
	btn2.innerHTML="Continuer mes achats";
	el.appendChild(product);
	el.appendChild(btn1);
	el.appendChild(btn2);
	
	// then assign actions
	btn1.onclick=function(){
		History.add(["store","cart"]);
		cleanPopup();
	};
	btn2.onclick=cleanPopup;
	showPopup(el,340,150);
};

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////

function showPopup(inEl,w,h)
{
	var popup=document.createElement("div");
	popup.id = "popup-box";
	
	popup.appendChild(inEl);
		
	var bpopup=document.createElement("div");
	bpopup.id = "back-popup";
	
	bpopup.onclick =  cleanPopup;
	
	//var button = document.createElement("a");
	//button.onclick = cleanPopup;
	
	setTimeout("cleanPopup()",5000);
	
	//button.innerHTML = "Click Me To Close";
	//popup.appendChild(button);
	//size
	
	if (typeof window.innerWidth != 'undefined') {
		viewportheight = window.innerHeight;
	} else {
		viewportheight = document.documentElement.clientHeight;
	}
	
	popUpDiv_height=viewportheight/2-(h/2);//90 is half popup's height
	popup.style.top = popUpDiv_height + 'px';
	
	//position
	
	if (typeof window.innerWidth != 'undefined') {
		viewportwidth = window.innerHeight;
	} else {
		viewportwidth = document.documentElement.clientHeight;
	}
	if ((viewportwidth > document.body.parentNode.scrollWidth) && (viewportwidth > document.body.parentNode.clientWidth)) {
		window_width = viewportwidth;
	} else {
		if (document.body.parentNode.clientWidth > document.body.parentNode.scrollWidth) {
			window_width = document.body.parentNode.clientWidth;
		} else {
			window_width = document.body.parentNode.scrollWidth;
		}
	}
	window_width=window_width/2-(w/2);//90 is half popup's width
	popup.style.left = window_width + 'px';
	
	var t=0,from=0;
	
	popup.tic=setInterval(function(){
		if (t>=1) 
		{
			popup.style.opacity=1;
			popup.style.filter='alpha(opacity=100);';
			clearInterval(popup.tic);
		} 
		else 
		{
			from = Math.max(0, quad.easeInOut(t,0,1,1));
			popup.style.opacity=from;
			popup.style.filter='alpha(opacity='+from*100+');';
			t+=.05;
		}
	},5);
	document.body.appendChild(bpopup);
	document.body.appendChild(popup);
		
}

function cleanPopup()
{
	if($("popup-box") != undefined)
	{
		var popup = $("popup-box");
		var t=0,from=1;
		clearInterval(popup.tic);
		popup.tic=setInterval(function(){
			if (t>=1) 
			{
				popup.style.opacity=0;
				popup.style.filter='alpha(opacity=0);';
				clearInterval(popup.tic);
				document.body.removeChild($("popup-box"));
			} 
			else 
			{
				from = Math.max(0, quad.easeInOut(t,1,-1,1));
				popup.style.opacity=from;
				popup.style.filter='alpha(opacity='+from*100+');';
				t+=.05;
			}
		},5);
	}
	
	if($("back-popup") != undefined)
		document.body.removeChild($("back-popup"));
}




/////////////////////////////////////////////////////////////////////////////////////////////////////////////////


function userConnected(flag) {
	if( isUserPage(_page._selectedPageID) ) {
		// reload this page:
		trace("Page connection.onUserConnected() - IS SWF connected ="+ $("aveComicsSWF").getAveConnected());
		//$("aveComicsSWF").goPage(_libraryPageID);
		MainSWFComics.secureGoPage(_libraryPageID);	
	}
};
function validCart(){
	var reg=/(http|https):\/\/([^\/]+)/gi;
	var m=reg.exec(window.location.href);
	var serverURL="https://"+m[2]+"/";
	
	var formString = '<FORM name="goToPayForm" action="'+serverURL+'fr/shop/confirmation.php" method="POST">';
	formString +='<INPUT type="text" name="caddyId" value="'+$("aveComicsSWF").getIdCart()+'">';
	formString +='<INPUT type="text" name="paymentMode" value="'+$("aveComicsSWF").getModeToPay()+'">';
	formString +='<INPUT type="text" name="pageOk" value="'+$("aveComicsSWF").getResultOk()+'">';
	formString +='<INPUT type="text" name="pageKo" value="'+$("aveComicsSWF").getResultKo()+'">';
	formString +='<INPUT type="text" name="currency" value="'+$("aveComicsSWF").getCurrency()+'">';
	formString +='<INPUT type="text" name="language" value="'+$("aveComicsSWF").getLanguage()+'">';
	var formDiv = document.createElement('div');
	formDiv.innerHTML = formString;
	formDiv.style.display="none";
	document.body.appendChild(formDiv);
	document.goToPayForm.submit();
};

var someoneIsWaiting =function (){
    return false;
};
//////////////////////////////////////////////
///div de Classement (left/right column)//////
//////////////////////////////////////////////

var limiteNombre_classement = 10;
var resultString_classement = "";

/*****fonction handler changement de page swf*****/
function searchArtist(target, value){	
	var hd='$("aveComicsSWF").searchArtist("'+target+'","'+value+'");';
	//window._page._addVirtualPageToHistory("searchArtist-"+ calcMD5(value), hd)
	eval(hd);
};
function searchGenre(target, value){
	var hd='$("aveComicsSWF").searchGenre("'+target+'","'+value+'");';
	//window._page._addVirtualPageToHistory("searchGenre-"+ calcMD5(value), hd)
	eval(hd);
};
function searchEditor(target, value){	
	var hd='$("aveComicsSWF").searchEditor("'+target+'","'+value+'");';
	//window._page._addVirtualPageToHistory("searchEditor-"+ calcMD5(value), hd)
	eval(hd);
};
function showDetailOfProduct(productId, page, page2, page3, page4, page5, page6){
	$("aveComicsSWF").showDetailOfProduct(productId, page, page2, page3, page4, page5, page6);
};

//idDiv : le div dans lequel on veut afficher ce classement
//stringClassement : chaine de charactere indiquant le nom de la catégorie a afficher : top_nouveautes, top_100, top_jeunesse, top_humour, top_manga
function afficheDesignBoxClassement(idDiv, stringClassement){
    var resultString=""; 
  	$(idDiv).innerHTML = resultString; 
}

var CatNavStore={
	load:false	
};

//idDiv : le div dans lequel on veut afficher ce classement
//stringClassement : chaine de charactere indiquant le nom de la catégorie a afficher : top_nouveautes, top_100, top_jeunesse, top_humour, top_manga
function afficheClassement(idDiv, stringClassement){
	var adressePHP = "/ave-comics-test/friends/stats.php?stats=";
    if( stringClassement!= "top_nouveautes" && stringClassement!= "top_100"  ) {
    	adressePHP+="top_of_key_word&data="+stringClassement.substr(4,1).toUpperCase()+stringClassement.substr(5,stringClassement.length);
    } else {
    	adressePHP+=stringClassement;	
    }
	sendPHPRequestclassement(idDiv, adressePHP);
};
function sendPHPRequestclassement(idDiv, adressePHP) {
	var flag = true;
	var xhr_object=getHTTPRequest();
  	xhr_object.open("GET", adressePHP, true);
  	xhr_object.onreadystatechange = function() {
	    //ajout d'un flag car avec IE la fonction s'excute encore une ou deux fois mme si readyState == 4
	    if (xhr_object.readyState == 4 && flag) { 
	       flag = false;
	   	   parseXMLresult_classement(xhr_object.responseXML, idDiv);
	    }
  	}
  	xhr_object.send(null);
};
function parseXMLresult_classement(resultXml, idDiv) {
	var mediaID=null;
	var AFAVEClassement_categorie = idDiv.substr(4, idDiv.length);
	var classement = new Array();
	var productID, count, title, imageID;
    if(resultXml){
		var subxml = resultXml.getElementsByTagName("row");	
	    for (var j=0; j<Math.min(subxml.length, limiteNombre_classement); j++) {
	    	for(var i=0; i<subxml[j].childNodes.length ; i++){
				switch(subxml[j].childNodes[i].nodeName) {
					case "product_id" :
				    	productID = subxml[j].childNodes[i].firstChild.nodeValue;
				    	break;
				    case "count" :
				    	count = subxml[j].childNodes[i].firstChild.nodeValue;
				    	break;
				    case "title" :
				    	title = subxml[j].childNodes[i].firstChild.nodeValue;
	                    title =  AFAVEClassementComputeString(title);
				    	break;
				    case "image" :
				    	imageID = subxml[j].childNodes[i].firstChild.nodeValue;
				    	break;
				}
	    	}
	    	classement[classement.length] = new AFAVEClassement_comic(productID, count, title, imageID);
	    }
	    var width=0;
	    if($(idDiv) ) width = $(idDiv).offsetWidth -20;
	    if(width<=10) width = 183; 
	    var resultString="";
	    if(!$("color-"+AFAVEClassement_categorie)){ //si la box vide n'est pas encore affichée, l'afficher.
	        resultString+="<div class='effect'>";
	        resultString+="<div class='topEffect'></div>";
	        resultString+="<div class='middleEffect'></div>";
	        resultString+="<div class='bottomEffect'></div>";
	        resultString+="</div>";
	        resultString+="<div id=\"color-" + AFAVEClassement_categorie +"\" class=\"color-boxStore\"></div>";
	        resultString+="<div onclick=\"History.add(['store','category','"+AFAVEClassement_categorie+"'])\" id=\"title-"+AFAVEClassement_categorie+"\" class='title-boxStore'></div>";
	    }    
	    resultString+="<ul class='white-boxStore'>";
		
		
	  	for (var i=0; i<classement.length; i++){
			var hd='_page.showDetailOfProduct('+classement[i]._productID+')';
			var tmptitle;
			// HEAD
			if(i==0) {
				resultString+="<li onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'>&nbsp;&nbsp;1. "+classement[i]._title+"</li>";
				// 143 103
				var mediaID=classement[i]._imageID;
				//loadingMedias.push( mediaID );	
				var imgIDC=AFAVEClassement_categorie +"-"+mediaID;
				// default media loading...
				resultString+="<li><img id='media-"+imgIDC+"' onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'";
				resultString+=" src='"+Media.MEDIA_LOAD+"' class='img-bd' alt='bd' width='103' height='143' /></li>";
			}
			else {
				if(i<9){
					resultString+= "<li onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'>&nbsp;";
				}
				else  resultString+= "<li onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'>";
				
				tmptitle =classement[i]._title;
				if( tmptitle.length>15 ) {
					tmptitle=tmptitle.substr(0,13)+"...";
				}
			  
			  
			  
			  // TODO undefined loop on IE !
		/*	  
			  while(tmptitle.textWidth('sans-serif', 8) > width-20 && (width-20)>0){
					//tmptitle = tmptitle.substr(0,tmptitle.length - 4)+"...";   
			  }
		*/
			  resultString+= "&nbsp;"+(i+1)+". "+tmptitle+"</li>";
		  }
	  }
	  resultString+="</ul><ul class='black-boxStore'>";
	  for (var i=0; i<classement.length; i++){
	 		var hd='_page.showDetailOfProduct('+classement[i]._productID+')';
		  	var tmptitle;
		 	// HEAD
		  	if(i==0){			  
			  resultString+="<li onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'>&nbsp;&nbsp;1. "+classement[i]._title+"</li>";
			  resultString+="<li><img id='shadow-"+imgIDC+"' class='shadow-bd' width='"+"111";
			  resultString+="' height='150' src='images/avecomics-1.1/store/shadow-img-box.png' alt='shadow' /></li>";		
			} 
			else {
			  if(i<9){
				  resultString+= "<li onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'>&nbsp;";
			  }
			  else  resultString+= "<li onclick='AFAVENavBox_selectFilter(\"store\",\""+hd+"\")'>";
			  tmptitle =classement[i]._title;
			  
			  if( tmptitle.length>15 ) {
					tmptitle=tmptitle.substr(0,13)+"...";
				}
		
		/*
			  while(tmptitle.textWidth('sans-serif', 8) > (width-20) && (width-20)>0 ){
				tmptitle = tmptitle.substr(0,tmptitle.length - 4)+"...";   
			  }
		*/
			 //  $("debug").innerHTML+="<br/>"+tmptitle;
			  resultString+= "&nbsp;"+(i+1)+". "+tmptitle+"</li>";
			 
		  }
	  }
	  resultString+="</ul>";
	  
	  if(!$("color-"+AFAVEClassement_categorie)){
	    	if($(idDiv)) $(idDiv).innerHTML = resultString;
	  }
	  else
	    $("box-"+AFAVEClassement_categorie).innerHTML += "<div onclick='window._page.goToPage('"+AFAVEClassement_categorie+"');' id='title-"+AFAVEClassement_categorie+"' class='title-boxStore' ></div>"+resultString;
	
	  
	  var ombreIsNeeded =true;
	  var divsDansLaDiv = document.getElementsByTagName('div');
	  for(var count=0; count<divsDansLaDiv.length; count++){
	    if(divsDansLaDiv[count].id ==  'ombreCover') 
	        ombreIsNeeded =false;
	  }
	  
		if (classement[0]) {
			var coverRatio = 0.76; //valeur par défaut
			var dc=$("color-" + AFAVEClassement_categorie);
			if (dc) {
				var divsUl = dc.getElementsByTagName('ul');
				for (i in divsUl) {
					var divUl = divsUl[i];
					if (divUl.childNodes) {
						var divPicture = divUl.childNodes[1];
					}
				}
			}
		}
    }
    else {
        var resultString="<div class='effect'><div class='topEffect'></div><div class='middleEffect'></div><div class='bottomEffect'></div></div><div id='color-"+AFAVEClassement_categorie+"'><div onclick='window._page.goToPage('"+AFAVEClassement_categorie+"');' id='title-"+AFAVEClassement_categorie+"'></div></div>";
		$(idDiv).innerHTML = resultString;
    }
	// load media cover and resize it to the good dimension
	// with aspect ratio respect
	if( mediaID ){
		Media.getFriendMedia(AFAVEClassement_categorie,mediaID,103 ,143,function(){
			var pf=this.preffix;
			var nm=Media._normalize(103,143,this);
			var mediaIMG=$("media-"+pf+"-"+this.id);
			var shIMG=$("shadow-"+pf+"-"+this.id );
			//console.log( "Cload - " +pf +" " + this.id );
			mediaIMG.src=nm.src;
			mediaIMG.width=nm.width;
			mediaIMG.height=nm.height;
			// update the shadow
			shIMG.width=nm.width+7;
			shIMG.height=nm.height+7;
		});	
	}
	
};
var Media={
	DEFAULT_WIDTH:	103,
	DEFAULT_HEIGHT:	143,
	MEDIA_LOAD:		IMAGES_PATH_DIR+"/store/bdLoad.jpg",
	MEDIA_DEFAULT:	IMAGES_PATH_DIR+"/store/bdNotFound.jpg",
	_normalize:function(W,H,image) {
		var w=image.width;
		var h=image.height;
		var sc_ratio = W/H; 
		var vp_ratio = w/h;
		var mode=0;
		var zoom =1;
		if( vp_ratio > sc_ratio ) {	zoom = W/w;	} 
		else if( vp_ratio < sc_ratio ) { zoom = H/h; }	
		image.width = Math.round(image.width*zoom);
		image.height = Math.round(image.height*zoom);
		return image;	
	},
	getFriendMedia:function(preffix,key,maxWidth,maxHeight,updateHandler){
		var url="/ave-comics/friends/friend2.php?pattern=getmedia2&parameters="+key;
		var req=getHTTPRequest();
		req.open("GET",url,false);
		req.send(null);
		if( req.status== 404 ) {
			// give the rescue img:
			url=Media.MEDIA_DEFAULT;
		}
		// load image and check aspect ratio:
		var media=new Image();
		media.id=key;
		media.preffix=preffix;
		media.onload=updateHandler;
		media.src=url;
	}
};


//remove the string "version" and replace "- Chapter" by "#"  (EatItFresh #1)
function AFAVEClassementComputeString(stringTitle){
	var indiceChapter = stringTitle.indexOf("- Chapitre ");
	if(indiceChapter!= -1) stringTitle = stringTitle.substr(0,indiceChapter)+"#"+stringTitle.substr(indiceChapter+11, stringTitle.length);
    
    var indiceVersion = stringTitle.indexOf("version");
	if(indiceVersion!= -1) stringTitle = stringTitle.substr(0,indiceVersion)+stringTitle.substr(indiceVersion+7, stringTitle.length);
	
	return stringTitle;
}

//exemple de donnes stockees : 51 1 Lucky Luke : L'Homme de Washington 4715
function AFAVEClassement_comic(productID, count, title, imageID){
	this._productID = productID;
	this._count = count;
	this._title = title;
	this._imageID = imageID;	
}

function getPageNumberForCategorie(categorie){
    var pageNumber="";
    switch(categorie){
        case("nouveautes") :
            pageNumber= 30;
            break;
        case("manga") :
            pageNumber= 33;
            break;
        case("humour") :
            pageNumber= 32;
            break;
        case("jeunesse") :
            pageNumber= 31;
            break;
        case("100") :
            pageNumber= 26;
            break;
    }
    return pageNumber;
};
String.prototype.textWidth=function(police,taille){
	var container=document.createElement('div');
	container.style.visibility='hidden';
	container.style.fontFamily=police;
	container.style.fontSize=taille;
	container.style.display='inline';
	container.id="magicdiv";
	document.body.appendChild(container);
	$('magicdiv').innerHTML=this;
	var longueur = $('magicdiv').offsetWidth;
	$('magicdiv').parentNode.removeChild($('magicdiv'));
	return longueur;
};
///////////////////////////////
////validation d'un achat//////
///////////////////////////////

/** Debug Firefox/Safari 4 */
function trace(text) {
//	if (console) {
//		try {
//			console.log(text);
//		} 
//		catch (e) {
//		
//		}
//	}
}


/***********************************************
***BOX navigation (page Ma Bibliotheque) *******
************************************************/

///////////////////
// LIBRAY COLUMNS
var CatNavLibrary={
	LIBRARY_ID:"LeftColBibli",
	_visible:false,
	LC_SCRIPT:"/ave-comics/core/getLibraryColumns.php",
	LIBRARY_COLUMNS:["gender","author","editor","album"],
	domId:null,
	init:function(domId) {},	
	// SET VISIBLE !
	setVisible:function(flag) {},
	displayColumns:function(){},
	updateDisplayColumns:function() {	},
	_retrieveColumns:function(type) {	},
	// readystatechange
	_requestHandler:function(req,columnName,type) {	},
	_enrobeList:function(catName, htmlLIST){	},	
	initList:function() {	}
};
// AFAVEInitScroll --> create the handler
function AFHistoricalFilter(navs) {
	History.add(navs);
};
function AFAVENavBox_selectFilter(cat, link){	
	if (cat == "all") {
		if (window._page._selectedPageID != _libraryPageID) {
			MainSWFComics.secureGoPage(_libraryPageID);
		}
		$("aveComicsSWF").cleanSearch("lib_user_1");
		$("aveComicsSWF").cleanSearch("lib_user_2");
	} else if (cat == "album") {
		eval(link);
	} else if( cat =="store" ) {
		window._page._loadStorePage();
		eval(link);
	} else {
		// library links
		if (window._page._selectedPageID != _libraryPageID) {
			if( $("aveComicsSWF") ) {
				MainSWFComics.secureGoPage(_libraryPageID);
			} else {
				alert( "SWF NOT LOADED" );
			}
		}
		CatNavLibrary.setVisible(true);
		eval(link);
    }
};

//chaque entrée est une string a affiché et un lien associé
function AFAVENavigation_data(displayString, linkString, idDiv){
    this.originalDATA = displayString;
	this.computeString = function (stringData){
		var result = stringData;
        var result = stringData.replace("-etCom-", "&");
	    var width = $(idDiv).offsetWidth-50;
	   	while(result.textWidth('sans-serif', 8) >= width && width>0){
			result = result.substr(0, (result.length -4))+"...";
	   	}
	   	return result;
	}
    this.display = this.computeString(displayString);
	this.link = linkString;
}

/********gestion du scroll dans les panneau de navigation******/
/*** page : Ma Bibliotheque ***********************************/

 function AFAVENavigationScroll_isOnScrollBar (){
	this.genres = false;
	this.genresBackground = false;	
}

function findPos(obj) {
    var curleft = obj.offsetLeft || 0;
    var curtop = obj.offsetTop || 0;
    while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
    }
    return {x:curleft,y:curtop};
}
function AFAVEInitScroll(cat){
	if( $("scroll-background-"+cat)){
        var scrollDiv = document.createElement('div');
        $("scroll-background-"+cat).appendChild(scrollDiv);
	
    	var liste = $('liste-'+cat);
        var ul = liste.getElementsByTagName('ul')[0];

        $("scroll-background-"+cat).onmouseover= function(){
	        AFAVENavigationScroll_isOnScrollBar[cat+"Background"]=true;
        };
        $("scroll-background-"+cat).onmouseout= function(){
        	AFAVENavigationScroll_isOnScrollBar[cat+"Background"]=false;
        };
        scrollDiv.id = "scrollPict-"+cat;
        scrollDiv.className = "bar-scroll";
        scrollDiv.onmouseover= function(){ 
        	AFAVENavigationScroll_isOnScrollBar[cat] = true; 
        }; 
        scrollDiv.onmouseout= function(){ 
            if(AFAVEScrollNavigation_CurrentEvent == null)
                AFAVENavigationScroll_isOnScrollBar[cat] = false; 
        }; 
        scrollDiv.style.position= 'relative';
        scrollDiv.style.top= '3px';
        scrollDiv.style.left= '0px';
    }
};
function onclickScrollNavMaBibli(event){
    for (cat in AFAVENavigationScroll_isOnScrollBar) {

		if(AFAVENavigationScroll_isOnScrollBar[cat] == true && cat.indexOf('Background')!= -1){

			if(AFAVENavigationScroll_isOnScrollBar[cat.substr(0,cat.indexOf('Background'))]==false || !AFAVENavigationScroll_isOnScrollBar[cat.substr(0,cat.indexOf('Background'))]){

				cat =cat.substr(0,cat.indexOf('Background'));

				posYparent = findPos($("scroll-background-"+cat)).y;
				posY = getMouseCoords(event).y - posYparent;
				limiteY = $("scroll-background-"+cat).childNodes[0].style.top;
				limiteY = parseInt(limiteY.substr(0,limiteY.indexOf('px')));

	
				if(posY< limiteY){	
					AFAVENavScroll_up(cat, limiteY);
				}
				else if(posY> limiteY+$("scroll-background-"+cat).childNodes[0].offsetHeight){
					AFAVENavScroll_down(cat, limiteY);
				}
			}
            return true;
		}
	}
    return false;
}

function AFAVENavScroll_up(cat, posActuelle) {
	if(posActuelle == "" || posActuelle<0)
		posActuelle = parseInt($("scroll-background-"+cat).childNodes[0].style.top.substr(0,$("scroll-background-"+cat).childNodes[0].style.top.indexOf("px")));

	if(posActuelle-10 <3) $("scroll-background-"+cat).childNodes[0].style.top = '3px';
	else $("scroll-background-"+cat).childNodes[0].style.top = (posActuelle-10)+'px';
	
	var tmpTOP = parseInt($("scrollPict-"+cat).style.top.substr(0,$("scrollPict-"+cat).style.top.indexOf("px")));
	AFAVEScrollNav_updatePos(cat, (tmpTOP / ($("scroll-background-"+cat).offsetHeight - $("scrollPict-"+cat).offsetHeight -10)));
}

function AFAVENavScroll_down(cat, posActuelle){
	
	if(posActuelle == "" || posActuelle<0)
		posActuelle = parseInt($("scroll-background-"+cat).childNodes[0].style.top.substr(0,$("scroll-background-"+cat).childNodes[0].style.top.indexOf("px")));

	if(((posActuelle+10)+$("scrollPict-"+cat).offsetHeight) > $("scroll-background-"+cat).offsetHeight -10) 
		$("scroll-background-"+cat).childNodes[0].style.top = ($("scroll-background-"+cat).offsetHeight - $("scrollPict-"+cat).offsetHeight -10)+'px';				
	else $("scroll-background-"+cat).childNodes[0].style.top = (posActuelle+10)+'px';
	
		
	var tmpTOP = parseInt($("scrollPict-"+cat).style.top.substr(0,$("scrollPict-"+cat).style.top.indexOf("px")));
	AFAVEScrollNav_updatePos(cat, (tmpTOP / ($("scroll-background-"+cat).offsetHeight - $("scrollPict-"+cat).offsetHeight -10)));
}

var AFAVEScrollNavigation_CurrentEvent = null;
var AFAVEScrollNavigation_PreviousEvent = null;
var AFAVEScrollNavigation_selectedCat = "";
document.onmousemove = function(event){
	if(AFAVEScrollNavigation_CurrentEvent != null){
    	AFAVEScrollNavigation_PreviousEvent = AFAVEScrollNavigation_CurrentEvent; 	
		AFAVEScrollNavigation_CurrentEvent = event;
		cat = AFAVEScrollNavigation_selectedCat;
		if( cat != "") {
	   		if(AFAVENavigationScroll_isOnScrollBar[cat] == true && $("scrollPict-"+cat)){
				var topString = $("scrollPict-"+cat).style.top;
				
			    if (topString.indexOf('px') != -1) {
					topString = topString.substr(0, topString.indexOf('px'));
				}
				var tmpTOP = parseInt(topString);				
	   			tmpTOP += getMouseCoords(AFAVEScrollNavigation_CurrentEvent).y - getMouseCoords(AFAVEScrollNavigation_PreviousEvent).y;
				if(tmpTOP<3)tmpTOP=3;
				if((tmpTOP+$("scrollPict-"+cat).offsetHeight) > $("scroll-background-"+cat).offsetHeight -10) 
					tmpTOP = $("scroll-background-"+cat).offsetHeight - $("scrollPict-"+cat).offsetHeight -10;
	     		$("scrollPict-"+cat).style.top = tmpTOP+"px";
	  
	     		AFAVEScrollNav_updatePos(cat, (tmpTOP / ($("scroll-background-"+cat).offsetHeight - $("scrollPict-"+cat).offsetHeight -10)));
	     	}
		}
	}
};
document.onmousedown = function(e){
	for (cat in AFAVENavigationScroll_isOnScrollBar) {
		if(cat.indexOf('Background')==-1){
	   		if(AFAVENavigationScroll_isOnScrollBar[cat] == true){
				AFAVEScrollNavigation_CurrentEvent = e;
				AFAVEScrollNavigation_PreviousEvent = e;
				AFAVEScrollNavigation_selectedCat = cat;
				return false;
	   		}
		}
	}
	return true;
};
document.onmouseup = function(event){
	for (cat in AFAVENavigationScroll_isOnScrollBar) {
		if(cat.indexOf('Background')==-1)
			AFAVENavigationScroll_isOnScrollBar[cat] = false;
	}
	AFAVEScrollNavigation_CurrentEvent = null;
	AFAVEScrollNavigation_PreviousEvent = null;	
};   	
function getMouseCoords(event)
{
	var resX, resY=0;
	if ( navigator.appName.indexOf('Microsoft')!= -1 ) { //gestion de ie    
		resX = window.event.clientX + document.body.scrollLeft;
		resY = window.event.clientY + document.body.scrollTop;
	}
	else if (event.pageX == null && (event.clientX != null || window.event.clientX != null)){ //gestion des navigateurs ne connaissant pas event.pageX/Y
		var doc = document.documentElement, body = document.body;
		resX = (event.clientX ||  window.event.clientX) + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc.clientLeft || 0);
		resY = (event.clientY ||  window.event.clientY) + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc.clientTop || 0);
	}
	else { 
		resX = event.pageX;
		resY = event.pageY;
	}
   return {x : resX, y : resY};
};
function AFAVEScrollNav_updatePos(cat, position){
	var liste =$('liste-'+cat);

	var ul = liste.getElementsByTagName('ul')[0];
	var topMax =  ul.offsetHeight - liste.offsetHeight +20;

	ul.style.position ='relative';
	ul.style.top = Math.round(-topMax * position +10)+'px'; //position est compri entre 0 et 1
    
    var ul2 = liste.getElementsByTagName('ul')[1];
	if (ul2) {
		ul2.style.position = 'relative';
		ul2.style.top = Math.round((-topMax * position + 11) - ul.offsetHeight) + 'px'; //position est compri entre 0 et 1
	}
};
function AVENavBox_deselectAll(){
	var listNames=["gender","album","author","editor"];
	for( var i=0;i<listNames.length;i++ ) {
		var liste = $("liste-"+listNames[i]);
		if (liste) {
			var ul = liste.getElementsByTagName('ul')[0];
			if(ul){
				for(key in ul.childNodes){
					if (ul.childNodes[key].style) {
						ul.childNodes[key].style.color = 'white';
					}
				}
			}
		}
	}
};
/**Champ de recherche : placement d'un input dans l'image du header****/
function addSearchField(){
    var divParente = $('central-header');
    var field = document.createElement('input');
    divParente.appendChild(field);
    field.className='headerSearchField';
    field.size=11;
    field.onchange=function(){
    	if(isUserPage(_page._selectedPageID)){
			var navs=["library","result","all",this.value];
			History.add(navs);
    	} else {
			var navs=["store","result","all",this.value];
			History.add(navs);
    	}
        this.value="";
        boutonValid.style.visibility ='hidden';
    };
    field.onkeyup=function(){
        if(this.value=="") boutonValid.style.visibility ='hidden';
        else boutonValid.style.visibility ='visible';
    }
    
    var boutonValid = document.createElement('div');
    divParente.appendChild(boutonValid);
    boutonValid.className='headerSearchValid';
    boutonValid.onclick =  field.onchange;
};
/************DOCUMENT.ONCLICK et onSelectStart*(IE)*/
document.onclick=function(event){
	if (typeof onClickCanvaEtagere != 'undefined') {
		if (onClickCanvaEtagere(event) ) return true;
	}
    if(onclickScrollNavMaBibli(event))
        return true;
    return true;
};
//if the browser is IE4+
document.onselectstart= function (){
	for (cat in AFAVENavigationScroll_isOnScrollBar) {
		if(cat.indexOf('Background')==-1){
			return false;
		}
	}
	return true;				
};

/**********************/
/** MULTI INTERVALS **/
var Interval={
	loop:null,
	handlers:[],
	__init:function() {
		// global setInterval function handler
		this.loop=window.setInterval( function() {
			for( var i=0;i<Interval.handlers.length;i++ ) {
				if(Interval.handlers[i].handler) {
					Interval.handlers[i].handler();
				}
			}
		},20);
	},
	setInterval:function(handler,delay) {
		var h=new Object();
		h.handler=handler;
		h.delay=delay;
		this.handlers.push(h);
		if( this.loop==null ) {
			this.__init();
		}
	},				
	clearInterval:function(handler) {
		var newHandlers=[];
		for( var i=0;i<this.handlers.length;i++ ) {
			if( this.handlers[i].handler!=handler ) {
				newHandlers.push(this.handlers[i]);	
			}
		}
		if( newHandlers.length==0 ) {
			window.clearInterval(this.loop);
			this.loop=null;
		}
		// replace list:
		this.handlers=newHandlers;
	}
};



////////////////////////////////////////
////// EXTERNAL PLAYER /////////////////
////////////////////////////////////////

/* AB --> JS */
function openPlayer()
{
	/*
	 * 
	 * <object width="593" height="1309" type="application/x-shockwave-flash" data="ave-comics-test/AVEBrowser/AveBrowser.swf" 
	 * id="aveComicsSWF" style="visibility: hidden; height: 1309px;"><param name="bgcolor" value="#c0c5e0"/><param name="wmode" 
	 * value="transparent"/><param name="allowFullScreen" value="true"/>
	 * <param name="allowScriptAccess" value="sameDomain"/><param name="quality" value="high"/></object>
	 * 
	 * 
	 */
	
	var ind="";
	/*ind='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';
	ind+='id="externalPlayer" width="100%" height="100%"';
	ind+='codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">';*/
	
	var regParam="";
	if( navigator.userAgent.indexOf( "MSIE" ) >= 0 ) { // ie
		// IE store swf in cache, all external interface handler are lost ?
		regParam="?reg="+new Date().getTime();
	}
	ind='<object type="application/x-shockwave-flash" data="ave-comics/AVEBrowser/externalPlayer.swf'+regParam+'" ';
	ind+='id="externalPlayer" width="100%" height="100%">';
	ind+='<param name="movie" value="ave-comics/AVEBrowser/externalPlayer.swf" />';
	ind+='<param name="quality" value="high" />';
	ind+='<param name="bgcolor" value="#869ca7" />';
	ind+='<param name="allowFullScreen" value="true" />';
	ind+='<param name="allowScriptAccess" value="sameDomain" />';
	/*ind+='<embed src="ave-comics-test/AVEBrowser/externalPlayer.swf" quality="high" bgcolor="#869ca7"';
	ind+='width="100%" height="100%" name="externalPlayer" align="middle"';
	ind+='play="true"';
	ind+='loop="false"';
    ind+='allowFullScreen="true"';
	ind+='quality="high"';
	ind+='allowScriptAccess="sameDomain"';
	ind+='type="application/x-shockwave-flash"';
	ind+='pluginspage="http://www.adobe.com/go/getflashplayer">';
	ind+='</embed>';*/
	ind+='</object>';

	Shadowbox.open({
		player:     'html',
        title:      '',
        content:    ind,
        height:     782,
        width:      1212
    },{onClose: sbClose_Handler});
}



/* AB --> EP */
function checkIfPlayerIsConnected()
{
	if( $("externalPlayer") ) $("externalPlayer").checkIfPlayerIsConnected();
}

/* AB <-- EP */
function playerConnected()
{
    //$("aveComicsSWF").playerConnected();
    if(state==1)
    {
    var mail = Cookies.readCookie("AVemail")||"";
    var reg= /@(?!.*@.*)/;
    mail = mail.replace(reg, "*-at*");
    var pass = Cookies.readCookie("AVpassword")||"";
    readAVE("37",true,mail,pass);
    }
    else if(state == 2)
    {
     var mail = Cookies.readCookie("AVemail")||"";
    var reg= /@(?!.*@.*)/;
    mail = mail.replace(reg, "*-at*");
    var pass = Cookies.readCookie("AVpassword")||"";
    readAVE("76",true,mail,pass);
    }
}

/* AB --> EP */
function readAVE(in1,in2,in3,in4)
{
	if( $("externalPlayer") ) $("externalPlayer").readAVE(in1,in2,in3,in4);
}

/* AB --> EP */
function readBook(in1,in2,in3,in4,in5,in6,in7,in8)
{
	if( $("externalPlayer") ) $("externalPlayer").readBook(in1,in2,in3,in4,in5,in6,in7,in8);
}

/* AB --> EP */
function closePlayerSWF()
{
	//if( $("externalPlayer") ) $("externalPlayer").closePlayerSWF();
}

/* AB <-- EP */
function playerReadyToClose()
{
	//$("aveComicsSWF").playerReadyToClose();
	closePlayer();
}

/* AB --> JS */
function closePlayer()
{
	Shadowbox.close();
}

/* AB <-- JS */
function sbClose_Handler()
{
	//$("aveComicsSWF").closePlayer();
}

function readEIF1()
{
    openPlayer();
    state = 1;
}

function readEIF2()
{
    openPlayer();
    state = 2;
}
