/*************************************************************************************************
 * marumushi.widget.LiveSearch
 * @author:marcos@marumushi.com
 * @requires dojo framework.
 * @created: Nov 20, 2008.
 * 	based on: http://wiki.flux-cms.org/display/BLOG/LiveSearch
 * 	ported logic to work on top of dojo.
 ************************************************************************************************/
dojo.declare("marumushi.widget.LiveSearch", null, {
	
	INPUT_FIELD_ID				:'live_search',
	SELECTED_CONTAINER_ID 		:'live_search_selected',
	RESULT_CONTAINER_ID			:'live_search_result',
	FORM_ID						:'search_form',
	scriptURL					:'null',
	queryString					:'search?m=json&q=',
	keyDownTimeout				:200,
	requestTimeout				:5000,
	//private members
	timer						:null,
	activeRequest				:null,
	lastQuery					:"",
	list						:[],
	selectedCursor				:-1,
	
	constructor:function(url){
		this.scriptURL = url;
	},
	
	init:function(){
		var searchDiv = dojo.byId(this.INPUT_FIELD_ID);
		if(searchDiv){
			searchDiv.setAttribute("autocomplete","off");
			dojo.connect(searchDiv, "onkeydown", this, this.onKeyPress );
			dojo.connect(searchDiv, "blur", this, this.delayedHide );
		}else{
			console.error('search div not found');
		}
	},
	
	submit:function(){
		var selected = dojo.byId(this.SELECTED_CONTAINER_ID);
		if(selected){
			var url = selected.firstChild.getAttribute("href");
			window.location = url;
			return false;
		}else{
			dojo.byId(this.FORM_ID).submit();
		}
	},
	
	onKeyPress:function(event){
		switch(event.keyCode){
			//key down
			case 40 : this.selectPrevious(event); break;
			//key up
			case 38 : this.selectNext(event); break;
			//escape
			case 27 : this.hide(); break;
			//all the other
			default : this.start(); break;
		}
	},
	
	selectPrevious:function(event){
		var highlight = dojo.byId(this.SELECTED_CONTAINER_ID);
		if (!highlight) {
			this.selectedCursor = 0;
		} else {
			this.selectedCursor++;
			highlight.removeAttribute("id");	
		}
		highlight = this.list[this.selectedCursor];
		if (highlight) {
			highlight.setAttribute("id",this.SELECTED_CONTAINER_ID);
		} 
		if (!dojo.isIE) { event.preventDefault(); }
		
	},
	
	selectNext:function(event){
		var highlight = dojo.byId(this.SELECTED_CONTAINER_ID);
		if (!highlight) {
			this.selectedCursor = this.list.length-1;
		} else {
			this.selectedCursor--;
			highlight.removeAttribute("id");
		}
		highlight = this.list[this.selectedCursor];
		if (highlight) {
			highlight.setAttribute("id",this.SELECTED_CONTAINER_ID);
		}
		if (!dojo.isIE) { event.preventDefault(); }
	},
	
	sendRequest:function(){
		var scope=this;
		var query = dojo.byId(this.INPUT_FIELD_ID).value;
		this.lastQuery = query;
		if(this.activeRequest){
			this.activeRequest.cancel();
		}
		//nothing entered. hide the form
		if ( query == "" ) {
			this.hide();
			return false;
		}
		//send a new request
		this.activeRequest = dojo.xhrGet( { 
	    	url: this.scriptURL + this.queryString +query, 
	    	handleAs: "json",
	    	timeout: this.requestTimeout, // millis
	    	load: function(response, ioArgs) { 
		      	scope.onRequestData(response.results);
		      	return response;
	    	},
			error: function(response, ioArgs) {
				console.error("HTTP status code: ", ioArgs.xhr.status); 
				return response;
			}
	    });
	},
	
	highlightString:function(str,query){
			
		/*
		  Grrr I hate regex!
	      var regex = new RegExp("(.+?)"+query+"(.+?)","g");  
	      str.replace(regex,'$1<b>$2</b>$3'); 
	      return str;
	     */
	     
	    var n = str.indexOf(query);
		if(n>=0){
			before = str.substr(0,n);
			word   = str.substr(n,query.length);
			after  = str.substr(n+query.length);
			str    = before+'<b>'+word+'</b>'+after;
			//console.log(str);
		}
		return str;
	     
	},
	
	onRequestData:function(data){

		var str = '<div class="LiveSearchResult">';
		var news='';
		var works='';
		var tags='';
		var press='';
		var sketches='';
		
		var len = data.length;
		for (var n=0;n<len;n++){
			var item = data[n];
			var title = this.highlightString(item.title,this.lastQuery);
			var descr = item.description!='' ? '<p>'+this.highlightString(item.description,this.lastQuery)+'</p>' : '';
			var line='<div class="item"><a href="'+item.link+'"><h2>'+title+'</h2>'+descr+'</a></div>';
			switch(item.type){
				case 'news':		news +=line;break;
				case 'work':		works+=line;break;
				case 'tag':			tags +=line;break;
				case 'publication':	press+=line;break;
				case 'sketch':		sketches+=line;break;
			}
			//str+=line;
		}
		
		if(len==0){
			str+=	"<div><p>no results where found for <b>'"+this.lastQuery+"'</b></p></div>";
		}else{			
			if(tags.length>0)str+=		'<div class="header"><h1>tags</h1>'+tags+'</div>';
			if(works.length>0)str+=		'<div class="header"><h1>works</h1>'+works+'</div>';
			if(press.length>0)str+=		'<div class="header"><h1>press</h1>'+press+'</div>';
			if(sketches.length>0)str+=	'<div class="header"><h1>sketches</h1>'+sketches+'</div>';
			if(news.length>0)str+=		'<div class="header"><h1>news</h1>'+news+'</div>';
		}
		str+='</div>';
		var container = dojo.byId(this.RESULT_CONTAINER_ID);
		if(container){
			container.innerHTML = str; 
			container.style.display = "block";
			//create a list of all item divs so we can loop over them on keypress
			this.list = dojo.query(".LiveSearchResult .item");
			this.selectedCursor = 0;
		}else{
			console.error('container:'+this.RESULT_CONTAINER_ID+'was not found.')
		}
	},
	
	hide:function() {
		var highlight = dojo.byId(this.SELECTED_CONTAINER_ID);
		if (highlight) {
			highlight.removeAttribute("id");
		}
		dojo.byId(this.RESULT_CONTAINER_ID).style.display = "none";
	},
	
	delayedHide:function(){
		var scope = this;
		window.setTimeout(function(){scope.hide();},400);
	},
	
	start:function() {
		var scope = this;
		if (scope.timer) {
			window.clearTimeout(scope.timer);
		}
		scope.timer = window.setTimeout(function(){scope.sendRequest();},scope.keyDownTimeout);
	}
});


