var Searcher = Class.create({
	
	initialize: function() {
		this.currentPage = 0;
		this.pagesCount = 100;
		this.order = 'news';
		this.event = 'news';
	 	this.productsPerPage = 20;
	 	this.searchColor = "-1";
		this.searchSubcategory = false; 
		this.textPlaceHolderProductBrand = __("Buscar por referencia, producto, marca ...");
		this.setPlaceHolderProductBrand();
		this.lastContentUrl = '';
		this.showPredefinedImages = true;
	},
	changeImage: function( divImgId, imgSrc, alt ) {    
		var divImg = $( divImgId );  			
		var img = divImg.getElementsByTagName('img').item(0);
		
		if(imgSrc.length > 0){	
	    	var altDecoded = unescape(alt);      
	    	altDecoded = replaceAll(altDecoded,"\\+", " ", false);		
			divImg.title = altDecoded;
			
			img.src = imgSrc;
			img.onerror = function (evt) {
				img.src = "/images/imgnotavailable.gif";
			}
		} else {
			divImg.title = "";
			img.src = "/images/cargando.gif";
		}
	},
	search: function()
	{
		this.currentPage=0;
		this.pagesCount = 1;
		this.goNextPage();
	},
	searchByProductBrand: function() {

		var search = $F('productBrand');
		
		//alert("searchByProductBrand: " + search);
		
		if (search.strip().blank() || search == this.textPlaceHolderProductBrand) 
			return;  //DO Nothing 
		
		this.categoryname = search.strip();

		var contentUrl = "/product/ajaxProductList/productBrand/" + this.categoryname + "/page/1";

		//this.markProductsAsWaiting();
		new Ajax.Request(contentUrl,   {
			method:'get',
			onSuccess: function(transport) {
	        	var numProds = transport.responseXML.getElementsByTagName('products')[0].getAttribute("pagesCount");
      			if( numProds == 0 ) {
                	alert(__('No se encontraron productos que cumplen con su criterio!'));
                } else {
                	this.markProductsAsWaiting();
                	this.loadXMLResponse(transport.responseXML);
                	this.currentPage = 1;
                	this.event = 'search';
                	$('panelSearch').show();
                	this.showDivsSearchResult();
                	this.updateCurrentPageLabel();
                }
	   		}.bind(this),
			onFailure: function(){ 
				alert(__('Error guardando imagen.')); 
			}
		}); 
	},
	notSearchResult: function() {
	 	alert(__('No se encontraron productos que cumplen con su criterio!'));
	 	this.resetFields();
	 	return;
	},
	goNextPage: function()
	{
		if( this.currentPage < this.pagesCount ){
			var newPage = ++(this.currentPage);

			this.loadPage(newPage);
		}

		this.updateCurrentPageLabel();
	},
	goPreviousPage: function()
	{
	
		if( this.currentPage > 1 )
		{			
			var newPage = --(this.currentPage);
			this.loadPage(newPage);
		}
		this.updateCurrentPageLabel();
	},
	
	loadPage: function(newPage) {
		//alert("loadPage: " + this.event);
		switch(this.event)
		{
			case 'myImages':
				this.order = 'myImages';
				this.loadMyImages( newPage);
			break;
			case 'search':
				this.loadPageSearchResult( newPage );
			break;
			case 'promos':
				this.loadPagePromos( newPage );
				break;
			case 'category':
				this.loadPageCategory(newPage);
				break;
			default:
				this.order = 'news';
				this.event = 'news';
				this.loadPageNews( newPage );
				break;
		}
	},
	
	updateCurrentPageLabel: function()
	{
		var currentPage = this.currentPage;
		$('currentPage').innerHTML = currentPage;
	},
	
	loadPageCategory: function (page) {
		var contentUrl = "/ajax/product/ajaxSearchByCategory/category/" + this.categoryid + "/subcategory/" + this.subcategoryid + "/page/" + page;
		this.processAjax(contentUrl);
	},
	
	loadPageNews: function (page)
	{
		var contentUrl = "/product/ajaxHomePoducts/page/" + page;
		this.processAjax(contentUrl);
		
	},
	loadPageSearchResult: function (page)
	{
		
//		this.budget = "";
//		this.categoryid = "";
//		this.subcategoryid = "";
//		this.budget = "";
//		this.searchColor = "";
//		this.shop = "";
//		this.brand = "";
//		
//		if($('shop')) {
//			this.shop = $('shop').value;
//			if (this.shop == "all") this.shop = "";
//		}
//		
//		if($('brand')) {
//			this.brand = $('brand').value;
//			if (this.brand == "all") this.brand = "";
//		}
//		
//		if($('budget')) {
//			this.budget = $('budget').value;
//			if (this.budget == "all") this.budget = "";
//		}
//		
//		if($('subcategoryidSearch')) {
//			this.categoryid = $('subcategoryidSearch').value;
//			if (this.categoryid == "all") this.categoryid = "";
//		}
//		
//		
//		if ($F('productBrand').empty() || $F('productBrand')==this.textPlaceHolderProductBrand)
//			this.productBrand = '';

//		this.loadProducts(page, this.categoryid, this.subcategoryid, this.productBrand, this.budget, this.searchColor, this.order, this.shop, this.brand);

		var contentUrl = "/product/ajaxProductList/productBrand/" + this.categoryname + "/page/" + page;
		this.processAjax(contentUrl);
		
	},
	loadNewLayout: function (contentUrl)
	{	
		$('panelSearch').hide();
		$('panelImages').hide();
		this.resetFields();
		
		$('products').hide();
		$('componentSearch').show();

		new Ajax.Updater("componentSearch", contentUrl, {method: 'get', evalScripts:true, asynchronous:true,
		 onComplete:function(){
			 new Effect.Fade('ajax_loader_new_layout', {});}, 
		 onLoading:function(){
			 new Effect.Appear('ajax_loader_new_layout', {});}
			 });
	},
	loadPagePromos: function (page)
	{
	/*	$('products').hide();
		$('componentSearch').show();	
		var contentUrl = '/ajax/category/ajaxSearchCategory';
		new Ajax.Updater("componentSearch", contentUrl, {method: 'get', evalScripts:true});*/
		
		var contentUrl = "/product/ajaxPromos";
		var params = '';
		
		if(page != '') 	params += "/page/" + page;		
		
		contentUrl += params;
	    this.processAjax(contentUrl);
	   
	},
	loadProducts: function (page,categoryid,subcategoryid,productBrand,budget,color,order, shop, brand)
	{
		var contentUrl = "/product/ajaxProductList";
		var params = '';
		
		if(page != '') 	params += "/page/" + page;
		if(categoryid != '') 	params += "/categoryid/" + categoryid;
		if(subcategoryid != '') params += "/subcategoryid/" + subcategoryid;
		if(productBrand != '') 	params += "/productBrand/" + productBrand;
		if(budget != '') 		params += "/budget/" + budget;
		if(color != '') 		params += "/color/" + color;
		if(shop != '') 			params += "/shop/" + shop;
		if(brand != '') 		params += "/brand/" + brand;
		
		contentUrl += params;
	    if( order ) {
	    	contentUrl += "/order/" + order;
	    	this.processAjax(contentUrl);
	    }
	},
	
	processAjax: function (contentUrl){
			var current = this;
			
			this.markProductsAsWaiting();
			new Ajax.Request(contentUrl,   {     
					method:'get',     
					onSuccess: function(transport) {
		      			var xmldoc = transport.responseXML;
		      			var numProds = current.loadXMLResponse(xmldoc);
		      			if( numProds == 0 ) {
		      				current.processAjax(current.lastContentUrl);
		                	alert(__('No se encontraron productos que cumplen con su criterio!'));
		                }else{
		                	current.lastContentUrl = contentUrl;  //TODO this method will be deleted
		                }
			   		},     
					onFailure: function(){ 
						alert(__('Error guardando imagen.')); 
						}   
					}); 
	},
	
	updateSubcategories: function()
	{
		//$('selectSubcategory').show();

		var subcategoryid = this.subcategoryid;
		var xmlHttp = getXmlHttpObject();
		xmlHttp.onreadystatechange=function()
	    	{
				if(xmlHttp.readyState==4)
	      		{		
	      			var xmldoc = xmlHttp.responseXML;
	      			// alert(xmlHttp.responseText);
	      			
	      			var selectSubcat = $('subcategory');
					selectSubcat.innerHTML = '';
					var option = document.createElement( 'option' );
					option.value = 'all';
					option.innerHTML = __('Subcategoria');
		
					selectSubcat.appendChild(option);

	            	var subcategoriesNodes = xmldoc.getElementsByTagName('subcategory');
	            	for( var i = 0; i < subcategoriesNodes.length; i++ )
	            	{
	            		var nodeI = subcategoriesNodes.item( i );
	            		var subcatId = nodeI.attributes.getNamedItem('id').nodeValue;
						var subcatName = nodeI.getElementsByTagName('name').item(0).firstChild.nodeValue;
						
						var option = document.createElement( 'option' );
						option.value = subcatId;
						option.innerHTML = subcatName;
						
						//selected depending of result of the search
						if(subcatId == subcategoryid){
						option.selected = 'selected'; 
						}
						selectSubcat.appendChild(option);
							            		
	            	}	      
	            	
				}
			}
		var contentUrl = "/category/ajaxSubcategoriesByCategory/category_id/" + this.categoryid;
		
		
	  	//xmlHttp.open("GET",contentUrl,true);
	  	//xmlHttp.send(null);
		
		this.loadProducts( 1 ,this.categoryid, this.subcategoryid,'', '', '', 'new', '', '');
		
	},
	updatePagesCount: function()
	{
		var pagesCount = this.pagesCount;
		this.currentPage
		
		if(this.currentPage <= 1)
			$('leftButton').src = '/images/Pizq_off.gif';
		else
			$('leftButton').src = '/images/Pizq.gif';
		
		if(this.currentPage >= this.pagesCount)
			$('rightButton').src = '/images/Pder_off.gif';
		else
			$('rightButton').src = '/images/Pder.gif';
		//$('totalPages').innerHTML = pagesCount;
	},
	
	loadMyImages: function(page)
	{	
		var check = '0';
		if (this.showPredefinedImages) {
			check = '1';
		}
		this.markProductsAsWaiting();
		var contentUrl = "/product/ajaxMyImages/page/" + page;
		
		new Ajax.Request(contentUrl,   {     
			method:'GET',
			parameters: {check: check},
			onSuccess: function(transport)
			{
      			var xmldoc = transport.responseXML;
      			var numProds = this.loadXMLResponse(xmldoc);
      			if( numProds == 0 ) 
      			{
                	alert(__('No tiene imagenes cargadas aun'));
                	//this.resetProducts(0);
                }
			}.bind(this),
			onFailure: function(){ 
				alert(__('Error trayendo imagenes.')); 
			}   
		});
		
	},
	
	loadXMLResponse: function(xmldoc)
	{
		var current = this;
        var root = xmldoc.getElementsByTagName('products').item(0);
           	
        var products = root.getElementsByTagName('product');
        var numProds = products.length;
        if( numProds == 0 ) {
        	this.resetProducts(numProds);
         	return numProds;
       	}
        var pagesCount = root.attributes.getNamedItem('pagesCount').nodeValue;
        this.pagesCount = pagesCount;
        // The reason is the ticket 311
       	this.updatePagesCount();
           	                
        for (var iNode = 0; iNode < products.length; iNode++) {
       		var node = products.item(iNode);
       		
       		var imgThumbSrc = node.getElementsByTagName('thumb').item(0).firstChild.nodeValue;
       		
       		var imgSrc = node.getElementsByTagName('img').item(0).firstChild.nodeValue;
       		
       		var imgSrcMin = node.getElementsByTagName('thumb').item(0).firstChild.nodeValue;
       		
       		var name = node.getElementsByTagName('name').item(0).firstChild.nodeValue;
       		
       		var col = iNode % 4;
       		var row = Math.floor(iNode /4);
       		
       		var divImgId = "imgDiv" + col + row;
       		       			
       		this.changeImage(divImgId, imgThumbSrc, name);
 			      		
       		var divImg = document.getElementById( divImgId );
       		divImg.style.display = '';
       		
       		var inputId = divImg.getElementsByTagName('input').item(0);               		
       		inputId.value=node.attributes.getNamedItem('id').nodeValue;

       		var inputType = divImg.getElementsByTagName('input').item(1);               		
       		inputType.value=node.attributes.getNamedItem('type').nodeValue;
       		
       		var inputImgSrc = divImg.getElementsByTagName('input').item(2);               		
       		inputImgSrc.value= imgSrc;
       		
       		var inputImgSrcMin = divImg.getElementsByTagName('input').item(3);               		
       		inputImgSrcMin.value= imgSrcMin;
       		
       		divImg.originalWidth = node.attributes.getNamedItem('width').nodeValue;
       		divImg.originalHeight = node.attributes.getNamedItem('height').nodeValue;
       	}
        this.resetProducts(iNode);
        
		return numProds;
	},
	
	markProductsAsWaiting: function( )
	{
		var src = '';
		
		for (var prodI = 0; prodI < this.productsPerPage; prodI++) 
		{
			var col = prodI % 4;
	        var row = Math.floor(prodI /4);
			var divImgId = "imgDiv" + col + row;
       		this.changeImage(divImgId, src, name);
			$( divImgId ).style.display = '';

		}
	},
	
	resetProducts: function(initIndex)
	{
		if (!initIndex) initIndex = 0;
		
		for (var prodI = initIndex; prodI < this.productsPerPage; prodI++) 
		{
			var col = prodI % 4;
	        var row = Math.floor(prodI /4);
	        			
			var divImgId = "imgDiv" + col + row;
			var divImg = $( divImgId );  
			//var img = divImg.getElementsByTagName('img').item(0);
			
			//divImg.style.visibility = 'hidden';
			$( divImgId ).style.display = 'none';
			//img.style.visibility = 'hidden';
		}
	},
	
	searchByCategory: function(category, subcategory) {
//		alert("searchByCategory " + category + ", " + subcategory);

		var contentUrl = "/ajax/product/ajaxSearchByCategory/category/" + category + "/subcategory/" + subcategory + "/page/1";

		new Ajax.Request(contentUrl,   {     
			method:'get',     
			onSuccess: function(transport) {
        		var numProds = transport.responseXML.getElementsByTagName('products')[0].getAttribute("pagesCount");
        		if( numProds == 0 ) {
        			alert(__('No se encontraron productos que cumplen con su criterio!'));
        		} else {
        			this.markProductsAsWaiting();
        			this.loadXMLResponse(transport.responseXML);
                	this.currentPage = 1;
                	this.lastContentUrl = contentUrl;
                	this.categoryid = category;
                	this.subcategoryid = subcategory;
                	this.categoryname = $F('category_name');
                	this.event = 'category';
                	$('panelSearch').show();
                	this.showDivsSearchResult();
                	this.updateCurrentPageLabel();
                }
	   		}.bind(this),
			onFailure: function(){ 
				alert(__('Error guardando imagen.')); 
			}
		}); 
		
	},
	
	selectCategories: function()
	{
		this.resetTabs();
		var contentUrl = '/ajax/category/ajaxSearchCategory';
		this.loadNewLayout(contentUrl);	
	},
	
	selectNews: function()
	{
		if (this.event == 'news') 
			return; //don't refresh
		
		this.resetTabs();
		$('panelSearch').show();
		this.showDivProducts();

		this.event = 'news';
		this.currentPage=0;
		this.pagesCount = 1;
		this.goNextPage();
		
	},
	
	selectMyImages: function()
	{
		var user = isSession();
		if (user == '') {  
			Modalbox.show('/suscriber/new', {title: __('Registrarme'), width: 600});
			return;
		}
		
		//controls of divs
		$('panelSearch').hide();
		this.showDivProducts();
		this.event = 'myImages';
		this.resetTabs();
		$('panelImages').show();
		this.search();
	},
	selectPromos: function()
	{
		this.resetTabs();
		var contentUrl = '/ajax/promos/ajaxGetPromo';
		this.loadNewLayout(contentUrl);	
	},
	showDivsSearchResult: function()
	{
        $('searchResult_li').show(); // New tab appeared for the search
		$('componentSearch').hide(); // Necessary for loadding step view
		$('products').show(); // List of products
		
		if(this.categoryname.length > 8) {
			this.categoryname = this.categoryname.substring(0, 8)+"..";
		}
		
		$('titleSearchResult').innerHTML = this.categoryname;
	},
	showDivProducts: function()
	{
		$('products').show();
		$('componentSearch').hide();
		$('panelImages').hide();
	},
	searchOnEnter: function (event, callback) 
	{
		if (event.keyCode == 13) {
			eval(callback);
			Event.stop(event);		
		}
	},
	chooseColor: function( hexColor )
	{
		searcher.searchColor = hexColor;
	},
	resetColor: function( )
	{
		searcher.searchColor = "-1";
	},
	resetFields: function ()
	{
		this.searchColor = "-1";
		this.budget = "";
		this.categoryid = "";
		this.subcategoryid = "";
		this.shop = "";
		this.event = '';
		this.searchSubcategory = false;
		
		if($('subcategory')!=null) $('subcategory').value = '';	
		if($('subcategory_id')!=null) $('subcategory_id').value = '';	
		if($('category_id')!=null) $('category_id').value = '';	
		if($('budget')!=null) $('budget').value = '';	
		if($('shop')!=null) $('shop').value = 'all';
	},
	resetTabs: function() {
		$('searchResult_li').hide();
		$('productBrand').value = this.textPlaceHolderProductBrand;		
	},
	setPlaceHolderProductBrand: function()
	{	
		new PlaceHolder($('productBrand'), this.textPlaceHolderProductBrand);
	},
	setShowPredefinedImages: function(showPredefinedImages) {
		this.showPredefinedImages = showPredefinedImages;
		this.loadMyImages(this.currentPage);
	}
});