(function($) {



	var defaults = {
		action_start:	null, //
		action_success:	null, //
		thumbs_dir:		'/productos/archivos/miniaturas/',
		thumbs_ext:		'_100px.png',
		thumbsmini_ext:	'_44px.png',
		loading_class:	'ajax-loading',
		loading_text:	'Cargando',
		datatype:		'json',
		path:			'/productos/',
		filterurl:		'/productos/?filtrar',
		limit: 4,
		show_selects: false, 
		show_filters: false, 
		last:			''
	}

	
$.fn.productfinder = $.productfinder = function(method) {


	var methods = {
		init: function(){
			var obj = new Productfinder(dom,config);
			obj.init();
			return this;
		},
		showproducts: function(settings)
		{
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function(){
				var dom = $(this);
				if (dom.data('showproducts')) return; dom.data('showproducts', true);
				var obj = new Productfinder(dom,config);
				obj.showproducts();
			})
		},
		showfavproducts: function(settings)
		{
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function(){
				var dom = $(this);
				if (dom.data('showfavproducts')) return; dom.data('showfavproducts', true);
				var obj = new Productfinder(dom,config);
				obj.showfavproducts();
			})
		},
		setfirstfilter: function(settings)
		{
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function() {
				var dom = $(this);
				if (dom.data('setfirstfilter')) return; // already set
				dom.data('setfirstfilter', true);
				var obj = new Productfinder(dom,config);
				obj.setfirstfilter();
			})		
		},
		showselectors: function(settings)
		{
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function() {
				var dom = $(this);
				if (dom.data('showselectors')) return; dom.data('showselectors', true);
				var obj = new Productfinder(dom,config);
				dom.html(obj.formatSelectors());
				obj.appendAllSelectors();
			})
		},
		appendselectors: function(settings)
		{
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function() {
				var dom = $(this);
				if (dom.data('appendselectors')) return; dom.data('appendselectors', true);
				var obj = new Productfinder(dom,config);
				obj.appendAllSelectors();
			})
		},
		appendmostpopular: function(settings){
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function() {
				var dom = $(this);
				if (dom.data('appendmostpopular')) return; dom.data('appendmostpopular', true);
				var obj = new Productfinder(dom,config);
				obj.appendMostPopular();
			})
		},
		get: function(){
			var obj = new Productfinder(dom,config);
			obj.init();
			return obj.that;
		},
		getcomplete: function(){
			var obj = new Productfinder(dom,config);
			obj.init();
			return obj.getcomplete();
		},
		add: function(item,callback){
			return this.each(function() {
				var obj = new Productfinder(dom,config);
				obj.init();
				obj.add(item,callback);
			});
		}
	}



    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.productfinder' );
    }
};





$.fn.favorites = $.favorites = function(method) {

	var defaults = {
		action_start:	null, //
		action_success:	null, //
		thumbs_dir:		'/productos/archivos/miniaturas/',
		thumbs_ext:		'_100px.png',
		thumbsmini_ext:	'_44px.png',
		loading_class:	'ajax-loading',
		loading_text:	'Cargando',
		datatype:		'json',
		path:			'/productos/',
		filterurl:		'/productos/?filtrar',
		limit: 4,
		show_selects: false, 
		show_filters: false, 
		last:			''
	}


	var methods = {
		init: function(){
			var obj = new Favorites();
			obj.init();
			return this;
		},
		setaddtofavbutton: function(settings)
		{
			var config = defaults;
			if (settings) $.extend(config, settings);
			return this.each(function() {
				var dom = $(this);
				if (dom.data('setaddtofavbutton')) return; dom.data('setaddtofavbutton', true);
				var obj = new Favorites(dom,config);
				obj.setaddtofavbutton();
			})		
		},
		get: function(){
			var obj = new Favorites();
			obj.init();
			return obj.favorites;
		},
		getcomplete: function(){
			var obj = new Favorites();
			obj.init();
			return obj.getcomplete();
		},
		getformatted: function(){
			var obj = new Favorites();
			obj.init();
			return obj.getformatted();
		},
		add: function(item,callback){
			return this.each(function() {
				var obj = new Favorites();
				obj.init();
				obj.add(item,callback);
			});
		}
	}

    if ( methods[method] ) {
      return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
      return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.favorites' );
    }
};



