/*************************************************************************************************
 * marumushi.widget.Tagger
 * @author:marcos@marumushi.com
 * @requires dojo framework.
 * @created: Nov 20, 2008.
 *************************************************************************************************/
dojo.declare("marumushi.widget.Tagger", null, {
	
	INPUT_FIELD_ID				:'tag_name',
	OBJECT_ID					:'obj_id',
	TAGGER_ID					:'tagger_tags',
	FORM_ID						:'tagger_form',
	LOADER_ID					:'tagloader',
	scriptURL					:'null',
	queryString					:'addtag?m=json&q=',
	lastQuery					:null,
	
	constructor:function(url){
		this.scriptURL = url;
	},
	submit:function(){
		var scope	= this;
		var query 	= dojo.byId(this.INPUT_FIELD_ID).value;
		var id 		= dojo.byId(this.OBJECT_ID).value;
		this.lastQuery = query;
		if(this.activeRequest){
			this.activeRequest.cancel();
		}
		this.displayLoader(true);
		//send a new request
		this.activeRequest = dojo.xhrGet( { 
	    	url: this.scriptURL + this.queryString +query+'&id='+id, 
	    	handleAs: "json",
	    	timeout: this.requestTimeout, // millis
	    	load: function(response, ioArgs) { 
	    		scope.displayLoader(false);
		      	scope.onRequestData(response.result);
		      	return response;
	    	},
			error: function(response, ioArgs) {
				scope.displayLoader(false);
				console.error("HTTP status code: ", ioArgs.xhr.status); 
				return response;
			}
	    });
	},
	onRequestData:function(result){
		if(result.status=="OK" && result.message=="Success"){
			tags = dojo.byId(this.TAGGER_ID);
			tags.innerHTML+=('<a href="tags?tag='+result.tag+'">'+result.tag+'</a>');
		}
	},
	displayLoader:function(value){
		var loader = dojo.byId(this.LOADER_ID);
		loader.style.display = value ? '' : 'none';
		//alert(loader.style.display);
	}
});


