// *** COMMON ***************************************************************************

function Iterator(collection) 
{
	this.col = collection;
	this.idx = -1;

	if ( realTypeOf( collection ) == 'array' )
	{
		this.type = 'array';
		this.upperBound = this.col.length - 1; 
	}
	else
	{
		this.type = 'dictionary';
		this.keys = [];
		
		for ( var i in collection )
		{
			this.keys.push(i);
		}
		
		this.upperBound = this.keys.length - 1;
	}
}

Iterator.prototype.moveNext = function()
{
	this.idx++;
	return this.current();	
}

Iterator.prototype.moveNextUntil = function(index)
{
	this.idx++;
	if ( this.idx == index )
	{
		this.idx--;
		return null;
	}
	
	return this.current();	
}

Iterator.prototype.movePrevious = function()
{
	this.idx--;	
	return this.current();
}

Iterator.prototype.movePreviousUntil = function(index)
{
	this.idx--;
	if ( this.idx == index )
	{
		this.idx++;
		return null;
	}
	
	return this.current();	
}

Iterator.prototype.moveFirst = function()
{
	this.idx = 0;
	return this.current();
}

Iterator.prototype.moveLast = function()
{
	this.idx = this.upperBound;
	return this.current();	
}

Iterator.prototype.current = function()
{
	if ( this.idx > this.upperBound )
	{
		this.idx = this.upperBound + 1;
		return null;
	}
	else if ( this.idx < 0 )
	{
		this.idx = -1;
		return null;
	}	
	else
	{
		if ( this.type == 'array' )
		{
			return this.col[this.idx];
		}
		else
		{
			return this.col[this.keys[this.idx]];
		}
	}
}

Iterator.prototype.eof = function()
{
	return ( this.idx > this.upperBound );
}

Iterator.prototype.bof = function()
{
	return ( this.idx <= 0 );	
}

Iterator.prototype.index = function()
{
	return this.idx;
}

Iterator.prototype.reset = function()
{
	this.idx = -1;	
}

function lengthOf ( obj )
{
	var c = 0;
	for ( var i in obj )
	{
		c++;
	}
	
	return c;
}

function realTypeOf (o)
{
	if (o == null || o == undefined)
	{
		return null;
	}
	
	var t;
	var s = o.constructor.toString();
	
	if ( s.indexOf( 'Array()' ) > -1 )
	{
		t = 'array';
	}
	else if ( s.indexOf( 'String()' ) > -1 )
	{
		t = 'string';
	}
	else if ( s.indexOf( 'Function()' ) > -1 )
	{
		t = 'function';
	}
	else if ( s.indexOf( 'Number()' ) > -1 )
	{
		t = 'number';
	}
	else if ( s.indexOf( 'Date()' ) > -1 )
	{
		t = 'date';
	}
	else if ( s.indexOf( 'Boolean()' ) > -1 )
	{
		t = 'boolean';
	}
	else if ( s.indexOf( 'Object()' ) > -1 )
	{
		t = 'object';
	}	
	else
	{
		t = 'object';
	}	
	
	return t;
}

Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}


// ********************************************************************************************************

var bannerIterator;
var iteratorStep = 0;
var iteratorCount;

function parseAutocomplete(data) {
    var parsed = [];
    var item;
    
    data = eval("("+data+")");
    
    if (data.type=='Success')
    {
        for ( var i=0; i < data.result.length; i++ )
        {
        	item = data.result[i];
	        parsed.push ({
	        	data: [item],
	        	value: item,
	        	result: item
	        });
        }
    }
    
    return parsed;
};

