
var defaultValueActsAsHint = function(element){
      element = $(element);
      element._default = element.value;
      
      return element.observe('focus', function(){
        if(element._default != element.value) return;
        element.removeClassName('hint').value = '';
      }).observe('blur', function(){
        if(element.value.strip() != '') return;
        element.addClassName('hint').value = element._default;
      }).addClassName('hint');
};

/**
 * Borrowed from http://24ways.org/2007/javascript-internationalisation
 * This is the translation function that uses included .js translated
 * file with translations. The object holding translations is i18n
 * @param {Object} s
 */
var tr = function(s){
	if (typeof(i18n)!='undefined' && i18n[s]) {
		return i18n[s];
	}
	return s;
}

/**
 * Class holding Application variables and functionality
 * @param {Object} urlBase
 */
var LyrApp = {
	urlBase:"/",
	themeBase:"/",
	errorNotice:"Error",//TODO translate
	init:function(urlBase, themeBase){
		this.urlBase = urlBase;
		this.themeBase = themeBase;
		//init translations
		this.errorNotice = tr(this.errorNotice);
	},
	/**
	 * Show alert with notice and remove it in 2s
	 * @param {Object} notice	string to show
	 */
	showAlert:function(notice){
		if($('cntCell')) {
			var container = $('cntCell');
			var alert = new Element('div', { 'class': 'msgerror','position':'absolute'}).update(notice);
			container.insert({top:alert});
			setTimeout(function(){
				//Effect.BlindUp(alert,{duration:0.3,afterFinish:function(o){$(o.element).remove();}});
				alert.remove();
				},2000);
		} else {
			alert(notice);
		}
	}
}
var StargAjax = {
	readyState:[],
	readyStateFunct:null,
	isReadyState:function(){
		return (this.readyState.length == 0) ? true : false;
	},
	close:function(){this.readyState.pop();},
	//FIXME diferenciate many readyStateFunct
	//class variable readyStateFunct can loose its state
	waitReadyState:function(funct){
		//if (this.readyState.length == 0) {
		//	if(funct != null) this.readyStateFunct();
		//}
		//else {
		//	if (funct != null) this.readyStateFunct = funct;
		//var passFunct = function(){
		//	KtrAjax.waitReadyState(funct);
		//}
		if (!this.isReadyState()) {
			setTimeout(function(){KtrAjax.waitReadyState(funct)}, 1000);
		}
		else{
			funct();
		}
			
		//}
	},
	executeOnReady:function(funct){
		//funct
		if(!this.isReadyState()){
			//this.waitReadyState(this.doFetchLatestTwitts.bindAsEventListener(this));
			this.waitReadyState(funct);
		}
		else{
			//KtrBl.loadLatestTwitts(KtrObj.user.idViewUser);
			funct();
		}
	},
	request: function(action,params,funct){
		var postParams = "";
		this.readyState.push(1);
		
		if(params != null){
			for(var key in params) {
			    //alert(key+":"+params[key]);
				postParams += "&"+key+"="+encodeURIComponent(params[key]);
			}
		}
		if(postParams != ""){
			postParams = "?"+postParams.substring(1);
		}
		//return;
		new Ajax.Request(LyrApp.urlBase + action, {
			method: "post",
			parameters:postParams,
			onComplete:funct
		});
		 
	},
	parseResult: function(text){
		//split by |
		//eval("var arr = "+text+";");
	}
}
function loginWindow(){
	var ul = $("userLogin");
	if (ul.getStyle('display') == 'none') {
		var xy = $("userBar").cumulativeOffset();
		var dim = $('userBar').getDimensions();
		
		xy[0] += dim.width - ul.getWidth();
		xy[1] += dim.height;
		ul.setStyle({
			'left': xy[0] + 'px',
			'top': xy[1] + 'px',
			'visibility': 'show',
			'display': 'block'
		});
	}
	else{
		ul.setStyle({'display':'none'});
	}
}

/**
 * Allow submit form to change namespace
 * @param {Object} form
 */
function changeNamespace(form){
	//Wiki_EditArticle::$ACTION_EDIT
	$("editAction").value = "wedit";
}

function reportSpam(com_id){
	var params = {"method":"post"};
	StargAjax.request(LyrApp.urlBase+'special_ajax?action=reportSpam&com='+com_id,params,
		function(transport){
			if(transport.responseText == "1"){
				//$(el).parrent().addClassname
				alert("ok");
			}
			else{
				alert("Error");
			}
		}
	);
	return false;
}

