

/**
 * class AdinliveQuery
 * Allows us to construct a query for repository
 */

function AdinliveQuery(engine,encoding,trackId,start,lim,tags,sort,groupby,pricemin,pricemax,update,adinquery)
{
	this.engine=engine;
	this.encoding=encoding;
	this.trackId=trackId;
	this.start=start;
	this.limit=lim;
	this.tags=tags;
	this.sortby=sort;
	this.groupby=groupby;
	this.pricemin=pricemin;
	this.pricemax=pricemax;
	this.update=update;
	this.adinquery=adinquery;
}

AdinliveQuery.prototype = 
{
		/**
		 * construct the string that represent the call to the server
		 */
		toString: function()
		{
			var queryString = this.engine+"/jsonrepository?encoding="+this.encoding+"&trackingId="+this.trackId;
			if(this.start != null && this.start != "")
				queryString += "&start="+this.start*this.limit;
			if(this.limit != null && this.limit != "")
				queryString += "&limit="+this.limit;
			if(this.tags != null && this.tags != "")
				queryString += "&tags="+this.tags;
			if(this.sortby != null && this.sortby != "")
				queryString += "&sortby="+this.sortby;
			if(this.groupby != null && this.groupby != "")
				queryString += "&groupby="+this.groupby;
			if(this.update != null && this.update != "")
				queryString += "&update="+this.update;
			
			
			//gestion du prix
			
			var mypricemin = "0";
			if(this.pricemin != null && this.pricemin != "")
			{
				mypricemin = this.pricemin;
			}
			
			var mypricemax = "10000";
			if(this.start != null && this.pricemax != "")
			{
				mypricemax = this.pricemax;
			}
		
			queryString += "&price=" + mypricemin + "<>" + mypricemax;
			queryString += "&"+this.adinquery;
			
			return queryString;
		}
}

/**
 * 
 * class DisplayShoppyTab
 * Allow us to handle the pagination
 * and displaying query
 */
var DisplayShoppyTabInstances = 0;
function DisplayShoppyTab(pathAjaxLoader,divTemplate,divResult,divNbResultat,ejsless)
{
	this.currentQuery = null;
	this.pathAjaxLoader = pathAjaxLoader;
	this.divResult = divResult;
	this.divNbResultat = divNbResultat;
	this.divTemplate = divTemplate;
	this.id = DisplayShoppyTabInstances++;
	this.callback = null;
	eval('DisplayShoppyTab_'+this.id+'=this');
	this.randomFactor = Math.random();
	this.ejsless=ejsless;
	this.nbResult=0;
}

DisplayShoppyTab.prototype = 
{
		setPage : function(page)
		{
			this.currentQuery.start = page;
			this.displayQuery();
		},
		
		next :function(limit){
			var last=Math.floor((this.nbResult-1) / limit);
			if(this.currentQuery.start==last){
				this.currentQuery.start=0;
			}else{
				this.currentQuery.start++;
			}
			this.displayQuery();
		},

		previous :function(limit){
			var last=Math.floor((this.nbResult-1) / limit);
			if(this.currentQuery.start==0){
				this.currentQuery.start=last;
			}else{
				this.currentQuery.start--;
			}
				this.displayQuery();
		},
		
		onDisplay : function(callback)
		{
			this.callback = callback;
		},

		setSortBy : function(newsort)
		{
			this.currentQuery.sortby = newsort;
			this.displayQuery();
		},
		
		search : function(query)
		{
			this.currentQuery = query;
			this.displayQuery();
		},
		
		displayQuery : function()
		{
			
			if(this.pathAjaxLoader != "")
				this.divResult.innerHTML = "<img src='"+this.pathAjaxLoader+"'><br><p class='minishop_link'>Nous recherchons actuellement les produits disponibles</p>"
			
			var divNbResultat = this.divNbResultat;
			var divResult = this.divResult;
			var that = this;
			ajaxXsite(this.currentQuery.toString()+"&randomfactor="+this.randomFactor,
				function (json)
				{
					that.nbResult=json.resultset.total;
					if(divNbResultat != null)
						divNbResultat.innerHTML =that.nbResult +" r&eacute;sultats";
					try
					{
						if(that.ejsless){
							var myfunction=window[that.divTemplate];
							divResult.innerHTML=myfunction(json);
						}else 
							divResult.innerHTML=new EJS({element:that.divTemplate}).render(json);
						if(that.callback != null)
						{
							that.callback();
							that.callback = null;
						}
					}
					catch(e)
					{
					}
				}
			);
		}
}


/*************************************************************/
/*****************Afficher un template plusieur fois**********/
function G_includeT(that,divTemplate){
    var res= new EJS({element:divTemplate}).render(that.data);
    return res;
}




/**
 * class ShoppyTabEngine
 * Handle all jevascript mechanism for shoppytab
 */
function ShoppyTabEngine(engine,display,encoding,trackingId,limit,theme,merchant)
{
	this.engine = engine;
	this.encoding = encoding;
	this.trackingId = trackingId;
	this.limit = limit;
	this.display = display;
	this.themeTab = theme;
	this.merchant = merchant;
	this.moreArgument = null;
}