$(document).ready( function() 
{
    // define iterator
    iteratorCount = $('#contentIterator>div').length;
    if ( iteratorCount > 1 )
    {
        bannerIterator = setTimeout(iterateBanner, 10000);
    }
    
    // init menu
    $('#menu>div').click( function() 
    {
        if ( !$(this).hasClass('active') )
        {
            document.location = $('a', this).attr('href');
        }
    });
    
    
    // block UI
    $.blockUI.defaults = { 
        // message displayed when blocking (use null for no message) 
        message:  '<div class="blockMessage">Cargando...</div>', 
     
        // styles for the message when blocking; if you wish to disable 
        // these and use an external stylesheet then do this in your code: 
        // $.blockUI.defaults.css = {}; 
        css: { 
            padding:        '20px', 
            margin:         0, 
            width:          '30%', 
            top:            '35%', 
            left:           '35%', 
            textAlign:      'center', 
            color:          '#FEEFA6', 
            border:         '2px solid #8E200A', 
            backgroundColor:'#B1290F', 
            cursor:         'wait',
            fontSize:       'small'
        }, 
     
        // styles for the overlay 
        overlayCSS:  { 
            backgroundColor: '#000', 
            opacity:         0.6 
        }, 
     
        
        // IE issues: 'about:blank' fails on HTTPS and javascript:false is s-l-o-w 
        // (hat tip to Jorge H. N. de Vasconcelos) 
        iframeSrc: /^https/i.test(window.location.href || '') ? 'javascript:false' : 'about:blank', 
     
        // force usage of iframe in non-IE browsers (handy for blocking applets) 
        forceIframe: false, 
     
        // z-index for the blocking overlay 
        baseZ: 1200, 
     
        // set these to true to have the message automatically centered 
        centerX: true, // <-- only effects element blocking (page block controlled via css above) 
        centerY: true, 
     
        // allow body element to be stetched in ie6; this makes blocking look better 
        // on "short" pages.  disable if you wish to prevent changes to the body height 
        allowBodyStretch: true, 
     
        // enable if you want key and mouse events to be disabled for content that is blocked 
        bindEvents: true, 
     
        // be default blockUI will supress tab navigation from leaving blocking content 
        // (if bindEvents is true) 
        constrainTabKey: true, 
     
        // fadeIn time in millis; set to 0 to disable fadeIn on block 
        fadeIn:  200, 
     
        // fadeOut time in millis; set to 0 to disable fadeOut on unblock 
        fadeOut:  400, 
     
        // time in millis to wait before auto-unblocking; set to 0 to disable auto-unblock 
        timeout: 0, 
     
        // disable if you don't want to show the overlay 
        showOverlay: true, 
     
        // if true, focus will be placed in the first available input field when 
        // page blocking 
        focusInput: true, 
     
        // suppresses the use of overlay styles on FF/Linux (due to performance issues with opacity) 
        applyPlatformOpacityRules: true, 
     
        // callback method invoked when unblocking has completed; the callback is 
        // passed the element that has been unblocked (which is the window object for page 
        // blocks) and the options that were passed to the unblock call: 
        //     onUnblock(element, options) 
        onUnblock: null, 
     
        // don't ask; if you really must know: http://groups.google.com/group/jquery-en/browse_thread/thread/36640a8730503595/2f6a79a77a78e493#2f6a79a77a78e493 
        quirksmodeOffsetHack: 4 
    };
    
    $('#searchBar a').click(function()
    {
    	document.location = 'catalogo.aspx?search=' + $('#searchBar input').val();
    });
    
    // initialize catalog
    Catalog.initialize();
    
       
});

function iterateBanner()
{
    $('#contentIterator>div[rel="'+iteratorStep+'"]').fadeOut('slow', function()
    {
        iteratorStep++;
        if ( iteratorStep == iteratorCount )
        {
            iteratorStep = 0;
        }
        
        $('#contentIterator>div[rel="'+(iteratorStep)+'"]').fadeIn('slow');
        bannerIterator = setTimeout(iterateBanner, 10000);
    });
}

function showSection(section)
{
    $('#'+section).addClass('active');
    
    /*switch(section)
    {
    	case 'catalogo':
    		initializeCatalog();
    		break;
    }*/
}

var Common = 
{
	/**
	 * obtain the base url of the page
	 */
	baseUrl : function()
	{
		return window.location.protocol + '//' + window.location.host;
	},
	
	/**
	 * concat the base path with the action page's  path
	 */
	actionsUrl : function()
	{
	    return Common.baseUrl() + '/asynch.aspx';
	},
	
    /**
     * Executes a common asynch action by its name
     * @param {Object} action
     * @param {Object} params
     * @param {Object} callback
     */
    run : function( _action, _params, _callback )
    {
        if( $.isFunction(_params) )
        {
            _callback = _params;
            _params = {};
        }

        _params['action'] = _action;

        return $.ajax({
            type:        'GET',
            url:         Common.actionsUrl(),
            data:        _params,
            cache:        false,
            dataType:    'json',
            success:     _callback });       
    },


    /**
     * Executes a common asynch action by its name passing the parameters within the POST
     * @param {Object} action
     * @param {Object} params
     * @param {Object} callback
     */
    post : function( _action, _params, _callback )
    {
        if( $.isFunction(_params) )
        {
            _callback = _params;
            _params = {};
        }

        _params['action'] = _action;

        return $.ajax({
            type:         'POST',
            url:        Common.actionsUrl(),
            data:        _params,
            cache:        false,
            dataType:    'json',
            success:    _callback });

    }
	
};


