/**
 * Pavilion v0.1
 */
var gDebug=false;var gAllowTextSelect=true;var gAllowResizing=false;var gTotalPanelHeight=85;var gServer="./io.php";var gCurrentUser={};var gCurrentProject=false;var gCurrentTask=false;var gProjectWidgetIds=[];var gLastAction=null;var gAllUsers=[];var gRegArray=[];var gLoadedProjects=false;var calendar=null;function init(){showDebugArea();goCaptureEvents();blockSelection();loadTranslations();loadAllProjects();loadUIState();document.onkeydown=new Function("return processKeys();");}function loadTranslations(){document.getElementById('labelPavilion').innerHTML=i18n.LBL_Pavilion_name;document.getElementById('labelLogout').innerHTML=i18n.BTN_Logout;document.getElementById('buttonFilterAll').value=i18n.BTN_Filter_all;document.getElementById('buttonFilterMine').value=i18n.BTN_Filter_mine;document.getElementById('buttonInvite').title=i18n.BTN_Invite;document.getElementById('buttonProjectHistory').title=i18n.BTN_ProjectHistory;document.getElementById('buttonProjectDetails').title=i18n.BTN_ProjectDetails;document.getElementById('buttonProjectNew').title=i18n.BTN_ProjectNew;document.getElementById('buttonTaskNew').title=i18n.BTN_TaskNew;}function userAgentLanguage(){var lang=navigator.systemLanguage;if(typeof lang=="undefined"){lang=navigator.language;}if(lang.indexOf("bg")!="-1"){return"bg";}else{return"en";}}var gObject=this;Function.prototype.inherits=function(parent){var d=0;this.prototype=new parent();this.uber=function(fname){var f,r,t=d,v=parent.prototype;if(t){while(t){v=v.constructor.prototype;--t;}f=v[fname];}else{f=p[fname];if(f==this[fname]){f=v[fname];}}++d;r=f.apply(this,Array.prototype.slice.apply(arguments,[1]));--d;return r;};};Function.prototype.swissInherit=function(parent){for(var i=1;i<arguments.length;++i){var fname=arguments[i];this.prototype[fname]=parent.prototype[fname];}return this;};function isAlien(a){return isObject(a)&&typeof a.constructor!='function';}function isArray(a){return isObject(a)&&a.constructor==Array;}function isDate(a){return isObject(a)&&a.constructor==Date;}function isBoolean(a){return typeof a=='boolean';}function isEmpty(o){var i,v;if(isObject(o)){for(i in o){v=o[i];if(isUndefined(v)&&isFunction(v)){return false;}}}return true;}function isFunction(a){return typeof a=='function';}function isNull(a){return typeof a=='object'&&!a;}function isNumber(a){return typeof a=='number'&&isFinite(a);}function isObject(a){return(a&&typeof a=='object')||isFunction(a);}function isString(a){return typeof a=='string';}function isUndefined(a){return typeof a=='undefined';}String.prototype.escapeForHTML=function(){return this.toString().replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\n/g,"<br />");};String.prototype.supplant=function(o){var i,j,s=this,v;for(;;){i=s.lastIndexOf('{');if(i<0){break;}j=s.indexOf('}',i);if(i+1>=j){break;}v=o[s.substring(i+1,j)];if(!isString(v)&&!isNumber(v)){break;}s=s.substring(0,i)+v+s.substring(j+1);}return s;};String.prototype.trim=function(){return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1");};if(!isFunction(Function.apply)){Function.prototype.apply=function(o,a){var r,x='____apply';if(!isObject(o)){o={};}o[x]=this;switch((a&&a.length)||0){case 0:r=o[x]();break;case 1:r=o[x](a[0]);break;case 2:r=o[x](a[0],a[1]);break;case 3:r=o[x](a[0],a[1],a[2]);break;case 4:r=o[x](a[0],a[1],a[2],a[3]);break;case 5:r=o[x](a[0],a[1],a[2],a[3],a[4]);break;case 6:r=o[x](a[0],a[1],a[2],a[3],a[4],a[5]);break;default:alert('Too many arguments to apply.');}delete o[x];return r;};}if(!isFunction(Array.prototype.pop)){Array.prototype.pop=function(){return this.splice(this.length-1,1)[0];};}if(!isFunction(Array.prototype.push)){Array.prototype.push=function(){this.splice.apply(this,[this.length,0].concat(Array.prototype.slice.apply(arguments)));return this.length;};}if(!isFunction(Array.prototype.shift)){Array.prototype.shift=function(){return this.splice(0,1)[0];};}if(!isFunction(Array.prototype.splice)){Array.prototype.splice=function(s,d){var max=Math.max,min=Math.min,a=[],e,i=max(arguments.length-2,0),k=0,l=this.length,n,v,x;s=s||0;if(s<0){s+=l;}s=max(min(s,l),0);d=max(min(isNumber(d)?d:l,l-s),0);v=i-d;n=l+v;while(k<d){e=this[s+k];if(!isUndefined(e)){a[k]=e;}k+=1;}x=l-s-d;if(v<0){k=s+i;while(x){this[k]=this[k-v];k+=1;x-=1;}this.length=n;}else if(v>0){k=1;while(x){this[n-k]=this[l-k];k+=1;x-=1;}}for(k=0;k<i;++k){this[s+k]=arguments[k+2];}return a;};}if(!isFunction(Array.prototype.unshift)){Array.prototype.unshift=function(){this.splice.apply(this,[0,0].concat(Array.prototype.slice.apply(arguments)));return this.length;};}Function.prototype.bind=function(object){var method=this;return function(){return method.apply(object);};};function logMessage(message,debug){if(gDebug&&debug){document.getElementById("debugArea").innerHTML+="<p>"+String.prototype.escapeForHTML.apply(message)+"</p>";}}function showDebugArea(){if(!gDebug){return false;}var debug=document.createElement("DIV");debug.id="debugArea";debug.className="debugArea";if(typeof hidden!="undefined"&&hidden===true){debug.style.display="none";}document.body.appendChild(debug);}function sqlDate(str){var date=str.substring(0,str.indexOf(' '));var time=str.substring(date.length);var year=Number(date.substring(0,date.indexOf('-')));var month=Number(date.substring(str.indexOf('-')+1,date.lastIndexOf('-')))-1;var day=Number(date.substring(date.lastIndexOf('-')+1));var hour=Number(time.substring(0,time.indexOf(':')));var minute=Number(time.substring(time.indexOf(':')+1,time.lastIndexOf(':')));var second=Number(time.substring(time.lastIndexOf(':')+1));return new Date(year,month,day,hour,minute,second);}function makeDate(jsDate){function leadZero(num){if(num<10){return("0"+num);}else{return num;}}return(jsDate.getFullYear()+"-"+leadZero(jsDate.getMonth()+1)+"-"+leadZero(jsDate.getDate()));}function makeFriendlyDate(jsDate){if(!isDate(jsDate)){return jsDate;}var d=new Date();if(makeDate(d)==makeDate(jsDate)){return i18n.LBL_Today;}d.setDate(d.getDate()-1);if(makeDate(d)==makeDate(jsDate)){return i18n.LBL_Yesterday;}d.setDate(d.getDate()+2);if(makeDate(d)==makeDate(jsDate)){return i18n.LBL_Tomorrow;}return makeDate(jsDate);}function convertToDate(strDate){var d=new Date();function explodeDate(strDate){var yy=strDate.substr(0,4);var mm=strDate.substring(strDate.indexOf("-")+1,strDate.lastIndexOf("-"));var dd=strDate.substring(strDate.lastIndexOf("-")+1,strDate.length);if(dd===""||mm===""||yy===""){return null;}else{return[0,yy,mm,dd];}}var date_fields=explodeDate(strDate);if(strDate===i18n.LBL_Today){return d;}else if(strDate===i18n.LBL_Yesterday){d.setDate(d.getDate()-1);return d;}else if(strDate===i18n.LBL_Tomorrow){d.setDate(d.getDate()+1);return d;}else if(date_fields!==null){d=new Date(parseInt(date_fields[1],10),parseInt(date_fields[2],10)-1,parseInt(date_fields[3],10));return d;}return d;}function trim(TRIM_VALUE){if(TRIM_VALUE.length<1){return"";}TRIM_VALUE=rtrim(TRIM_VALUE);TRIM_VALUE=ltrim(TRIM_VALUE);if(TRIM_VALUE===""){return"";}else{return TRIM_VALUE;}}function rtrim(VALUE){var w_space=String.fromCharCode(32);var v_length=VALUE.length;var strTemp="";if(v_length<0){return"";}var iTemp=v_length-1;while(iTemp>-1){if(VALUE.charAt(iTemp)==w_space){}else{strTemp=VALUE.substring(0,iTemp+1);break;}iTemp=iTemp-1;}return strTemp;}function ltrim(VALUE){var w_space=String.fromCharCode(32);var v_length=VALUE.length;if(v_length<1){return"";}var strTemp="";var iTemp=0;while(iTemp<v_length){if(VALUE.charAt(iTemp)==w_space){}else{strTemp=VALUE.substring(iTemp,v_length);break;}iTemp=iTemp+1;}return strTemp;}function extractErrorName(str){var end=str.substring(4,str.length).indexOf(" ")+4;return str.substring(4,end);}function extractErrorComment(str){try{var space2=str.substring(4).indexOf(" ")+4;if(space2==-1){return null;}else{return str.substring(space2+1);}}catch(e){return null;}}function isError(str){return str.indexOf("ERR")===0;}function logError(err,debug){if(extractErrorName(err)=="NOCONNECT"){showErrorDialog("NOCONNECT");}logMessage("Server returned error "+extractErrorName(err)+" - "+extractErrorComment(err),true);}function createUID(){var result="";for(var i=0;i<32;++i){result+=Math.floor(Math.random()*9);}return result;}function getXMLNamedNode(root,nodeName){return root.getElementsByTagName(nodeName).item(0).firstChild;}function getXMLNodeValue(root,nodeName){var node=getXMLNamedNode(root,nodeName);if(isNull(node)){return"";}else{return node.nodeValue;}}function drawUserSelectOption(existingUser){var projectObj=getCurrentProject();if(projectObj===null){projectObj=getProject(-2);}var users=projectObj.users;var s="";for(var i=0;i<users.length;i++){s+="<option value='"+users[i].id+"'";if(existingUser==users[i].id){s+=" selected='selected' ";}s+=">"+users[i].username+"</option>";}return s;}function drawManyUsersSelectOptions(users){var result="";for(i=0;i<users.length;i++){result+="<option value='"+users[i].id+"'>"+users[i].username+"</option>";}return result;}function moveSelectedOptions(from,to){var index,o;if(from===null||from.options===null){return;}for(var i=0;i<from.options.length;i++){o=from.options[i];if(o.selected){if(to===null||to.options===null){index=0;}else{index=to.options.length;}to.options[index]=new Option(o.text,o.value,false,false);}}for(var j=(from.options.length-1);j>=0;j--){o=from.options[j];if(o.selected){from.options[j]=null;}}from.selectedIndex=-1;to.selectedIndex=-1;}function stripPX(str){var num=parseInt(str.replace(/px/,""),10);if(isNaN(num)){return 0;}else{return num;}}function shortenText(str,to){if(str.length>to){return(str.substring(0,to)+"...");}else{return str;}}function getValue(elem){if(typeof elem=="undefined"||elem===null){return"";}if(typeof elem.value!="undefined"){return elem.value;}else{return elem.getAttribute("value");}}function pushAction(funcName,args){gLastAction={};gLastAction.func=funcName;if(!isEmpty(args)){gLastAction.args=args;}}function popAction(){if(gLastAction!==null){if(isEmpty(gLastAction.args)){logMessage("Restoring last known action ["+gLastAction.func+"]...",true);eval(gLastAction.func+"();");clearAction();}else{logMessage("Last known action had aruments... TODO...",true);}}}function clearAction(){gLastAction=null;}function createXHR(){var ret=null;if(window.XMLHttpRequest){ret=new XMLHttpRequest();}else if(window.ActiveXObject){ret=new ActiveXObject("Microsoft.XmlHttp");}else{logMessage(i18n.MSG_NoXMLHTTP,false);}return ret;}function XHRObject(onLoad,waitToLoad,onLoadData){this.uid=addObject("XHRO",null,this,false);this.url="";this.xhr=createXHR();this.onLoad=onLoad;if(isUndefined(waitToLoad)){this.sync=true;}else{this.sync=waitToLoad?false:true;}if(isUndefined(onLoadData)){this.onLoadData=null;}else{this.onLoadData=onLoadData;}}function XHR_onreadystatechange(uid){var self=getObject("XHRO",uid);var xhr=self.xhr;if(xhr.readyState!=4){return;}if(xhr.status!=200){logMessage("WARNING! xhr status is not 200.",true);if(xhr.status==403){logMessage("ERROR! Access Forbidden while trying to access "+self.url+". Stop Loading.",true);}else if(xhr.status==404){logMessage("ERROR! Not Found while trying to access "+self.url+". Stop Loading.",true);}}self.onLoad(xhr,self.onLoadData);}XHRObject.prototype.load=function(url,postData){this.url=url;this.xhr.open("POST",url,this.sync);if(this.sync){eval('this.xhr.onreadystatechange = function() { XHR_onreadystatechange("'+this.uid+'"); }');}this.xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');this.xhr.send(postData);};function PObject(){}PObject.prototype.toHTML=function(){return"<p>An object</p>";};PObject.prototype.toString=function(){return this.toHTML();};function PWidget(){this.containerType="1";}PWidget.inherits(PObject);PWidget.prototype.initWidget=function(){this.oid=addObject("WIDGET",null,this,false);};PWidget.prototype.getThis=function(){return('getObject( "WIDGET", "'+this.oid+'" )');};PWidget.prototype.setContainer=function(containerId,type){if(isUndefined(type)){this.containerType=1;}else{this.containerType=type;}this.containerId=containerId;this.update();return this;};PWidget.prototype.getContainerId=function(){if(isNull(this.containerId)||isUndefined(this.containerId)){return false;}else{return this.containerId;}};PWidget.prototype.update=function(){if(isNull(this.containerId)||isUndefined(this.containerId)){return this;}var container=null;switch(this.containerType){case 1:container=document.getElementById(this.containerId);if(!isNull(container)&&!isUndefined(container)){container.innerHTML=this.toHTML();}break;case 2:container=getObject("WIDGET",this.containerId);container.update();break;default:return this;}return this;};PWidget.prototype.onDelete=function(){if(isUndefined(this.containerId)||isNull(this.containerId)||this.containerType==2){return false;}var container=document.getElementById(this.containerId);var parent=container.parentNode;parent.removeChild(container);return true;};function addObject(ns,uid,object,overwrite){if(isUndefined(overwrite)){overwrite=false;}if(isUndefined(gRegArray[ns])){gRegArray[ns]=[];}if(isNull(uid)){do{uid=createUID();}while(!isUndefined(gRegArray[ns][uid]));gRegArray[ns][uid]=object;return uid;}if(isUndefined(gRegArray[ns][uid])){gRegArray[ns][uid]=object;return uid;}else{if(overwrite){delObject(ns,uid);gRegArray[ns][uid]=object;return uid;}else{logMessage("Failed to register "+ns+"/"+uid+" - object already exists",true);return false;}}return false;}function delObject(ns,uid){if(isUndefined(gRegArray[ns])){if(isNull(uid)){return true;}else{return false;}}if(isNull(uid)){while(gRegArray[ns].length>0){try{top=gRegArray[ns].pop();if(isObject(top)&&isFunction(top.onDelete)){top.onDelete();}}catch(e){logMessage("ERROR!!! Unable to remove "+ns+"/"+uid+" from registry: [ "+e+" ]",true);return false;}}return true;}if(isUndefined(gRegArray[ns][uid])){return true;}try{if(isFunction(gRegArray[ns][uid].onDelete)){gRegArray[ns][uid].onDelete();}delete gRegArray[ns][uid];}catch(e){logMessage("ERROR!!! Unable to remove "+ns+"/"+uid+" from registry: [ "+e+" ]",true);return false;}return true;}function getObject(ns,uid){if(isUndefined(gRegArray[ns])){return false;}if(isUndefined(gRegArray[ns][uid])){return false;}return gRegArray[ns][uid];}function getObjectsByNS(ns){if(isUndefined(gRegArray[ns])){gRegArray[ns]=[];}return gRegArray[ns];}function getAllUsersExcept(exceptions){var excSet={};var i;for(i=0;i<exceptions.length;i++){excSet[exceptions[i].id.toString()]=1;}result=[];for(i=0;i<gAllUsers.length;i++){if((typeof excSet[gAllUsers[i].id])=="undefined"){result.push(gAllUsers[i]);}}return result;}function getUser(id){if(id=="-1"){return gCurrentUser;}var user=getObject("USER",id);if(user===false){var shit=new User(id);user=getObject("USER",id);}return user;}function setCurrentUser(id){var theuser=getUser(id);if(gCurrentUser===false||typeof gCurrentUser.username=="undefined"||gCurrentUser.username===""){gCurrentUser=theuser;logMessage("settingcurrentuser - "+id);}else{eval('window.setTimeout( new Function ("setCurrentUser('+id+')"), 50 )');}}function User(id){this.username="";this.email="";var projectObj=getCurrentProject();if(projectObj!==null){for(var player in projectObj.users){if(id==projectObj.users[player].id){this.username=projectObj.users[player].username;break;}}}this.tasks=[];this.id=id;if(addObject("USER",this.id,this,false)!==false){var loader=new XHRObject(this.load,false,this.id);startWaitAnimation();loader.load(gServer,"action=getuser&id="+this.id);}}User.prototype.load=function(xhr,id){stopWaitAnimation();var xhrText=xhr.responseText;var self=getObject("USER",id);if(isError(xhrText)){logError(xhrText);if(extractErrorName(xhrText)=="NOUSER"){self.username="Invalid user";self.email="none";}}else{var xml=xhr.responseXML.documentElement;self.username=getXMLNodeValue(xml,"name");self.email=getXMLNodeValue(xml,"email");self.id=getXMLNodeValue(xml,"id");}};User.prototype.addTask=function(task){this.tasks[task]="1";};User.prototype.delTask=function(task){this.tasks.splice(task,1);};User.prototype.update=function(){var task=null;for(var index in this.tasks){task=getObject("TASK",index);if(task!==false){task.update();}}};function UserWidget(id){this.initWidget();this.username="...";var loader=new XHRObject(this.load,false,this.oid);loader.load(gServer,"action=getuser&id="+id);}UserWidget.inherits(PWidget);UserWidget.prototype.load=function(xhr,oid){var self=getObject("WIDGET",oid);self.update();};UserWidget.prototype.toHTML=function(){if(isFunction(this.username.escapeForHTML())){return(this.username.escapeForHTML());}return this.username.toString().escapeForHTML();};function requestLogin(username,password){if(username===""||password===""||isNull(username)||isNull(password)||isUndefined(username)||isUndefined(password)){return false;}var loader=new XHRObject(null,true);loader.load(gServer,"action=login&u="+username+"&p="+password);var xhr=loader.xhr;if(!isError(xhr.responseText)){logMessage("Login complete with session_id: "+xhr.responseText,true);}else{if(extractErrorName(xhr.responseText)=="NOUSERPASS"){logError(xhr.responseText,true);}else{logError(xhr.responseText,false);}return false;}return true;}function requestLogout(){var loader=new XHRObject(null,true);loader.load(gServer,"action=logout");var xhr=loader.xhr;if(!isError(xhr.responseText)){clearAction();logMessage("Logout",true);document.getElementById("taskArea").innerHTML="";document.getElementById("projectArea").innerHTML="";drawLogoutDialog();}else{logMessage("Logout was unsuccessful (WTF!?)",true);}}function startInvite(inviteDialogWidgetId,email){var invDialog=getObject('WIDGET',inviteDialogWidgetId).process();var loader=new XHRObject(null,true);loader.load(gServer,"action=invite&email="+username);}function getCurrentProject(){if(!gCurrentProject){return null;}var pw=getObject("WIDGET",gCurrentProject);if(pw===null){return null;}return getObject("PROJECT",pw.pid);}function createProjectTag(id){var node=document.createElement("div");node.id="project"+id;node.className="inactiveProject";return node;}function getProject(id){var project=getObject("PROJECT",id);if(project===false){var shit=new Project(id);project=getObject("PROJECT",id);}return project;}function newProject(){drawProjectDialog();logMessage("Creating new project...",true);return;}function loadAllProjects(){pushAction("loadAllProjects");var parseXMLForAllProjects=function(xhr){if(isError(xhr.responseText)){if(extractErrorName(xhr.responseText)=="NOSESSION"){drawLoginDialog();}else{logError(xhr.responseText);}return false;}delObject("PROJECT",null);delObject("TASK",null);xml=xhr.responseXML.documentElement;var pw=false;var pid=false;var projectArea=document.getElementById("projectArea");var projects=xml.firstChild.childNodes;for(var proji=0;proji<projects.length;++proji){pid=projects.item(proji).firstChild.nodeValue;pw=new ProjectWidget(pid);pw=getObject("WIDGET",pw.oid);projectArea.appendChild(createProjectTag(pid));pw.setContainer("project"+pid);}gAllUsers=[];var users=xml.firstChild.nextSibling.childNodes;for(var useri=0;useri<users.length;useri++){gAllUsers.push({id:users[useri].firstChild.firstChild.nodeValue,username:users[useri].firstChild.nextSibling.firstChild.nodeValue});}gLoadedProjects=true;stopWaitAnimation();return true;};var loader=new XHRObject(parseXMLForAllProjects,false);loader.load(gServer,"action=getallprojects");startWaitAnimation();}function Project(id){this.id=id;this.widget="-1";this.tasks=[];this.users=[{id:gCurrentUser.id,username:gCurrentUser.username}];this.title="";this.displaytitle="";this.description="";this.name="";this.responsible_person=gCurrentUser.id;this.url="";this.iseditable=false;this.countAllTasks=0;this.countMyTasks=0;this.version=0;addObject("PROJECT",this.id,this,false);if(this.id!=-2){var loader=new XHRObject(this.load,false,this.id);loader.load(gServer,"action=getproject&id="+this.id);}}Project.prototype.onDelete=function(){if(this.widget!="-1"){delObject("WIDGET",this.widget);}return this;};Project.prototype.newTask=function(){var tw=new TaskWidget(-2);tw=getObject("WIDGET",tw.oid);var thetask=createTaskTag(-2);thetask.onclick=eval("new Function ('"+tw.getThis()+".makeActive();')");document.getElementById("taskArea").insertBefore(thetask,document.getElementById("taskArea").firstChild);tw.setContainer("task"+"-2");tw.edit();pw=getObject("WIDGET",this.widget);window.setTimeout(new Function("focusTaskArea()"),50);return this;};Project.prototype.load=function(xhr,id){var self=getObject("PROJECT",id);if(isError(xhr.responseText)){logError(xhr.responseText);return false;}xml=xhr.responseXML.documentElement;self.title=trim(getXMLNodeValue(xml,"title"));self.displaytitle=trim(shortenText(self.title,55));self.description=trim(getXMLNodeValue(xml,"description"));self.name=getXMLNodeValue(xml,"shortname");self.responsible_person=getXMLNodeValue(xml,"responsible_person");self.url=getXMLNodeValue(xml,"url");self.version=parseInt(getXMLNodeValue(xml,"version"),10);self.iseditable=(getXMLNodeValue(xml,"iseditable")=="true")?true:false;self.tasks=[];var taskIds=xml.getElementsByTagName("tasks").item(0).childNodes;for(var taski=0;taski<taskIds.length;++taski){self.tasks.push(taskIds.item(taski).firstChild.firstChild.nodeValue);if(getXMLNodeValue(taskIds.item(taski),"my")=="true"){self.countMyTasks++;}}self.countAllTasks=taskIds.length;self.users=[];var userIds=xml.getElementsByTagName("users").item(0).childNodes;for(var useri=0;useri<userIds.length;++useri){var u=userIds.item(useri).firstChild;self.users.push({id:u.firstChild.nodeValue,username:u.nextSibling.firstChild.nodeValue});}self.total_tasks_count=taskIds.length;self.my_tasks_count=0;for(var taski2=0;taski2<taskIds.length;++taski2){if(taskIds.item(taski2).firstChild.nextSibling.firstChild.nodeValue=="true"){self.my_tasks_count++;}}self.update();};Project.prototype.reload=function(){var loader=new XHRObject(this.load,false,this.id);loader.load(gServer,"action=getproject&id="+this.id);};Project.prototype.save=function(){var players="";for(var ui=0;ui<this.users.length;ui++){if(players!==""){players+=",";}players+=this.users[ui].id;}parameters={"id":this.id,"title":this.title,"description":this.description,"shortname":this.shortname,"responsible_person":this.responsible_person,"url":this.url,"version":this.version,"players":players};parameters_url="";for(p in parameters){parameters_url+="&"+encodeURIComponent(p)+"="+encodeURIComponent(parameters[p]);}var loader=new XHRObject(function(xhr){if(isError(xhr.responseText)){logError(xhr.responseText);alert("Unable to update project: "+xhr.responseText);alert("Unable to update project: "+extractErrorName(xhr.responseText));}else if(xhr.responseText.substr(0,2)=="OK"){var prj=getCurrentProject();if((typeof prj.version)=="string"){prj.version=parseInt(prj.version,10);}prj.version=prj.version+1;logMessage("Project updated successfully.",true);prj.reload();}else if(!isNaN(parseInt(xhr.responseText,10))){delObject("PROJECT",-2);var pid=parseInt(xhr.responseText,10);var pw=new ProjectWidget(pid);pw=getObject("WIDGET",pw.oid);var projectArea=document.getElementById("projectArea");projectArea.appendChild(createProjectTag(pid));pw.setContainer("project"+pid);pw.makeActive();logMessage("New project created successfully.",true);}else{logMessage("Weird error while updating task: "+xhr.responseText,true);}stopWaitAnimation();},false);loader.load(gServer,"action=updateproject"+parameters_url);logMessage("Updating project",true);startWaitAnimation();return this;};Project.prototype.setContainer=function(widget){this.widget=widget;this.update();};Project.prototype.onDelete=function(){if(this.widget!="-1"){delObject("WIDGET",this.widget);}};Project.prototype.update=function(){if(this.widget=="-1"){return this;}getObject("WIDGET",this.widget).update();return this;};function ProjectWidget(id){this.initWidget();this.pid=id;this.lastTaskNum=0;this.showInfo=false;getProject(this.pid).setContainer(this.oid);}ProjectWidget.inherits(PWidget);ProjectWidget.prototype.toHTML=function(){var prj=getProject(this.pid);var ret="<div onclick='"+this.getThis()+".makeActive()' >";ret+='<div class="controlArea">';if(prj.iseditable){ret+="&diams; ";}if(prj.countMyTasks>0){ret+="<span title='"+i18n.LBL_CountMyTasks+" "+gCurrentUser.username+"'>("+prj.countMyTasks+") </span>";}ret+="<span title='"+i18n.LBL_CountAllTasks+"'>";if(prj.countAllTasks===0){ret+="-";}else{ret+=prj.countAllTasks;}ret+="</span> ";ret+='</div>';ret+='<span title="'+prj.title.escapeForHTML()+'">'+prj.displaytitle.escapeForHTML()+'</span>';ret+="</div>";return ret;};ProjectWidget.prototype.makeInactive=function(){if(gCurrentProject!=this.oid){return this;}var task=false;var project=getProject(this.pid);for(var index in project.tasks){task=getObject("TASK",project.tasks[index]);if(task!==false){if(task.widget!="-1"){delObject("WIDGET",task.widget);}}}this.showInfo=false;gCurrentProject=false;document.getElementById(this.containerId).className="inactiveProject";enableProjectButtons();this.redraw();this.checkNoTasks();return this;};ProjectWidget.prototype.makeActive=function(){if(gCurrentProject==this.oid){return this;}if(gCurrentProject!==false){getObject("WIDGET",gCurrentProject).makeInactive();}this.showInfo=true;gCurrentProject=this.oid;document.getElementById(this.containerId).className="activeProject";enableProjectButtons();var project=getProject(this.pid);var taskNum=project.tasks.length;this.lastTaskNum=taskNum;for(var datask in project.tasks){delObject("TASK",project.tasks[datask]);}project.tasks=[];var loader=new XHRObject(function(xhr,id){if(isError(xhr.responseText)){logError(xhr.responseText,false);return;}else if(typeof xhr.responseXML=="undefined"||typeof xhr.responseXML.documentElement=="undefined"){logMessage("Error loading tasks: "+xhr.responseText,false);return;}var p=getObject("PROJECT",id);var xml=xhr.responseXML.documentElement;for(var task_xml=xml.firstChild;task_xml!==null;task_xml=task_xml.nextSibling){var tid=task_xml.getElementsByTagName("id").item(0).firstChild.nodeValue;var task=new Task(tid,true);p.tasks.push(task.id);task.load({responseText:"OK",responseXML:{documentElement:task_xml}},tid);tw=new TaskWidget(tid);tw=getObject("WIDGET",tw.oid);var thetask=createTaskTag(tid);thetask.onclick=eval("new Function ('"+tw.getThis()+".makeActive();')");document.getElementById("taskArea").appendChild(thetask);tw.setContainer("task"+tid);}getObject("WIDGET",p.widget).checkNoTasks();stopWaitAnimation();},false,project.id);loader.load(gServer,"action=loadalltasks&pid="+encodeURIComponent(project.id));logMessage("Updating project",true);startWaitAnimation();if(taskNum>0){var tw=false;for(var task in project.tasks){tw=new TaskWidget(project.tasks[task]);tw=getObject("WIDGET",tw.oid);var thetask=createTaskTag(project.tasks[task]);thetask.onclick=eval("new Function ('"+tw.getThis()+".makeActive();')");document.getElementById("taskArea").appendChild(thetask);tw.setContainer("task"+project.tasks[task]);}}focusProjectArea();this.redraw();return this;};ProjectWidget.prototype.update=function(){PWidget.prototype.update.apply(this);if(gCurrentProject!=this.oid){return this;}this.makeInactive().makeActive();return this;};ProjectWidget.prototype.redraw=function(){PWidget.prototype.update.apply(this);};ProjectWidget.prototype.checkNoTasks=function(){var area=document.getElementById("taskArea");var p=getProject(this.pid);if(!p.countAllTasks){area.innerHTML="<div id='noTaskArea' class='noTasks'>"+i18n.MSG_NoTasks+"<br />"+"<input id='buttonProjectTaskNew' type='button' />"+"</div>";var original=document.getElementById('buttonTaskNew');var clone=document.getElementById('buttonProjectTaskNew');clone.value=original.value;clone.onclick=function(){var button_task_new=document.getElementById('buttonTaskNew');var no_tasks=document.getElementById('buttonProjectTaskNew').parentNode;no_tasks.parentNode.removeChild(no_tasks);button_task_new.onclick();};}else{var no_tasks=document.getElementById("noTaskArea");if(typeof no_tasks!="undefined"&&no_tasks!==null){area.removeChild(no_tasks);}}};function viewProjectLog(){var cp=getCurrentProject();if(cp!==null){logMessage("TODO: Project history...",true);}}function viewCurrentProject(){var cp=getCurrentProject();if(cp!==null){if(cp.iseditable){drawProjectDialog(cp,true);}else{drawProjectDialog(cp);}}}function editCurrentProject(){var cp=getCurrentProject();if(cp!==null){drawProjectDialog(cp,true);}}function enableProjectButtons(){if(gCurrentProject===false){document.getElementById('buttonProjectHistory').disabled=true;document.getElementById('buttonProjectDetails').disabled=true;document.getElementById('buttonInvite').disabled=true;document.getElementById('buttonFilterAll').disabled=true;document.getElementById('buttonFilterMine').disabled=true;document.getElementById('buttonTaskNew').disabled=true;}else{document.getElementById('buttonProjectDetails').disabled=false;document.getElementById('buttonInvite').disabled=false;document.getElementById('buttonTaskNew').disabled=false;}}function getCurrentTask(){if(!gCurrentTask){return null;}var tw=gCurrentTask;if(tw===null){return null;}return getObject("TASK",tw.tid);}function createTaskTag(id){var node=document.createElement("div");node.id="task"+id;node.className="inactiveTask";return node;}function newTask(){var p=getCurrentProject();if(p===null){logMessage("Error: Trying to create task with no current project.");}p.newTask();}function delTask(uid){var realDel=function(xhr,uid){if(isError(xhr.responseText)){logError(xhr.responseText);}else if(xhr.responseText=="OK"){delObject("WIDGET",uid);}else{logMessage("ARGH. Me no delete task "+uid);}};var loader=new XHRObject(realDel,false,uid);loader.load(gServer,"action=deltask&id="+uid);logMessage("Deleting task "+uid,true);}function getTask(id){var task=getObject("TASK",id);if(task===false){var shit=new Task(id);task=getObject("TASK",id);}return task;}function addTask(byUser,toUser,created,deadline,text,uid,status){var area=document.getElementById("taskArea");if(isNull(area)||isUndefined(area)||!area.innerHTML){return false;}if(isUndefined(uid)||isNull(uid)){uid=createUID();while(document.getElementById(uid)){uid=createUID();}}var container=document.createElement("div");container.id="task"+uid;area.innerHTML+="<div id='task"+uid+"' class='task'></div>";var task=new Task(byUser,toUser,created,deadline,text,uid,status);getObject("WIDGET",task.oid).setContainer("task"+uid);return true;}function Task(id,dont_load){this.by="-1";this.to="-1";this.createDate=new Date();this.endDate=makeFriendlyDate(new Date());this.entitled="";this.displaytitle="";this.text="";this.answer="";this.id=id;this.widget="-1";this.version=0;this.isdeleted=0;this.hours=0;this.hoursdone=0;this.isdone=0;this.status="";this.myrole=0;if(addObject("TASK",this.id,this,false)!==false&&dont_load!==true){var loader=new XHRObject(this.load,false,this.id);loader.load(gServer,"action=gettask&id="+this.id);}}Task.prototype.load=function(xhr,id){var self=getObject("TASK",id);var xhrText=xhr.responseText;if(isError(xhrText)){logError(xhrText,false);}else{var xml=xhr.responseXML.documentElement;self.by=getXMLNodeValue(xml,"from");self.to=getXMLNodeValue(xml,"to");self.createDate=sqlDate(getXMLNodeValue(xml,"created"));self.endDate=sqlDate(getXMLNodeValue(xml,"deadline"));self.entitled=trim(getXMLNodeValue(xml,"title"));self.displaytitle=trim(shortenText(self.entitled,35));self.text=trim(getXMLNodeValue(xml,"text"));self.answer=trim(getXMLNodeValue(xml,"answer"));self.hours=getXMLNodeValue(xml,"hours")+""+i18n.LBL_hourStr;self.hoursdone=getXMLNodeValue(xml,"hoursdone")+""+i18n.LBL_hourStr;self.isdone=getXMLNodeValue(xml,"isdone");self.status=getXMLNodeValue(xml,"status");self.version=parseInt(getXMLNodeValue(xml,"version"),10);self.myrole=parseInt(getXMLNodeValue(xml,"myrole"),10);self.update();}};Task.prototype.update=function(){if(this.widget!="-1"){getObject("WIDGET",this.widget).update();}return this;};Task.prototype.save=function(){logMessage("Sending save task request...",true);parameters={"project_id":getCurrentProject().id,"id":this.id,"creator_id":this.by,"assignee_id":this.to,"title":this.entitled,"deadline":this.endDate,"text":this.text,"answer":this.answer,"hours":this.hours,"hoursdone":this.hoursdone,"isdone":this.isdone,"status":this.status,"version":this.version,"isdeleted":this.isdeleted};parameters_url="";for(p in parameters){parameters_url+="&"+encodeURIComponent(p)+"="+encodeURIComponent(parameters[p]);}var loader=new XHRObject(function(xhr,task_id){if(isError(xhr.responseText)){logError(xhr.responseText);alert("Unable to update task: "+xhr.responseText);}else if(xhr.responseText=="OK"){var t=getTask(task_id);if(task_id==-2){delObject("TASK",t.id);gCurrentTask=false;getCurrentProject().reload();logMessage("Reloading project to display new task properly...",true);return false;}if((typeof t.version)=="string"){t.version=parseInt(t.version,10);}t.version=t.version+1;var w=getObject("WIDGET",t.widget);if(t.isdeleted){t.onDelete();}else if(w.editing){w.showInfo=true;w.editing=false;w.update();}logMessage("Task updated successfully.",true);}else{logMessage("Weird error while updating task",true);}},false,this.id);loader.load(gServer,"action=updatetask"+parameters_url);return this;};Task.prototype.setContainer=function(widget){this.widget=widget;this.update();};Task.prototype.setStatus=function(status){this.status=status;this.save();this.update();};Task.prototype.onDelete=function(){if(this.widget!="-1"){delObject("WIDGET",this.widget);}};Task.prototype.isVisible=function(){return this.widget!="-1";};Task.prototype.removeWithConfirm=function(){if(!confirm(i18n.MSG_ConfirmDel)){return;}this.remove();};function TaskWidget(id){this.initWidget();this.showInfo=false;this.editing=false;if(typeof id=="undefined"||id==-2){this.tid=-2;this.editing=true;this.showInfo=true;}else{this.tid=id;}var task=getTask(this.tid);if(task.widget=="-1"){task.setContainer(this.oid);}else{logMessage("Trying to assign task "+this.tid+" to TaskWidget "+this.oid+", but it is already assigned to TaskWidget "+task.widget,true);}}TaskWidget.inherits(PWidget);TaskWidget.prototype.toHTML=function(){var task=getTask(this.tid);var hasAnswer=(task.answer.replace(/ /g,"")==="")?false:true;var isNew=(this.tid==-2)?true:false;var amCreator=(isNew||task.myrole==2||task.myrole==1)?true:false;var amAssignee=(task.myrole==3||task.myrole==1)?true:false;var info="";if(this.editing){info+="<form id='task_edit' name='task_edit' action='#' onsubmit='"+this.getThis()+".save(); return false;' onreset='"+this.getThis()+".toggleHilite(); return false;' method='get'>";}info+="<table>";var moreInfo="";if(this.editing&&((amCreator||amAssignee)||isNew)){info+="<tr>";info+="<th rowspan='4' class='colDisclose'>";info+="<img src='images/disclose_shown.gif' alt='-' />";info+="</th>";info+="<th class='colStatus'>";info+="<select tabindex='1' onclick='cancelBubble();' id='taskedit_status' onchange='"+this.getThis()+".changeStatus(this.value);'>"+drawTaskStatus(task.status)+"</select>";info+="</th>";info+="<th colspan='4' style='width: 100%;'>";info+="<div style='float:right'>";if(amCreator){info+="<input tabindex='3' type='text' class='dateField' id='taskedit_end' value='"+makeFriendlyDate(task.endDate)+"' /> ";}else{info+=makeFriendlyDate(task.endDate)+" ";}info+="<input type='button' disabled='disabled' onclick='"+this.getThis()+".edit();' value='"+i18n.BTN_TaskEdit+"' />";info+="</div>";if(amCreator){info+="<div class='taskViewTitleEx'><input tabindex='2' type='text' style='width:60%;' id='taskedit_title' value='"+task.entitled.escapeForHTML()+"' /></div>";}else{info+="<div class='taskViewTitle' title='"+task.entitled.escapeForHTML()+"'>"+task.displaytitle.escapeForHTML()+"</div>";}info+="</th>";info+="</tr>";info+="<tr>";info+="<td colspan='2' rowspan='2' class='taskMark'>";if(amCreator){info+="<input tabindex='13' onclick='"+this.getThis()+".markDone();' id='task_valid' type='button' value='"+i18n.BTN_MarkDone+"' /><br />";info+="<a href='javascript:void(0)' onclick='"+this.getThis()+".erase();'>"+i18n.BTN_TaskDel+"</a>";}info+="</td>";info+="<td class='colEdit'>";if(amCreator){info+="<select tabindex='4' id='taskedit_from' name='taskedit_from'> "+drawUserSelectOption(getUser(task.by).id)+"</select>";info+="<input tabindex='5' id='taskedit_hours' onclick='this.select();' type='text' class='fieldHours' value='"+task.hours+"' size='5' />";}else{info+=i18n.LBL_TaskFrom+" "+getUser(task.by).username.escapeForHTML();info+=", "+task.hours;}info+="</td>";info+="<td>&nbsp;</td>";info+="<td class='colEdit'>";info+="<select tabindex='6' id='taskedit_to'>"+drawUserSelectOption(getUser(task.to).id)+"</select>";if(amAssignee){info+="<input tabindex='7' onmouseup='addHoursDone(-0.5);' style='width: 24px;' type='button' value='-'";info+="/><input tabindex='8' id='taskedit_hoursdone' onclick='this.select();' type='text' class='fieldHours' value='"+task.hoursdone+"' size='5'";info+="/><input tabindex='9' onmouseup='addHoursDone(0.5);' style='width: 24px;' type='button' value='+' />";}else if(task.hoursdone!="0h"){info+=" "+task.hoursdone;}info+="</td>";info+="</tr>";info+="<tr>";if((amCreator&&amAssignee)||(amCreator&&task.answer==="")){info+="<td colspan='3' class='colEditAlone'>";info+="<textarea tabindex='10' id='taskedit_text' class='fieldEdit' rows='5' cols='5'>"+htmlToTextLines(task.text.escapeForHTML())+"</textarea>";info+="<input type='hidden' id='taskedit_text' value='"+task.answer.escapeForHTML()+"' />";}else{info+="<td class='colEdit'>";if(amCreator){info+="<textarea tabindex='11' id='taskedit_text' class='fieldEdit' rows='5' cols='5'>"+htmlToTextLines(task.text.escapeForHTML())+"</textarea>";}else{info+="<div>"+htmlToTextLines(task.text.escapeForHTML())+"</div>";}info+="</td>";info+="<td>&nbsp;</td>";info+="<td class='colEdit'>";if(amAssignee){info+="<textarea tabindex='12' id='taskedit_answer' class='fieldEdit' rows='5' cols='5'>"+htmlToTextLines(task.answer.escapeForHTML())+"</textarea>";}else{info+="<div>"+task.answer.escapeForHTML()+"</div>";}}info+="</td>";info+="</tr>";info+="<tr>";info+="<td colspan='6' class='taskControl'>";info+="<input tabindex='14' type='submit' value='"+i18n.BTN_SaveTask+"' />&nbsp;";info+="<input tabindex='15' type='reset' value='"+i18n.BTN_Cancel+"' />";info+="</td>";info+="</tr>";info+="<tr><td colspan='6'>&nbsp;</td></tr>";}else{info+="<tr>";info+="<th rowspan='3' class='colDisclose'>";if(this.showInfo){info+="<img src='images/disclose_shown.gif' onclick='"+this.getThis()+".toggleHilite();'  alt='-' />";}else{info+="<img src='images/disclose_hidden.gif' onclick='"+this.getThis()+".toggleHilite();'  alt='+' />";}info+="</th>";info+="<th class='colStatus'>";if(amCreator||amAssignee){info+="<select onclick='cancelBubble();' onchange='"+this.getThis()+".changeStatus(this.value);'>"+drawTaskStatus(task.status)+"</select>";}else{info+="<select disabled='disabled'>"+drawTaskStatus(task.status)+"</select>";}info+="</th>";info+="<th colspan='4' style='width: 100%;'>";info+="<div style='float:right'>";info+=makeFriendlyDate(task.endDate)+" ";if(amCreator||amAssignee){info+="<input type='button' onclick='"+this.getThis()+".edit();' value='"+i18n.BTN_TaskEdit+"' />";}else{info+="<input type='button' disabled='disabled' value='"+i18n.BTN_TaskEdit+"' />";}info+="</div>";if(this.showInfo){info+="<div class='taskViewTitleEx'>"+task.entitled.escapeForHTML()+"</div>";}else{info+="<div class='taskViewTitle' title='"+task.entitled.escapeForHTML()+"'>"+task.displaytitle.escapeForHTML()+"</div>";}info+="</th>";info+="</tr>";moreInfo+="<tr>";moreInfo+="<td colspan='2' rowspan='2' class='taskMark'>";if(amCreator){moreInfo+="<input name='task_valid' onclick='"+this.getThis()+".markDone();' type='button' value='"+i18n.BTN_MarkDone+"' /><br />";}moreInfo+="</td>";moreInfo+="<th class='colEdit'>";moreInfo+=i18n.LBL_TaskFrom+" "+getUser(task.by).username.escapeForHTML();if(task.hours!="0h"){moreInfo+=", "+task.hours;}moreInfo+="</th>";moreInfo+="<td>&nbsp;</td>";moreInfo+="<th class='colEdit'>";moreInfo+=i18n.LBL_TaskTo+" "+getUser(task.to).username.escapeForHTML();if(task.hoursdone!="0h"){moreInfo+=", "+task.hoursdone;}moreInfo+="</th>";moreInfo+="</tr>";moreInfo+="<tr>";moreInfo+="<td class='colEdit'";if(!hasAnswer){moreInfo+=" colspan='3' ";}moreInfo+=">";moreInfo+=task.text.escapeForHTML();moreInfo+="</td>";if(hasAnswer){moreInfo+="<td>&nbsp;</td>";moreInfo+="<td class='colEdit'>";moreInfo+=task.answer.escapeForHTML();moreInfo+="</td>";}moreInfo+="</tr>";moreInfo+="<tr><td colspan='6'>&nbsp;</td></tr>";}if(this.showInfo){info+=moreInfo;}info+="</table>";if(this.editing){info+="</form>";}return(info);};TaskWidget.prototype.toggleHilite=function(){if(this.tid==-2){this.remove();}var taskContainer=document.getElementById(this.containerId);if(taskContainer===null){return;}taskContainer.parentNode.onclick();if(this.showInfo){this.showInfo=false;this.editing=false;this.update();}else{this.showInfo=true;this.update();}if(gCurrentTask!=this){this.makeActive();}};TaskWidget.prototype.changeStatus=function(newStatus){if(gCurrentTask==this&&this.editing){return;}var task=getTask(this.tid);if(task.status!=newStatus){task.setStatus(newStatus);}};TaskWidget.prototype.toggleCompleted=function(){var task=getTask(this.tid);if(task.status=="1"){task.setStatus("2");}else{task.setStatus("1");}this.update();return this;};TaskWidget.prototype.remove=function(){if(typeof gCurrentTask=="object"&&gCurrentTask.oid==this.oid){gCurrentTask=false;}delObject("WIDGET",this.oid);var project_widget=getObject("WIDGET",getCurrentProject().widget);project_widget.checkNoTasks();return this;};TaskWidget.prototype.edit=function(){document.getElementById(this.containerId).parentNode.onclick();this.editing=true;this.makeActive();this.update();return this;};TaskWidget.prototype.onDelete=function(){PWidget.prototype.onDelete.apply(this);getTask(this.tid).setContainer("-1");};TaskWidget.prototype.hilightStart=function(){document.getElementById(this.containerId).className="activeTask";};TaskWidget.prototype.hilightStop=function(){document.getElementById(this.containerId).className="inactiveTask";};TaskWidget.prototype.makeActive=function(){if(gCurrentTask==this){return;}this.showInfo=true;if(gCurrentTask!==false){if(gCurrentTask.tid==-2){gCurrentTask.remove();}else{gCurrentTask.makeInactive();}}this.hilightStart();gCurrentTask=this;this.update();};TaskWidget.prototype.makeInactive=function(){this.showInfo=false;this.editing=false;var taskContainer=document.getElementById(this.containerId);if(taskContainer===null){return;}this.hilightStop();gCurrentTask=false;this.update();};TaskWidget.prototype.save=function(){logMessage("Preparing save...",true);var task=getTask(this.tid);task.id=this.tid;task.by=getValue(document.getElementById('taskedit_from'));task.to=getValue(document.getElementById("taskedit_to"));task.entitled=getValue(document.getElementById("taskedit_title"));task.endDate=makeDate(convertToDate(getValue(document.getElementById("taskedit_end"))));task.text=getValue(document.getElementById("taskedit_text"));task.answer=getValue(document.getElementById("taskedit_answer"));task.hours=getValue(document.getElementById("taskedit_hours"));task.hoursdone=getValue(document.getElementById("taskedit_hoursdone"));task.status=getValue(document.getElementById("taskedit_status"));task.save();task.endDate=makeFriendlyDate(convertToDate(getValue(document.getElementById("taskedit_end"))));};TaskWidget.prototype.erase=function(){var task=getTask(this.tid);if(confirm(i18n.MSG_DelTask+'\n"'+task.entitled+'"?')){task.isdeleted=true;task.save();}};TaskWidget.prototype.markDone=function(){if(confirm(i18n.MSG_ConfirmDone)){}};TaskWidget.prototype.update=function(){PWidget.prototype.update.apply(this);var taskedit_end=document.getElementById("taskedit_end");if(taskedit_end!==null){taskedit_end.onclick=function(){taskedit_end.value=makeDate(convertToDate(taskedit_end.value));if(calendar===null){calendar=new CalendarPopup();calendar.showNavigationDropdowns();calendar.setWeekStartDay(1);calendar.setReturnFunction("calendar_return_function");}calendar.select(taskedit_end,'taskedit_end','yyyy-MM-dd');return false;};}var taskTitle=document.getElementById('taskedit_title');if(typeof taskTitle=='undefined'||taskTitle===null){return;}else{taskTitle.focus();}};function calendar_return_function(year,month,day){var taskedit_end=document.getElementById("taskedit_end");taskedit_end.value=makeFriendlyDate(convertToDate(year+"-"+month+"-"+day));}function drawTaskStatus(statusCode){var statz=[1,2,3];var echo="";for(var i=1;i<=statz.length;i++){echo+='<option value="'+i+'" ';if(i==statusCode){echo+='selected="selected" ';}echo+='>';echo+=i18n["LBL_Task_Status_"+i];echo+='</option>';}return(echo);}function showTaskStatus(statusCode){var statusMsg=i18n["LBL_Task_Status_"+statusCode];if(typeof statusMsg=="undefined"){return"";}return i18n["LBL_Task_Status_"+statusCode];}function htmlToTextLines(str){return str.replace(/<br \/>/g,"\n");}function addHoursDone(timespan){var hd=document.getElementById('taskedit_hoursdone');if(typeof hd=='undefined'||hd===null){return;}var time=hd.value;time=time.replace(/h/g,"");time=parseFloat(time)+parseFloat(timespan);if(time>=0){hd.value=time+"h";}}function drawModalDialog(widget){var curtains=document.getElementById("curtains");if(isNull(curtains)||isUndefined(curtains)){curtains=document.createElement("div");curtains.id="curtains";curtains.className="curtains";document.body.appendChild(curtains);}curtains.style.display="block";var dialogArea=document.getElementById("modalDialogArea");if(isNull(dialogArea)||isUndefined(dialogArea)){dialogArea=document.createElement("div");dialogArea.className="dialogContents";dialogArea.id="modalDialogArea";document.body.appendChild(dialogArea);}widget.onDelete=function(){blockSelection();displaySelectElements(true);fixOverflowBug(false);document.getElementById("curtains").style.display="none";document.getElementById("modalDialogArea").style.display="none";};dialogArea.style.display="block";widget.setContainer("modalDialogArea",1);blockSelection(false);displaySelectElements(false);fixOverflowBug(true);}function drawLoginDialog(){var loginDialog=new LoginWidget();loginDialog=getObject("WIDGET",loginDialog.oid);loginDialog.onSuccessfulLogin=function(){popAction();this.onDismiss();};loginDialog.onDismiss=function(){delObject("WIDGET",this.oid);};drawModalDialog(loginDialog);document.getElementById("text"+loginDialog.oid).focus();}function drawLogoutDialog(){var logoutDialog=new LogoutWidget();logoutDialog=getObject("WIDGET",logoutDialog.oid);logoutDialog.onDismiss=function(){delObject("WIDGET",this.oid);};drawModalDialog(logoutDialog);}function showErrorDialog(errorCode){var errorDialog=new ErrorWidget(i18n['ERR_'+errorCode]);errorDialog=getObject("WIDGET",errorDialog.oid);errorDialog.onDismiss=function(){delObject("WIDGET",this.oid);};drawModalDialog(errorDialog);}function drawProjectDialog(prj,edit){var projectDialog;if(typeof edit=="undefined"){edit=false;}else{edit=true;}if(typeof prj!="undefined"&&prj){projectDialog=new ProjectEditWidget(prj.id);}else{projectDialog=new ProjectEditWidget();}projectDialog=getObject("WIDGET",projectDialog.oid);drawModalDialog(projectDialog);if(edit){projectDialog.onEdit();}}function LoginWidget(){this.initWidget();this.wrongUP=false;}LoginWidget.inherits(PWidget);LoginWidget.prototype.toHTML=function(){var contents='<div class="dialogArea">';contents+='<form action="#" onsubmit="getObject( \'WIDGET\', \''+this.oid+'\' ).onLogin();return false;">';if(this.wrongUP){contents+='<div class="error"><img src="images/alert.png" /></div>';}else{contents+='<div class="error"><img src="images/pavilion.png" /></div>';}contents+='<h2 class="dialogTitle">'+i18n.MSG_Auth_req+'</h2>';contents+='<p>'+i18n.LBL_Username+' <input type="text" id="text'+this.oid+'" class="textField" value="" /></p>';contents+='<p>'+i18n.LBL_Password+' <input type="password" id="pass'+this.oid+'" class="textField" value="" /></p>';contents+='<div class="controlArea">';contents+='<input type="submit" value="'+i18n.BTN_Login+'" />';contents+='<input type="button" onclick="getObject( \'WIDGET\', \''+this.oid+'\' ).onDismiss()" value="'+i18n.BTN_Cancel+'" /></div>';contents+='</form>';contents+='</div>';return contents;};LoginWidget.prototype.onLogin=function(){var username=document.getElementById("text"+this.oid).value;var password=document.getElementById("pass"+this.oid).value;if(requestLogin(username,password)){this.onSuccessfulLogin();}else{this.onUnsuccessfulLogin();}};LoginWidget.prototype.onSuccessfulLogin=function(){alert("The 'onSuccessfulLogin' method should be redefined!");return this;};LoginWidget.prototype.onUnsuccessfulLogin=function(){this.setWrongUP();return this;};LoginWidget.prototype.setWrongUP=function(){if(this.wrongUP===false){this.wrongUP=true;this.update();}return this;};function LogoutWidget(){this.initWidget();this.wrongUP=false;}LogoutWidget.inherits(LoginWidget);LogoutWidget.prototype.toHTML=function(){var contents='<div class="dialogArea">';contents+='<form action="#" onsubmit="getObject( \'WIDGET\', \''+this.oid+'\' ).onDismiss();drawLoginDialog();return false;">';contents+='<div class="error"><img src="images/pavilion.png" /></div>';contents+='<h2 class="dialogTitle">'+i18n.MSG_Bye+'</h2>';contents+='<div class="controlArea">';contents+='<input type="submit" value="'+i18n.BTN_Login+'..." />';contents+='</form>';contents+='</div>';return contents;};function ErrorWidget(errorMessage){this.initWidget();this.errorMessage=errorMessage;}ErrorWidget.inherits(PWidget);ErrorWidget.prototype.toHTML=function(){var contents='';contents+='<div class="dialogArea"><form action="#" onsubmit="getObject( \'WIDGET\', \''+this.oid+'\' ).onDismiss();return false;">';contents+='<div class="error"><img src="images/alert.png" /></div>';contents+='<br /><p>'+this.errorMessage+'</p>';contents+='<div class="contolArea"><input type="submit" value="'+i18n.BTN_OK+'" /></div>';contents+='</form></div>';return contents;};function ProjectEditWidget(pid){this.editing=false;this.error=false;if(typeof pid=="undefined"){pid=-2;this.editing=true;}this.pid=pid;this.initWidget();}ProjectEditWidget.inherits(PWidget);ProjectEditWidget.prototype.toHTML=function(){var prj=getProject(this.pid);var contents="";var url="";contents+='<div class="dialogArea">';contents+='<form action="#" onsubmit="getObject( \'WIDGET\', \''+this.oid+'\' ).onDismiss();return false;">';if(this.editing){if(this.error){contents+='<img src="images/alert.png" />';}else if(this.pid==-2){contents+='<h2>'+i18n.BTN_ProjectNew+'</h2>';}else{contents+='<br />';}contents+='<p><input style="width: 96%;" type="text" id="projectedit_title" value="'+prj.title+'" /></p>';contents+='<fieldset><legend>Info</legend>';contents+='<p title="Project description"><textarea id="projectedit_description" style="width: 100%; height: 100px;" name="">'+prj.description+'</textarea></p>';url=(prj.url==="")?"http://":prj.url;contents+='<p title="URL of the project">';contents+='<input id="projectedit_url" style="width: 100%;" type="text" name="" value="'+url+'" /></p>';contents+='</fieldset>';contents+='<fieldset><legend>Participants</legend>';contents+='<div style=" clear:both;">';contents+='<div style="float: left;">';contents+='<div class="maximumSelect" style="width: 130px; padding-bottom: 10px;" title="Responsible person">';contents+='<select id="projectedit_responsible">'+drawUserSelectOption(prj.responsible_person)+"</select>";contents+='</div>';contents+='<select id="projectedit_players" ondblclick="removeProjectUser();" id="projectUsers" style="width: 130px;" size="5">';contents+=drawManyUsersSelectOptions(prj.users);contents+='</select>';contents+='</div>';contents+='<div style="float: right;">';contents+='<select id="projectedit_users" ondblclick="addProjectUser();" style="width: 130px;" size="7">';contents+=drawManyUsersSelectOptions(getAllUsersExcept(prj.users));contents+='</select>';contents+='</div>';contents+='<br /><br /><input type="button" onclick="removeProjectUser();" name="" value="  &gt;  " />';contents+='<br /><br /><input type="button" onclick="addProjectUser();" name="" value="  &lt;  " />';contents+='<div>';contents+='</div>';contents+='</div>';contents+='</fieldset>';contents+='<div class="controlArea"><input type="button" onclick="getObject( \'WIDGET\', \''+this.oid+'\' ).onSave()" value="'+i18n.BTN_SaveProject+'" />';}else{contents+='<h2>'+prj.title+'</h2>';contents+='<div style="padding-bottom: 20px;">'+prj.description+'</div>';url=(prj.url!=="")?"<a href='"+prj.url+"'>"+prj.url+"</a>":"";contents+='<div>'+url+'</div>';var theusers="";for(var u=0;u<prj.users.length;u++){theusers+=(prj.users[u].username);if(u<prj.users.length-1){theusers+=", ";}}if(theusers!==""){theusers="Participants:"+theusers;}contents+='<div>Managed by: '+getUser(prj.responsible_person).username+'</div>';contents+='<div>'+theusers+'</div>';contents+='<a href="javascript:logMessage(\'TODO: invite participant to project ....\',true)">Invite someone</a>';contents+='<div class="controlArea">';}contents+='&nbsp; <input type="submit" value="'+i18n.BTN_Cancel+'" />';contents+='</div>';contents+='</form></div>';return contents;};ProjectEditWidget.prototype.onEdit=function(){this.editing=true;this.update();};ProjectEditWidget.prototype.onDismiss=function(){delObject("WIDGET",this.oid);};ProjectEditWidget.prototype.onSave=function(){var p=getProject(this.pid);p.title=getValue(document.getElementById("projectedit_title"));p.description=getValue(document.getElementById("projectedit_description"));p.responsible_person=getValue(document.getElementById("projectedit_responsible"));p.url=getValue(document.getElementById("projectedit_url"));if(p.url=="http://"){p.url="";}var players=document.getElementById("projectedit_players").options;var new_users=[];for(var i=0;i<players.length;i++){new_users.push({id:players[i].value,username:players[i].text});}p.users=new_users;if(p.title===""||p.description===""){this.error=true;this.update();return false;}else{this.error=false;}p.save();this.onDismiss();};function removeProjectUser(){var allU=document.getElementById('projectedit_users');var prjU=document.getElementById('projectedit_players');moveSelectedOptions(prjU,allU);if(prjU.length>0){prjU.options[0].selected=true;}}function addProjectUser(){var allU=document.getElementById('projectedit_users');var prjU=document.getElementById('projectedit_players');moveSelectedOptions(allU,prjU);if(allU.length>0){allU.options[0].selected=true;}}function drawInviteDialog(){var inviteDialog=new InviteWidget();inviteDialog=getObject("WIDGET",inviteDialog.oid);inviteDialog.onDismiss=function(){delObject("WIDGET",this.oid);};drawModalDialog(inviteDialog);}function InviteWidget(){this.sentScreen=false;this.initWidget();}InviteWidget.inherits(PWidget);InviteWidget.prototype.toHTML=function(){var contents='';var cp=getCurrentProject();if(this.sentScreen){contents+='<div class="dialogArea">';contents+='<h2>This feature will be implemented soon</h2>';contents+='<p>Thank you for your patience.</p>';contents+='<input type="button" value="'+i18n.BTN_OK+'" onclick="getObject( \'WIDGET\', \''+this.oid+'\').onDismiss();" />';contents+='</div>';}else{contents+='<div class="dialogArea"><form action="#" onsubmit="getObject( \'WIDGET\', \''+this.oid+'\' ).send();return false;">';contents+='<br />';contents+='<fieldset><legend>'+i18n.MSG_InviteTitle+'</legend>';contents+='<h2>'+cp.title+'</h2>';contents+='<p>'+i18n.LBL_Email+' <input id="invite_email" style="width: 200px;" type="text" name="" value="" /></p>';contents+='</fieldset>';contents+='<div class="contolArea"><br /><input type="submit" value="'+i18n.BTN_Invite+'" />';contents+='&nbsp; <input type="button" value="'+i18n.BTN_Cancel+'" onclick="getObject( \'WIDGET\', \''+this.oid+'\' ).onDismiss();" /></div>';contents+='</form></div>';}return contents;};InviteWidget.prototype.send=function(){this.sentScreen=true;var mailto=document.getElementyById("invite_email").value;startInvite(this.oid,mailto);this.update();};InviteWidget.prototype.process=function(){alert("PROCESSING RESULT");};function startWaitAnimation(){document.getElementById('waitIndicator').src="images/wait_animation.gif";}function stopWaitAnimation(){document.getElementById('waitIndicator').src="images/wait_still.gif";}function PanelResize(objName){if(!gAllowResizing){return false;}this.dragging=false;this.upStop=null;this.downStop=null;this.incarnation=document.getElementById(objName);this.panelProjects=document.getElementById("projectArea");this.panelTasks=document.getElementById("taskArea");if(!this.incarnation||!this.panelProjects||!this.panelTasks){return false;}this.totalHeight=gTotalPanelHeight;this.lastY=-1;this.incarnation.onmousedown=this.startResize.bind(this);}PanelResize.prototype.startResize=function(e){this.incarnation.className="gripperLineDrag";document.onmouseup=this.stopResize.bind(this);document.onmousemove=this.goDrag.bind(this);var prj=this.panelProjects;var tsk=this.panelTasks;prj.style.height=fixClientHeight(prj.clientHeight,prj)+"px";tsk.style.height=fixClientHeight(tsk.clientHeight,tsk)+"px";this.dragging=true;};PanelResize.prototype.stopResize=function(e){document.onmouseup=null;document.onmousemove=null;document.onselectstart=null;this.incarnation.className="gripperLine";if(this.dragging){var bh=document.body.clientHeight;var ph=this.panelProjects.clientHeight;var th=this.panelTasks.clientHeight;ph=Math.ceil(ph/bh*100)+0.5;th=this.totalHeight-ph;this.panelProjects.style.height=ph+"%";this.panelTasks.style.height=th+"%";}this.dragging=false;this.upStop=null;this.downStop=null;saveUIState();};PanelResize.prototype.goDrag=function(e){var y=window.event.clientY;var prj=this.panelProjects;var tsk=this.panelTasks;var pmin=60;var tmin=80;var ph=stripPX(prj.style.height);var th=stripPX(tsk.style.height);if(this.lastY==-1){this.lastY=y;}var step=y-this.lastY;if(ph+step<pmin){step=pmin-ph;}if(th-step<tmin){step=th-tmin;}if(ph+step>pmin&&th-step>tmin){prj.style.height=(ph+step)+"px";tsk.style.height=(th-step)+"px";this.lastY=y;}};function blockSelection(prevent){if(gAllowTextSelect){return false;}if(typeof prevent!="undefined"&&prevent===false){if(typeof document.onselectstart!="undefined"){document.onselectstart=null;}else{document.onmousedown=null;document.onmouseup=null;}}else{if(typeof document.onselectstart!="undefined"){document.onselectstart=disableselect;}else{document.onmousedown=disableselect;document.onmouseup=new Function("return true");}}}function disableselect(e){var omitformtags="input|textarea|select";var etarget=(typeof e=="undefined"||typeof e.target=="undefined")?window.event.srcElement:e.target;if(typeof etarget.tagName!="undefined"&&omitformtags.indexOf(etarget.tagName.toLowerCase())==-1){return false;}else{return true;}}function goCaptureEvents(){if(document.addEventListener){document.addEventListener("mousedown",function(e){window.event=e;},true);document.addEventListener("mouseup",function(e){window.event=e;},true);document.addEventListener("mousemove",function(e){window.event=e;},true);document.addEventListener("click",function(e){window.event=e;},true);document.addEventListener("keydown",function(e){window.event=e;},true);}}function cancelBubble(){if(typeof window.event.stopPropagation=="function"){window.event.stopPropagation();}else{window.event.cancelBubble=true;}return false;}function focusProjectArea(){document.getElementById('taskArea').className='taskArea';document.getElementById('projectArea').className='projectAreaHi';}function focusTaskArea(){document.getElementById('taskArea').className='taskAreaHi';document.getElementById('projectArea').className='projectArea';}function loadUIState(){if(!gLoadedProjects){window.setTimeout(loadUIState,100);return false;}pushAction("loadUIState");var loader=new XHRObject(function(xhr){if(isError(xhr.responseText)){if(extractErrorName(xhr.responseText)=="NOSESSION"){drawLoginDialog();}else{logError(xhr.responseText);}return false;}if(xhr.responseXML===null){logError("Bad UI state is returned.");}xml=xhr.responseXML.documentElement;setCurrentUser(getXMLNodeValue(xml,"uid"));var project_id=getXMLNodeValue(xml,"project");var task_id=getXMLNodeValue(xml,"task");var gripper_project=getXMLNodeValue(xml,"gripper-project");var gripper_task=gTotalPanelHeight-gripper_project;var gripper=new PanelResize("gripperLine");restoreSelection(project_id,task_id);if((gripper_project>0&&gripper_task>0)&&gAllowResizing){document.getElementById('projectArea').style.height=gripper_project+"%";document.getElementById('taskArea').style.height=gripper_task+"%";gripper.totalHeight=parseFloat(gripper_project)+parseFloat(gripper_task);}clearAction();},false);loader.load(gServer,"action=getstate");logMessage("State is loading",true);}function saveUIState(){var parameters="";var p=getCurrentProject();if(p!==null){parameters+="&project_id="+p.id;}var t=getCurrentTask();if(t!==null){parameters+="&task_id="+t.id;}var ph=parseFloat(document.getElementById('projectArea').style.height);var th=gTotalPanelHeight-ph;if(ph+th<100){parameters+="&gripper_project="+ph;parameters+="&gripper_task="+th;}var loader=new XHRObject(function(xhr){if(xhr.responseText!="OK"){alert(1);}},false);loader.load(gServer,"action=setstate"+parameters);logMessage("State is saving",true);}var crc=20;function restoreSelection(prj,tsk){var cycle=200;crc--;if(crc<0){logMessage("Restore state - unsuccessful. Giving up.",true);return;}if(gCurrentProject===false){var p=getProject(prj);if(p!==null){p=getObject("WIDGET",p.widget);}else{eval("window.setTimeout(function () {restoreSelection("+prj+", "+tsk+")}, "+cycle+")");return;}if(p){p.makeActive();}else{eval("window.setTimeout(function () {restoreSelection("+prj+", "+tsk+")}, "+cycle+")");return;}focusProjectArea();}if(gCurrentTask===false){var t=getTask(tsk);if(t!==null){t=getObject("WIDGET",t.widget);}else{eval("window.setTimeout(function () {restoreSelection("+prj+", "+tsk+")}, "+cycle+")");return;}if(t){t.makeActive();}else{eval("window.setTimeout(function () {restoreSelection("+prj+", "+tsk+")}, "+cycle+")");return;}focusTaskArea();}}function fixOverflowBug(setHidden){var of="auto";if(setHidden){of="hidden";}document.getElementById('taskArea').style.overflow=of;document.getElementById('projectArea').style.overflow=of;}function fixClientHeight(clientHeight,obj){if(obj.currentStyle){return(obj.clientHeight+stripPX(obj.currentStyle.borderWidth)*2);}else{return(clientHeight);}}function displaySelectElements(show){if(typeof document.body.currentStyle=="undefined"){return;}var selz=document.getElementsByTagName("select");var viz=(typeof show!="undefined"&&show===true)?"visible":"hidden";for(var i=0;i<selz.length;i++){selz[i].style.visibility=viz;}}function processKeys(){var omitformtags="input|textarea|select";var etarget=(typeof event.srcElement=="undefined")?event.target:event.srcElement;var ct=getCurrentTask();switch(event.keyCode){case 49:if(event.ctrlKey){newTask();cancelBubble();return false;}break;case 13:if(ct===false||ct===null||typeof ct.widget=="undefined"){return true;}ct=getObject("WIDGET",ct.widget);if(event.ctrlKey){if(ct.editing){ct.save();cancelBubble();return false;}}else if(ct.editing===false&&omitformtags.indexOf(etarget.tagName.toLowerCase())==-1){ct.edit();cancelBubble();return false;}break;case 27:if(ct===false||ct===null||typeof ct.widget=="undefined"){return true;}ct=getObject("WIDGET",ct.widget);if(ct.editing){ct.toggleHilite();cancelBubble();return false;}break;case 40:if(omitformtags.indexOf(etarget.tagName.toLowerCase())!=-1){return true;}if(ct===false||ct===null||typeof ct.widget=="undefined"){return true;}ct=getObject("WIDGET",ct.widget).getContainerId();if(ct!==false){ct=document.getElementById(ct);if((typeof ct!='undefined'||ct!==null)&&(ct.nextSibling!==null)){ct.nextSibling.onclick();ct.nextSibling.scrollIntoView();cancelBubble();return false;}}break;case 38:if(omitformtags.indexOf(etarget.tagName.toLowerCase())!=-1){return true;}if(ct===false||ct===null||typeof ct.widget=="undefined"){return true;}ct=getObject("WIDGET",ct.widget).getContainerId();if(ct!==false){ct=document.getElementById(ct);if((typeof ct!='undefined'||ct!==null)&&(ct.previousSibling!==null)){ct.previousSibling.onclick();ct.previousSibling.scrollIntoView();cancelBubble();return false;}}break;default:return true;}}