ShoppyTabEngine.prototype = 
{				
		privatesearch : function(keyword,catpath,priceMin,priceMax,minproduct,adinquery,sortby)
		{
			var feedkey = this.feedkey(this.merchant)
			this.display.search(new AdinliveQuery(this.engine,this.encoding,this.trackingId,"",this.limit,"",sortby,"",priceMin,priceMax,minproduct,((feedkey != null)? feedkey+"&" : "")+this.createAdinQuery(keyword, catpath)+((adinquery != null)?adinquery:"")+((this.moreArgument != null)?this.moreArgument:"")));
		},

		search : function(keyword,themeName,priceMin,priceMax,minproduct)
		{
			var keytab = [];
			var theme = this.themeTab[themeName];
			if(theme != null)
			{
				if(keyword != null && keyword != "")
					keytab.push(keyword);
				if(theme.keyword != null && theme.keyword != "")
					keytab.push(theme.keyword);
				if(priceMin == "")
					priceMin = theme.priceMin;
				if(priceMax == "")
					priceMax = theme.priceMax;
				return this.privatesearch(keytab,theme.category,priceMin,priceMax,minproduct);
			}
			else
			{
				return this.searchOnAllTheme(keyword,priceMin,priceMax,minproduct);
			}
		},
		
		searchOnAllTheme : function(keyword,priceMin,priceMax,minproduct)
		{
			var request = "";
			
			if(this.themeTab.length > 0)
			{
				if(keyword != null && keyword != "")
					request += this.orfunction(keyword)+"&";
				request += "(";
				for(var j = 0 ; j < this.themeTab.length; j++)
				{
					if(j != 0)
						request += "|";
					request += "("+this.createAdinQuery([this.themeTab[j].keyword],this.themeTab[j].category);
					var priceMinT = 0;
					var priceMaxT = 10000;
					if(this.themeTab[j].priceMin != "")
						priceMinT = this.themeTab[j].priceMin;
					if(this.themeTab[j].priceMax != "")
						priceMaxT = this.themeTab[j].priceMax;
					request += "&price="+priceMinT+"<>"+priceMaxT+")";
				}
				
				request += ")";
					
	
				this.privatesearch(null, null, priceMin, priceMax, minproduct, request,"random");
			}
			
		},
		
		createAdinQuery : function(keyword,catpath)
		{
			var adinliveQueryField =  "";
			var isCatpath = true;
			if(catpath != null && catpath != "")
				adinliveQueryField += "catpath="+catpath;
			else
				isCatpath = false;

			if(keyword != null)
			{
				for(var i = 0; i<keyword.length;i++)
				{
					if(keyword[i] != "" && isCatpath)
						adinliveQueryField += "&"+this.orfunction(keyword[i]);
					else
					{
						if(isCatpath == false)
						{
							adinliveQueryField += this.orfunction(keyword[i]);
							isCatpath = true;
						}
					}
				}
			}
			return adinliveQueryField;
		},
		
		orfunction : function(keyword)
		{
			var request = "";
			var tab = keyword.split(",");
			var debut = false;
			if(tab.length > 1)
			{
				request += "(";
				for(var i = 0; i < tab.length; i++)
				{
					if(debut)
						request += "|";
					else
						debut = true;
					request += "(model="+tab[i]+"|description="+tab[i]+")";
				}
				request += ")";
			}
			else
			{
				request = "(model="+keyword+"|description="+keyword+")";
			}
			return request;
		},
		
		feedkey : function(merchant)
		{
			feedkey = null;
			if(this.merchant.length > 0 )
			{
				var feedkey = "(";
				var debut = false;
				for(var i = 0 ; i < this.merchant.length; i++)
				{
					if(debut)
						feedkey += "|";
					else
						debut = true;
					
					feedkey += "merchantname="+this.merchant[i];
				}
				feedkey += ")";
			}
			return feedkey;
		},
		
		addArgument : function(arg)
		{
			if(this.moreArgument == null)
				this.moreArgument = "";
			
			this.moreArgument += "&"+arg;
		}
}

/**
 * API pour chaque boutique
 */
function ShopAPI(shoppytabengine,productByPage)
{
	this.shoppytabengine = shoppytabengine;
	this.currentPricemin = "";
	this.currentPricemax = "";
	this.currentCategory = -1;
	this.currentKeyword = "";
	this.nbProduct = productByPage;
}