// Contact 

var SendMail = function(params)
{
    if ( params === undefined || params === null )
    {
        params = {
            fromMail:       $('#mailTextBox').val(),
            fromName:       $('#nameTextBox').val(),
            fromTelephone:  $('#telTextBox').val(),
            subject:        $('#subjectTextBox').val(),
            message:        $('#mensajeTextBox').val()
        };
    }
    
    $.blockUI({ message: '<div class="blockMessage">Enviando mensaje...</div>' }); 
    
    Common.run ( 'common.sendMail',
        params,
        function( result )
        {
            HandleGenericResult(result);
        });
}

var HandleGenericResult = function(result)
{
    if ( result.type == 'Success' )
    {
        $.unblockUI();
    }
    else
    {
		showError(result);
    }
}

var showError = function(result)
{
    $.blockUI({ 
        css: { 
            backgroundColor: '#300', 
            color: '#fafafa', 
            borderColor: '#200' 
        },
        message: 
            '<div class="errorMessage"><h3>Ocurri&oacute; un error</h3><p title="'+
            result.exception+
            '">'+
            result.message+
            '</p><br /><br /><strong><small>Clickee fuera del mensaje para salir</small></strong></div>' 
    }); 
            
    $('.blockOverlay').attr('title','Clickee para volver...').click($.unblockUI);	
}

var Catalog = {};

Catalog.contentQueue = [];

