/*implements version loader by D.PECCHIOLI
 need list object first
*/

Version.prototype.constructor = Version;

	function Version(type_ob,brand,model,ss_cat,nb_res){
		this.type_ob = type_ob;
		this.brand = brand;
		this.model = model;
		this.ss_cat = ss_cat;
		this.sessid = this.get_Sessid();/*get php_sessid*/
		this.ready = false;
		this.xmlhttp_data = null;
		this.data_ = null;
		this.fade = 0;
		this.inter = null;
		this.all_tag = false;
		this.refreshes = 0;
		this.nb_res = nb_res;
		this.IE = document.all?true:false;
		this.div = document.getElementById('Version_list');
		this.div_shadow = document.getElementById('Version_list_shadow');
		this.restore = false;
		this.Tdata = null;
		this.prepareTime = null;
		this.NAPL = 2000;
		this.Reg_code = (/^(1|605|575|607|606|60|61|62|63|64|65|66|67|68|69|70|71|72)+(,|$)/.test(ss_cat)? new RegExp("(\n)","g") : new RegExp("([0-9]+)( +)([a-z]{1,2}( |$))","gi"));
		this.defaultDivHeight = (this.type_ob=='ve_ads'?'':'275px');
		this.Reg_decode = new RegExp("_","g");
		this.progress_bar = document.getElementById('progress_bar');
		if(this.IE)this.progress_bar.style.filter = 'alpha(opacity=30);';
		else this.progress_bar.style.opacity=0.3;
		this.Tkeys = document.getElementById('version').value.split(' ');
		this.closeWin = (this.getCookie('close-win')=='false'?false:true);
		this.listlabel=(this.type_ob=='ve_ads'?'annonce':'finition');		
		this.Scolor = (this.type_ob=='ve_ads'?'#007EFF':(this.type_ob=='ve_quot'?'#007EFF':'#BECFDA'));
		if(!this.IE)this.div.style.marginLeft='1px';
	}
	
	Version.prototype.SetBrandModelCat = function(brand,model,ss_cat){
		this.brand = brand;
		this.model = model;
		this.ss_cat = ss_cat;
		this.restore = true;
		this.Reset_(true,true);
	}
	
	Version.prototype.request = function() {
		try {
				this.xmlhttp_data = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch (e) { 
			this.ready=true;
		}
		if(this.xmlhttp_data!=null){
				this.xmlhttp_data.onreadystatechange = vs.prepareData;
				if(this.type_ob=='ve_ads')this.xmlhttp_data.open("GET", '/ze_version.php?restore='+this.restore+
																													'&SS_CATEGORIE='+this.ss_cat+
																													'&marque='+this.brand+
																													'&modele='+this.model+
																													'&uncache='+Math.random());
				this.xmlhttp_data.send(null);
		}
	}
	
	Version.prototype.get_Sessid = function(){
		return this.getCookie('php_sessid');
	}
	
	Version.prototype.getCookie = function(key_id)
	{
		var i,j;
		var cookie = document.cookie;
		i = cookie.indexOf(key_id+'=');
		if(i==-1)return false;
		j = cookie.indexOf(";",i);		
		if(j==-1)j=cookie.length;
		return (unescape(cookie.substring(i+key_id.length+1,j)));
	}
	
	Version.prototype.Reset_ = function(clear_all,noprocess){
		if(clear_all)document.getElementById('version').value='';
		this.refreshes = 0;
		this.ready = false;
		this.data_ = null;
		this.Tdata = null;
		this.xmlhttp_data = null;
		if(this.type_ob=='ve_ads')this.restore = true;
		else push(false);
		if(!noprocess)this.Process();
	}
	
	Version.prototype.Push_data = function(versions) {
		if(this.type_ob=='ve_ads')return false;
		this.data_ = versions;
		this.Tdata = null;
		this.ready = true;
	}
	
	Version.prototype.Process = function(show_me) {
		if(!this.brand.length || !this.model.length)return;
		if(this.type_ob=='ve_ads' && !this.ready && this.xmlhttp_data==null)this.request();
		else if(this.ready && this.data_ !=null && this.data_.length){
			if(show_me && this.div.style.display=='')return;
			if(show_me || this.div.style.display=='none')this.showList();
			else {
				window.clearInterval(this.inter);
				this.inter = setInterval('vs.fadeDown(true);',25);
			}
		}
	}
	
	Version.prototype.closeList = function() {
		if(this.inter || this.div.style.display=='none')return;
		window.clearInterval(this.inter);
		this.inter = setInterval('vs.fadeDown(true);',25);
	}
	
	Version.prototype.Simulate_and_Count = function(Version_label,exact_match){
		var i,j,k;
		var Ttemp = '';
		var found;
		var res;
		var Tscore = new Array();
		var max_;
		var keyv = null;
		Version_label = Version_label.replace(/( )+$/,'').replace(/^( )+/,'');
		var TtokenVersion = Version_label.split(' ');
		if(this.Tdata==null){
			this.Tdata = this.data_.split('|');
			for(i=0;i<this.Tdata.length;i++){
				this.Tdata[i] = this.Tdata[i].split(';');
				this.Tdata[i][0] = this.Tdata[i][0].replace(this.Reg_code,'$1_$3');
			}
		}
		i=0;found=false;
		/*delete a token whitch should be a subchain of last inserted token*/
		while(i<TtokenVersion.length-1){
			found = TtokenVersion[TtokenVersion.length-1].indexOf(TtokenVersion[i])>-1;
			if(found){
				TtokenVersion[i] = TtokenVersion[TtokenVersion.length-1];
				Ttemp = '';
				i=0;
				for(j=0;j<TtokenVersion.length-1;j++)Ttemp += (Ttemp.length?' ':'')+TtokenVersion[j];
				TtokenVersion = Ttemp.split(' ');
			}
			else i++;
		}
		if(Ttemp.length){/*a word is a sub word of another one*/
			return this.Simulate_and_Count(Ttemp,exact_match);
		}
		max_ = 0;
		i=0;
		while(i<this.Tdata.length){
			found = false;
			while(i<this.Tdata.length && !found){
				j=0;while(j<TtokenVersion.length && this.Tdata[i][0].indexOf(TtokenVersion[j])>-1)j++;
				found = (j==TtokenVersion.length);/*this.Tdata[i][0] version contains every version token?*/
				if(!found)i++;
			}
			if(found){
				res='';
				k=0;
				TtokenVersionDB = this.Tdata[i][0].split(' ');
				for(k in TtokenVersionDB){
					found = false;
					/*simulate query by findind a subchain and not exactly the same because of like in query except if exact_match is true*/
					j=0;while(j<TtokenVersion.length && !found){
						found = (!exact_match && TtokenVersionDB[k].indexOf(TtokenVersion[j])>-1) || (exact_match && TtokenVersionDB[k]==TtokenVersion[j]);
						if(found)res+=(res.length?' ':'')+TtokenVersion[j];
						j++;
					}
				}
				if(res!=''){
					if(typeof(Tscore[res])=='undefined')Tscore[res]=parseInt(this.Tdata[i][1]);
					else Tscore[res]+=parseInt(this.Tdata[i][1]);
					if(Tscore[res] > max_){
						max_ = Tscore[res];
						keyv = res;/*save best matching*/
					}
				}
			}
			i++;
		}
		if(keyv==null || keyv=='' || keyv.length < Version_label.length){
			keyv = '';
			Tscore[keyv]='';
		}
		return keyv+"\n"+Tscore[keyv];
	}
	
	Version.prototype.ReoderVersionTokens = function(exact_match){
		var Tres;
		var versionlabel = document.getElementById('version');
		if(versionlabel.value.length){
			Tres = this.Simulate_and_Count(versionlabel.value.toUpperCase().replace(this.Reg_code,'$1_$3'),exact_match).split("\n");
			if(Tres[0]!=''){
				if(versionlabel.value.substr(versionlabel.value.length-1,1)==' ')versionlabel.value = Tres[0]+' ';
				else versionlabel.value = Tres[0];
				if(this.type_ob!='ve_ads')push(true);
			}
		}else if(this.type_ob!='ve_ads')push(false);
		if(exact_match)this.CompareTokens(versionlabel.value.split(' '));
		this.Tkeys = versionlabel.value.split(' ');
	}
	
	Version.prototype.CompareTokens = function(afterT){
		var i,j,found,word;
		var comptB = 0;
		var comptA = 0;
		var k;
		for(k=0;k<afterT.length;k++){comptA+=(afterT[k].length?1:0);}
		for(k=0;k<this.Tkeys.length;k++)comptB+=(this.Tkeys[k].length?1:0);
		i=0;found = false;word='';
		if(comptA>=comptB){
			while(i < afterT.length){
				j=0;
				while(j<this.Tkeys.length && this.Tkeys[j]!=afterT[i])j++;
				if(j == this.Tkeys.length)word += (word.length?' ':'')+afterT[i];
				i++;
			}
			if(word.length)document.getElementById('VersionLabel').innerHTML='Ajout du mot-clef <B>'+word.replace(this.Reg_decode,' ')+'';
		}
		else if(comptA<comptB){
			document.getElementById('VersionLabel').innerHTML='<a href="#" onClick="vs.Process();return false;">Cliquez pour ajouter un mot-clef</a>';
		}
	}
	
	Version.prototype.showList = function() {
		var color_;
		var Tkeys = new Array();
		var i,j,k,Ttoken,max_occurs,seuil_min,compt;		
		var out = '';
		var version = document.getElementById('version').value.replace(/( )+$/,'').replace(/^( )+/,'').toUpperCase();
		var TtokenVersion = (version.length?version.split(' '):new Array());
		var Tpredictive_value;
		var nbmatch = 0;
		var memomatch = null;
		var is_match = false;
		var auto_complet = true;
		var Plist = null;
		var regTestCompletion = (TtokenVersion.length?new RegExp('(^| )'+TtokenVersion[TtokenVersion.length-1]
														.replace(/\)/g,'\\)').replace(/\(/g,'\\(')+'( |$)','i'):null);
		if(this.Tdata==null){
			this.Tdata = this.data_.split('|');
			for(i=0;i<this.Tdata.length;i++){
				this.Tdata[i] = this.Tdata[i].split(';');
				this.Tdata[i][0] = this.Tdata[i][0].replace(this.Reg_code,'$1_$3');
			}
		}
		max_occurs = 0;
		
		for(i=0;i<this.Tdata.length;i++){/*for every version in base*/
			j=0;while(j<TtokenVersion.length && this.Tdata[i][0].indexOf(TtokenVersion[j])>-1)j++;
			if(j==TtokenVersion.length){/*every input text version token matches this.Tdata[i][0] version*/
				is_match = true;
				auto_complet = (auto_complet && TtokenVersion.length && !regTestCompletion.test(this.Tdata[i][0]));
				Ttoken = this.Tdata[i][0].split(' ');
				for(j=0;j<Ttoken.length;j++){/*for every token of the base version*/
					if(Ttoken[j].length>1){
						k=0;while(k<TtokenVersion.length && Ttoken[j]!=TtokenVersion[k])k++;
						if(k==TtokenVersion.length){/*base token version is not in version input text but version input text contains token(s) of base version*/
							if(typeof(Tkeys[Ttoken[j]])=='undefined')Tkeys[Ttoken[j]] = parseInt(this.Tdata[i][1]);
							else Tkeys[Ttoken[j]]+=parseInt(this.Tdata[i][1]);
							max_occurs = (Tkeys[Ttoken[j]]>max_occurs?Tkeys[Ttoken[j]]:max_occurs);
						}
					}
				}
			}
		}
		compt = 0;
		for(k in Tkeys){
			compt ++;
			Plist = insert(Plist,k);
			if(auto_complet && k.indexOf(TtokenVersion[TtokenVersion.length-1])>-1){
				nbmatch ++;
				memomatch = k;
			}
		}
		if(nbmatch==1){
			document.getElementById('version').value = '';
			for(i=0;i<TtokenVersion.length-1;i++)
				document.getElementById('version').value+=(document.getElementById('version').value.length?' ':'')+TtokenVersion[i];
			document.getElementById('version').value+=(document.getElementById('version').value.length?' ':'')+memomatch;
			this.Tkeys[this.Tkeys.length-1]='';
			this.ReoderVersionTokens(true);/*auto completion*/
			return;
		}
		seuil_min = (this.all_tag || compt<40?0:Math.round(Math.pow(max_occurs,0.3)));
		while(Plist != null){
			k = Plist.val;
			if(Tkeys[k]>= seuil_min){
				if((this.type_ob=='ve_ads' && this.nb_res<this.NAPL && !this.restore) || (this.type_ob!='ve_ads')){
					Tpredictive_value = this.Simulate_and_Count(version+(version.length?' ':'')+k).split("\n");
				}
				color_ = Math.round((-7*(Tkeys[k]/max_occurs))+7);color_ = '#'+color_+color_+color_+color_+color_+color_;
				out += (out!=''?' ':'')+'<span'+(((this.type_ob=='ve_ads' && this.nb_res<this.NAPL && !this.restore)||(this.type_ob!='ve_ads'))?' title="'+Tpredictive_value[1]+' '+this.listlabel+(Tpredictive_value[1]>1?'s':'')+ ' avec le'+(Tpredictive_value[0].indexOf(' ')>-1?'s mots-clef':' mot-clef')+' \''+Tpredictive_value[0]+'\'"':'')+' onMouseOver="this.style.backgroundColor=\''+this.Scolor+'\';" onMouseOut="this.style.backgroundColor=\'\';" style="white-space: nowrap;font-size:'+Math.round(10+(Tkeys[k]/max_occurs)*30)+'px;"><a style="text-decoration: none;color: '+color_+';" onMouseOver="this.style.color=\'#FFFFFF\';" onMouseOut="this.style.color=\''+color_+'\';" href="javascript: ;" onMouseDown="if(vs.fade >= 100){document.getElementById(\'version\').value+=(document.getElementById(\'version\').value.length?\' \':\'\')+\''+k+'\';document.getElementById(\'VersionLabel\').innerHTML=\'Finition : <a href=\\\'#\\\' onClick=\\\'vs.Process();return false;\\\'><B>ajout</B></a> du mot-clef <B>'+k.replace(this.Reg_decode,' ')+'</B>'
					+(((this.type_ob=='ve_ads' && this.nb_res<this.NAPL && !this.restore)||(this.type_ob!='ve_ads'))?' (<B>'+Tpredictive_value[1]+'</B>&nbsp;'+this.listlabel+(Tpredictive_value[1]>1?'s':'')+(this.type_ob=='ve_ads'?'&nbsp;environ':'')+')':'')+'\';vs.ReoderVersionTokens();vs.fadeList();}return false;">'
											+k.replace(this.Reg_decode,' ')+'</a></span>';
			}
			Plist = Plist.suiv;
		}
		if(compt>=40)out += (!this.all_tag? ' <span style="font-size: 18px"><a href="#" onClick="vs.all_tag=true;vs.refreshes=0;vs.fadeList(true);return false;">...&nbsp;plus</a></span>':' <span style="font-size: 18px"><a href="#" onClick="vs.all_tag=false;vs.refreshes=0;vs.fadeList(true);return false;">moins&nbsp;...</a></span>');
		this.div.innerHTML = '<span style="font-weight:bold;font-size:15px;color:'+this.Scolor+';">Mots-clef parmi les <i>'+(!this.restore?this.nb_res:'')+' '+this.listlabel+(this.nb_res>1?'s':'')+' '+this.brand.toUpperCase()+'&nbsp;'+this.model.toUpperCase()+'&nbsp;'+version.replace(this.Reg_decode,' ')+'</i></span><br>'
													+out+(compt>=40?'<br><span style="font-size: 10px;"><input id="checkSetCloseList" title="Referme cette liste lorsque vous avez sélectionné '+(this.closeWin?'1 mot-clef':'2 mots-clef')+'" onClick="vs.setCloseList();" type="checkbox" '+(this.closeWin?'checked':'')+'>refermer&nbsp;la&nbsp;liste</input></span>':'');
		if(!is_match){
			document.getElementById('VersionLabel').innerHTML='Mot-clef non reconnu <span style="color: #FF0000">'+TtokenVersion[TtokenVersion.length-1].toLowerCase()+'&nbsp;<span style="font-weight:bold;font-size: 18px;color: #FF0000">!</span>';
				+TtokenVersion[TtokenVersion.length-1]+'</span>';
		}else{
			if(document.getElementById('VersionLabel').innerHTML.indexOf('non reconnu')>-1)
				document.getElementById('VersionLabel').innerHTML='<a href="#" onClick="vs.Process();return false;">Cliquez pour ajouter un mot-clef</a>';
		}
		if(this.IE){
			this.div.style.filter = 'alpha(opacity='+this.fade+');';
			this.div_shadow.style.filter = 'alpha(opacity='+this.fade+');';
		}
		else {
			this.div.style.opacity=(this.fade/100);
			this.div_shadow.style.opacity=(this.fade/100);
		}
		this.div.style.display='';
		this.div_shadow.style.display='';
		window.clearInterval(this.inter);
		this.div_shadow.style.height = this.defaultDivHeight;
		this.inter = setInterval('vs.fadeUp();',25);
		if(typeof(display_pub)=='function')display_pub('top');
	}
	
	Version.prototype.prepareData = function() {
		var width_ = parseInt(vs.progress_bar.style.width.substring(0,vs.progress_bar.style.width.length - 2));
		if(width_ < 250){
			vs.progress_bar.style.width = ((vs.IE?38:32)+width_)+'px';
			vs.progress_bar.style.border = "1px solid #7f9db9";
		}
		try{
				if((vs.xmlhttp_data.readyState == 4) && (vs.xmlhttp_data.status == 200)) {
					if(vs.xmlhttp_data.responseText.length){
						vs.data_ = vs.xmlhttp_data.responseText.toUpperCase();
					}else {
						vs.progress_bar.style.width = '0px';
						vs.progress_bar.style.border = '0px';
					}
					vs.ready=true;
					vs.Process();
				}
		}
		catch (e){
			vs.progress_bar.style.width = '0px';
			vs.progress_bar.style.border = '0px';
			vs.ready=true;
		}	
	}
	
	Version.prototype.setCloseList = function(){
		var largeExpDate = new Date ();
    largeExpDate.setTime(largeExpDate.getTime() + (86400 * 1000 * 150));
    this.closeWin = !this.closeWin;
    document.getElementById('checkSetCloseList').title='Referme cette liste lorsque vous avez sélectionné '+(this.closeWin?'1 mot-clef':'2 mots-clef');
		this.setCookie('close-win',this.closeWin,largeExpDate);
	}
	
	Version.prototype.setCookie = function (name, value, expires, path, secure) {
		var domain;
		var myReg = new RegExp('\.lacentrale\.fr');
		domain = (myReg.test(window.location)?'.lacentrale.fr':'');
		document.cookie= name + '=' + escape(value) +
		((expires) ? '; expires=' + expires.toGMTString() : '') +
		((path) ? '; path=' + path : '; path=/') +
		((domain.length) ? '; domain=' + domain : '') +
		((secure) ? '; secure' : '');
	}
	
	Version.prototype.fadeList = function(not_compt) {
		if(!not_compt)this.refreshes ++;
		window.clearInterval(this.inter);
		this.inter = setInterval('vs.fadeDown();',25);
	}
	
	Version.prototype.fadeDown = function(hide) {
		this.fade -= (this.IE?20:10);
		if(this.IE){
			this.div.style.filter = 'alpha(opacity='+this.fade+');';
			this.div_shadow.style.filter = 'alpha(opacity='+(this.fade/5)+');';
		}
		else {
			this.div.style.opacity=(this.fade/100);
			this.div_shadow.style.opacity = (this.fade/500);
		}
		if(this.fade<=0){
			if(this.refreshes<(this.closeWin?1:2) && !hide){
				this.showList();
			}else {
				this.UnDeploy();
			}
		}
	}
	
	Version.prototype.fadeUp = function() {
		this.fade += (this.IE?20:10);
		if(this.IE){
			this.div.style.filter = 'alpha(opacity='+this.fade+');';
			this.div_shadow.style.filter = 'alpha(opacity='+(this.fade/5)+');';
		}
		else {
			this.div.style.opacity=(this.fade/100);
			this.div_shadow.style.opacity = (this.fade/500);
		}
		if(this.fade>=100){
			window.clearInterval(this.inter);
			this.inter=null;
			this.progress_bar.style.width = '0px';
			this.progress_bar.style.border = '0px';
		}
	}
	
	Version.prototype.UnDeploy = function(){
		window.clearInterval(this.inter);
		this.progress_bar.style.width = '0px';
		this.progress_bar.style.border = '0px';
		this.inter = setInterval('vs.CloseWindow();',25);
	}
	
	Version.prototype.CloseWindow = function(){
		var height_ = this.div_shadow.style.height.substr(0,this.div_shadow.style.height.length-2);
		height_ *= 0.75;
		if(height_>2){
			this.div_shadow.style.height = height_+'px';
		}
		else{
			window.clearInterval(this.inter);
			this.inter=null;
			this.div.style.display='none';
			this.div_shadow.style.display='none';
			if(this.IE){
				this.div.style.filter = '';
				this.div_shadow.style.filter = '';
			}
			else {
				this.div.style.opacity='';
				this.div_shadow.style.opacity='';
			}
			this.fade = 0 ;
			if(typeof(display_pub)=='function')display_pub('bottom');
		}
	}
	
	Version.prototype.Prepare = function (){
		window.clearTimeout(this.prepareTime);
		if(!this.restore && this.type_ob=='ve_ads')this.Reset_();
		this.prepareTime = setTimeout('vs.refreshes=0;vs.fadeList(true);vs.ReoderVersionTokens(true);',350);
	}