ShopAPI.prototype = 
{
	search : function()
	{
		this.shoppytabengine.search(this.currentKeyword,this.currentCategory,this.currentPricemin,this.currentPricemax,this.nbProduct);
	},

	customSearch : function (query)
	{
		this.shoppytabengine.privatesearch(null,null,this.currentPricemin,this.currentPricemax,100,query);
	},

	searchLotOfProduct : function ()
	{
		this.shoppytabengine.search(this.currentKeyword,this.currentCategory,this.currentPricemin,this.currentPricemax,100);
	},

	allProduct : function ()
	{
		this.setCategoryById(-1);
		this.setKeyword('');
		this.setPrice(0,10000);
		this.shoppytabengine.searchOnAllTheme("","","",100);
	},

	setCategoryById : function (id)
	{
		this.currentCategory = id;
	},

	setCategoryByName : function (name)
	{
		this.currentCategory = -1;
		for(i in this.shoppytabengine.themeTab)
		{
			if(this.shoppytabengine.themeTab[i].title == name)
				this.currentCategory = i;
		}
	},

	setKeyword : function (keyword)
	{
		this.currentKeyword = keyword;
	},

	setPrice : function (pricemin,pricemax)
	{
		this.currentPricemin = pricemin;
		this.currentPricemax = pricemax;
	},

	setPage : function (newpage)
	{
		this.shoppytabengine.display.setPage(newpage);
	},
	
	next : function()
	{
		this.shoppytabengine.display.next(this.shoppytabengine.limit);
	},
	
	previous : function(){
		this.shoppytabengine.display.previous(this.shoppytabengine.limit);
	},

	setSortBy : function (newsort)
	{
		this.shoppytabengine.display.setSortBy(newsort);
//		if(document.getElementById('sortPrice') != null)
//		{
//			if(newsort == 'price')
//			document.getElementById('sortPrice').className = 'minishop_page_select';
//		else
//			document.getElementById('sortPrice').className = 'minishop_page';
//			
//		if(newsort == 'cpc')
//			document.getElementById('sortPop').className = 'minishop_page_select';
//		else
//			document.getElementById('sortPop').className = 'minishop_page';
//		}
	},
	
	onDisplay : function(callback)
	{
		this.shoppytabengine.display.onDisplay(callback);
	},
	
	setDivForDisplay : function(div)
	{
		this.shoppytabengine.display.divResult = div;
	}
}

function ST_include(fileName,onload) {	
	script = document.createElement("script");
	script.type = "text/javascript";
	if(onload!=null)
		script.onload=onload;
	script.src = fileName;
	document.getElementsByTagName("head")[0].appendChild(script);		
	
}

function ST_includeCss(fileName,onload){
	  var fileref=document.createElement("link");
	  fileref.setAttribute("rel", "stylesheet");
	  fileref.setAttribute("type", "text/css");
	  fileref.setAttribute("href", fileName);
	  if(onload)
		  fileref.onload=onload;
	  document.getElementsByTagName("head")[0].appendChild(fileref);
}

function ajaxXsite(url,callback){
	var idcall=""+Math.random();	
	idcall="G"+(idcall.substring(2));
	window[idcall]=function(res){callback(res);};
		
	url+="&function="+idcall;
	ST_include(url);	
}

//function of popup
function ST_popupStr(code){
	if(!TINY)
		alert(code);
	TINY.box.show(code,0,0,0,1);
}
function ST_popupDiv(div){	
	ST_popupStr(ed(div).innerHTML);
}

function ST_popupInfo(){
	/*ST_includeCss("http://www.shoppytab.com/commons/css/tinybox.css");
	ST_include("http://www.shoppytab.com/commons/js/tinybox.js",function(){		
			ST_open();
	});*/
	if(window.location==window.parent.location){
		window.location="http://www.shoppytab.com";
	}else{
		window.parent.location="http://www.shoppytab.com";
	}
}

function ST_open(){
	var str="<iframe width='500' height='650' scrolling='no' src='http://www.shoppytab.com/widget-presentation' frameborder='0'></iframe>";
	ST_popupStr(str);
}

function simpleConnect(source,event,func,mode){
	if(mode==null)
		mode='after';
	if(source==null)
		source=document;
	if(source[event]==null){
		source[event]=func;	
	}else{
		var old=source[event];
		//console.debug(old);
		if(mode=='after')
			source[event]=function(e){old(e);return func(e);};
		else
			source[event]=function(e){func(e);return old(e);};
	}
}


function resiz(im){
	  var image=new Image();  
	  image.onload=function(){
		  
	    if(this.width<this.height){
	      //im.style.width="auto";->dont work because not centered since margin-left work only with fixed sizes!
	      var he=im.offsetHeight;
	      
	      var wi=he*this.width/this.height;
	      alert(wi+" "+he);
	      im.style.width=wi+"px";
	      im.style.marginLeft=((he-wi)/2)+"px";
	      
	    }else if(this.width>this.height){
	    	//alert(this.width+" "+this.height);
	      //im.style.height="auto";//im.className="minishop_image_horizontal";
	      //im.style.marginTop="auto";
	      
	      /*var wi=im.offsetWidth;         
	      var he=wi*this.height/this.width;
	      im.style.height=he+"px !important";
	      im.style.marginTop=((he-wi)/2)+"px !important";*/
	    	im.style.width="110px";
		    im.style.height="110px";
	    }else{
	    	im.style.width="110px";
		    im.style.height="110px";
	    }
	  }
	  image.src=im.src;
	}
function correctImageErrors(image){
	  var ssrc=""+image.src;
	  if(image.tried==null)
	    image.tried=0;
	  if(image.tried<15){
	          
	      image.tried++;
	      setTimeout(function(){image.src=ssrc;},1000);
	  } 
	}
