/**
 * u2Start catalogue browser
 * @param {Object} options
 */

function compareObjects(a,x)
{

for(p in a)
{
    if(typeof(x[p])=='undefined') {return false;}
}

for(p in a)
{
    if (a[p])
    {
        switch(typeof(a[p]))
        {
                case 'object':
                        if (!compareObjects(a[p],x[p])) { return false }; break;
                case 'function':
                        if (typeof(x[p])=='undefined' || (p != 'equals' && a[p].toString() != x[p].toString())) { return false; }; break;
                default:
                        if (a[p] != x[p]) { return false; }
        }
    }
    else
    {
        if (x[p])
        {
            return false;
        }
    }
}

for(p in x)
{
    if(typeof(a[p])=='undefined') {return false;}
}

return true;
}


Catalogue = function(options) {this.ctor(options);}

$.extend(Catalogue.prototype, {
    timeout: null,
	loaded: false,
	firstchanged: false,
    defOptions: {
		sort: 'nosort',
		showCheckBox: false
	},
	defFilters:{
		tours: [],
		soort: [],
		minQuality: -1,
		compare: 'showall',
		type: 'notype',
		torrents: 'ignore',
		query: ''
	},
	userShows: [],
	ctor: function(useroptions) {
		var $this = this;
		this.options = $.extend(true,{},this.defOptions,useroptions);
		this.userShows = this.options.userShows;
		
		this.filters = $.extend(true,{},this.defFilters, useroptions.filters || []);
		
		
		$.getJSON(
			this.options.dataURL,
			function(data) {
				$this.loaded = true;
				$this.shows = data;
				if($this.options.load)
					$this.options.load($this);
				$this.init();
				
			}
		);
		
	},
	loadSettings: function(settings){
		var newoptions = $.extend({},this.options, settings.options);
		var newfilters = $.extend({},this.filters, settings.filters);
		
		if (compareObjects(newoptions,this.options) == false || compareObjects(newfilters,this.filters) == false) {
			this.options = newoptions;
			this.filters = newfilters;
			this.get();
		}
	},
	init: function(func){
		$this=this;
		if ($.browser.msie && $.browser.version == "6.0") {
		  $("form *").click(function() {
		    this.blur();
		    this.focus();
		  });
		}
		$("select, input",this.options.filters).bind("change", function(e){
			//$this.get();
		});	
		
	},
	sort: function(data){
		$this = this;
		
		if(this.options.sort == 'nosort') return data;
		
		return data.sort(function (a, b) {
			switch ($this.options.sort){
				case 'audioquality':
					return (a.maxQuality - b.maxQuality)*-1;
				case 'downloads':
					return (a.downloads*1.0 - b.downloads*1.0)*-1;
				default:
					return 0;
				
			}			
		});
	},
	
	sortDate:function(a,b){
		tmp = a.date.split('-');
		aDate = new Date(tmp[0],tmp[1],tmp[2]);
		tmp = b.date.split('-');
		bDate = new Date(tmp[0],tmp[1],tmp[2]);
		
		return aDate - bDate;
	},
	
	get: function(){
		$this = this;
		var data = new Array();
		var otheritems = new Array();
		var resCount = 0;
		
		if (this.shows) {
		
		
			$.each(this.shows, function(i, item){
				item.maxQuality = (item.sources && item.sources.length>0) ? item.sources[0].quality : 0;
				
				if ($this.userShows[item.id] == 1) {
					state = 'downloaded';
				}
				else if (item.sources) {
					state = 'available';
				}
				else {
					state = 'unavailable';
				}
				
				item.state = state;
				
				
				
				if ($this.match(i, item)) {
					item.suffix = '' ;
					
					if($this.filters.torrents == 'show'){
						item.suffix = '#torrents';
					}
					
					if ($this.options.sort == 'nosort') {
						if ($.isArray(data['' + item.tourId]) == false) {
							data[item.tourId] = new Array();
						}
						
						if (item.legId in data[item.tourId] == false) {
							data[item.tourId][item.legId] = new Array();
						}
						
						data[item.tourId][item.legId].push(item);
					}
					else {
						data.push(item);
					}
					resCount++;
				}/*else if($this.options.showCheckBox && item.incollection){
					otheritems.push(item.id);
				}*/
			});
			this.tmp = data;
			
			if (resCount > 0) {
				if (this.options.sort != 'nosort') {
					data = this.sort(data);
					this.renderSorted(data);
				}
				else {
					this.renderGrouped(data);
				}
			} else{
				$($this.options.results).html($this.options.noResults);
			}
		}
		
		if($this.options.onRenderSuccess)
			$this.options.onRenderSuccess();
		
		//$(this.options.results).prepend('<input type="hidden" name="othershows" value="'+otheritems.join(",")+'" />');
		
	},	
	match: function(i,item) {
		var tour = this.filters.tours.length == 0 || this.filters.tours[0] == -1;
		var minQuality = this.filters.minQuality < 0;
		var soort = this.filters.soort.length == 0 || this.filters.soort[0] == -1;
		var compare = true;
		var torrents = (this.filters.torrents == 'show' && item.torrents && item.torrents.length > 0) || this.filters.torrents == 'ignore';
		var goodType = this.filters.type == 'notype';
		
		item.incollection = item.id in this.userShows;
		
		$this = this;
		
		
		if (this.filters.tours.length > 0 && this.filters.tours[0] > -1) {
			tour = $.inArray(item.tourId, this.filters.tours) != -1;
			if(tour == false) return false
		}
		
		if (this.filters.minQuality > 0 || soort == false || this.filters.type != 'notype') {
			var src = [];
			if ($.isArray(item.sources) && this.filters.torrents == 'ignore') {
				src = item.sources;
			} else if($.isArray(item.torrents) && this.filters.torrents == 'show'){
				src = item.torrents;

			}
			
			$.each(src, function(i, source){
					if(minQuality == false) minQuality = $this.filters.minQuality > 0 && source.quality >= $this.filters.minQuality;
					if(soort == false) soort = $.inArray(source.soort, $this.filters.soort) != -1;
					
					goodType = ($this.filters.type == source.type) || ($this.filters.type == 'notype');
					
					// BREAK IF GOOD // RETURN FALSE == break
					if(minQuality && soort && goodType) return false; 
				});
		}
		
		if(this.filters.compare == 'showall'){
			compare = true;
		} else if (this.filters.compare == 'mycol'){
			compare = this.userShows[item.id+''] == 1;
		} else if(this.filters.compare == 'missing'){
			compare = item.id in this.userShows == false;
		}
		
		if(this.filters.query.length>3)
			search = this._search(item);
		else search = true;
				
		return tour && minQuality && soort && compare && goodType && torrents && search;
	},
	_search: function(show){
		var text = show.date + ' ' + show.location;
		return text.toLowerCase().indexOf(this.filters.query.trim().toLowerCase()) > -1;
	},
	renderSorted: function(data){
		var html ='<table>';
		
		var length = Math.ceil(data.length/2);
		for(i=0; i<length; i++){
			var item1 = data[i];
			var item2 = null;			
			var item2downloads = null;		
			if(i+length < data.length){
				item2 = data[i + length];
				item2downloads = item2.downloads;
				item2quality = item2.maxQuality;
			}
			
			switch(this.options.sort){
				case 'audioquality':
					html += $this.renderRow(item1,item2, item1.maxQuality, item2quality);
					break;
				case 'downloads':
					html += $this.renderRow(item1,item2, item1.downloads, item2downloads);
					break;
				default:
					html += $this.renderRow(item1,item2, item1.downloads, item2downloads);	
			}
		}
		
		html += '</table>';
		$($this.options.results).html(html);
	},
	
	renderRow: function(item1, item2, label1, label2){
		
		
		if(label1 || label1 === 0) 
			label1 = ' <font class="donker">('+label1+')</label>';
		else label1='';
		
		if(label2 || label2 === 0) 
			label2 = ' <font class="donker">('+label2+')</label>';
		else label2='';
		
		var checkbox1 = '';
		if(this.options.showCheckBox){
			checked = item1.incollection ? 'checked="checked"' : '';
			
			checkbox1 = '<input type="checkbox" name="showid['+item1.id+']" value="1" '+checked+' />&nbsp;';
			item1.state = 'nodot';
		}
		
		data = '<tr><td class="' + item1.state + '">'+checkbox1+'<a href="/shows/' + item1.id + '/' + item1.suffix +'"><font class=\"donker\">' + item1.date + '</font> ' + item1.location + label1 +"</a></td>";
		
		if (item2) {
			var checkbox2 = '';
			if(this.options.showCheckBox){
				checked = item2.incollection ? 'checked="checked"' : '';
				checkbox2 = '<input type="checkbox" name="showid['+item2.id+']" value="1" '+checked+' />&nbsp;';
				item2.state ='nodot';
			}
			data += '<td class="' + item2.state + '">'+checkbox2+'<a href="/shows/' + item2.id + '/' + item2.suffix + '"><font class=\"donker\">' + item2.date + '</font> ' + item2.location + label2 +"</a></td>";
		}
		
		data += '</tr>';
		
		return data;
	},
	
	renderGrouped: function(tours){
		var data ='';
		var prevTourId = -1;
		
		$this=this;
		
		
		$.each(tours, function(i, tour){
			if (tour && tour.length > 0) {
			
				tourPrinted = false;
				
				$.each(tour, function(i, legs){
					if (legs && legs.length > 0) {
					
						shows = tour[i].sort($this.sortDate);
						
						var length = Math.ceil(shows.length / 2);
						
						if (tourPrinted == false) {
							data += '<h2>' + shows[0].tourName + '</h2>';
							tourPrinted = true;
						}
						
						if (i > 0) 
							data += "<h4>" + shows[0]['legName'] + "</h4>";
						
						data += '<table>';
						
						for (var i = 0; i < length; i++) {
							
							if(typeof(shows[i]) == "undefined")
								break;
								
							var item1 = shows[i];
							var item2 = null;
							if (i + length < shows.length) {
								item2 = shows[i + length];
							}
							
							data += $this.renderRow(item1, item2);
						}
						data += '</table>';
					}
				});
			}
		});
		
		$($this.options.results).html(data);
	}
});