function setCommentScore(el,com_id,thumb){
	var params = {"method":"post"};
	var score = (thumb == "1") ? "1" : "-1";
	score += "";
	StargAjax.request(LyrApp.urlBase+'special_ajax?action=thumbs&score='+score,params,function(transport){
			if(transport.responseText == "1"){
				//$(el).parrent().addClassname
				alert("ok");
			}
			else{
				alert("Error");
			}
		}
	);
	return false;
}

/**
 * Remove user search results from session and update the element with
 * latest search resuts.
 * @param {Object} el
 */
function removeUserSearch(el){
	//var params = {"method":"post"};
	var script = 'index.php?a=ajax&ajaxMode=removeUserSearchData';
	StargAjax.request(script,null,function(transport){
			$(el).replace(transport.responseText);
		}
	);
	return false;
}

/**
 * Set current wiki page stared/not stared. Stared pages are like
 * favourites - think of gmail stars
 * @param {Object} el
 */
function toggleStar(el,title){
	var script = 'index.php?a=ajax&ajaxMode=toggleStar&ajTitle='+encodeURIComponent(title);
	StargAjax.request(script,null,function(transport){
		var responseObj = eval("("+transport.responseText+")");
		var imgEl = $(el).down(0);
		if(responseObj.toggle == 1){
			imgEl.setAttribute('src',LyrApp.themeBase+'star_yes.gif');
		} else if(responseObj.toggle == -1) {
			imgEl.setAttribute('src',LyrApp.themeBase+'star_no.gif');
		} else {
			LyrApp.showAlert(LyrApp.errorNotice);
		}
		imgEl.setAttribute('alt','');
		imgEl.setAttribute('title','');
	});
	return false;
}

Event.observe(window,"load", function(){
	if ($(favFilter.field)) {
		Event.observe($(favFilter.field), "keypress", favFilter.filterFavourites.bindAsEventListener(favFilter));
		Event.observe($(favFilter._cssRemoveCheckbox), "change", favFilter.onChangeEnableEdit.bindAsEventListener(favFilter));
	}
});

var favFilterX = {
	field:"favsFilter",
	timer:null,
	cache:[],
	filterFavourites: function(e){
		var el = Event.element(e);
		var cacheData = this.findInCache($F(el));
		if(cacheData != null){
			this.doFilter(cacheData);
		} else if(this.timer == null){
			this.timer = setTimeout(favFilter.executeAjax.bindAsEventListener(favFilter),1000);
		}
	},
	findInCache:function(filter){
		return (this.cache[filter]) ? this.cache[filter] : null; 
	},
	executeAjax:function(){
		console.log("executeAjax ",this.field);
		var val = $F(this.field);

		var script = 'index.php?a=ajax&ajaxMode=filterFavourites&filter='+encodeURIComponent(val);
		StargAjax.request(script,null,favFilter.handleAjaxResponse.bindAsEventListener(favFilter)
		);

	},
	/**
	 * Response is an object with 2 properties: filter and list. "list" holds
	 * all the items that should be show to the user
	 * @param {Object} transport
	 */
	handleAjaxResponse:function(transport){
		console.log("doFilter");
		//$(el).replace(transport.responseText);
		var res = eval("("+transport.responseText+")");
		var list = res.list;
		//add to cache
		this.cache[res.filter] = list;
		console.log("handleAjaxResponse ",this.cache);
		
		this.doFilter(list);
	},
	doFilter:function(list){
		this.timer = null;
		$$(".userFavs A").each(function(s){
			if(!list.include(s.id.substring(2))){
				s.hide();
			} else{
				s.show();
			}
		});
	}
}

/**
 * All action is done on A nodes in a container. There is no list
 * @param {Object} e
 */