function Productfinder(dom,config) {
	var that = this;
	this.filters = false;
	
	this.page = 1;
	this.filterscode = false;





	this.setfirstfilter = function() {
		dom.click(function() {
			that.removeAllFilters(function() {
				that.addFilter(dom,function() {
					location.href = config.filterurl;
				});
			});
			return false;
		});
	}

	this.showproducts = function()
	{
		that.initiarFavorites();
		that.initiar();
	}
	this.showfavproducts = function()
	{
		that.initiarFavorites(function(data) {
			that.queryProducts();
		});
		config.filters = that.favorites.favorites;
		$.extend(config.filters, {favorites: true});
		that.initiar();
	}
	
	
	this.initiarFavorites = function(callback) {
		that.favorites = new Favorites(dom,config);
		that.favorites.init(callback);

	}
	
	this.initiar = function() {
		dom.empty().addClass('browse_container').append(that.formatFinder());
		that.getPage();
		that.getFiltersCode();
		that.showall();
		that.queryProducts();
		$(window).bind('hashchange', function(e) { that.hashchanged(e); }).trigger('hashchange');
	}
	
	this.hashchanged = function(e) {
        if (that.filterscode != e.getState('filterscode'))
        {	
			that.filterscode = e.getState('filterscode');
			that.showall();
			if(that.page!=1) that.setPage(1);
			else that.queryProducts();
			
        }
        if (that.page != (e.getState('page',true) || '1'))
        {
        	that.page = e.getState('page',true) || '1';
        	that.queryProducts();
		}
	}
	
	


	this.setPage = function(page){
		var state = {};
		state['page'] = parseInt(page);
		$.bbq.pushState(state);
	}
	
	
	
	
	this.getPage = function(){
		return that.page = $.bbq.getState('page',true) || '1';
	}
	this.getFiltersCode = function(){
		return that.filterscode = $.bbq.getState('filterscode',true);
	}
	
	
	this.setFiltersCode = function(code){
		var state = {};
		state['filterscode'] = code;
		$.bbq.pushState(state);
	}

	this.setLastFiltersCode = function(){
		that.setFiltersCode(that.getLastFiltersCode());
	}
		
	this.getLastFiltersCode = function(){
		var result = "";
		$.ajax({
			url: '/productos/filters.php?action=getLastId',
			type: "POST",
			async: false,
			success: function (data) {
				result = data;
			}
		});
		return result;
	}
	  
	  

	this.correctFilters = function()
	{
		if (that.filters == undefined) that.filters = new Object;
		if (that.filters.marcas == undefined) that.filters.marcas = new Array;
		if (that.filters.tecnicas == undefined) that.filters.tecnicas = new Array;
		if (that.filters.subtecnicas == undefined) that.filters.subtecnicas = new Array;
		if (that.filters.mercados == undefined) that.filters.mercados = new Array;
	}
	  
	this.getFilters = function(){
		if (config.filters) return that.filters = config.filters;
		that.filters = getJsonObject(config.path+'filters.php?action=json&filterscode='+that.filterscode);
		
		that.correctFilters();
		
		return that.filters;
	}
	
	this.getFiltersComplete = function(){
		return that.filterscomplete = (!config.filters)?getJsonObject(config.path+'filters.php?action=showjson&filterscode='+that.filterscode):config.filters;
	}
	

	this.showall = function() {
		that.getFilters();
		that.getFiltersComplete();
		that.showFilters();
		that.showSelects();
		dom.find(".removeFilter").click(function() { that.removeFilter($(this), function(code){ that.setFiltersCode(code);}); return false;}).button({ icons: {secondary: "ui-icon-close"} });
		dom.find(".removeAllFilters").click(function() { that.removeAllFilters(function(code){ that.setFiltersCode(code); }); return false;}).button({ icons: {secondary: "ui-icon-trash"} });
	}	

	
	this.showSelects = function() {
		var queries = getJsonObject(config.path+'filters.results.json.php', {filters: that.filters})
		dom.find('.selects .tecnicas').empty().append('<a href="#" id="select_tecnicas">T&eacute;cnicas</a>');
		dom.find('.selects .mercados').empty().append('<a href="#" id="select_mercados">Mercados</a>');
		dom.find('.selects .marcas').empty().append('<a href="#" id="select_marcas">Marcas</a>');
		tecnicas = that.objtolist(queries.tecnicas, "tecnicas");
		mercados = that.objtolist(queries.mercados, "mercados");
		marcas = that.objtolist(queries.marcas, "marcas");
		dom.find('#select_tecnicas')
		.button({ icons: { secondary: 'ui-icon-triangle-1-s' } })
		.qmenu({
			content: tecnicas, flyOut: true, width:280, 
			action: function(item){
				that.addFilter(item,function(code) {
					that.setFiltersCode(code);
				});
			}
		});
		dom.find('#select_mercados')
		.button({ icons: { secondary: 'ui-icon-triangle-1-s' } })
		.qmenu({
			width: 200,
			content: mercados,
			action: function(item){
				that.addFilter(item,function(code) {
					that.setFiltersCode(code);
				});
			}
		});
		dom.find('#select_marcas')
		.button({ icons: { secondary: 'ui-icon-triangle-1-s' } })
		.qmenu({
			width: 200,
			content: marcas,
			action: function(item){
				that.addFilter(item,function(code) {
					that.setFiltersCode(code);
				});
			}
		});
	}


	this.showFilters = function() {
		dom.find('.filters').children().empty();
		if(that.filterscomplete!="")
		{
			$.each(that.filterscomplete, function(what, filter) {
				$.each(filter, function(key, content) {
					dom.find('.filters .'+what+'').append(that.formatFilter(what,content.id,content.title));
				});
			});
			dom.find('.message').html('<a href="#removeAllFilters" class="removeAllFilters">Eliminar todos los filtros</a>');
		}
		else
		{
			dom.find('.message').html('<h4>Seleccione un filtro para refinar la b&uacute;squeda</h4>');
		}
	}


	
	
	this.removeAllFilters = function(callback,before) {
		$.ajax({
			url: config.path+'filters.php?action=removeall&filterscode='+that.filterscode,
			type: "POST",
			async: false,
			success: function(data) {
				that.filters = [];
				if (callback) callback(data);
			}
		});
	}

	this.removeFilter = function(item,callback,before) {
		var filter = $(item).attr("rel");
		var id = parseInt($(item).attr("id"));
		$.ajax({
			url: config.path+'filters.php?action=remove&filterscode='+that.filterscode,
			type: "POST",
			data: ({ filter: filter, id: id }),
			async: false,
			success: function(data) {
				that.filters[filter] = $.grep(that.filters[filter], function (a) { return a != id; });
				if (callback) callback(data);
			}
		});
	}

	this.addFilter = function(item,callback,before) {
		var filter = ($(item).attr("name"))?($(item).attr("name")):($(item).attr("title"))
		var id = parseInt($(item).attr("id"));
		if (id=="0") return 0;
		$.ajax({
			url: '/productos/filters.php?action=add&filterscode='+that.filterscode,
			type: "POST",
			data: ({ filter: filter, id: id }),
			async: false,
			success: function (data) {
				that.correctFilters();
				that.filters[filter].push(id);
				if (callback) callback(data);
			}
		});
	}
	


	this.queryProducts = function() {
		var page = parseInt(that.page);
		var start = config.limit*(page-1);
		var height = dom.find(".navigation").css('height');
		if (height!=("0px")) { dom.find(".navigation").css('height',height); }
		dom.find(".navigation").addClass(config.loading_class).html(config.loading);
		dom.find(".results").fadeTo('fast', 0);
		$.ajax({
			type: "POST",
			url: "/actions.php?subject=filters&action=getjson",
			dataType: "json",
			data: {
				limit: config.limit,
				start: start,
				filters: that.filters
			},
			success: function(data) {
				var gets = '';
				if (data.variables.filters)
				{
					var marcas = data.variables.filters.marcas;
					var mercados = data.variables.filters.mercados;
					var subtecnicas = data.variables.filters.subtecnicas;
					if (marcas) if (marcas.length == 1) gets+='&idMarca='+marcas[0]+'';
					if (mercados) if (mercados.length == 1) gets+='&idMercado='+mercados[0]+'';
					if (subtecnicas) if (subtecnicas.length == 1) gets+='&idSubtecnica='+subtecnicas[0]+'';
				}
				dom.find(".results").html('');

				$.each(data.products, function(i,item){
					if (item.idProducto!="NO") {item.destino = '?idProducto='+item.idProducto; item.name = 'idProducto'; item.id=item.idProducto; }
					if (item.idFamilia!="NO") {item.destino = '?idFamilia='+item.idFamilia; item.name = 'idFamilia'; item.id=item.idFamilia;  }
					if (item.thumb == "") item.thumb = "noimagen";
					item.isfavorite = (that.favorites.is(item)) ? true : false ;
					that.productBox(item,i,gets);
				});				

				
				dom.find(".title").html(data.variables.title);
				
				
				
				
				
				
				
				
				
		////// PAGINADOR	
				if (data.variables.num_total > config.limit)
				{
					var actual_page = parseInt(page);
					var prev_page = page-1;
					var next_page = page+1;
					var pages = Math.ceil(data.variables.num_total/config.limit);
					var filters = data.variables.filters;
					dom.find(".navigation").empty();

					if (actual_page > 4) dom.find(".navigation").append('<a href="#gotopage_first" class="nav_button first_button" rel="1">Primera</a> ');
					if (prev_page) dom.find(".navigation").append('<a href="#gotopage_prev" class="nav_button prev_button" rel="'+prev_page+'">Anterior</a> ');
					for(i=1; i<=pages ; i++) {
						var diferencia = i-actual_page;
						var distancia = diferencia < 0 ? -diferencia : diferencia;
						var is_actual_page = (i==actual_page)?true:false;
						if (is_actual_page) actual_page_class = 'actual_page'; else actual_page_class = '';
						if (distancia < 4) dom.find(".navigation").append('<a href="#gotopage_'+i+'" id="nav_button_'+i+'" class="nav_button '+actual_page_class+'" rel='+i+'>'+i+'</a> ');
					}
					if (i != next_page) dom.find(".navigation").append('<a href="#gotopage_next" class="nav_button next_button" rel="'+next_page+'">Siguiente</a> ');
					if (actual_page <= pages-4) dom.find(".navigation").append('<a href="#gotopage_end" class="nav_button end_button" rel="'+pages+'">&Uacute;ltima</a> ');

					dom.find('.nav_button').click(function () {
						that.setPage(parseInt($(this).attr("rel")));
						return false;
					});


					dom.find('.nav_button').button();
					dom.find('.prev_button').button({text: false,icons: {primary: 'ui-icon-seek-prev'}});
					dom.find('.next_button').button({text: false,icons: {primary: 'ui-icon-seek-next'}});
					dom.find('.first_button').button({text: false,icons: {primary: 'ui-icon-seek-first'}});
					dom.find('.end_button').button({text: false,icons: {primary: 'ui-icon-seek-end'}});
					
					dom.find(".navigation").css('height','');
				}
				else {
					dom.find(".navigation").empty().css('height','0px');
				}
		////// FIN PAGINADOR
				
				
				
				dom.find(".results").fadeTo('fast', 1);
				dom.find(".navigation").removeClass(config.loading_class);
				
				return data.variables.num_total;
			}
		});


	}
	
	
	
	
	
	this.objtolist = function(obj,what) {
		var list = new String;
		if (obj==null) return 'No hay m&aacute;s filtros disponibles';
		list = "<ul>"+"\n";
		$.each(obj, function(i,item){
			list += ""+'<li><a href="#addFilter_'+what+'_'+item.id+'" id="'+item.id+'_addfilter" name="'+what+'">'+item.nombre+'</a>'+"";
			if (item.subtecnicas) list += that.objtolist(item.subtecnicas, "subtecnicas");
			list += ""+'</li>'+"\n";
		});
		list += "</ul>"+"\n";
		return list;
	}
	
	
	
	
	
	this.appendAllSelectors = function() {
		var queries = getJsonObject(config.path+'filters.results.json.php', {filters: {}})
		dom.find('#tecnicas_container').empty().append('<a href="#" id="select_tecnicas">T&eacute;cnicas</a>');
		dom.find('#mercados_container').empty().append('<a href="#" id="select_mercados">Mercados</a>');
		dom.find('#marcas_container').empty().append('<a href="#" id="select_marcas">Marcas</a>');
		tecnicas = that.objtolist(queries.tecnicas, "tecnicas");
		mercados = that.objtolist(queries.mercados, "mercados");
		marcas = that.objtolist(queries.marcas, "marcas");
		dom.find('#select_tecnicas')
		.button({ icons: { secondary: 'ui-icon-triangle-1-s' } })
		.qmenu({
			content: tecnicas, flyOut: true, width:280, 
			action: function(item){
				that.removeAllFilters(function() {
					that.addFilter(item,function() {
						location.href = config.filterurl;
					});
				});
				return false;
			}
		});
		dom.find('#select_mercados')
		.button({ icons: { secondary: 'ui-icon-triangle-1-s' } })
		.qmenu({
			width: 200,
			content: mercados,
			action: function(item){
				that.removeAllFilters(function() {
					that.addFilter(item,function() {
						location.href = config.filterurl;
					});
				});
				return false;
			}
		});
		dom.find('#select_marcas')
		.button({ icons: { secondary: 'ui-icon-triangle-1-s' } })
		.qmenu({
			width: 200,
			content: marcas,
			action: function(item){
				that.removeAllFilters(function() {
					that.addFilter(item,function() {
						location.href = config.filterurl;
					});
				});
				return false;
			}
		});
	}

	this.appendMostPopular = function()
	{
		$.ajax({
			type: "POST",
			url: "/actions.php?subject=favorites&action=getpopular",
			dataType: "json",
			data: {
				limit: config.limit
			},
			success: function(data) {
				$.each(data.products, function(i,item){
					if (item.idProducto!="NO") {item.destino = '?idProducto='+item.idProducto; item.name = 'idProducto'; item.id=item.idProducto; }
					if (item.idFamilia!="NO") {item.destino = '?idFamilia='+item.idFamilia; item.name = 'idFamilia'; item.id=item.idFamilia;  }
					if (item.thumb == "") item.thumb = "noimagen";
					dom.append(that.formatProductPopular(item,i));
				});			
			}
		});
	}

	this.formatSelectors = function()
	{
	
	
	return ''+
		'<p class="inline"><a href="/productos/?filtrar" class="button">B&uacute;squeda Avanzada</a></p>'+
		'<p class="inline" id="mercados_container"></p>'+
		'<p class="inline" id="marcas_container"></p>'+
		'<p class="inline" id="tecnicas_container"></p>'+
        '';
	}

	this.productBox = function(item,i,gets)
	{
		dom.find(".results").append(that.formatProduct(item,i,gets));
		that.favorites.buttonInsert($('#'+i+'favoritep'),item);
	}
	
	
	this.formatProduct = function(product,i,gets) {
		poi = (i%2)?"par":"impar";
		return ""+
		"\t"+'<div class="product_found '+poi+'" id="'+i+'_product_found" name="'+product.name+'">'+"\n"+
		"\t"+"\t"+'<h3><img src="'+defaults.thumbs_dir+product.thumb+defaults.thumbs_ext+'" class="left"><p class="destacada inline">'+product.nombreMarca+'</p>&nbsp;<a href="/productos/'+product.destino+gets+'">'+product.nombre+'</a></h3>'+"\n"+
		"\t"+"\t"+'<p>'+product.descripcion+'</p>'+"\n"+
		"\t"+"\t"+'<p>'+product.resumen+'</p>'+"\n"+
		"\t"+"\t"+'<p class="scoring">'+product.scoring+'</p>'+"\n"+
		"\t"+"\t"+'<p class="favorite" id="'+i+'favoritep"></p>'+"\n"+
		"\t"+'</div>'+"\n";
	}
	
	this.formatProductMini = function(product,i,gets) {
		poi = (i%2)?"par":"impar";
		return ""+
		"\t"+'<div class="product_mini '+poi+'" id="'+i+'_product" name="'+product.name+'">'+"\n"+
		"\t"+"\t"+'<h3><img src="'+defaults.thumbs_dir+product.thumb+defaults.thumbsmini_ext+'" class="left"><p class="destacada inline">'+product.nombreMarca+'</p>&nbsp;<a href="/productos/'+product.destino+gets+'">'+product.nombre+'</a></h3>'+"\n"+
		"\t"+'</div>'+"\n";
	}
	
	this.formatProductPopular = function(product,i) {
		poi = (i%2)?"odd":"even";
		return ""+
		'<li class="'+poi+'">'+
		'<img src="'+defaults.thumbs_dir+product.thumb+defaults.thumbsmini_ext+'">'+
		'<a href="/productos/'+product.destino+'" style=" text-decoration: none; ">'+
		'<p><span class="destacada">'+product.nombreMarca+'</span>&nbsp;'+product.nombre+'</p>'+
		'<p>'+product.descripcion+'</p>'+
		'</a>'+
		'</li>';
	}
	
	this.formatFinder = function(){
		var formatFilters = (!config.filters)?that.formatFilters():"";
		return ''+
		"\t"+'<div class="finder" id="products_finder">'+"\n"+
		formatFilters+
		"\t\t"+'<div class="navigation"></div>'+"\n"+
		"\t\t"+'<div class="results"></div>'+"\n"+
		"\t"+'</div>'+"\n"+
		'';
	}
	this.formatFilters = function(){
		return ''+
		"\t\t"+'<div class="selects">'+"\n"+
		"\t\t\t"+'<div class="tecnicas"></div>'+"\n"+
		"\t\t\t"+'<div class="mercados"></div>'+"\n"+
		"\t\t\t"+'<div class="marcas"></div>'+"\n"+
		"\t\t"+'</div>'+"\n"+
		"\t\t"+'<div class="filters">'+"\n"+
		"\t\t\t"+'<div class="tecnicas subtecnicas"></div>'+"\n"+
		"\t\t\t"+'<div class="mercados"></div>'+"\n"+
		"\t\t\t"+'<div class="marcas"></div>'+"\n"+
		"\t\t"+'</div>'+"\n"+
		"\t\t"+'<div class="message"></div>'+"\n"+
		'';
	}
	this.formatFilter = function(filter,id,text){return '<a class="removeFilter" id="'+id+'_'+filter+'" rel="'+filter+'" href="#removeFilter">'+text+'</a>';}
	this.formatFilterType = function(text){return '<h6>'+text+'</h6>';}



	
}


