Catalog.initialize = function()
{
	$('#catalogoCategorias li').click( function() {
			
		$('#catalogoCategorias li.active').removeClass('active');
		$(this).addClass('active');
		
		$('.findGroup:visible').hide();
		$('.findGroup[rel="'+this.id+'"]').show();
		
	});
	
    $('#brandTextBox').autocomplete(Common.actionsUrl(),{
    	'extraParams': {
    		action: 'autocomplete.brand'
    	},
    	'selectFirst': false,
		'parse': parseAutocomplete 
    });
    
    $('#modelTextBox').autocomplete(Common.actionsUrl(),{
    	'extraParams': {
    		action: 'autocomplete.model',
    		brand: function() { return $('#brandTextBox').val(); }
    	},
    	'selectFirst': false,
		'parse': parseAutocomplete 
    });
    
    $('#motorTextBox').autocomplete(Common.actionsUrl(),{
    	'extraParams': {
    		action: 'autocomplete.motor',
    		brand: function() { return $('#brandTextBox').val(); },
    		model: function() { return $('#modelTextBox').val(); }
    	},
    	'selectFirst': false,
		'parse': parseAutocomplete 
    });
    
    
    $('#codeTextBox').autocomplete(Common.actionsUrl(),{
    	'extraParams': {
    		action: 'autocomplete.code'
    	},
    	'selectFirst': false,
		'parse': parseAutocomplete 
    });
    
    
    $('#eqBrandSelectBox').autocomplete(Common.actionsUrl(),{
    	'extraParams': {
    		action: 'autocomplete.eqBrand'
    	},
    	'selectFirst': false,
		'parse': parseAutocomplete 
    });    
    
    
    $('#eqCodeTextBox').autocomplete(Common.actionsUrl(),{
    	'extraParams': {
    		action: 'autocomplete.eqCode',
    		company: function() { return $('#eqBrandSelectBox').val(); }
    	},
    	'selectFirst': false,
		'parse': parseAutocomplete 
    });
    
    
	
	$('#advancedFinder .button').click( function() {
		
		var action, params, title, builder;
		$('#goBackLink').hide();
		Catalog.contentQueue = [];
		
		switch ( $('#catalogoCategorias .active')[0].id )
		{
			case 'catVehiculos':
				action = 'catalog.searchVehicles';
				params = {
							brand: $('#brandTextBox').val(),
							model: $('#modelTextBox').val(),
							motor: $('#motorTextBox').val()
  						 };
  				title = 'Resultados de la b&uacute;squeda por veh&iacute;culo';
  				builder = Catalog.buildVehiclesTable;
  				
  				/*if ( params.brand == '' || params.model == '' )
  				{
  					alert('Debe ingresar al menos la marca y modelo del vehiculo para iniciar la busqueda');
  					return false;
  				}*/
  				
				break;

			case 'catCodigo':
				action = 'catalog.searchFilters';
				params = {
							keyword: $('#codeTextBox').val()
  						 };
  				title = 'Resultados de la b&uacute;squeda por c&oacute;digo Masterfilt';
  				builder = Catalog.buildFiltersTable;
  				
  				if ( params.keyword == '' )
  				{
  					alert('Debe ingresar un codigo de filtro para iniciar la busqueda');
  					return false;
  				}
  				
				break;

			case 'catEquivalencia':
				action = 'catalog.searchReferences';
				params = {
							brand: $('#eqBrandSelectBox').val(),
							code:  $('#eqCodeTextBox').val()
  						 };
  				title = 'Resultados de la b&uacute;squeda por equivalencia';
  				builder = Catalog.buildFiltersTable;
  				
  				if ( params.code == '' )
  				{
  					alert('Debe ingresar un codigo de equivalencia para iniciar la busqueda');
  					return false;
  				}
  						
				break;
		}
		
		Catalog.doSearch(action, params, title, builder);
	});
	
	$('table.filters .expandFilters').live('click', function()
	{
		var selector;
		if ($('#catalogoCategorias .active')[0].id == 'catEquivalencia')
		{
			selector = 'th:first, td:first, td:last';
		}
		else
		{
			selector = 'th:first, td:first';
		}
		
		var $this = $(this);
		var $row = $this.parent().hide().parent();
		
		var span = $this.attr('rel') * 1;
		$row
			.prev().prev().prev()
			.find(selector)
				.attr('rowspan', span + 1);
		
		span -= 3;
		while(span > 0)
		{
			$row = $row.next().show();
			span--;
		}
	});
	
	$('#goBackLink')
		.hide()
		.click(function()
		{
			Catalog.goBack();	
		});
	
    try
    {
	    switch ( $('#postbackType').text() )
	    {
	    	case 'filterTable':
	    		Catalog.buildFiltersTable( eval('('+ $('#postbackContent').text() +')') );
	    		break;
	    		
	    	case 'vehicleTable':
	    		Catalog.buildVehiclesTable ( eval('('+$('#postbackContent').text() +')') );
	    		break;
	    		
	    	case 'filterDetails':
	    		Catalog.buildFilterDetails ( $('#content')[0], eval('('+$('#postbackContent').text() +')') );
	    		break;	    		
	    		
	    	default:
	    		break;
	    }
    }
    catch (err) {}	
}

Catalog.loadFilter = function (code)
{
	$.blockUI({ message: '<div class="blockMessage">Obteniendo informaci&oacute;n...</div>' }); 
	
	Catalog.contentQueue.push ( { action: 'loadFilter', params: [ code ] } );
	if ( Catalog.contentQueue.length > 1 )
	{
		$('#goBackLink').show();
	}
		
	Common.run(
		'catalog.getFilterDetails',
		{ 'code': code },
		function(response)
		{
		    if ( response.type == 'Success' )
		    {
		    	$('#content')
		    		.fadeOut('slow', function() { 

						Catalog.buildFilterDetails(this, response.result);
		    			
		    			$('#content').fadeIn('slow');
		    			$.unblockUI();
		    		} );
		    }
		    else
		    {
				showError(response);
		    }			
		});
}

Catalog.buildFilterDetails = function( e, filter )
{
	$('.sectionContent h1').html('Detalles del Filtro');
	
	$(e)
		.empty()
		.append(
			'<div class="filters">' +
			'   <div class="filterDetails">' +
			'		<img />' +
			'		<h1></h1>' +
			'		<h2></h2>' +
			'		<h3>Dimensiones</h3>' +
			'		<table></table>' +
			'	</div>' +
			'	<h2 style="clear:left;margin-top:45px;">Aplicaciones</h2>' +
			'	<div id="tableContainer"></div>' +
			'</div>'
			)
		.find('.filterDetails img')
			.attr('src', filter.imageUrl)
			.end()
		.find('.filterDetails h1')
			.text(filter.code)
			.end()
		.find('.filterDetails h2')
			.text(filter.type.description)
			.end()
		.find('.filterDetails table')
			.append(Catalog.getDimensionsTable(filter.dimensions));
			
	Catalog.buildVehiclesTable(filter.filterVehicles);	
}