/*************************************************************************************************
 * marumushi.widget.FormControl
 * @author:marcos@marumushi.com
 * @requires dojo framework.
 * @created: Nov 20, 2008.
 *************************************************************************************************/
dojo.declare("marumushi.widget.FormControl", null, {
	
	FORM_ID						:'comments-form',
	LOADER_ID					:'loader-spinner',
	scriptURL					:'null',
	queryString					:'postcomment',
	lastQuery					:null,
	requestTimeout				:5000,
	validateList				:["captcha","author","email","comment_text"],
	
	constructor:function(url){
		this.scriptURL = url;
	},
	
	validate:function(){
		var len = this.validateList.length;
		var valid = true;
		for(var n=0;n<len;n++){
			var id = this.validateList[n];
			var element = dojo.byId(id);
			var img 	= dojo.byId(id+'_error');
			if(element.value==""){
				img.style.display = '';
				valid = false;
			}else{
				img.style.display = 'none';
			}
		}
		if(!valid){
			//alert('make sure to fill in the required fields!');
			dojo.byId('validation_error').style.display='';
		}else{
			dojo.byId('validation_error').style.display='none';
		}
		return valid;
	},
	submit:function(){
		if(this.validate()){
			var scope	= this;
			if(this.activeRequest){
				this.activeRequest.cancel();
			}
			this.displayLoader(true);
			//send a new request
			this.activeRequest = dojo.xhrPost( { 
		    	url: this.scriptURL + this.queryString,
		    	form: this.FORM_ID,
		    	handleAs: "json",
		    	timeout: this.requestTimeout, // millis
		    	load: function(response, ioArgs) { 
		    		scope.displayLoader(false);
			      	scope.onRequestData(response.result);
			      	return response;
		    	},
				error: function(response, ioArgs) {
					scope.displayLoader(false);
					//console.error("HTTP status code: ", ioArgs.xhr.status); 
					return response;
				}
		    });
		}
	},
	onRequestData:function(result){
		if(result.status=="OK"){
			//window.location(window.location);
			window.location.reload();
		}else{
			dojo.byId('captcha_error').style.display = '';
			dojo.byId('captcha_img').src = this.scriptURL+"/captcha.php?="+new Date().valueOf();
			alert('try Entering that Captcha code again');
		}
	},
	displayLoader:function(value){
		var loader = dojo.byId(this.LOADER_ID);
		loader.style.display = value ? '' : 'none';
		//alert(loader.style.display);
	}
});

dojo.declare("marumushi.widget.Rwtr", null, {
	web_root:'',
	constructor:function(url){
		//alert(scriptURL);
		this.web_root = url;
	},
	rw:function(b,d,e,g,h,f,i){
		//alert(b.href);
		var a=encodeURIComponent||escape;
		b.href=this.web_root+"rwt?q="+a(d);
		//alert(b.href);
		b.onmousedown="";
		return true;
	}
});

/*************************************************************************************************
 * marumushi.widget.StarRater
 * @author:marcos@marumushi.com
 * @requires dojo framework.
 * @created: Nov 20, 2008.
 *************************************************************************************************/
dojo.declare("marumushi.widget.StarRater", null, {
	
	web_root:'',
	activeRequest:null,
	instance:null,
	requestTimeout:5000,
	endpoint:'rateentry',
	
	constructor:function(url){
		//alert(scriptURL);
		this.web_root = url;
		var scope = this;
		document.observe('starbox:rated', function(event){scope.rate(event);});
	},
	rate:function(event){
		if(this.activeRequest){
			this.activeRequest.cancel();
		}
		//this.displayLoader(true);
		//send a new request
		console.log(event.memo,this.web_root);
		this.activeRequest = dojo.xhrPost( { 
	    	url: this.web_root + this.endpoint,
	    	content: event.memo,
	    	handleAs: "json",
	    	timeout: this.requestTimeout, // millis
	    	load: function(response, ioArgs) { 
	    		scope.displayLoader(false);
		      	scope.onRequestData(response.result);
		      	return response;
	    	},
			error: function(response, ioArgs) {
				scope.displayLoader(false);
				//console.error("HTTP status code: ", ioArgs.xhr.status); 
				return response;
			}
	    });
	}
});