var favFilter = {
	delay:200,
	field:"favsFilter",
	timer:null,
	cache:[],
	_cssRemoveCheckbox: "enableRemove",
	filterFavourites: function(e){
		this.disableEditOnFavs();//remove editing stuff
		var el = Event.element(e);
		//var cacheData = this.findInCache($(el).value);
		var cacheData = null;
		if(cacheData != null){
			this.doFilter(cacheData);
		} else if(this.timer == null){
			this.timer = setTimeout(favFilter.doFilter.bindAsEventListener(favFilter),this.delay);
		}
	},
	findInCache:function(filter){
		return (this.cache[filter]) ? this.cache[filter] : null; 
	},
	doFilter:function(){
		var val = $F(this.field);
		this.timer = null;
		var regs = new RegExp(val,"ig");
		$$("#userFavs A").each(function(s){
			var item = this.cleanHref($(s).href);
			if(!item.match(regs)) {
				s.hide();
				s.previous().hide();
			} else{
				s.show();
				if (s.previous("a") && s.previous("a").getStyle('display') == 'none') {
					s.previous().hide();
				} else {
					s.previous().show();
				}
			}
		},this);
		
	},
	cleanHref:function(str){
		var host = 'http://'+window.location.hostname+LyrApp.urlBase;
		return str.substring(host.length);
	},
	onChangeEnableEdit:function(e){
		var el = Event.element(e);
		if(el.checked){
			this.enableEditOnFavs();
		} else {
			this.disableEditOnFavs();
		}
	},
	enableEditOnFavs:function(){
		$$("#userFavs A").each(function(s){
			var btn = s.next();
			if(btn && btn.className == "removeBtn"){
				return;//continue
			} else {
				var img = new Element('img',{"src":LyrApp.themeBase+"removeBtn.gif"})
							.setStyle({"border": "0px"});
				var rem = new Element('a',{"href":"#","class":"removeBtn"}).update(img);
				Element.insert(s,{after:rem});
				Event.observe(rem,"click",favFilter.removeFavFromList.bindAsEventListener(favFilter));
			}
		});
	},
	disableEditOnFavs:function(){
		$(this._cssRemoveCheckbox).checked = false;
		$$("#userFavs A").each(function(s){
			var btn = s.next();
			if(btn && btn.className == "removeBtn"){
				btn.remove();
			}
		});
	},
	removeFavFromGui:function(favEl){
		var comma = favEl.previous();
		if (comma && comma.innerHTML == ", ") {
			favEl.previous().remove();
		} else {
			var lastComma = favEl.next(1);
			if (lastComma && lastComma.innerHTML == ", ") {
				favEl.next(1).remove();
			}
		}
		if(favEl.next().className == "removeBtn"){
			favEl.next().remove();
		}
		favEl.remove();
	},
	/**
	 * Element clicked on is not link, but image
	 * @param {Object} e
	 */
	removeFavFromList:function(e){
		var el = Event.element(e).up();
		var favEl = el.previous();
		var title = this.cleanHref(favEl.href);
		var script = 'index.php?a=ajax&ajaxMode=removeStar&ajTitle='+encodeURIComponent(title);
		StargAjax.request(script,null,function(transport){
			var responseObj = eval("("+transport.responseText+")");
			if (responseObj.removed == 1) {
				//remove successful
				favFilter.removeFavFromGui(favEl);
			} else {
				LyrApp.showAlert(LyrApp.errorNotice);
			}
		});
	}
}

/**
 * Object holding the functionality to select a homepage
 */
var LyrHp = {
	selected:null,
	contentBackup:"",
	currentHp:"",
	_cssTitleId:"hpTitle",
	_cssContainerDesc:".cntSubMenu",
	_cssInputId:"hpInput",
	_cssOptionsId:"hpOptions",
	_cssOkButtonId:"okButtonId",
	list:[],//fills later automatically
	initSelector:function(e){
		var c = this.firstElOfClass(this._cssContainerDesc);
		this.contentBackup = c.innerHTML;
				
		c.update("");//empty
		
		var input = new Element('input',{'type':'text',	'class':'hpInput','value':this.currentHp,
										'id':this._cssInputId,'autocomplete':'off'});
		var optionsBox = new Element('div',{'class':'autocomplete','id':this._cssOptionsId})
							.setStyle({display:'none'});	
		Element.insert(c,{top:optionsBox});
		Element.insert(c,{top:input});
		Event.observe(input,"keypress",function(e){this.selected = null;});
		defaultValueActsAsHint(input);
		//console.log($F(input));
		if($F(input) == "") {
			input.focus();
		}
		//cancel button
		var cancelButton = new Element("a", {'href': '#'}).update(tr("Cancel")).addClassName("autoConfirm");
		Element.insert(input,{after:cancelButton});
		Event.observe(cancelButton,'click',LyrHp.onCancelClick.bindAsEventListener(LyrHp));
		//ok button
		var okButton = new Element("a", {'href': '#','id':this._cssOkButtonId}).update(tr("Ok")).addClassName("disabled autoConfirm");
		Element.insert(input,{after:" "});
		Element.insert(input,{after:okButton});
		Event.observe(okButton,'click',LyrHp.onOkClick.bindAsEventListener(LyrHp));
		
		var list = this.generateList();
		new Autocompleter.Local(this._cssInputId, this._cssOptionsId, list, {
						partialSearch:true,
						fullSearch:true,
						afterUpdateElement:LyrHp.afterUpdateElement.bindAsEventListener(LyrHp),
						 });
	},
	generateList:function(){
		return this.list;
	},
	onOkClick:function(e){
		if(this.selected == null) return false;
		var hp = this.selected;
		//set homepage
		var script = 'index.php?a=ajax&ajaxMode=changeHomepage&hpTitle='+encodeURIComponent(hp);
		StargAjax.request(script,null,function(transport){
			if(transport.responseText == 1){
				LyrApp.showAlert(tr("Success, your home page has been changed. Please refresh page!"));
			} else{
				LyrApp.showAlert(LyrApp.errorNotice);
			}
		});
	},
	/**
	 * Return interface back to normal
	 * @param {Object} e
	 */
	onCancelClick:function(e){
		var c = this.firstElOfClass(this._cssContainerDesc);
		c.update(this.contentBackup);
	},
	firstElOfClass:function(css){
		return ($$(css).toArray())[0];
	},
	afterUpdateElement:function(li){
		this.selected = li.value;
		$(this._cssOkButtonId).toggleClassName("disabled");
	}

}