Catalog.getDimensionsTable = function (dimensions)
{
	var html='';
	for ( var variable in dimensions )
	{
		html += '<tr><th>'+variable+'</th><td>'+dimensions[variable]+'</td></tr>';
	} 
	
	return html;
}

Catalog.loadVehicle = function (id)
{
	action = 'catalog.searchVehicleByID';
	params = {
				'id': id
			 };
	title = 'Resultados de la b&uacute;squeda por veh&iacute;culo';
	builder = Catalog.buildVehiclesTable;
	
	Catalog.doSearch(action, params, title, builder);	
}

Catalog.doSearch = function(action, params, title, builder)
{
	$.blockUI({ message: '<div class="blockMessage">Buscando filtros...</div>' }); 
	
	Catalog.contentQueue.push ( { action: 'doSearch', params: [ action, params, title, builder ] } );
	if ( Catalog.contentQueue.length > 1 )
	{
		$('#goBackLink').show();
	}	
	
	Common.run(
		action,
		params,
		function( response )
		{
		    if ( response.type == 'Success' )
		    {
		    	$('.sectionContent h1').html(title);
		    	
		    	$('#content')
		    		.fadeOut('slow', function() { 
		    			$(this)
		    				.empty()
		    				.append('<div id="tableContainer"></div>');
		    			
		    			builder(response.result);
		    			
		    			$('#content').fadeIn('slow');
		    			
		    			$.unblockUI();
		    		} );
		    }
		    else
		    {
				showError(response);
		    }
		});	
}

Catalog.getFilterLink = function (filter)
{
	return '<a href="javascript:Catalog.loadFilter(\''+
			filter.code+'\')">'+
			filter.code+'</a>'; 
}

Catalog.getVehicleLink = function(vehicle)
{
	return '<a href="javascript:Catalog.loadVehicle('+
			vehicle.id+
			')">'+
			vehicle.brand.name + ' ' + vehicle.model + ' ' + vehicle.motor +
			'</a>';
}

var months = ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'];

Catalog.getPeriodCells = function(period)
{
	function getFormatedDate (date)
	{
		return date.getFullYear() + '-' + months[date.getMonth()];
	}
	
	if ( period == null ) { period = { validFrom: null, validThru: null } };
	
	return '<td class="dateCell">'+
			(period.validFrom?getFormatedDate(period.validFrom):'<img src="imgs/icon16_arrow_left.png" />') +
			'</td><td class="dateCell">'+
			(period.validThru?getFormatedDate(period.validThru):'<img src="imgs/icon16_arrow_right.png" />') +
			'</td>';
}

