/* @author Stefan Rumzucker <stefan-rumzucker.at> */

var JsonSelectList=new Class({Implements:[Options,Events],options:{url:null,onOptionRequest:$empty,onOptionResponse:$empty,onOptionSet:$empty,onOptionReset:$empty},initialize:function(){var params=Array.link(arguments,{options:Object.type,element:$defined});this.setOptions(params.options||null);this._SELECT=$(params.element||null);if(this._SELECT.get('tag')!='select')return false;this._SELECT.setStyle('display','none');this._suggestedOptions=[];this._lastQuery='';this._lastKey='';this._optionAccepted=false;this._using=false;this._markedOption=-1;this._INPUT=new Element('input',{'class':this._SELECT.getProperty('class')+' suggestion'});this.spanSelectField=new Element('span',{'class':this._SELECT.getProperty('class')+' suggestion'}).adopt(this._INPUT).injectAfter(this._SELECT);this._LIST=new Element('div',{'class':this._SELECT.getProperty('class')+' suggestionList hidden','opacity':this.options.opacity}).adopt(new Element('ul')).injectAfter(this._SELECT);this._INPUT.addEvents({'keydown':this.handleKeyDown.bindWithEvent(this),'keyup':this.requestByQuery.bindWithEvent(this),'focus':this.toggleList.create({bind:this,arguments:true,delay:100}),'blur':this.toggleList.create({bind:this,arguments:false,delay:100})});this._REQUEST=new Request.JSON({'url':this.options.url,'link':'cancel',onComplete:this.queryResponse.bind(this)});if(this._SELECT.getElement('option')){this.requestByValue();}
this.specialKeys=['escape','backspace','delete','left','right','up','down'];return true;},handleKeyDown:function(event){event=new Event(event);this._lastKey=event.key;if(['enter','up','down','esc'].indexOf(event.key)!==-1){event.stop();}
if(event.key=='enter'&&this._suggestedOptions[this._markedOption]){this.acceptSuggestion(false,this._suggestedOptions[this._markedOption]);return true;}
if(event.key=='down'&&this._markedOption<(this._suggestedOptions.length-1)){this._markedOption++;this.markSuggestedOption(false,false,this._markedOption);return true;}
if(event.key=='up'&&this._markedOption>0){this._markedOption--;this.markSuggestedOption(false,false,this._markedOption);return true;}
return true;},queryResponse:function(data){if(!data){return alert('Error: List couldn\'t be loaded!');}
this._suggestedOptions=data;this.fireEvent('onOptionResponse',[this._INPUT]);this.showList();return true;},requestByQuery:function(){this._using=true;query=this._INPUT.get('value').trim();if(query!==this._lastQuery){this._lastQuery=query;if(query.length>0){this._REQUEST.post({'query':query});this.fireEvent('onOptionRequest',[this._INPUT,query]);}
if(this._optionAccepted){this.resetOption();}}
return true;},requestByValue:function(){this._REQUEST.post({'value':this._SELECT.getElement('option').get('value')});this.fireEvent('onOptionRequest',[this._INPUT,false]);return true;},setOption:function(value,name){this._SELECT.empty();this._optionAccepted=true;this._SELECT.adopt(new Element('option',{'value':value,'selected':'selected'}).set('text',name));this.fireEvent('onOptionSet',[this._INPUT]);return true;},resetOption:function(){this._SELECT.empty();this._optionAccepted=false;this.fireEvent('onOptionReset',[this._INPUT]);return true;},acceptSuggestion:function(e,sOption,index){if(e){e=new Event(e).stop();}
this.setOption(sOption.value,sOption.name);this._INPUT.set('value',sOption.name);if(this._using){this._INPUT.selectRange(this._lastQuery.length,sOption.name.length).focus();}
this._lastQuery=sOption.name;this._suggestedOptions=[];this.hideList();return true;},toggleList:function(state){if(state&&this._suggestedOptions.length){this.showList();return true;}
this.hideList();return true;},markSuggestedOption:function(e,sOption,index){this._markedOption=index;$each(this._suggestedOptions,function(opt,index){this._suggestedOptions[index].el.removeClass('marked');},this);this._suggestedOptions[index].el.addClass('marked');},showList:function(){inputCoords=this._INPUT.getCoordinates();inputCoords.top=inputCoords.bottom;inputCoords.height=undefined;this._LIST.setStyles(inputCoords).getElement('ul').empty();this._LIST.removeClass('hidden');this._markedOption=-1;if(this._suggestedOptions.length==1&&this._lastKey!='backspace'){this.acceptSuggestion(false,this._suggestedOptions[0]);return true;}
if(this._suggestedOptions.length>0){$each(this._suggestedOptions,function(item,index){repName=item.name.replace(new RegExp('('+this._lastQuery+')','i'),'<b>$1</b>');this._suggestedOptions[index].el=a=new Element('a',{'href':'#','title':item.name,'html':repName}).addEvent('click',this.acceptSuggestion.bindWithEvent(this,[item])).addEvent('mouseenter',this.markSuggestedOption.bindWithEvent(this,[item,index]));this._LIST.getElement('ul').adopt(new Element('li').adopt(a));if(this._INPUT.get('value')==item.name){this.acceptSuggestion(item.value,item.name);}},this);return true;}
this._LIST.getElement('ul').adopt(new Element('li').adopt(new Element('span',{'html':'No options ...'})));return false;},hideList:function(){this._LIST.addClass('hidden');},stateNotifier:function(state){}});
var ActionCountdown=new Class({Implements:[Options,Events],options:{onUpdate:$empty,onFinished:$empty},initialize:function(endTime,startTime,options){this._endTime=endTime;this._startTime=startTime;this._lastTime=global.TIME;this._activeSeconds=0;this._timer=null;this.setOptions(options);this._timeDif=(this._endTime-(this._startTime?this._startTime:global.TIME));},set:function(){this.update();this._timer=this.update.periodical(1000,this);},update:function(){if(this._lastTime!=global.TIME){this._lastTime=global.TIME;this._activeSeconds=0;}
Today=new Date((global.TIME+this._activeSeconds)*1000);this._activeSeconds++;this._timestamp=this._endTime*1000-Today.getTime();if(this._timestamp<1){this._timestamp=0;$clear(this._timer);}
DT=new Date(this._timestamp);this.fireEvent('onUpdate',[DT,(this._timestamp/this._timeDif/1000)]);if(this._timestamp==0){this.fireEvent('onFinished');}
return true;}});
var PeriodicalToggle=new Class({Implements:[Options,Events],options:{interval:750},initialize:function(funcA,funcB,options){this.setOptions(options||null);this._fActive=0;this._funcA=funcA||$empty;this._funcB=funcB||$empty;this.toggle();this._periodical=this.toggle.periodical(this.options.interval,this);},toggle:function(){if(!this._fActive){this._funcA.run();this._fActive=1;}else{this._funcB.run();this._fActive=0;}},stop:function(){$clear(this._periodical);}});
var TitleChanger=new Class({Implements:[Options,Events],options:{separator:' - ',slotOrder:[]},initialize:function(options){this.setOptions(options);this._docTitle=null;this._slots={};window.addEvent('domready',function(){this.fetchTitle();}.bind(this));},fetchTitle:function(){this._docTitle=document.title;this.setSlot('_',this._docTitle);},setTitle:function(title){document.title=title;},resetTitle:function(){document.title=this._docTitle;},updateTitle:function(){newTitleArr=[];this.options.slotOrder.each(function(item,index){if($defined(this._slots[item])){newTitleArr.include(this._slots[item]);}},this);this.setTitle(newTitleArr.join(this.options.separator));},setSlot:function(name,content){this._slots[name]=content;return this;},clearSlot:function(name){this._slots[name]=undefined;return this;}});
var PeriodicalDataUpdater=new Class({Implements:[Options,Events],options:{url:'',updateTime:10,params:{},onDataRequest:$empty,onDataResponse:$empty},initialize:function(options){this.setOptions(options||null);this._data={};this._timer=null;this._REQUEST=new Request.JSON({url:this.options.url,onRequest:this.dataRequest.bind(this),onComplete:this.dataResponse.bind(this)});return true;},start:function(){if(this._timer){$clear(this._timer);}
this.update();this._timer=this.update.periodical((this.options.updateTime*1000),this);return true;},update:function(){this._REQUEST.post();return true;},dataRequest:function(){this.fireEvent('onDataRequest');return true;},dataResponse:function(data){if(!data){$clear(this._timer);return false;}
this._data=data;this.fireEvent('onDataResponse',[this._data]);return true;},registerParams:function(params){}});
Array.implement({domify:function(parent){if($type(this[0])=='string'){var elArr=Array.link(this,{elType:String.type,props:Object.type,html:String.type,children:Array.type});var el=new Element(this[0],elArr.props);if(elArr.html){el.set('html',elArr.html);}
if(elArr.children){elArr.children.domify(el);}
if($defined($(parent))){$(parent).adopt(el);}
return el;}else{this.each(function(item){item.domify($(parent));});}
return true;},isSimilar:function(array){return(this.toString()==array.toString());},complement:function(array){for(var i=0,j=this.length;i<j;i++)this[i]=$pick(this[i],array[i]||null);return this;}});
Date.implement({TodayYesterdayCheck:function(){var today=Date.today();var yesterday=Date.today().add(-1).days();whichDay=0;if(this.compareTo(yesterday)>0){whichDay=2;if(this.compareTo(today)>0){whichDay=1;}}
return whichDay;}});
Element.implement({});
Number.implement({zeroFill:function(n){var str='';(n-this.toString().length).times(function(){str+='0';});return(str+this.toString());},numberFormat:function(decimals,dec_point,thousands_sep){x=(this+'').split('.');x1=x[0];x2=x.length>1?(dec_point||'.')+x[1]:'';var rgx=/(\d+)(\d{3})/;while(rgx.test(x1)){x1=x1.replace(rgx,'$1'+(thousands_sep||',')+'$2');}
return(x1+x2);}});
String.implement({rc4Encrypt:function(key){pt=this;s=new Array();for(var h=0;h<256;h++){s[h]=h;}
var j=0;var x;for(var i=0;i<256;i++){j=(j+s[i]+key.charCodeAt(i%key.length))%256;x=s[i];s[i]=s[j];s[j]=x;}
i=0;j=0;var ct='';for(var y=0;y<pt.length;y++){i=(i+1)%256;j=(j+s[i])%256;x=s[i];s[i]=s[j];s[j]=x;ct+=String.fromCharCode(pt.charCodeAt(y)^s[(s[i]+s[j])%256]);}
return ct;},utf8encode:function(){},utf8decode:function(){}});