function Favorites(dom,config)
{

	var that = this;
	this.favorites = new Object;

	this.add = function(item,callback)
	{
		var what = $(item).attr("name");
		var id = parseInt($(item).attr("id"));
		if (id=="0") return 0;
		$.ajax({
			url: '/actions.php?subject=favorites&action=add',
			type: "POST",
			data: ({ what: what, id: id }),
			//async: false,
			success: function (data) {
				that.favorites[what].push(id);
				if (callback) callback(data);
			}
		});
	}
	
	this.remove = function(item,callback)
	{
		var what = $(item).attr("name");
		var id = parseInt($(item).attr("id"));
		if (id=="0") return 0;
		$.ajax({
			url: '/actions.php?subject=favorites&action=remove',
			type: "POST",
			data: ({ what: what, id: id }),
			//async: false,
			success: function (data) {
				that.favorites[what] = $.grep(that.favorites[what], function (a) { return a != id; });
				if (callback) callback(data);
			}
		});
	}
	
	this.get = function()
	{
		that.favorites = getJsonObject('/actions.php?subject=favorites&action=getjson');
		if (that.favorites == false) that.favorites = new Array;
		if (that.favorites.idProducto == undefined) that.favorites.idProducto = new Array;
		if (that.favorites.idFamilia == undefined) that.favorites.idFamilia = new Array;
		return that.favorites;
	}
	
	this.getcomplete = function()
	{
		return getJsonObject('/actions.php?subject=favorites&action=getcomplete');
	}
	
	this.getformatted = function()
	{
		return getHTML('/actions.php?subject=favorites&action=getformatted');
	}
	
	
	this.is = function(item)
	{
		var is = false;
		if (that.favorites[item.name] == undefined) return is;
		$.each(that.favorites[item.name],function(index,value){
			if (value==item.id) is = true;
		});
		return is;
	}
	
	
	
	
	this.init = function(callback)
	{
	
		$('a.star').live("mouseover mouseout",function () {
				$(this).toggleClass("starred");
		});
	
		$('a.addtofav').live('click',function(){
			var thisdom = $(this);
			var product = new Object;
			product.name = thisdom.attr('name');
			product.id = parseInt(thisdom.attr('id'));
			$(this).effect( "transfer", { to: "#favorites_button" }, 200, function(){ 
				that.buttonRemove(thisdom,product);
			});
			that.add($(this),function(data){
				if (callback) callback(data);
			});
			return false;
		});
		
		$('a.removefromfav').live('click',function(){
			var thisdom = $(this);
			var product = new Object;
			product.name = thisdom.attr('name');
			product.id = parseInt(thisdom.attr('id'));
			that.buttonAdd(thisdom,product);
			that.remove(thisdom,function(data){
				if (callback) callback(data);
			});
			return false;
		});
		
		that.get();
	}
	
	
	
	this.buttonAdd = function(dom,product)
	{
		dom.parent().html(that.formatButtonAdd(product)).find('a').tooltip(tooltipconfig);
	}
	this.buttonRemove = function(dom,product)
	{
		dom.parent().html(that.formatButtonRemove(product)).find('a').tooltip(tooltipconfig);
	}
	this.buttonInsert = function(dom,product)
	{
		dom.html(that.insertButton(product)).find('a').tooltip(tooltipconfig);
	}
	
	
	this.formatButtonAdd = function(product)
	{
		return '<a href="#addtofav" class="addtofav star" id="'+product.id+'_favorite" name="'+product.name+'" title="Agregar a Mis Elegidos"></a>';
	}
	this.formatButtonRemove = function(product)
	{
		return '<a href="#removefromfav" class="removefromfav star starred" id="'+product.id+'_favorite" name="'+product.name+'" title="Quitar de Mis Elegidos"></a>';
	}

	this.insertButton = function(product)
	{
		return (product.isfavorite == false) ? this.formatButtonAdd(product) : this.formatButtonRemove(product) ;
	}



	this.setaddtofavbutton = function()
	{
		that.init();
		var product = new Object;
		product.name = dom.attr('name');
		product.id = parseInt(dom.attr('id'));
		product.isfavorite = (this.is(product)) ? true : false ;
		that.buttonInsert(dom,product);
		
	}
}





})(jQuery);