Catalog.buildFiltersTable = function(filters)
{
	var showEquivalences = ($('#catalogoCategorias .active')[0].id == 'catEquivalencia');
	
	var equivalenceHeader = '', expandMark;
	
	if ( showEquivalences )
	{
		equivalenceHeader = '<th rowspan="2">Equivalencias</th>';
	}
	 
	var tableHtml = '<table class="filters" cellpadding="0" cellspacing="0">' +
			'<thead>' +
            '        <tr>' +
            '            <th rowspan="2"></th>' +
            '            <th rowspan="2">C&oacute;digo</th>' +
            '            <th colspan="3">Aplicaciones</th>' +
			equivalenceHeader +
            '        </tr>' +
            '        <tr class="secondLine">' +
            '            <th>Veh&iacute;culo</th>' +
            '            <th>Desde</th>' +
            '            <th>Hasta</th>' +
            '        </tr>' +
            '    </thead>' +
            '    <tbody>' +
            '    </tbody>' +
            '</table>';

	var html = '', filter, appSpan, appIterator;
	
	var getAppCells = function(app)
	{
		if ( app != null )
		{
			return '<td class="vehicleCell">'+
			Catalog.getVehicleLink(app.vehicle)+
			'</td>'+
			Catalog.getPeriodCells(app);
		}
		
		return '';
	};	

	for ( var i=0; i < filters.length; i++ )
	{
		filter = filters[i];
		
		html += '<tr'+((i % 2)?' class="odd"':'')+'>';
		
		if ( filter.filterVehicles && filter.filterVehicles.length > 1 )
		{
			if ( filter.filterVehicles.length > 3 )
			{
				appSpan = ' rowspan="4"'; // its going to be collapsed the first time
			}
			else
			{
				appSpan = ' rowspan="'+filter.filterVehicles.length+'"';
			}
		}
		else
		{
			appSpan = '';
		}
		
		// image
		html += '<th'+appSpan+'><div class="thumbnail" style="background-image: url('+filter.thumbUrl+')" /></th>';
		
		// code
		html += 
			'<td title="'+
			filter.type.description+'"'+
			appSpan+
			'>'+
			Catalog.getFilterLink(filter)+
			'</td>';
			
		// applications
		if ( filter.filterVehicles && filter.filterVehicles.length > 0 )
		{
			appIterator = new Iterator(filter.filterVehicles);
			
			appIterator.moveFirst();
			html += getAppCells(appIterator.current());
		}
		else
		{
			html += '<td colspan="3">No hay aplicaciones</td>';
			appIterator = null;
		}
		
		// cross references
		if(showEquivalences)
		{	
			if ( filter.equivalences && filter.equivalences.length > 0 )
			{
				var eqs = [];
				//var selectedBrandId = $('#eqBrandSelectBox').val();
				
				var selectedBrand = $('#eqBrandSelectBox').val();
				var selectedCode  = $('#eqCodeTextBox').val();
				
				if ( filter.equivalences[0].brand == selectedBrand || filter.equivalences[0].code == selectedCode )
				{
					eqs.push( filter.equivalences[0].brand + ' ' + filter.equivalences[0].code);
				}
				
				for ( var j=1; j < filter.equivalences.length; j++ )
				{
					if ( filter.equivalences[j].brand == selectedBrand || filter.equivalences[j].code == selectedCode )
					{					
						eqs.push( filter.equivalences[j].brand + ' ' + filter.equivalences[j].code );
					}
				}
				
				html += '<td'+appSpan+'>'+eqs.join(', ')+'</td>';
			}
			else
			{
				html += '<td'+appSpan+'>No hay equivalencias</td>';
			}
		}
		
		html += '</tr>';
		
		if ( appIterator )
		{
			while ( appIterator.moveNextUntil(3) )
			{
				html += '<tr'+((i % 2)?' class="odd" ':' ') + '>'+getAppCells(appIterator.current())+'</tr>';
			}
			
			if ( appIterator.moveNext() )
			{
				html += '<tr'+((i % 2)?' class="odd" ':' ') + 
					'><td colspan="3"><a href="#none" class="expandFilters" rel="'+
					filter.filterVehicles.length+
					'">Ver todas las aplicaciones ('+(filter.filterVehicles.length - 3)+' m&aacute;s)</a></td></tr>';
				
				appIterator.movePrevious();
				while ( appIterator.moveNext() )
				{
					html += '<tr'+((i % 2)?' class="odd" ':' ') + ' style="display: none;">'+getAppCells(appIterator.current())+'</tr>';
				}				
			}
		}
	}
	
	// need to show the side panel first
	$('.sectionContent').removeClass('extended');
	$('.sidePanel').fadeIn('slow');	
	
	$('#tableContainer')
		.append(tableHtml)
		.find('tbody')
			.append(html);
}