/**
 * Manage user status - change
 */
var LyrUserStatus = {
	_cssInput:"userStatusInput",
	_cssBtn:"statusBtn",//when exists
	currentStatus:"",
	/**
	 * Defaut value is set in html, we just add defaultValueAsHint and
	 * show/hide "Update" buttons on focus/blur
	 */
	init:function(){
		var el = $(this._cssInput);
		this.currentStatus = el.value;
		defaultValueActsAsHint(el);
		Event.observe(el,"blur",function(e){
			LyrUserStatus.hideButton();
		});
		Event.observe(el,"focus",function(e){
			LyrUserStatus.showButton();
		});
		Event.observe(el,"keypress",function(e){
			var key = e.which ? e.which : e.keyCode;
			if (key == Event.KEY_RETURN) {
				LyrUserStatus.onSubmitStatus();
			} else if(key == Event.KEY_ESC){
				//LyrUserStatus.blur();
				if ($(LyrUserStatus._cssBtn)) {
					$(LyrUserStatus._cssBtn).hide();
					$(LyrUserStatus._cssBtn).focus();
				}
				//dog eat dog
				//LyrUserStatus.hideButton();
			}
		});
	},
	showButton:function(e){
		//todo
		var el = $(this._cssInput);
		var btn = new Element('input',{'type':'button',
										'value':tr("Update"),
										'id':this._cssBtn});
		Element.insert(el,{before:btn});
		Event.observe(btn,"click",this.onSubmitStatus.bindAsEventListener(LyrUserStatus));
	},
	onSubmitStatus:function(e){
		var el = $(this._cssInput);
		var btn = $(this._cssBtn);
		if(!btn) {
			LyrApp.showAlert(LyrApp.errorNotice);
			return;
		}
		$(LyrUserStatus._cssInput).toggleClassName("sel");
		btn.disabled = true;
		var status = $F(el);
		var script = 'index.php?a=ajax&ajaxMode=updateStatus&status='+encodeURIComponent(status);
		StargAjax.request(script,null,function(transport){
			if(transport.responseText == 1){
				LyrApp.showAlert(tr("Success, your status has been updated!"));
				btn.remove();
				$(LyrUserStatus._cssInput).toggleClassName("sel");
				$(LyrUserStatus._cssInput).value = status;
				LyrUserStatus.currentStatus = status;
			} else{
				LyrApp.showAlert(LyrApp.errorNotice);
				btn.disabled = false;
			}
		});
	},
	hideButton:function(e){
		//delay to register click
		setTimeout(function(){
			if($(LyrUserStatus._cssBtn) && !$(LyrUserStatus._cssBtn).disabled){
				$(LyrUserStatus._cssBtn).remove();
				$(LyrUserStatus._cssInput).toggleClassName("sel");
				$(LyrUserStatus._cssInput).value = LyrUserStatus.currentStatus;
			}
		},200);
		
	}

};

Event.observe(window,"load", function(){
	if ($(LyrUserStatus._cssInput)) {
		LyrUserStatus.init();
	}
});

/**
 * Translate time to a parsable format
 * @param {Object} parseField
 */
function translateTime(parseField){
	var val = $F(parseField);
	var d = Date.parse(val);
	var str = "";
	if(d != null){
		str = d.toString('yyyy-MM-dd HH:mm:ss');
	}
	return str;
}
