/*String.implement({
	pad:function(){
		console.log(this);
	}
});
*/
var Search = new Class({
	options:{
		communication:'./_scripts/service/json_search.asp',
		star_w:14,
		client_id:111,
		default_search_key:'date'
	},
	current_search_key:false,
	initialize:function(){
		this.current_search_key = this.options.default_search_key;
		this.communicator = new Request.JSON({
			'url':this.options.communication,
			'encoding':'iso-8859-1',
			'onSuccess':this.receive.bind(this),
			'onRequest':this.loading.start.bind(this)
		});
		this.qs = new QS();
		
		this.element	= $('h_search');
		this.searchingEl 	= new Element('div',{'html':'','style':'display:none;','id':'h_loading'});
		this.resultEl 	= new Element('div');
		this.filterEl = new Element('div',{'id':'h_filter'});
		this.element.adopt(this.filterEl,this.searchingEl,this.resultEl);
		
	},
	makeSearchFilter:function(){
		this.searchButtons = new Hash({
			'date':		Element('a',{'href':'#','html':' [publicatie datum] '}),
			'viewcount':Element('a',{'href':'#','html':' [meest bekeken] '}),
			'rating':	Element('a',{'href':'#','html':' [waardering] '})
		});
		this.searchButtons.each(function(item,key){
			item.addEvent('click',function(ev){
				
				this.searchButtons.each(function(b){b.removeClass('active')});
				
				ev.target.addClass('active');
				
				this.sortResults(key);
				this.makeHTML();
				
				return false;
			}.bind(this));
			
			if(this.current_search_key==key) item.addClass('active');
		},this);
		
		this.filterEl.empty().adopt([
			Element('span',{'html':'sorteer zoekresultaten op: '}),
			this.searchButtons.getValues()
		]);
	},
	createSortKeys:function(search_key,sv) {
		sv['viewcount'] = sv['viewcount'].pad(10,0,"left");
		sv['date'] = new Date(sv['date']).format("%Y%m%d%H%M%S");
		var rand = Math.random().toString().substr(1,9);

		switch(search_key) {
			case "date":		return '1'+sv['date']+sv['rating']+sv['viewcount']+rand;	break;
			case "rating":		return '1'+sv['rating']+sv['date']+sv['viewcount']+rand;	break;
			case "viewcount":	return '1'+sv['viewcount']+sv['rating']+sv['date']+rand;	break;
		}
		
	},
	
	sortResults:function(search_key){
		if(!search_key) search_key = this.options.default_search_key;
		if(  !['date','rating','viewcount'].contains(search_key)  ) return;

		this.current_search_key = search_key;
		
		var tmpresults = new Hash();
		this.results.each(function(item,x){tmpresults[this.createSortKeys(search_key,item.search)]=item;},this);
		
		this.results=[];
		tmpresults.getKeys().sort().each(function(item,x){
			this.results.push(tmpresults[item]);
		},this);
		this.results.reverse();
		
	},
	receive:function(responseJSON,response){
		if(responseJSON) {
			this.results=responseJSON;
			this.makeSearchFilter();
			this.sortResults();
			this.makeHTML();
		} else {
			this.filterEl.empty();
			this.resultEl.set('html','Wij hebben helaas geen resultaat gevonden.');
		}
		this.loading.stop.run(null,this);
	},
	loading:{
		start:function(){
			this.searchingEl.setStyle('display','block');
		},
		stop:function(){
			this.searchingEl.setStyle('display','none');
		}
	},
	search:function(term) {
		var term 	= term.replace(/'/g,'"');
		var qts		= RegExp('"[^"]*"',"gim");
		var remains = term;
		var search	= Array();
		
		while ((quotedtext = qts.exec(term)) != null) {
			search.push(quotedtext[0].replace(/"/g,""));
			remains=remains.replace(quotedtext,"");
		}
		remains = remains.split(" ");
		remains.each(function(item,x){
			if(item!="") search.push(item.trim());
		},this);
		//console.log(search);
		this.communicator.post({searchvalue:search.join("||")});
	},
	makeHTML:function(){
		//console.log('t',this.results);
		var output = Array();
		
		this.results.each(function(item,x){
			var vid = Element('a',{'class':'videocontainer','href':'./?mid='+item.media_id+'&mcid='+item.media_cat_id}).adopt([
				Element('div',{'class':'h_img'}).adopt([
					Element('div',{'class':'img'}).adopt(Element('img',{'src':'/media/'+this.options.client_id+'/'+item.thumbnail_id+'.jpg'})),
					Element('div',{'class':'border'})
				]),
				Element('div',{'class':'h_title','html':item.title}),
				Element('div',{'class':'h_description','html':item.media_description}),
				Element('div',{'class':'bg_rating'}).adopt(
					Element('div',{'class':'h_rating','style':'width:'+item.rating*this.options.star_w+'px'})
				),
				Element('div',{'class':'h_time','html':'speelduur: '+sec_to_time(item.length)}),
				Element('div',{'class':'h_date','html':'publicatie: '+item.created}),
				Element('div',{'class':'h_viewcount','html':'bekeken: '+item.viewcount})
			]);
			output.push(vid);
		},this);
		this.resultEl.empty().adopt(output);
	}

});