Catalog.buildVehiclesTable = function(vehicles)
{
	var tableHtml = '<table class="filters" cellpadding="0" cellspacing="0">' +
			'    <thead>' +
            '        <tr>' +
            '            <th rowspan="2">Veh&iacute;culo</th>' +
            '            <th rowspan="2">Motor</th>' +            
            '            <th colspan="2">A&ntilde;o</th>' +
            '            <th colspan="5">Filtros</th>' +
            '        </tr>' +
            '        <tr class="secondLine">' +
            '            <th>Desde</th>' +
            '            <th>Hasta</th>' +                        
            '            <th>Aire</th>' +
            '            <th>Aceite</th>' +
            '            <th>Combustible</th>' +
            '            <th>Habitaculo</th>' +
            '            <th>Otros</th>' +            
            '        </tr>' +
            '    </thead>' +
            '    <tbody>' +
            '    </tbody>' +
            '</table>';

	var getFiltersCells = function(filters, period)
	{
		var air = [], oil = [], fuel = [], hab = [], others = [];
		var periods = null;
		
		for ( var f=0; f < filters.length; f++ )
		{
			if ( getPeriodIdentifier(filters[f]) == period )
			{
				periods = periods ||
					 {
					 	validFrom: filters[f].validFrom,
					 	validThru: filters[f].validThru	
					 };
					 
				switch ( filters[f].filter.group )
				{
					/*case 'EA':
					case 'MAP':
					case 'ECO':*/
					case 'Oil':
						oil.push(Catalog.getFilterLink(filters[f].filter));
						break;
						
					/*case 'EC':
					case 'MCP':
					case 'ECOGS':
					case 'NM':
					case 'NMI':*/
					case 'Gas':
						fuel.push(Catalog.getFilterLink(filters[f].filter));
						break;
						
					/*case 'AMP':
					case 'AMPI':*/
					case 'Air':
						air.push(Catalog.getFilterLink(filters[f].filter));
						break;
						
					/*case 'HM':*/
					case 'Interior':
						hab.push(Catalog.getFilterLink(filters[f].filter));
						break;
						
					default:
						others.push(Catalog.getFilterLink(filters[f].filter));
						break;
				}
			} 
		}
		
		/*var periods = {
			validFrom:period.split(' ')[0],
			validThru:period.split(' ')[1]
		};*/
		
		return Catalog.getPeriodCells(periods)+
			'<td>'+air.join('<br />')+
			'</td><td>'+oil.join('<br />')+
			'</td><td>'+fuel.join('<br />')+
			'</td><td>'+hab.join('<br />')+
			'</td><td>'+others.join('<br />')+'</td>';		
	}

	var html = '', vehicle, years;
	
	//for ( var i=0; i < vehicles.length; i++ )
	
	var iterator = new Iterator(vehicles);
	
	while(iterator.moveNext())
	{
		vehicle = iterator.current().vehicle || iterator.current();
		
		// determine the number of periods 
		years = [];
		
		if ( vehicle.filters != null )
		{
			for ( var f=0; f < vehicle.filters.length; f++ )
			{
				valid = getPeriodIdentifier(vehicle.filters[f]);    
				if ( !(years.find( valid )) )
				{
					years.push(valid);	
				}
			}
		}
		
		years.sort();
		
		rowSpan = (years.length>1)?' rowspan="'+years.length+'"':'';
		
		// add vehicle name and motor
		html += '<tr'+((iterator.index() % 2)?' class="odd"':'')+'><td'+rowSpan+'>' + 
			vehicle.brand.name + ' ' + vehicle.model + 
			'</td><td'+rowSpan+'>'+vehicle.motor+'</td>';
			
		// add filters
		if ( years.length > 0 )
		{
			html += getFiltersCells(vehicle.filters, years[0]) + '</tr>';
			
			for ( var y=1; y < years.length; y++ )
			{
				html += '<tr'+((iterator.index() % 2)?' class="odd"':'')+'>'+getFiltersCells(vehicle.filters, years[y])+'</tr>';
			}
		}
		else
		{
			html += '<td colspan="7">No hay filtros asociados a este vehiculo</td></tr>';
		}
	}

	// need to hide the side panel first
	$('.sidePanel').fadeOut('slow', function() { $('.sectionContent').addClass('extended'); } );

	$('#tableContainer')
		.append(tableHtml)
		.find('tbody')
			.append(html);
}

Catalog.goBack = function()
{
	Catalog.contentQueue.pop(); // discard the first
	
	var action = Catalog.contentQueue.pop();
	switch ( action.action )
	{
		case 'doSearch':
			Catalog[action.action]( action.params[0], action.params[1], action.params[2], action.params[3] );
			break;
			
		case 'loadFilter':
			Catalog[action.action]( action.params[0] );
			break;
	}
	
	if ( Catalog.contentQueue.length <= 1 )
	{
		$('#goBackLink').hide();
	}
}

var getPeriodIdentifier = function(app)
{
	return (app.validFrom?(app.validFrom.getFullYear() + app.validFrom.getMonth()):'-') + (app.validThru?(app.validThru.getFullYear() + app.validThru.getMonth()):"-");
}


