egroupware/etemplate/js/etemplate2.min.js

38 lines
886 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*!
* EGroupware (http://www.egroupware.org/) minified Javascript
*
* full sources are available under https://svn.stylite.de/viewvc/egroupware/
*
* build Wed Mar 02 2016 15:23:55
*/
function et2_loadXMLFromURL(_url,_callback,_context){"undefined"==typeof _context&&(_context=null);var win;try{opener&&opener.etemplate2&&(win=opener)}catch(e){}"undefined"==typeof win&&(win=top),win.jQuery.ajax({url:_url,context:_context,type:"GET",dataType:"xml",success:function(_data,_status,_xmlhttp){_callback.call(_context,_data.documentElement)},error:function(_xmlhttp,_err){egw().debug("error","Loading eTemplate from "+_url+" failed! "+_xmlhttp.status+" "+_xmlhttp.statusText)}})}function et2_directChildrenByTagName(_node,_tagName){_tagName=_tagName.toLowerCase();for(var result=[],i=0;i<_node.childNodes.length;i++)_tagName==_node.childNodes[i].nodeName.toLowerCase()&&result.push(_node.childNodes[i]);return result}function et2_filteredNodeIterator(_node,_callback,_context){for(var i=0;i<_node.childNodes.length;i++){var node=_node.childNodes[i],nodeName=node.nodeName.toLowerCase();"#"!=nodeName.charAt(0)&&_callback.call(_context,node,nodeName)}}function et2_readAttrWithDefault(_node,_name,_default){var val=_node.getAttribute(_name);return null===val?_default:val}function et2_evalBool(_val){return"string"!=typeof _val||"false"!=_val&&"0"!=_val?!!_val:!1}function et2_form_name(_cname,_name){for(var parts=[],i=0;i<arguments.length;++i){var name=arguments[i];"string"==typeof name&&name.length>0&&(parts=parts.concat(name.replace(/]/g,"").split("[")))}var name=parts.shift();return parts.length?name+"["+parts.join("][")+"]":name}function et2_checkType(_val,_type,_attr,_widget){function _err(){var res=et2_typeDefaults[_type];return"undefined"!=typeof _val&&_val&&egw.debug("warn","Widget %o: '"+_val+"' was not of specified _type '"+_type+(null!=_attr?"' for attribute '"+_attr+"' ":"")+"and is now '"+res+"'",_widget),res}if("undefined"==typeof _attr&&(_attr=null),"any"==_type)return _val;if(_val===et2_typeDefaults[_type])return _val;if("boolean"==_type){if(_val===!0||_val===!1)return _val;if("string"==typeof _val){var lcv=_val.toLowerCase();if("true"===lcv||"false"===lcv||""===lcv)return"true"===_val;if("0"===lcv||"1"===lcv)return"1"===_val}else if("number"==typeof _val)return 0!=_val;return _err()}if("string"==_type||"html"==_type||"rawstring"==_type)return"number"==typeof _val?_val.toString():"string"==typeof _val?"string"==_type?html_entity_decode(_val):_val:"object"==typeof _val&&jQuery.isEmptyObject(_val)?"":_err();if("float"==_type)return"number"==typeof _val?_val:isNaN(_val)?_err():parseFloat(_val);if("integer"==_type)return parseInt(_val)==_val?parseInt(_val):_err();if("dimension"==_type)return"auto"==_val?_val:isNaN(_val)?"string"==typeof _val&&(_val.indexOf("px")==_val.length-2&&!isNaN(_val.split("px")[0])||_val.indexOf("%")==_val.length-1&&!isNaN(_val.split("%")[0]))?_val:_err():parseFloat(_val)+"px";if("js"==_type){if("function"==typeof _val||"undefined"==typeof _val)return _val;if(_val&&(_val=_val.replace(/window\.close\(\)/g,"egw(window).close()")),"string"==typeof _val&&"app."==_val.substr(0,4)&&window.app){for(var parts=_val.split("."),func=parts.pop(),parent=window,i=0;i<parts.length&&"undefined"!=typeof parent[parts[i]];++i)parent=parent[parts[i]];if("function"==typeof parent[func])try{return jQuery.proxy(parent[func],parent)}catch(e){return req.egw.debug("error","Function",_val),_err()}}if(!_val||"string"==typeof _val)return _val}throw"Invalid type identifier '"+_attr+"': '"+_type+"'"}function et2_validateAttrib(_id,_attrib){"undefined"==typeof _attrib.ignore&&(_attrib.ignore=!1),_attrib.ignore||("undefined"==typeof _attrib.name&&(_attrib.name=_id,egw.debug("log","Human name ('name'-Field) for attribute '"+_id+"' has not been supplied, set to '"+_id+"'")),"undefined"==typeof _attrib.description&&(_attrib.description="",egw.debug("log","Description for attribute '"+_id+"' has not been supplied")),"undefined"==typeof _attrib.type?_attrib.type="any":et2_validTypes.indexOf(_attrib.type)<0&&egw.debug("error","Invalid type '"+_attrib.type+"' for attribute '"+_id+"' supplied. Valid types are ",et2_validTypes),"undefined"==typeof _attrib.default&&(_attrib.default=et2_typeDefaults[_attrib.type]))}function et2_arrayValues(_arr){var result=[];for(var key in _arr)parseInt(key)==key&&result.push(_arr[key]);return result}function et2_arrayKeys(_arr){var result=[];for(var key in _arr)result.push(key);return result}function et2_arrayIntKeys(_arr){var result=[];for(var key in _arr)result.push(parseInt(key));return result}function et2_substr(str,start,len){var end=str.length;return 0>start&&(start+=end),end="undefined"==typeof len?end:0>len?len+end:len+start,start>=str.length||0>start||start>end?"":str.slice(start,end)}function et2_csvSplit(_str,_num,_delimiter,_enclosure){if("undefined"!=typeof _str&&null!=_str||(_str=""),"undefined"==typeof _num&&(_num=null),"undefined"==typeof _delimiter&&(_delimiter=","),"undefined"==typeof _enclosure&&(_enclosure='"'),-1==_str.indexOf(_enclosure))return null===_num?_str.split(_delimiter):_str.split(_delimiter,_num);for(var parts=_str.split(_delimiter),n=0;"undefined"!=typeof parts[n];n++){var part=parts[n];if(part.charAt(0)===_enclosure){for(var m=n;"undefined"!=typeof parts[m+1]&&parts[n].substr(-1)!==_enclosure;)parts[n]+=_delimiter+parts[++m],delete parts[m];parts[n]=et2_substr(parts[n].replace(new RegExp(_enclosure+_enclosure,"g"),_enclosure),1,-1),n=m}}return parts=et2_arrayValues(parts),null!==_num&&_num>0&&_num<parts.length&&parts.length>0&&(parts[_num-1]=parts.slice(_num-1,parts.length).join(_delimiter),parts=parts.slice(0,_num)),parts}function et2_activateLinks(_content){function _splitPush(_matches,_proc){if(_matches){_match=!0;for(var i=1;i<_matches.length;i++)"undefined"==typeof _matches[i]&&(_matches[i]="");var splitted=_content.split(_matches[0]),left=splitted.shift();left&&(arr=arr.concat(et2_activateLinks(left))),_proc(_matches),_content=splitted.join(_matches[0])}}var _match=!1,arr=[],mail_regExp=/(mailto:)?([a-z0-9._-]+)@([a-z0-9_-]+)\.([a-z0-9._-]+)/i,protocol="(http:\\/\\/|(ftp:\\/\\/|https:\\/\\/))",domain="([\\w-]+\\.[\\w-.]+)",subdir="([\\w\\-\\.,@?^=%&;:\\/~\\+#]*[\\w\\-\\@?^=%&\\/~\\+#])?",http_regExp=new RegExp(protocol+domain+subdir,"i"),domain="www(\\.[\\w-.]+)",subdir="([\\w\\-\\.,@?^=%&:\\/~\\+#]*[\\w\\-\\@?^=%&\\/~\\+#])?",www_regExp=new RegExp(domain+subdir,"i");do{if(_match=!1,!_content)break;_splitPush(_content.match(mail_regExp),function(_matches){arr.push({href:(_matches[1]?"":"mailto:")+_matches[0],text:_matches[2]+"@"+_matches[3]+"."+_matches[4]})}),_splitPush(_content.match(http_regExp),function(_matches){arr.push({href:_matches[0],text:_matches[2]+_matches[3]+_matches[4]})}),_splitPush(_content.match(www_regExp),function(_matches){arr.push({href:"http://"+_matches[0],text:_matches[0]})})}while(_match);return arr.push(_content),arr}function et2_insertLinkText(_text,_node,_target){if(!_node)return void egw.debug("warn","et2_insertLinkText called without node",_text,_node,_target);for(var i=_node.childNodes.length-1;i>=0;i--)_node.removeChild(_node.childNodes[i]);for(var i=0;i<_text.length;i++){var s=_text[i];if("string"==typeof s||"number"==typeof s)for(var lines=s.split?s.split("\n"):[s],j=0;j<lines.length;j++)_node.appendChild(document.createTextNode(lines[j])),j<lines.length-1&&_node.appendChild(document.createElement("br"));else if(s.text){s.href||(egw.debug("warn","et2_activateLinks gave bad data",s,_node,_target),s.href="");var a=$j(document.createElement("a")).attr("href",s.href).text(s.text);"undefined"!=typeof _target&&_target&&"_self"!=_target&&"mailto:"!=s.href.substr(0,7)&&a.attr("target",_target),"mailto:"==s.href.substr(0,7)&&(egw.user("apps").mail||egw.user("apps").felamimail)&&"1"!=egw.preference("force_mailto","addressbook")&&a.click(function(event){return egw.open_link(this.href),!1}),a.appendTo(_node)}}}function et2_cloneObject(_obj){var result={};for(var key in _obj)result[key]=_obj[key];return result}function et2_hasChild(_nodes,_child){for(var i=0;i<_nodes.length;i++){if(_nodes[i]==_child)return!0;if(_nodes[i].childNodes){var res=et2_hasChild(_nodes[i].childNodes,_child);if(res)return!0}}return!1}function et2_range(_top,_height){return{top:_top,bottom:_top+_height}}function et2_bounds(_top,_bottom){return{top:_top,bottom:_bottom}}function et2_rangeIntersect(_ar1,_ar2){return!(_ar1.bottom<_ar2.top||_ar1.top>_ar2.bottom)}function et2_rangeIntersectDir(_ar1,_ar2){return _ar1.bottom<_ar2.top?-1:_ar1.top>_ar2.bottom?1:0}function et2_rangeEqual(_ar1,_ar2){return _ar1.top===_ar2.top&&_ar1.bottom===_ar2.bottom}function et2_rangeSubstract(_ar1,_ar2){var res=[_ar1];et2_rangeIntersect(_ar1,_ar2)&&(res=[et2_bounds(_ar1.top,_ar2.top),et2_bounds(_ar2.bottom,_ar1.bottom)]);for(var i=res.length-1;i>=0;i--)res[i].bottom-res[i].top<=0&&res.splice(i,1);return res}function html_entity_decode(_str){return _str&&-1!=_str.indexOf("&")?jQuery("<span>"+_str+"</span>").text():_str}function et2_arrayMgrs_expand(_owner,_mgrs,_data,_row){var result={};for(var key in _mgrs)if(result[key]=_mgrs[key],"undefined"!=typeof _data[key]){var rowData={};rowData[_row]=_data[key],result[key]=_mgrs[key].openPerspective(_owner,rowData,_row)}return result}function et2_register_widget(_constructor,_types){"use strict";for(var i=0;i<_types.length;i++){var type=_types[i].toLowerCase();et2_registry[type]&&egw.debug("warn","Widget class registered for "+type+" will be overwritten."),et2_registry[type]=_constructor}}function et2_createWidget(_name,_attrs,_parent){"use strict";"undefined"==typeof _attrs&&(_attrs={}),"undefined"==typeof _parent&&(_parent=null);var nodeName=_attrs.type=_name,readonly=_attrs.readonly="undefined"==typeof _attrs.readonly?!1:_attrs.readonly,constructor="undefined"==typeof et2_registry[nodeName]?et2_placeholder:et2_registry[nodeName];return readonly&&"undefined"!=typeof et2_registry[nodeName+"_ro"]&&(constructor=et2_registry[nodeName+"_ro"]),constructor.prototype.generateAttributeSet(_attrs),new constructor(_parent,_attrs)}function et2_action_object_impl(widget,node){var aoi=new egwActionObjectInterface,objectNode=node;return aoi.getWidget=function(){return widget},aoi.doGetDOMNode=function(){return objectNode?objectNode:widget.getDOMNode()},aoi.doSetState=function(_state,_outerCall){},aoi.doTriggerEvent=function(_event,_data){switch(_event){case EGW_AI_DRAG_OVER:$j(this.node).addClass("ui-state-active");break;case EGW_AI_DRAG_OUT:$j(this.node).removeClass("ui-state-active")}},aoi}function expose(widget){"use strict";var IMAGE_DEFAULT={title:egw.lang("loading"),href:"",type:"image/png",thumbnail:"",loading:!0},mime_regex=new RegExp(/(video\/(mp4|ogg|webm))|(image\/:*(?!tif|x-xcf|pdf))/);navigator.userAgent.match(/(MSIE|Trident)/)&&mime_regex.compile(/(video\/mp4)|(image\/:*(?!tif|x-xcf|pdf))/);var gallery=null,find_nextmatch=function(widget){for(var current=widget,nextmatch=null;null==nextmatch&&current;)current=current.getParent(),"undefined"!=typeof current&&current.instanceOf(et2_nextmatch)&&(nextmatch=current);return null!=nextmatch&&null!=nextmatch.controller&&nextmatch.dom_id.match(/filemanager/,"ig")?nextmatch:null},read_from_nextmatch=function(nm,images,start_at){start_at||(start_at=0);for(var image_index=start_at,stop=Math.max.apply(null,Object.keys(nm.controller._indexMap)),i=start_at;stop>=i;i++)if(nm.controller._indexMap[i]&&nm.controller._indexMap[i].uid){var uid=nm.controller._indexMap[i].uid;if(uid){var data=egw.dataGetUIDdata(uid);if(data&&data.data&&data.data.mime&&mime_regex.test(data.data.mime)){var media=this.getMedia(data.data);images[image_index++]=jQuery.extend({},data.data,media[0])}}}else images[image_index++]=IMAGE_DEFAULT},set_slide=function(index,image){for(var active=index==gallery.index;index>gallery.getNumber();)gallery.add([jQuery.extend({},IMAGE_DEFAULT)]);if(image.loading)return void(gallery.slidesContainer.find('[data-index="'+index+'"]').hasClass(gallery.options.slideErrorClass)&&$j(gallery.slides[index]).addClass(gallery.options.slideLoadingClass).removeClass(gallery.options.slideErrorClass));$j(gallery.slides[index]).removeClass(gallery.options.slideLoadingClass);var new_index=gallery.num;gallery.add([image]),gallery.list[index]=gallery.list[new_index],gallery.list.splice(new_index,1);var dom_nodes=["indicators","slides"];for(var i in dom_nodes){var var_name=dom_nodes[i];$j(gallery[var_name][index]).remove(),gallery[var_name][index]=gallery[var_name][new_index];var node=$j(gallery[var_name][index]);node.attr("data-index",index).insertAfter($j("[data-index='"+(index-1)+"']",node.parent())),active&&node.addClass(gallery.options.activeIndicatorClass),gallery[var_name].splice(new_index,1)}active&&(gallery.activeIndicator=$j(gallery.indicators[index])),gallery.positions[index]=active?0:index>gallery.index?gallery.slideWidth:-gallery.slideWidth,gallery.positions.splice(new_index,1),gallery.elements[index]&&(delete gallery.elements[index],gallery.loadElement(index)),gallery.num-=1};return widget.extend([et2_IExposable],{init:function(){this._super.apply(this,arguments),this.mime_regexp=mime_regex;var self=this;this.expose_options={container:"#blueimp-gallery",slidesContainer:"div",titleElement:"h3",displayClass:"blueimp-gallery-display",controlsClass:"blueimp-gallery-controls",singleClass:"blueimp-gallery-single",leftEdgeClass:"blueimp-gallery-left",rightEdgeClass:"blueimp-gallery-right",playingClass:"blueimp-gallery-playing",slideClass:"slide",slideLoadingClass:"",slideErrorClass:"slide-error",slideContentClass:"slide-content",toggleClass:"toggle",prevClass:"prev",nextClass:"next",closeClass:"close",playPauseClass:"play-pause",fullscreenClass:"fullscreen",typeProperty:"type",titleProperty:"title",urlProperty:"href",displayTransition:!0,clearSlides:!0,stretchImages:!0,toggleControlsOnReturn:!0,toggleSlideshowOnSpace:!0,enableKeyboardNavigation:!0,closeOnEscape:!0,closeOnSlideClick:!1,closeOnSwipeUpOrDown:!0,emulateTouchEvents:!0,stopTouchEventsPropagation:!1,hidePageScrollbars:!0,disableScroll:!0,carousel:!0,continuous:!1,unloadElements:!0,startSlideshow:!1,slideshowInterval:3e3,index:0,preloadRange:2,transitionSpeed:400,hideControlsOnSlideshow:!0,toggleFullscreenOnSlideShow:!0,slideshowTransitionSpeed:void 0,indicatorContainer:"ol",activeIndicatorClass:"active",thumbnailProperty:"thumbnail",thumbnailIndicators:!0,thumbnailWithImgTag:!0,onopen:jQuery.proxy(this.expose_onopen,this),onopened:jQuery.proxy(this.expose_onopened,this),onslide:function(index,slide){self.expose_onslide.apply(self,[this,index,slide])},onslideend:function(index,slide){self.expose_onslideend.apply(self,[this,index,slide])},onslidecomplete:function(index,slide){self.expose_onslidecomplete.apply(self,[this,index,slide])},onclose:jQuery.proxy(this.expose_onclose,this),onclosed:jQuery.proxy(this.expose_onclosed,this)};var $body=jQuery("body");if(0==$body.find("#blueimp-gallery").length){var $expose_node=jQuery(document.createElement("div")).attr({id:"blueimp-gallery",class:"blueimp-gallery"});$expose_node.append('<div class="slides"></div><h3 class="title"></h3><a class="prev"></a><a class="next"></a><a title="'+egw().lang("Close")+'" class="close">×</a><a title="'+egw().lang("Play/Pause")+'" class="play-pause"></a><a title="'+egw().lang("Fullscreen")+'" class="fullscreen"></a><a title="'+egw().lang("Save")+'" class="download"></a><ol class="indicator"></ol>'),$body.append($expose_node)}},set_value:function(_value){if("undefined"!=typeof this._super&&(this._super.apply(this,arguments),this.options.expose_view)){var self=this;_value&&"string"==typeof _value.mime&&_value.mime.match(mime_regex,"ig")&&"undefined"!=typeof _value.download_url&&"undefined"!=typeof this.options.expose_view&&this.options.expose_view&&jQuery(this.node).on("click",function(event){event.altKey||event.ctrlKey||event.shiftKey||event.metaKey||self._init_blueimp_gallery(event,_value),event.stopImmediatePropagation()}).addClass("et2_clickable")}},_init_blueimp_gallery:function(event,_value){var mediaContent=[],nm=find_nextmatch(this),current_index=0;if(nm&&!this._is_target_indepth(nm,event.target)){var current_entry=nm.controller.getRowByNode(event.target);read_from_nextmatch.call(this,nm,mediaContent);for(var i=0;i<mediaContent.length;i++)if("filemanager::"+mediaContent[i].path==current_entry.uid){current_index=i;break}window.setTimeout(function(){nm.applyFilters({col_filter:{mime:"/"+mime_regex.source+"/"}})},1)}else mediaContent=this.getMedia(_value),this.expose_options.thumbnailIndicators=!1;this.expose_options.index=current_index,gallery=blueimp.Gallery(mediaContent,this.expose_options)},_is_target_indepth:function(nm,target){var res=!1;if(nm){if(!target)var target=this.getDOMNode();var entry=nm.controller.getRowByNode(target);entry&&entry.controller.getDepth()>0&&(res=!0)}return res},expose_onopen:function(event){},expose_onopened:function(event){var nm=find_nextmatch(this),self=this;if(nm){var total_count=nm.controller._grid.getTotalCount();if(total_count>=gallery.num){var $indicator=gallery.container.find(".indicator");$indicator.off().addClass("paginating").swipe(function(event,direction,distance){if(direction==jQuery.fn.swipe.directions.LEFT)distance*=-1;else if(direction!=jQuery.fn.swipe.directions.RIGHT)return;$j(this).css("left",min(0,parseInt($j(this).css("left"))-30*distance)+"px")}),$indicator.bind("mousewheel DOMMousewheel",function(event,_delta){var delta=_delta||event.originalEvent.wheelDelta/120;if(!(delta>0&&parseInt($j(this).css("left"))>gallery.container.width()/2)){if(0>delta&&$j(this).width()+parseInt($j(this).css("left"))<gallery.container.width()){var nextIndex=gallery.indicatorContainer.find('[title="loading"]')[0];return void(nextIndex&&self.expose_onslideend(gallery,nextIndex.dataset.index-1))}$j(this).css("left",parseInt($j(this).css("left"))- -delta*gallery.activeIndicator.width()*5+"px"),event.preventDefault()}})}}},expose_onslide:function(gallery,index,slide){if("undefined"!=typeof this._super){this._super.apply(this,arguments);var nm=find_nextmatch(this);if(nm){var indicator=gallery.container.find(".indicator"),current=$j(".active",indicator).position();current&&indicator.animate({left:gallery.container.width()/2-current.left},10)}}},expose_onslideend:function(gallery,index,slide){var nm=find_nextmatch(this);if(nm){var total_count=nm.controller._grid.getTotalCount();if(index==total_count-1||0==index)return;var direction=1;for(var i in gallery.elements)if(1==gallery.elements[i]||3==gallery.elements[i]||gallery.list[i].loading){direction=i>=index?1:-1;break}if(!gallery.list[index+direction]||gallery.list[index+direction].loading||total_count>gallery.getNumber()&&index+ET2_DATAVIEW_STEPSIZE>gallery.getNumber()){var start=Math.max(0,direction>0?index:index-ET2_DATAVIEW_STEPSIZE),end=Math.min(total_count-1,start+ET2_DATAVIEW_STEPSIZE);nm.controller._gridCallback(start,end);var images=[];read_from_nextmatch.call(this,nm,images,start);for(var i in images)set_slide(i,images[i])}}},expose_onslidecomplete:function(gallery,index,slide){},expose_onclose:function(event){var nm=find_nextmatch(this);nm&&!this._is_target_indepth(nm)&&(gallery.container.find(".indicator").removeClass("paginating").off("mousewheel").off("swipe"),nm.applyFilters({col_filter:{mime:""}}))},expose_onclosed:function(event){}})}function date(format,timestamp){var jsdate,f,formatChrCb,that=this,formatChr=/\\?([a-z])/gi,_pad=function(n,c){return(n+="").length<c?new Array(++c-n.length).join("0")+n:n},txt_words=["Sun","Mon","Tues","Wednes","Thurs","Fri","Satur","January","February","March","April","May","June","July","August","September","October","November","December"];return formatChrCb=function(t,s){return f[t]?f[t]():s},f={d:function(){return _pad(f.j(),2)},D:function(){return f.l().slice(0,3)},j:function(){return jsdate.getDate()},l:function(){return txt_words[f.w()]+"day"},N:function(){return f.w()||7},S:function(){var j=f.j();return j>4||21>j?"th":{1:"st",2:"nd",3:"rd"}[j%10]||"th"},w:function(){return jsdate.getDay()},z:function(){var a=new Date(f.Y(),f.n()-1,f.j()),b=new Date(f.Y(),0,1);return Math.round((a-b)/864e5)+1},W:function(){var a=new Date(f.Y(),f.n()-1,f.j()-f.N()+3),b=new Date(a.getFullYear(),0,4);return _pad(1+Math.round((a-b)/864e5/7),2)},F:function(){return txt_words[6+f.n()]},m:function(){return _pad(f.n(),2)},M:function(){return f.F().slice(0,3)},n:function(){return jsdate.getMonth()+1},t:function(){return new Date(f.Y(),f.n(),0).getDate()},L:function(){return 1===new Date(f.Y(),1,29).getMonth()|0},o:function(){var n=f.n(),W=f.W(),Y=f.Y();return Y+(12===n&&9>W?-1:1===n&&W>9)},Y:function(){return jsdate.getFullYear()},y:function(){return(f.Y()+"").slice(-2)},a:function(){return jsdate.getHours()>11?"pm":"am"},A:function(){return f.a().toUpperCase()},B:function(){var H=3600*jsdate.getUTCHours(),i=60*jsdate.getUTCMinutes(),s=jsdate.getUTCSeconds();return _pad(Math.floor((H+i+s+3600)/86.4)%1e3,3)},g:function(){return f.G()%12||12},G:function(){return jsdate.getHours()},h:function(){return _pad(f.g(),2)},H:function(){return _pad(f.G(),2)},i:function(){return _pad(jsdate.getMinutes(),2)},s:function(){return _pad(jsdate.getSeconds(),2)},u:function(){return _pad(1e3*jsdate.getMilliseconds(),6)},e:function(){throw"Not supported (see source code of date() for timezone on how to add support)"},I:function(){var a=new Date(f.Y(),0),c=Date.UTC(f.Y(),0),b=new Date(f.Y(),6),d=Date.UTC(f.Y(),6);return 0+(a-c!==b-d)},O:function(){var a=jsdate.getTimezoneOffset();return(a>0?"-":"+")+_pad(Math.abs(a/60*100),4)},P:function(){var O=f.O();return O.substr(0,3)+":"+O.substr(3,2)},T:function(){return"UTC"},Z:function(){return 60*-jsdate.getTimezoneOffset()},c:function(){return"Y-m-d\\Th:i:sP".replace(formatChr,formatChrCb)},r:function(){return"D, d M Y H:i:s O".replace(formatChr,formatChrCb)},U:function(){return jsdate.getTime()/1e3|0}},this.date=function(format,timestamp){return that=this,jsdate="undefined"==typeof timestamp?new Date:timestamp instanceof Date?new Date(timestamp):new Date(1e3*timestamp),format.replace(formatChr,formatChrCb)},this.date(format,timestamp)}function et2_dataview_rowAOI(_node){"use strict";var aoi=new egwActionObjectInterface;aoi.node=_node,aoi.selectMode=EGW_SELECTMODE_DEFAULT,aoi.checkBox=null,aoi.doGetDOMNode=function(){return aoi.node},$j(_node).mousedown(egwPreventSelect);var selectHandler=function(e,_params){if(egwUnfocus(),_node.onselectstart=null,e.target!=aoi.checkBox){var selected=egwBitIsSet(aoi.getState(),EGW_AO_STATE_SELECTED),state=egwGetShiftState(e);if(_params&&egwIsMobile())switch(_params.swip){case"left":case"right":state=1,_egw_active_menu&&_egw_active_menu.hide();break;case"up":case"down":return}switch(aoi.selectMode){case EGW_SELECTMODE_DEFAULT:aoi.updateState(EGW_AO_STATE_SELECTED,!egwBitIsSet(state,EGW_AO_SHIFT_STATE_MULTI)||!selected,state);break;case EGW_SELECTMODE_TOGGLE:aoi.updateState(EGW_AO_STATE_SELECTED,!selected,egwSetBit(state,EGW_AO_SHIFT_STATE_MULTI,!0))}}};return egwIsMobile()?$j(_node).swipe({allowPageScroll:"vertical",swipe:function(event,direction){selectHandler(event,{swip:direction})},click:function(event){selectHandler(event)}}):$j(_node).click(selectHandler),$j(aoi.checkBox).change(function(){aoi.updateState(EGW_AO_STATE_SELECTED,this.checked,EGW_AO_SHIFT_STATE_MULTI)}),aoi.doSetState=function(_state){var selected=egwBitIsSet(_state,EGW_AO_STATE_SELECTED);this.checkBox&&(this.checkBox.checked=selected),$j(this.node).toggleClass("focused",egwBitIsSet(_state,EGW_AO_STATE_FOCUSED)),$j(this.node).toggleClass("selected",selected)},aoi}function nm_action(_action,_senders,_target,_ids){if(!_action.checkbox||_action.data&&"undefined"!=typeof _action.data.nm_action){if("undefined"!=typeof _action.data&&_action.data||(_action.data={}),"undefined"==typeof _action.data.nm_action&&"popup"==_action.type&&(_action.data.nm_action="submit"),"undefined"==typeof _ids){for(var nm=null,action=_action;null==nm&&null!=action;)null!=action.data&&action.data.nextmatch&&(nm=action.data.nextmatch),action=action.parent;nm&&(_ids=nm.getSelection(),_action.data.nextmatch=nm)}for(var idsArr=_ids.ids,i=0;i<idsArr.length;i++)idsArr[i]?idsArr[i]=idsArr[i].split("::").pop():idsArr.splice(i,1);for(var ids="",i=0;i<idsArr.length;i++){var id=idsArr[i];ids+=(id.indexOf(",")>=0?'"'+id.replace(/"/g,'""')+'"':id)+(i<idsArr.length-1?",":"")}var mgr=_action.getManager(),url="#";"undefined"!=typeof _action.data.url&&(url=_action.data.url.replace(/(\$|%24)id/,encodeURIComponent(ids)).replace(/(\$|%24)select_all/,_ids.all));var target=null;switch("undefined"!=typeof _action.data.target&&(target=_action.data.target),_action.data.nm_action){case"alert":alert(_action.caption+" ('"+_action.id+"') executed on rows: "+ids);break;case"location":"undefined"!=typeof _action.data.targetapp?top.egw_appWindowOpen(_action.data.targetapp,url):target?egw.open_link(url,target,_action.data.width?_action.data.width+"x"+_action.data.height:!1):window.location.href=url;break;case"popup":egw.open_link(url,target,_action.data.width+"x"+_action.data.height);break;case"long_task":if(doLongTask(idsArr,_ids.all,_action,mgr.data.nextmatch))break;case"egw_open":var params=_action.data.egw_open.split("-"),egw_open_id=idsArr[0],type=params.shift(),app=params.shift();"undefined"!=typeof params[2]&&(egw_open_id.indexOf(":")>=0?egw_open_id=egw_open_id.split(":")[params.shift(params[2])]:params.length>1&&""==params[0]&&-1!=params[1].indexOf("from=merge")?params.shift():params.shift(params[2])),params.length>1&&""==params[0]&&-1!=params[1].indexOf("from=merge")&&params.shift();var extra=params.join("-");egw(app,window).open(egw_open_id,app,type,extra,target);break;case"open_popup":if(null==nm_popup_action){nm_open_popup(_action,_ids.ids);break}case"submit":var checkboxes=mgr.getActionsByAttr("checkbox",!0),checkbox_values={};if(checkboxes)for(var i in checkboxes)checkbox_values[checkboxes[i].id]=checkboxes[i].checked;var nextmatch=_action.data.nextmatch;if(!nextmatch&&_senders.length&&(nextmatch=_senders[0]._context._widget),nextmatch){var old_value=nextmatch.getValue,value=nextmatch.getValue();jQuery.extend(value,this.activeFilters,{selected:idsArr,select_all:_ids.all,checkboxes:checkbox_values}),value[nextmatch.options.settings.action_var]=_action.id,nextmatch.getValue=function(){return value},_action.data.postSubmit?nextmatch.getInstanceManager().postSubmit():nextmatch.getInstanceManager().submit(),"open_popup"==_action.data.nm_action&&(nextmatch.refresh(idsArr),nextmatch.getValue=old_value)}else egw().debug("error","Missing nextmatch widget, could not submit",_action)}}}function fetchAll(ids,nextmatch,callback){if(!nextmatch||!nextmatch.controller)return!1;var selection=nextmatch.getSelection();if(!selection.all)return!1;if(nextmatch.controller._grid&&nextmatch.controller._grid.getTotalCount()>ids.length){var idsArr=[],count=idsArr.length,total=nextmatch.controller._grid.getTotalCount(),cancel=!1,dialog=et2_dialog.show_dialog(function(){count=total,cancel=!0},egw.lang("Loading"),egw.lang("please wait..."),{},[{button_id:et2_dialog.CANCEL_BUTTON,text:"cancel",id:"dialog[cancel]",image:"cancel"}]);do nextmatch.controller.dataFetch({start:count,num_rows:200},function(data){if(data&&data.order)for(var i=0;i<data.order.length;i++)idsArr.push(data.order[i].split("::").pop());data&&data.total&&(total=data.total),idsArr.length>=total&&(dialog.destroy(),cancel||callback.call(this,idsArr))},this),count+=200;while(total>count);return!0}return!1}function doLongTask(idsArr,all,_action,nextmatch){if(all||idsArr.length>1||"undefined"==typeof _action.data.egw_open){if(all){var fetching=fetchAll(idsArr,nextmatch,function(idsArr){et2_dialog.long_task(null,_action.data.message||_action.caption,_action.data.title,_action.data.menuaction,idsArr)});if(fetching)return!0}return et2_dialog.long_task(null,_action.data.message||_action.caption,_action.data.title,_action.data.menuaction,idsArr),!0}return!1}function nm_compare_field(_action,_senders,_target){var value=!1,field=document.getElementById(_action.data.fieldId);if(field)value=$j(field).val();else{var nextmatch=_action.data.nextmatch;if(!nextmatch&&_senders.length&&(nextmatch=_senders[0]._context._widget),!nextmatch)return!1;field=nextmatch.getWidgetById(_action.data.fieldId),value=field.getValue()}return field?"!"==_action.data.fieldValue.substr(0,1)?value!=_action.data.fieldValue.substr(1):value==_action.data.fieldValue:!1}function nm_open_popup(_action,_selected){var uid;"undefined"!=typeof _action.data.nextmatch?uid=_action.data.nextmatch.getInstanceManager().uniqueId:"undefined"!=typeof _selected[0]&&(uid=_selected[0].manager.data.nextmatch.getInstanceManager().uniqueId);var popup=jQuery("#"+(uid||"")+"_"+_action.id+"_popup").first()||jQuery("[id*='"+_action.id+"_popup']").first();if(popup){nm_popup_action=_action,_selected.length&&"object"==typeof _selected[0]?(_action.data.nextmatch=_selected[0]._context._widget,nm_popup_ids=_selected):(egw().debug("warn","Not proper format for IDs, should be array of egwActionObject",_selected),nm_popup_ids=_selected);var dialog=jQuery(".action_popup-content",popup);if(0==dialog.length&&(dialog=jQuery(document.createElement("div")).addClass("action_popup-content"),1==popup.children().length?dialog.append(popup.children().children().slice(1,popup.children().children().length-1)):dialog.append(popup.children().slice(1,popup.children().length-1)),dialog.appendTo(popup)),1==dialog.length){var dialog_parent=dialog.parent(),d_buttons=[],action=_action;popup.show();var buttons=jQuery("button:visible",popup).each(function(index){var but=jQuery(this);if(but.hide(),but.attr("id"))var widget_id=but.attr("id").replace(_action.data.nextmatch.getInstanceManager().uniqueId+"_",""),button=nm_popup_action.data.nextmatch.getRoot().getWidgetById(widget_id);d_buttons.push({text:but.text(),click:button&&button.onclick?function(e){dialog.dialog("close"),nm_popup_action=action,button.onclick.apply(button,e.currentTarget)}:function(e){dialog.dialog("close"),nm_popup_action=null}})}),dialog_width=dialog.outerWidth(!0);popup.hide(),dialog.dialog({title:jQuery(".promptheader",popup).text(),modal:!0,buttons:d_buttons,minWidth:dialog_width,close:function(event,ui){dialog.dialog("destroy"),dialog.appendTo(dialog_parent),buttons.show()}})}nm_popup_action=null,nm_popup_senders=null}}function nm_submit_popup(button){if(nm_popup_action.data.nextmatch){var widget_id=$j(button).attr("id").replace(nm_popup_action.data.nextmatch.getInstanceManager().uniqueId+"_","");nm_popup_action.data.nextmatch.getRoot().getWidgetById(widget_id).clicked=!0}if(nm_popup_ids.length&&"object"!=typeof nm_popup_ids[0]){var ids={ids:[]};for(var i in nm_popup_ids)nm_popup_ids[i]&&ids.ids.push(nm_popup_ids[i])}nm_action(nm_popup_action,nm_popup_ids,button,ids),nm_hide_popup(button,null),nm_popup_ids=null}function nm_hide_popup(element,div_id){var prefix=element.id.substring(0,element.id.indexOf("[")),popup=div_id?document.getElementById(div_id):jQuery("#"+prefix+"_popup").get(0)||jQuery("[id*='"+prefix+"_popup']").get(0);return popup&&(popup.style.display="none"),nm_popup_action=null,nm_popup_senders=null,!1}function nm_activate_link(_action,_senders){$j(_senders[0].iface.getDOMNode()).find(".et2_clickable:first").trigger("click")}function dtmlXMLLoaderObject(t,e,n,i){return this.xmlDoc="",this.async="undefined"!=typeof n?n:!0,this.onloadAction=t||null,this.mainObject=e||null,this.waitCall=null,this.rSeed=i||!1,this}function callerFunction(t,e){return this.handler=function(n){return n||(n=window.event),t(n,e),!0},this.handler}function getAbsoluteLeft(t){return getOffset(t).left}function getAbsoluteTop(t){return getOffset(t).top}function getOffsetSum(t){for(var e=0,n=0;t;)e+=parseInt(t.offsetTop),n+=parseInt(t.offsetLeft),t=t.offsetParent;return{top:e,left:n}}function getOffsetRect(t){var e=t.getBoundingClientRect(),n=document.body,i=document.documentElement,a=window.pageYOffset||i.scrollTop||n.scrollTop,s=window.pageXOffset||i.scrollLeft||n.scrollLeft,r=i.clientTop||n.clientTop||0,o=i.clientLeft||n.clientLeft||0,d=e.top+a-r,l=e.left+s-o;return{top:Math.round(d),left:Math.round(l)}}function getOffset(t){return t.getBoundingClientRect?getOffsetRect(t):getOffsetSum(t);
}function convertStringToBoolean(t){switch("string"==typeof t&&(t=t.toLowerCase()),t){case"1":case"true":case"yes":case"y":case 1:case!0:return!0;default:return!1}}function getUrlSymbol(t){return-1!=t.indexOf("?")?"&":"?"}function dhtmlDragAndDropObject(){return window.dhtmlDragAndDrop?window.dhtmlDragAndDrop:(this.lastLanding=0,this.dragNode=0,this.dragStartNode=0,this.dragStartObject=0,this.tempDOMU=null,this.tempDOMM=null,this.waitDrag=0,window.dhtmlDragAndDrop=this,this)}function _dhtmlxError(){return this.catches||(this.catches=[]),this}function dhtmlXHeir(t,e){for(var n in e)"function"==typeof e[n]&&(t[n]=e[n]);return t}function dhtmlxEvent(t,e,n){t.addEventListener?t.addEventListener(e,n,!1):t.attachEvent&&t.attachEvent("on"+e,n)}function dhtmlxDetachEvent(t,e,n){t.removeEventListener?t.removeEventListener(e,n,!1):t.detachEvent&&t.detachEvent("on"+e,n)}function dhtmlxDnD(t,e){e&&(this._settings=e),dhtmlxEventable(this),dhtmlxEvent(t,"mousedown",dhtmlx.bind(function(e){this.dragStart(t,e)},this))}function dataProcessor(t){return this.serverProcessor=t,this.action_param="!nativeeditor_status",this.object=null,this.updatedRows=[],this.autoUpdate=!0,this.updateMode="cell",this._tMode="GET",this.post_delim="_",this._waitMode=0,this._in_progress={},this._invalid={},this.mandatoryFields=[],this.messages=[],this.styles={updated:"font-weight:bold;",inserted:"font-weight:bold;",deleted:"text-decoration : line-through;",invalid:"background-color:FFE0E0;",invalid_cell:"border-bottom:2px solid red;",error:"color:red;",clear:"font-weight:normal;text-decoration:none;"},this.enableUTFencoding(!0),dhtmlxEventable(this),this}function itempickerDocumentAction(context,data){"use strict";var formid="itempicker_action_form",form="<form id='"+formid+"' action='index.php?menuaction="+data.app+"."+data.app+"_merge.download_by_request' method='POST'><input type='hidden' name='data_document_name' value='"+data.value.name+"' /><input type='hidden' name='data_document_dir' value='"+data.value.dir+"' /><input type='hidden' name='data_checked' value='"+data.checked.join(",")+"' /></form>";$j("body").append(form),$j("#"+formid).submit().remove()}function etemplate2(_container,_menuaction){"undefined"==typeof _menuaction&&(_menuaction="home.etemplate_new.ajax_process_content.etemplate"),this.DOMContainer=_container,this.menuaction=_menuaction,this.uniqueId=_container.getAttribute("id")?_container.getAttribute("id").replace(".","-"):"",this.widgetContainer=null}function etemplate2_handle_load(_type,_response){var data=_response.data;if(jQuery.isArray(data["refresh-opener"])&&window.opener){var egw=window.egw(opener);egw.refresh.apply(egw,data["refresh-opener"])}var egw=window.egw(window);if("object"==typeof data.data&&"string"==typeof data.data.app_header&&(egw.app_header(data.data.app_header,data.data.currentapp||null),delete data.data.app_header),jQuery.isArray(data.message)&&egw.message.apply(egw,data.message),data["window-close"])return"string"==typeof data["window-close"]&&"true"!==data["window-close"]&&alert(data["window-close"]),egw.close(),!0;if(data["window-focus"]&&window.focus(),window.framework&&jQuery.isArray(data.setSidebox)&&window.framework.setSidebox.apply(window.framework,data.setSidebox),"string"==typeof data.url&&"object"==typeof data.data){if("function"==typeof this.load)return this.load(data.name,data.url,data.data),!0;var node=document.getElementById(data.DOMNodeID);if(node){if(node.children.length){var old=etemplate2.getById(node.id);old&&old.clear()}var et2=new etemplate2(node);return et2.load(data.name,data.url,data.data),!0}egw.debug("error","Could not find target node %s",data.DOMNodeId)}throw"Error while parsing et2_load response"}function etemplate2_handle_validation_error(_type,_response){for(var id in _response.data){var widget=this.widgetContainer.getWidgetById(id);if(widget){widget.showMessage(_response.data[id],"validation_error");for(var tmpWidget=widget;tmpWidget._parent&&"tabbox"!=tmpWidget._type;)tmpWidget=tmpWidget._parent;"tabbox"==tmpWidget._type&&tmpWidget.activateTab(widget)}}egw().debug("warn","Validation errors",_response.data)}function etemplate2_handle_assign(type,res,req){if("undefined"!=typeof res.data.id&&"undefined"!=typeof res.data.key&&"undefined"!=typeof res.data.value){if("undefined"==typeof res.data.etemplate_exec_id||res.data.etemplate_exec_id!=this.etemplate_exec_id)return!1;if("etemplate_exec_id"==res.data.key)return this.etemplate_exec_id=res.data.value,!0;if(null==this.widgetContainer)return egw.debug("warn","Tried to call assign on an un-loaded etemplate",res.data),!1;var widget=this.widgetContainer.getWidgetById(res.data.id);if(widget){if("function"!=typeof widget["set_"+res.data.key])return egw.debug("warn","Cannot set %s attribute %s via JSON assign, no set_%s()",res.data.id,res.data.key,res.data.key),!1;try{return widget["set_"+res.data.key].call(widget,res.data.value),!0}catch(e){egw.debug("error","When assigning %s on %s via AJAX, \n"+(e.message||e+""),res.data.key,res.data.id,widget)}}return!1}throw"Invalid parameters"}function xajax_eT_wrapper(obj,widget){if(egw().debug("warn","xajax_eT_wrapper() is deprecated, replace with widget.getInstanceManager().submit()"),"object"==typeof obj){if($j("div.popupManual div.noPrint").hide(),$j("div.ajax-loader").show(),"undefined"==typeof widget&&obj.id)for(var et2=etemplate2.getByApplication(egw_getAppName()),i=0;i<et2.length&&(widget=et2[i].widgetContainer.getWidgetById(obj.id),!widget.getInstanceManager);i++);widget.getInstanceManager().submit(this)}else $j("div.popupManual div.noPrint").show(),$j("div.ajax-loader").hide()}"undefined"==typeof Array.prototype.indexOf&&(Array.prototype.indexOf=function(_elem){for(var i=0;i<this.length;i++)if(this[i]===_elem)return i;return-1});var et2_validTypes=["boolean","string","rawstring","html","float","integer","any","js","dimension"],et2_typeDefaults={boolean:!1,string:"",rawstring:"",html:"",js:null,float:0,integer:0,any:null,dimension:"auto"},et2_no_init=new Object,ClassWithAttributes=function(){"use strict";return Class.extend({getAttribute:function(_name){return"undefined"==typeof this.attributes[_name]||this.attributes[_name].ignore?void egw.debug("error",this,"Attribute '"+_name+"' does not exist!"):"function"==typeof this["get_"+_name]?this["get_"+_name]():this[_name]},setAttribute:function(_name,_value,_override){if("undefined"!=typeof this.attributes[_name]){if(!this.attributes[_name].ignore){"undefined"==typeof _override&&(_override=!0);var val=et2_checkType(_value,this.attributes[_name].type,_name,this);"function"==typeof this["set_"+_name]?this["set_"+_name](val):(_override||"undefined"==typeof this[_name])&&(this[_name]=val)}}else egw.debug("warn",this,"Attribute '"+_name+"' does not exist!")},generateAttributeSet:function(_attrs){for(var key in _attrs)"undefined"!=typeof this.attributes[key]?this.attributes[key].ignore||(_attrs[key]=et2_checkType(_attrs[key],this.attributes[key].type,key,this)):(delete _attrs[key],egw.debug("warn",this,"Attribute '"+key+"' does not exist in "+_attrs.type+"!"));for(var key in this.attributes)if("undefined"==typeof _attrs[key]){var _default=this.attributes[key].default;_default==et2_no_init&&(_default=void 0),_attrs[key]=_default}return _attrs},initAttributes:function(_attrs){for(var key in _attrs)"undefined"==typeof this.attributes[key]||this.attributes[key].ignore||void 0==_attrs[key]||this.setAttribute(key,_attrs[key],!1)},_validate_attributes:function(attributes){for(var key in attributes)et2_validateAttrib(key,attributes[key])}})}.call(this),et2_IDOMNode=new Interface({getDOMNode:function(_sender){}}),et2_IInput=new Interface({getValue:function(){},isDirty:function(){},resetDirty:function(){},isValid:function(messages){}}),et2_IResizeable=new Interface({resize:function(){}}),et2_IAligned=new Interface({get_align:function(){}}),et2_ISubmitListener=new Interface({submit:function(_values){}}),et2_IDetachedDOM=new Interface({getDetachedAttributes:function(_attrs){},getDetachedNodes:function(){},setDetachedAttributes:function(_nodes,_values){}}),et2_IPrint=new Interface({beforePrint:function(){},afterPrint:function(){}});(function(){"use strict";function _throwParserErr(_p,_err){throw"Syntax error while parsing '"+_p.expr+"' at "+_p.pos+", "+_err}function _php_parseDoubleQuoteString(_p,_tree){for(var state=STATE_DEFAULT,str="";_p.pos<_p.expr.length;){var c=_p.expr.charAt(_p.pos++);switch(state){case STATE_DEFAULT:case STATE_CURLY_BRACE_OPEN:switch(c){case"\\":state=STATE_ESCAPED;break;case"$":if("$"==_p.expr.charAt(_p.pos)&&state==STATE_DEFAULT){_p.pos++,str+="$$";break}if(_p.pos==_p.expr.length){str+="$";break}if("/"==_p.expr.charAt(_p.pos)&&"/"==_p.expr.charAt(0)){str+="$";break}str&&(_tree.push(str),str=""),"{"==_p.expr.charAt(_p.pos)&&state!=STATE_CURLY_BRACE_OPEN&&(state=STATE_CURLY_BRACE_OPEN,_p.pos++),state==STATE_CURLY_BRACE_OPEN?(_tree.push(_php_parseVariable(_p)),state=STATE_EXPECT_CURLY_BRACE_CLOSE):_tree.push(_php_parseVariable(_p));break;case"{":state=STATE_CURLY_BRACE_OPEN;break;default:state==STATE_CURLY_BRACE_OPEN&&(str+="{",state=STATE_DEFAULT),str+=c}break;case STATE_ESCAPED:str+=c;break;case STATE_EXPECT_CURLY_BRACE_CLOSE:"}"!=c&&_throwParserErr(_p,"expected '}', but got "+c),state=STATE_DEFAULT}}state==STATE_EXPECT_CURLY_BRACE_CLOSE&&_throwParserErr(_p,"unexpected end of string, expected '}'"),state==STATE_CURLY_BRACE_OPEN&&(str+="{"),str&&_tree.push(str)}function _php_parseVariableName(_p){var vname=PHP_VAR_PREG.exec(_p.expr.substr(_p.pos));return vname?(_p.pos+=vname[0].length,{variable:vname[0],accessExpressions:[]}):void _throwParserErr(_p,"expected variable identifier.")}function _php_parseVariable(_p){for(var variable=_php_parseVariableName(_p),state=STATE_DEFAULT;_p.pos<_p.expr.length;){var c=_p.expr.charAt(_p.pos++);switch(state){case STATE_DEFAULT:switch(c){case"[":variable.accessExpressions.push(_php_parseExpression(_p)),state=STATE_EXPECT_RECT_BRACE_CLOSE;break;default:return _p.pos--,variable}break;case STATE_EXPECT_RECT_BRACE_CLOSE:"]"!=c&&_throwParserErr(_p," expected ']', but got "+c),state=STATE_DEFAULT}}return variable}function _php_readString(_p,_delim){for(var state=STATE_DEFAULT,str="";_p.pos<_p.expr.length;){var c=_p.expr.charAt(_p.pos++);switch(state){case STATE_DEFAULT:if("\\"==c)state=STATE_ESCAPED;else{if(c===_delim||"string"!=typeof _delim&&_delim.test(c))return str;str+=c}break;case STATE_ESCAPED:str+=c,state=STATE_DEFAULT}}_throwParserErr(_p,"unexpected end of string while parsing string!")}function _php_parseExpression(_p){for(var state=STATE_EXPR_BEGIN,result=null;_p.pos<_p.expr.length;){var c=_p.expr.charAt(_p.pos++);switch(state){case STATE_EXPR_BEGIN:switch(c){case" ":case"\n":case"\r":case" ":break;case'"':result=[];var p=_php_parser(_php_readString(_p,'"'));_php_parseDoubleQuoteString(p,result),state=STATE_EXPR_END;break;case"'":var result=_php_readString(_p,"'");state=STATE_EXPR_END;break;case"$":var result=_php_parseVariable(_p);state=STATE_EXPR_END;break;default:_p.pos--;var result=_php_readString(_p,/[^A-Za-z0-9_#]/);result||_throwParserErr(_p,"unexpected char "+c),_p.pos--,state=STATE_EXPR_END}break;case STATE_EXPR_END:switch(c){case" ":case"\n":case"\r":case" ":break;default:return _p.pos--,result}}}_throwParserErr(_p,"unexpected end of string while parsing access expressions!")}function _php_parser(_expr){return{expr:_expr,pos:0}}function _throwCompilerErr(_err){throw"PHP to JS compiler error, "+_err}function _php_compileVariable(_vars,_variable){if(_vars.indexOf(_variable.variable)>=0){for(var result="_"+_variable.variable,i=0;i<_variable.accessExpressions.length;i++)result+="["+_php_compileString(_vars,_variable.accessExpressions[i])+"]";return"(typeof _"+_variable.variable+' != "undefined" && typeof '+result+'!="undefined" && '+result+" != null ? "+result+':"")'}_throwCompilerErr("Variable $"+_variable.variable+" is not defined.")}function _php_compileString(_vars,_string){_string instanceof Array||(_string=[_string]);for(var parts=[],hasString=!1,i=0;i<_string.length;i++){var part=_string[i];"string"==typeof part?(hasString=!0,parts.push("'"+part.replace(/\\/g,"\\\\").replace(/'/g,"\\'")+"'")):parts.push(_php_compileVariable(_vars,part))}return hasString||parts.push('""'),parts.join(" + ")}function _php_compileJSCode(_vars,_tree){return"return "+_php_compileString(_vars,_tree)+";"}var STATE_DEFAULT=0,STATE_ESCAPED=1,STATE_CURLY_BRACE_OPEN=2,STATE_EXPECT_CURLY_BRACE_CLOSE=3,STATE_EXPECT_RECT_BRACE_CLOSE=4,STATE_EXPR_BEGIN=5,STATE_EXPR_END=6,PHP_VAR_PREG=/^([A-Za-z0-9_]+)/;this.et2_compilePHPExpression=function(_expr,_vars){"undefined"==typeof _vars&&(_vars=[]);try{var parser=_php_parser(_expr),syntaxTree=[];_php_parseDoubleQuoteString(parser,syntaxTree);var js=_php_compileJSCode(_vars,syntaxTree);egw.debug("log","Compiled PHP "+_expr+" --> "+js)}catch(e){return egw.debug("warn","Error compiling PHP "+_expr+" --> using it literally ("+("string"==typeof e?e:e.message)+")!"),function(){return _expr}}for(var attrs=[],i=0;i<_vars.length;i++)attrs.push("_"+_vars[i]);return attrs.push(js),Function.apply(Function,attrs)}}).call(window);var et2_arrayMgr=function(){"use strict";return Class.extend({splitIds:!0,init:function(_data,_parentMgr){if("undefined"==typeof _parentMgr&&(_parentMgr=null),this.parentMgr=_parentMgr,"undefined"!=typeof _data&&_data||(egw.debug("log","No data passed to content array manager. Probably a mismatch between template namespaces and data."),_data={}),this.splitIds)for(var key in _data){var indexes=key.replace(/&#x5B;/g,"[").split("[");if(indexes.length>1){for(var value=_data[key],target=_data,i=0;i<indexes.length;i++)indexes[i]=indexes[i].replace(/&#x5D;/g,"").replace("]",""),"undefined"==typeof target[indexes[i]]&&(target[indexes[i]]=i==indexes.length-1?value:{}),target=target[indexes[i]];delete _data[key]}}this.data=_data,this.perspectiveData={owner:null,key:null,row:null}},getRoot:function(){return null!=this.parentMgr?this.parentMgr.getRoot():this},explodeKey:function(_key){var indexes=[_key];if("string"==typeof _key&&(_key=_key.replace(/&#x5B;/g,"[").replace(/&#x5D;/g,"]"),indexes=_key.split("[")),indexes.length>1){indexes=[indexes.shift(),indexes.join("[")],indexes[1]=indexes[1].substring(0,indexes[1].length-1);var children=indexes[1].split("][");children.length&&(indexes=jQuery.merge([indexes[0]],children))}return indexes},getPath:function(_path){return"undefined"==typeof _path&&(_path=[]),null!=this.perspectiveData.key&&(_path=this.perspectiveData.key.replace(/]/g,"").split("[").concat(_path)),null!=this.parentMgr&&(_path=this.parentMgr.getPath(_path)),_path},getEntry:function(_key,_referenceInto,_skipEmpty){"undefined"==typeof _referenceInto&&(_referenceInto=!1),"undefined"==typeof _skipEmpty&&(_skipEmpty=!1);for(var indexes=this.explodeKey(_key),entry=this.data,i=0;i<indexes.length;i++){var isObject="object"==typeof entry;if(!isObject&&!_referenceInto||null==entry||jQuery.isEmptyObject(entry))return null;var idx=indexes[i];if(_skipEmpty&&(!isObject||"undefined"==typeof entry[idx]))return null;entry=entry[idx]}return entry},compiledExpressions:{},expandName:function(_ident){var is_index_in_content="@"==_ident.charAt(0),pos_var=_ident.indexOf("$");if(pos_var>=0&&(null!=this.perspectiveData.row||!_ident.match(/\$\{?row\}?/))){var row=this.perspectiveData.row,row_cont=this.data[row]||{},cont=this.data,_cont=this.data,proto=this.constructor.prototype;if("undefined"==typeof proto.compiledExpressions[_ident])try{null==this.perspectiveData.row?proto.compiledExpressions[_ident]=et2_compilePHPExpression(_ident,["cont","_cont"]):proto.compiledExpressions[_ident]=et2_compilePHPExpression(_ident,["row","cont","row_cont","_cont"])}catch(e){proto.compiledExpressions[_ident]=null,egw.debug("error","Error while compiling PHP->JS ",e)}if(proto.compiledExpressions[_ident])try{_ident=null==this.perspectiveData.row?proto.compiledExpressions[_ident](cont,_cont):proto.compiledExpressions[_ident](row,cont,row_cont,_cont)}catch(e){egw.debug("log","object"==typeof e?e.message:e),_ident=null}}return is_index_in_content&&(_ident="@"==_ident.charAt(1)?this.getRoot().getEntry(_ident.substr(2)):this.getEntry(_ident.substr(1))),_ident},parseBoolExpression:function(_expression){if("!"==_expression.charAt(0))return!this.parseBoolExpression(_expression.substr(1));var parts=_expression.split("="),val=this.expandName(parts[0]);if("undefined"!=typeof parts[1]){var checkVal=this.expandName(parts[1]);return"/"==checkVal.charAt(0)?!!new RegExp(checkVal.substr(1,checkVal.length-2)).test(val):val==checkVal}return et2_evalBool(val)},openPerspective:function(_owner,_root,_row){var root="string"==typeof _root?this.data[_root]:null==_root?this.data:_root;"undefined"==typeof root&&"string"==typeof _root&&(root=this.getEntry(_root));var constructor=this.isReadOnly?et2_readonlysArrayMgr:et2_arrayMgr,mgr=new constructor(root,this);return mgr.perspectiveData.owner=_owner,"string"==typeof _root&&(mgr.perspectiveData.key=_root),"undefined"!=typeof _row&&(mgr.perspectiveData.row=_row),mgr}})}.call(this),et2_readonlysArrayMgr=function(){"use strict";return et2_arrayMgr.extend({isReadOnly:function(_id,_attr,_parent){var entry=null;if(null!=_id){(_id.indexOf("$")>=0||_id.indexOf("@")>=0)&&(_id=this.expandName(_id));for(var mgr=this;mgr.parentMgr&&jQuery.isEmptyObject(mgr.data);)mgr=mgr.parentMgr;entry=mgr.getEntry(_id)}return"undefined"!=typeof entry&&"object"!=typeof entry?entry:"undefined"!=typeof _attr&&null!==_attr?et2_evalBool(_attr):"undefined"!=typeof _parent&&_parent?!0:(entry=this.getEntry("__ALL__"),null!==entry&&"undefined"!=typeof entry)},expandName:function(ident){return this.perspectiveData.owner.getArrayMgr("content").expandName(ident)}})}.call(this),et2_registry={},et2_widget=function(){"use strict";return ClassWithAttributes.extend({attributes:{id:{name:"ID",type:"string",description:"Unique identifier of the widget"},no_lang:{name:"No translation",type:"boolean",default:!1,description:"If true, no translations are made for this widget"},span:{ignore:!0},type:{name:"Widget type",type:"string",ignore:!0,description:"What kind of widget this is"},readonly:{ignore:!0}},legacyOptions:[],createNamespace:!1,init:function(_parent,_attrs){"undefined"==typeof _parent&&(_parent=null),"undefined"==typeof _attrs&&(_attrs={}),this._mgrs={},this._inst=null,this._children=[],this._type=_attrs.type,this.id=_attrs.id,null!=_parent&&_parent.addChild(this),this.supportedWidgetClasses=[et2_widget],_attrs.id&&this.createNamespace&&this.checkCreateNamespace(),this.id,this.transformAttributes(_attrs),this.options=et2_cloneObject(_attrs)},destroy:function(){for(var i=this._children.length-1;i>=0;i--)this._children[i].free();"undefined"!=typeof this._parent&&null!==this._parent&&this._parent.removeChild(this);for(var key in this._mgrs)this._mgrs[key]&&this._mgrs[key].owner==this&&this._mgrs[key].free()},clone:function(_parent){"undefined"==typeof _parent&&(_parent=null);var copy=new this.constructor(_parent,this.options);return copy.assign(this),copy},assign:function(_obj){"undefined"==typeof _obj._children&&this.egw().debug("log","Foo!");for(var i=0;i<_obj._children.length;i++)_obj._children[i].clone(this);this.setArrayMgrs(_obj.mgrs)},getParent:function(){return this._parent},getChildren:function(){return this._children},getRoot:function(){return null!=this._parent?this._parent.getRoot():this},addChild:function(_node){this.insertChild(_node,this._children.length)},insertChild:function(_node,_idx){this.isOfSupportedWidgetClass(_node)?(_node._parent&&_node._parent.removeChild(_node),_node._parent=this,this._children.splice(_idx,0,_node),_node.implements(et2_IDOMNode)&&this.implements(et2_IDOMNode)&&_node.parentNode&&(_node.detachFromDOM(),_node.parentNode=this.getDOMNode(_node),_node.attachToDOM())):this.egw().debug("error","Widget "+_node._type+" is not supported by this widget class",this)},removeChild:function(_node){var idx=this._children.indexOf(_node);idx>=0&&(_node._parent=null,this._children.splice(idx,1))},getWidgetById:function(_id){if(this.id==_id)return this;if(!this._children)return null;for(var i=0;i<this._children.length;i++){var elem=this._children[i].getWidgetById(_id);if(null!=elem)return elem}return null},iterateOver:function(_callback,_context,_type){"undefined"==typeof _type&&(_type=et2_widget),this.isInTree()&&this.instanceOf(_type)&&_callback.call(_context,this);for(var i=0;i<this._children.length;i++)this._children[i].iterateOver(_callback,_context,_type)},isInTree:function(_sender,_vis){return"undefined"==typeof _vis&&(_vis=!0),this._parent?_vis&&this._parent.isInTree(this):_vis},isOfSupportedWidgetClass:function(_obj){for(var i=0;i<this.supportedWidgetClasses.length;i++)if(_obj.instanceOf(this.supportedWidgetClasses[i]))return!0;return!1},parseXMLAttrs:function(_attrsObj,_target,_proto){if("undefined"!=typeof _attrsObj)for(var mgr=this.getArrayMgr("content"),i=0;i<_attrsObj.length;i++){var attrName=_attrsObj[i].name,attrValue=_attrsObj[i].value;if("options"==attrName&&_proto.legacyOptions.length>0){if(_target.id&&this.getArrayMgr("modifications").getEntry(_target.id)){var mod=this.getArrayMgr("modifications").getEntry(_target.id);"undefined"!=typeof mod.options&&(attrValue=_attrsObj[i].value=mod.options)}"@"!=attrValue.charAt(0)&&-1==attrValue.indexOf("$")||(attrValue=mgr.expandName(attrValue));for(var splitted=et2_csvSplit(attrValue+""),j=0;j<splitted.length&&j<_proto.legacyOptions.length;j++)if(0!=splitted[j].trim().length&&"undefined"==typeof _target[_proto.legacyOptions[j]]){attrValue=splitted[j],j==_proto.legacyOptions.length-1&&splitted.length>_proto.legacyOptions.length&&(attrValue=splitted.slice(j));var attr=_proto.attributes[_proto.legacyOptions[j]];"boolean"==attr.type?attrValue=mgr.parseBoolExpression(attrValue):"object"!=typeof attrValue&&(attrValue=mgr.expandName(attrValue)),_target[_proto.legacyOptions[j]]=attrValue}}else{if(null!=mgr&&"undefined"!=typeof _proto.attributes[attrName]){var attr=_proto.attributes[attrName];attrValue="boolean"==attr.type?mgr.parseBoolExpression(attrValue):mgr.expandName(attrValue)}_target[attrName]=attrValue}}},transformAttributes:function(_attrs){if(this.id&&("string"!=typeof this.id&&console.log(this.id),this.getArrayMgr("modifications"))){var data=this.getArrayMgr("modifications").getEntry(this.id);if(this.createNamespace&&this.getArrayMgr("modifications").perspectiveData.owner==this&&(data=this.getArrayMgr("modifications").data),"object"==typeof data)for(var key in data)_attrs[key]=data[key]}for(var key in _attrs)_attrs[key]&&"undefined"!=typeof this.attributes[key]&&(this.attributes[key].translate===!0||"!no_lang"===this.attributes[key].translate&&!_attrs.no_lang)&&(_attrs[key]=this.egw().lang(_attrs[key],"%s"))},createElementFromNode:function(_node){var attributes={},_nodeName=attributes.type=_node.getAttribute("type")?_node.getAttribute("type"):_node.nodeName.toLowerCase(),readonly=attributes.readonly=this.getArrayMgr("readonlys")?this.getArrayMgr("readonlys").isReadOnly(_node.getAttribute("id"),_node.getAttribute("readonly"),"undefined"!=typeof this.readonly?this.readonly:this.options.readonly):!1,modifications=this.getArrayMgr("modifications");if(modifications&&_node.getAttribute("id")){var entry=modifications.getEntry(_node.getAttribute("id"));if(null==entry){var entry=modifications.data[_node.getAttribute("id")];if(entry)this.egw().debug("warn","getEntry("+_node.getAttribute("id")+") failed, but the data is there.",modifications,entry);else var entry=modifications.getRoot().getEntry(_node.getAttribute("id"))}entry&&entry.type&&(_nodeName=attributes.type=entry.type),entry=null}("@"==_nodeName.charAt(0)||_nodeName.indexOf("$")>=0)&&(_nodeName=attributes.type=this.getArrayMgr("content").expandName(_nodeName));var constructor="undefined"==typeof et2_registry[_nodeName]?et2_placeholder:et2_registry[_nodeName];readonly&&"undefined"!=typeof et2_registry[_nodeName+"_ro"]&&(constructor=et2_registry[_nodeName+"_ro"]),this.parseXMLAttrs(_node.attributes,attributes,constructor.prototype),constructor.prototype.generateAttributeSet(attributes);var widget=new constructor(this,attributes);return widget.loadFromXML(_node),widget},loadFromXML:function(_node){for(var i=0;i<_node.childNodes.length;i++){var node=_node.childNodes[i],widgetType=node.nodeName.toLowerCase();"#comment"!=widgetType&&("#text"!=widgetType?this.createElementFromNode(node):node.data.replace(/^\s+|\s+$/g,"")&&this.loadContent(node.data))}},loadContent:function(_content){},loadingFinished:function(promises){if(this.initAttributes(this.options),"undefined"==typeof promises){promises=[];var warn_if_deferred=!0}var loadChildren=function(){for(var i=0;i<this._children.length;i++)try{this._children[i].loadingFinished(promises)}catch(e){egw.debug("error","There was an error with a widget:\nError:%o\nProblem widget:%o",e.valueOf(),this._children[i],e.stack)}},result=this.doLoadingFinished();"boolean"==typeof result&&result?loadChildren.apply(this,arguments):"object"==typeof result&&result.done&&(warn_if_deferred&&egw.debug("warn","Loading was deferred for widget %o, but creator is not checking. Pass a list to loadingFinished().",this),promises.push(result),result.done(jQuery.proxy(loadChildren,this)))},initAttributes:function(_attrs){for(var key in _attrs)if("undefined"!=typeof this.attributes[key]&&!this.attributes[key].ignore&&void 0!=_attrs[key]){var val=_attrs[key];"js"==this.attributes[key].type&&"string"==typeof _attrs[key]&&(val=et2_compileLegacyJS(val,this,this.instanceOf(et2_inputWidget)?this.getInputNode():this.implements(et2_IDOMNode)?this.getDOMNode():null)),this.setAttribute(key,val,!1)}},doLoadingFinished:function(){return!0},egw:function(){if("undefined"==typeof this._egw){if(null!=this._parent)return this._parent.egw();var wnd=null;if(this.implements(et2_IDOMNode)){var node=this.getDOMNode();node&&node.ownerDocument&&(wnd=node.ownerDocument.parentNode||node.ownerDocument.defaultView)}return egw("phpgwapi",wnd)}return this._egw},setApiInstance:function(_egw){this._egw=_egw},setArrayMgrs:function(_mgrs){this._mgrs=et2_cloneObject(_mgrs)},getArrayMgrs:function(_mgrs){"undefined"==typeof _mgrs&&(_mgrs={});for(var key in this._mgrs)"undefined"==typeof _mgrs[key]&&(_mgrs[key]=this._mgrs[key]);return this._parent&&this._parent.getArrayMgrs(_mgrs),_mgrs},setArrayMgr:function(_part,_mgr){this._mgrs[_part]=_mgr},getArrayMgr:function(_part){return this._mgrs&&"undefined"!=typeof this._mgrs[_part]?this._mgrs[_part]:this._parent?this._parent.getArrayMgr(_part):null},checkCreateNamespace:function(){var mgrs=this.getArrayMgrs();for(var key in mgrs){var mgr=mgrs[key];"undefined"!=typeof this._mgrs[key]&&mgr.perspectiveData.owner==this&&(mgr=mgr.parentMgr);var entry=mgr.getEntry(this.id);"object"==typeof entry&&null!==entry||this.id?this._mgrs[key]=mgr.openPerspective(this,this.id):delete this._mgrs[key]}},setInstanceManager:function(_inst){this._inst=_inst},getInstanceManager:function(){return null!=this._inst?this._inst:this._parent?this._parent.getInstanceManager():null},getPath:function(){var path=this.getArrayMgr("content").getPath();return this.id&&this.createNamespace&&path[path.length-1]==this.id&&path.pop(),path}})}.call(this),et2_DOMWidget=function(){"use strict";return et2_widget.extend(et2_IDOMNode,{attributes:{disabled:{name:"Disabled",type:"boolean",description:"Defines whether this widget is visible. Not to be confused with an input widget's HTML attribute 'disabled'.",default:!1},width:{name:"Width",type:"dimension",default:et2_no_init,description:"Width of the element in pixels, percentage or 'auto'"},height:{name:"Height",type:"dimension",default:et2_no_init,description:"Height of the element in pixels, percentage or 'auto'"},class:{name:"CSS Class",type:"string",default:et2_no_init,description:"CSS Class which is applied to the dom element of this node"},overflow:{name:"Overflow",type:"string",default:et2_no_init,description:"If set, the css-overflow attribute is set to that value"},parent_node:{name:"DOM parent",type:"string",default:et2_no_init,description:"Insert into the target DOM node instead of the normal location"},actions:{name:"Actions list",type:"any",default:et2_no_init,description:"List of egw actions that can be done on the widget. This includes context menu, drag and drop. TODO: Link to action documentation"},default_execute:{name:"Default onExecute for actions",type:"js",default:et2_no_init,description:"Set default onExecute javascript method for action not specifying their own"},resize_ratio:{name:"Resize height of the widget on callback resize",type:"string",default:"",description:"Allow Resize height of the widget based on exess height and given ratio"},data:{name:"comma-separated name:value pairs set as data attributes on DOM node",type:"string",default:"",description:'data="mime:${row}[mime]" would generate data-mime="..." in DOM, eg. to use it in CSS on a parent'},background:{name:"Add background image",type:"string",default:"",description:"Sets background image, left, right and scale on DOM"}},init:function(){this._super.apply(this,arguments),this.parentNode=null,this._attachSet={node:null,parent:null},this.disabled=!1,this._surroundingsMgr=null},destroy:function(){if(this.detachFromDOM(),this.parentNode=null,this._attachSet={},this._actionManager){var app_om=egw_getObjectManager(this.egw().getAppName(),!1,1);if(app_om){var om=app_om.getObjectById(this.id);om&&om.remove()}this._actionManager.remove(),this._actionManager=null}this._surroundingsMgr&&(this._surroundingsMgr.free(),this._surroundingsMgr=null),this._super()},doLoadingFinished:function(){return this._parent&&this._parent.implements(et2_IDOMNode)&&(this.options.parent_node?this.set_parent_node(this.options.parent_node):this.setParentDOMNode(this._parent.getDOMNode(this))),!0},detachFromDOM:function(){if(this._attachSet.node&&this._attachSet.parent){try{this._attachSet.parent.removeChild(this._attachSet.node)}catch(e){}return this._attachSet={node:null,parent:null},!0}return!1},attachToDOM:function(){var node=this.getDOMNode(this);if(node&&this.parentNode&&(node!=this._attachSet.node||this.parentNode!=this._attachSet.parent)){this._surroundingsMgr&&(node=this._surroundingsMgr.getDOMNode(node));var idx=this.getDOMIndex();return 0>idx||idx>=this.parentNode.childNodes.length-1?this.parentNode.appendChild(node):this.parentNode.insertBefore(node,this.parentNode.childNodes[idx]),this._attachSet={node:node,parent:this.parentNode},!0}return!1},isAttached:function(){return null!=this.parentNode},getSurroundings:function(){return this._surroundingsMgr||(this._surroundingsMgr=new et2_surroundingsMgr(this)),this._surroundingsMgr},set_parent_node:function(_node){if("string"==typeof _node){var parent=$j("#"+_node);0==parent.length?this.egw().debug("warn",'Unable to find DOM parent node with ID "%s" for widget %o.',_node,this):this.setParentDOMNode(parent.get(0))}else this.setParentDOMNode(_node)},setParentDOMNode:function(_node){_node!=this.parentNode&&(this.detachFromDOM(),this.parentNode=_node,this.attachToDOM())},getParentDOMNode:function(){return this.parentNode},getDOMIndex:function(){if(this._parent){var idx=0,children=this._parent.getChildren();if(children&&children.indexOf)return children.indexOf(this);egw.debug("warn","No Array.indexOf(), falling back to looping. ");for(var i=0;i<children.length;i++){if(children[i]==this)return idx;children[i].isInTree()&&idx++}}return-1},set_id:function(_value){this.id=_value,this.dom_id=_value?this.getInstanceManager().uniqueId+"_"+_value.replace(/\./g,"-"):_value;var node=this.getDOMNode(this);node&&(""!=_value?node.setAttribute("id",this.dom_id):node.removeAttribute("id"))},set_disabled:function(_value){var node=null!=this._surroundingsMgr?this._surroundingsMgr.getDOMNode(this.getDOMNode(this)):this.getDOMNode(this);node&&this.disabled!=_value&&(this.disabled=_value,_value?$j(node).hide():$j(node).show())},set_width:function(_value){this.width=_value;var node=this.getDOMNode(this);node&&$j(node).css("width",_value)},set_height:function(_value){
this.height=_value;var node=this.getDOMNode(this);node&&$j(node).css("height",_value)},set_class:function(_value){var node=this.getDOMNode(this);node&&(this.class&&$j(node).removeClass(this.class),$j(node).addClass(_value)),this.class=_value},set_overflow:function(_value){this.overflow=_value;var node=this.getDOMNode(this);node&&$j(node).css("overflow",_value)},set_data:function(_value){var node=this.getDOMNode(this);if(node&&_value)for(var pairs=_value.split(/,/g),i=0;i<pairs.length;++i){var name_value=pairs[i].split(":");$j(node).attr("data-"+name_value[0],name_value[1])}},set_background:function(_value){var node=this.getDOMNode(this),values="";_value&&node&&(values=_value.split(","),jQuery(node).css({"background-image":'url("'+values[0]+'")',"background-position-x":values[1],"background-position-y":values[2],"background-scale":values[3]}))},set_actions:function(actions){if(""==this.id||"undefined"==typeof this.id)return void this.egw().debug("warn","Widget should have an ID if you want actions",this);var gam=egw_getActionManager(this.egw().appName,!0,1);"object"!=typeof this._actionManager&&(null!==gam.getActionById(this.getInstanceManager().uniqueId,1)&&(gam=gam.getActionById(this.getInstanceManager().uniqueId,1)),null!=gam.getActionById(this.id,1)?this._actionManager=gam.getActionById(this.id,1):this._actionManager=gam.addAction("actionManager",this.id)),this._actionManager.updateActions(actions),this.options.default_execute&&this._actionManager.setDefaultExecute(this.options.default_execute),this._actionManager.data={widget:this},this._link_actions(actions)},set_default_execute:function(_default_execute){this.options.default_execute=_default_execute,this._actionManager&&this._actionManager.setDefaultExecute(null,_default_execute)},_get_action_links:function(actions){var action_links=[];for(var i in actions){var action=actions[i];action_links.push("undefined"!=typeof action.id?action.id:i)}return action_links},_link_actions:function(actions){var objectManager=egw_getAppObjectManager(!0),widget_object=objectManager.getObjectById(this.id);null==widget_object?widget_object=objectManager.insertObject(!1,new egwActionObject(this.id,objectManager,new et2_action_object_impl(this),this._actionManager||objectManager.manager.getActionById(this.id)||objectManager.manager)):widget_object.setAOI(new et2_action_object_impl(this,this.getDOMNode())),widget_object.clear(),widget_object.unregisterActions();var action_links=this._get_action_links(actions);widget_object.updateActionLinks(action_links)}})}.call(this),et2_surroundingsMgr=function(){"use strict";return ClassWithAttributes.extend({init:function(_widget){this.widget=_widget,this._widgetContainer=null,this._widgetSurroundings=[],this._widgetPlaceholder=null,this._widgetNode=null,this._ownPlaceholder=!0},destroy:function(){this._widgetContainer=null,this._widgetSurroundings=null,this._widgetPlaceholder=null,this._widgetNode=null},prependDOMNode:function(_node){this._widgetSurroundings.unshift(_node),this._surroundingsUpdated=!0},appendDOMNode:function(_node){this._ownPlaceholder&&null==this._widgetPlaceholder&&(this._widgetPlaceholder=document.createElement("span"),this._widgetSurroundings.push(this._widgetPlaceholder)),this._widgetSurroundings.push(_node),this._surroundingsUpdated=!0},insertDOMNode:function(_node){if(!this._ownPlaceholder||null==this._widgetPlaceholder)return void this.appendDOMNode(_node);var idx=this._widgetSurroundings.indexOf(this._widgetPlaceholder);this._widgetSurroundings.splice(idx,1,_node),this._widgetPlaceholder=null,this._ownPlaceholder=!1},removeDOMNode:function(_node){for(var i=0;this._widgetSurroundings&&i<this._widgetSurroundings.length;i++)if(this._widgetSurroundings[i]==_node){this._widgetSurroundings.splice(i,1),this._surroundingsUpdated=!0;break}},setWidgetPlaceholder:function(_node){if(_node!=this._widgetPlaceholder){if(null!=_node&&this._ownPlaceholder&&null!=this._widgetPlaceholder){var idx=this._widgetSurroundings.indexOf(this._widgetPlaceholder);this._widgetSurroundings.splice(idx,1),this._widgetPlaceholder=null,this._ownPlaceholder=!1}this._ownPlaceholder=null==_node,this._widgetPlaceholder=_node,this._surroundingsUpdated=!0}},_rebuildContainer:function(){if(!this._surroundingsUpdated)return!1;if(this._widgetSurroundings.length>0){var hasPlaceholder=et2_hasChild(this._widgetSurroundings,this._widgetPlaceholder);if(hasPlaceholder||(this._widgetPlaceholder=document.createElement("span"),this._widgetSurroundings.push(this._widgetPlaceholder),this._ownPlaceholder=!0),1==this._widgetSurroundings.length)this._widgetSurroundings[0]==this._widgetPlaceholder?this._widgetContainer=null:this._widgetContainer=this._widgetSurroundings[0];else{this._widgetContainer=document.createElement("span");for(var i=0;i<this._widgetSurroundings.length;i++)this._widgetContainer.appendChild(this._widgetSurroundings[i])}}else this._widgetContainer=null,this._widgetPlaceholder=null;return this._surroundingsUpdated=!1,!0},update:function(){if(this._surroundingsUpdated){var attached=this.widget?this.widget.isAttached():!1;attached&&this.widget&&(this.widget.detachFromDOM(),this.widget.attachToDOM())}},getDOMNode:function(_widgetNode){null!=this._widgetNode&&this._widgetNode!=_widgetNode&&(this._surroundingsUpdated=!0),this._widgetNode=_widgetNode;var updated=this._rebuildContainer();return null==this._widgetContainer?_widgetNode:(updated&&(this._widgetPlaceholder.parentNode.replaceChild(_widgetNode,this._widgetPlaceholder),this._ownPlaceholder||(this._widgetPlaceholder=_widgetNode)),this._widgetContainer)}})}.call(this),et2_template=function(){"use strict";return et2_DOMWidget.extend({attributes:{template:{name:"Template",type:"string",description:"Name / ID of template with optional cache-buster ('?'+filemtime of template on server)",default:et2_no_init},group:{name:"Group",description:"Not implemented",default:et2_no_init},version:{name:"Version",type:"string",description:"Version of the template"},lang:{name:"Language",type:"string",description:"Language the template is written in"},content:{name:"Content index",default:et2_no_init,description:"Used for passing in specific content to the template other than what it would get by ID."},url:{name:"URL of template",type:"string",description:"full URL to load template incl. cache-buster"}},createNamespace:!0,init:function(_parent,_attrs){if(_attrs.content&&(this.content=_attrs.content),this._super.apply(this,arguments),this.div=document.createElement("div"),this.loading=jQuery.Deferred(),""!=this.id||this.options.template){var parts=(this.options.template||this.id).split("?"),cache_buster=parts.length>1?parts.pop():null,template_name=parts.pop(),xml=null,templates=etemplate2.prototype.templates;if(!(xml=templates[template_name])){if(template_name.indexOf(".")<0){var root=_parent?_parent.getRoot():null,top_name=root&&root._inst?root._inst.name:null;top_name&&template_name.indexOf(".")<0&&(template_name=top_name+"."+template_name)}if(xml=templates[template_name],!xml){var url=this.options.url;if(!this.options.url){var splitted=template_name.split(".");url=this.getRoot()._inst.template_base_url+splitted.shift()+"/templates/default/"+splitted.join(".")+".xet"+(cache_buster?"?download="+cache_buster:"")}return-1==url.indexOf("?")&&(url+="?download="+(new Date).valueOf()),void((this.options.url||splitted.length)&&et2_loadXMLFromURL(url,function(_xmldoc){for(var i=0;i<_xmldoc.childNodes.length;i++){var template=_xmldoc.childNodes[i];"template"==template.nodeName.toLowerCase()&&(templates[template.getAttribute("id")]=template)}"undefined"!=typeof templates[template_name]&&this.loadFromXML(templates[template_name]),this.loading.resolve()},this))}}null!==xml&&"undefined"!=typeof xml?(this.egw().debug("log","Loading template from XML: ",template_name),this.loadFromXML(xml),this.loading.resolve()):(this.egw().debug("warn","Unable to find XML for ",template_name),this.loading.reject())}else this.loading.resolve()},checkCreateNamespace:function(){if(this.content){var old_id=this.id;this.id=this.content,this._super.apply(this,arguments),this.id=old_id}},getDOMNode:function(){return this.div},doLoadingFinished:function(){return this._super.apply(this,arguments),this.loading.done(jQuery.proxy(function(){$j(this).trigger("load")},this.div)),this.loading.promise()}})}.call(this);et2_register_widget(et2_template,["template"]);var et2_grid=function(){"use strict";return et2_DOMWidget.extend([et2_IDetachedDOM,et2_IAligned,et2_IResizeable],{createNamespace:!0,attributes:{border:{ignore:!0},align:{name:"Align",type:"string",default:"left",description:"Position of this element in the parent hbox"},spacing:{ignore:!0},padding:{ignore:!0},sortable:{name:"Sortable callback",type:"string",default:et2_no_init,description:"PHP function called when user sorts the grid. Setting this enables sorting the grid rows. The callback will be passed the ID of the grid and the new order of the rows."}},init:function(){this.table=$j(document.createElement("table")).addClass("et2_grid"),this.thead=$j(document.createElement("thead")).appendTo(this.table),this.tfoot=$j(document.createElement("tfoot")).appendTo(this.table),this.tbody=$j(document.createElement("tbody")).appendTo(this.table),this._super.apply(this,arguments),this.rowCount=0,this.columnCount=0,this.cells=[],this.rowData=[],this.colData=[],this.managementArray=[],this.template_node=null,this.wrapper=null},destroy:function(){this._super.call(this,arguments)},_initCells:function(_colData,_rowData){for(var w=_colData.length,h=_rowData.length,cells=new Array(h),y=0;h>y;y++){cells[y]=new Array(w);for(var x=0;w>x;x++)cells[y][x]={td:null,widget:null,colData:_colData[x],rowData:_rowData[y],disabled:_colData[x].disabled||_rowData[y].disabled,class:_colData[x].class,colSpan:1,autoColSpan:!1,rowSpan:1,autoRowSpan:!1,width:_colData[x].width,x:x,y:y}}return cells},_getColDataEntry:function(){return{width:"auto",class:"",align:"",span:"1",disabled:!1}},_getRowDataEntry:function(){return{height:"auto",class:"",valign:"top",span:"1",disabled:!1}},_getCell:function(_cells,_x,_y){if(_y>=0&&_y<_cells.length){var row=_cells[_y];if(_x>=0&&_x<row.length)return row[_x]}throw"Error while accessing grid cells, invalid element count or span value!"},_forceNumber:function(_val){if(isNaN(_val))throw _val+" is not a number!";return parseInt(_val)},_fetchRowColData:function(columns,rows,colData,rowData){if(et2_filteredNodeIterator(columns,function(node,nodeName){var colDataEntry=this._getColDataEntry();if(colDataEntry.disabled=this.getArrayMgr("content").parseBoolExpression(et2_readAttrWithDefault(node,"disabled","")),"column"==nodeName){colDataEntry.width=et2_readAttrWithDefault(node,"width","auto"),colDataEntry.class=et2_readAttrWithDefault(node,"class",""),colDataEntry.align=et2_readAttrWithDefault(node,"align",""),colDataEntry.span=et2_readAttrWithDefault(node,"span","1");for(var i in node.attributes){var attr=node.attributes[i];2==attr.nodeType&&"undefined"==typeof colDataEntry[attr.nodeName]&&(colDataEntry[attr.nodeName]=attr.value)}}else colDataEntry.span="all";colData.push(colDataEntry)},this),et2_filteredNodeIterator(rows,function(node,nodeName){var rowDataEntry=this._getRowDataEntry();if(rowDataEntry.disabled=this.getArrayMgr("content").parseBoolExpression(et2_readAttrWithDefault(node,"disabled","")),"row"==nodeName){this.lastRowNode=node,rowDataEntry.height=et2_readAttrWithDefault(node,"height","auto"),rowDataEntry.class=et2_readAttrWithDefault(node,"class",""),rowDataEntry.valign=et2_readAttrWithDefault(node,"valign",""),rowDataEntry.span=et2_readAttrWithDefault(node,"span","1"),rowDataEntry.part=et2_readAttrWithDefault(node,"part","body");var id=et2_readAttrWithDefault(node,"id","");id&&(rowDataEntry.id=id)}else rowDataEntry.span="all";rowData.push(rowDataEntry)},this),this.getArrayMgr("content"))for(var content=this.getArrayMgr("content"),rowDataEntry=rowData[rowData.length-1],rowIndex=rowData.length-1,cont=!0;cont;)if(content.data[rowIndex])rowData[rowIndex]=jQuery.extend({},rowDataEntry),rowIndex++;else{if(null==this.lastRowNode)break;for(var nm=!1,widget=this;!nm&&widget!=this.getRoot();)nm="nextmatch"==widget._type,widget=widget.getParent();if(nm)break;var currentPerspective=jQuery.extend({},content.perspectiveData),check=function(node,nodeName){if("box"==nodeName||"hbox"==nodeName||"vbox"==nodeName)return et2_filteredNodeIterator(node,check,this);content.perspectiveData.row=rowIndex;for(var attr in node.attributes){var value=et2_readAttrWithDefault(node,node.attributes[attr].name,"");if(value.indexOf("@")>0||value.indexOf("$")>0){var ident=content.expandName(value);for("@"!=value[0]&&(ident=content.getEntry(ident,!1,!0));null!=ident&&1e3>rowIndex;)rowData[rowIndex]=jQuery.extend({},rowDataEntry),content.perspectiveData.row=++rowIndex,ident=content.expandName(value),"@"!=value[0]&&(ident=content.getEntry(ident,!1,!0));return void(rowIndex>=1e3&&egw.debug("error","Problem in autorepeat fallback: too many rows for '%s'. Use a nextmatch, or start debugging.",value))}}};et2_filteredNodeIterator(this.lastRowNode,check,this),cont=!1,content.perspectiveData=currentPerspective}rowIndex<=rowData.length-1&&(this.lastRowNode=null)},_fillCells:function(cells,columns,rows){var h=cells.length,w=h>0?cells[0].length:0,currentPerspective=jQuery.extend({},this.getArrayMgr("content").perspectiveData),x=0;et2_filteredNodeIterator(columns,function(node,nodeName){function _readColNode(node,nodeName){if(y>=h)return void this.egw().debug("warn","Skipped grid cell in column, '"+nodeName+"'");var cell=this._getCell(cells,x,y);node.getAttribute("span")?cell.rowSpan=node.getAttribute("span"):(cell.rowSpan=cell.colData.span,cell.autoRowSpan=!0),"all"==cell.rowSpan&&(cell.rowSpan=cells.length);for(var span=cell.rowSpan=this._forceNumber(cell.rowSpan),widget=this.createElementFromNode(node,nodeName),i=0;span>i&&y<cells.length;i++,y++)this._getCell(cells,x,y).widget=widget}var y=0;"column"==nodeName?et2_filteredNodeIterator(node,_readColNode,this):_readColNode.call(this,node,nodeName),x++},this);for(var readRowNode,y=0,x=0,nm=!1,widget=this;!nm&&widget!=this.getRoot();)nm="nextmatch"==widget._type,widget=widget.getParent();for(et2_filteredNodeIterator(rows,function(node,nodeName){if(readRowNode=function(node,nodeName){if(x>=w)return void("description"!=nodeName&&this.egw().debug("warn","Skipped grid cell in row, '"+nodeName+"'"));var cell=this._getCell(cells,x,y);node.getAttribute("span")?cell.colSpan=node.getAttribute("span"):(cell.colSpan=cell.rowData.span,cell.autoColSpan=!0),"all"==cell.colSpan&&(cell.colSpan=cells[y].length);var span=cell.colSpan=this._forceNumber(cell.colSpan);if(node.getAttribute("align")&&(cell.align=node.getAttribute("align")),"nextmatch-"==nodeName.substr(0,10)&&(cell.nm_id=node.getAttribute("id")),node.getAttribute("class")&&(cell.class+=(cell.class?" ":"")+node.getAttribute("class")),!cell.disabled){if(!nm){var mgrs=this.getArrayMgrs();for(var name in mgrs)this.getArrayMgr(name).perspectiveData.row=y;this._getCell(cells,x,y).rowData.id&&(this._getCell(cells,x,y).rowData.id=this.getArrayMgr("content").expandName(this._getCell(cells,x,y).rowData.id)),this._getCell(cells,x,y).rowData.class&&(this._getCell(cells,x,y).rowData.class=this.getArrayMgr("content").expandName(this._getCell(cells,x,y).rowData.class))}var widget=this.createElementFromNode(node,nodeName)}for(var i=0;span>i&&x<cells[y].length;i++,x++){if(cell=this._getCell(cells,x,y),null!=cell.widget)throw"Grid cell collision, two elements defined for cell ("+x+","+y+")!";cell.widget=widget}},x=0,!this.lastRowNode||node!=this.lastRowNode){if("row"==nodeName){for(var name in this.getArrayMgrs());this._getCell(cells,x,y).rowData.id&&this.getArrayMgr("content").expandName(this.rowData[y].id);var disabled=!1;"1"==node.getAttribute("disabled")&&(disabled=!0),disabled||et2_filteredNodeIterator(node,readRowNode,this)}else readRowNode.call(this,node,nodeName);y++}},this),y;h>y;y++){var x=0;et2_filteredNodeIterator(this.lastRowNode,readRowNode,this)}for(var name in this.getArrayMgrs())this.getArrayMgr(name).perspectiveData=currentPerspective},_expandLastCells:function(_cells){for(var h=_cells.length,w=h>0?_cells[0].length:0,y=0;h>y;y++)for(var x=w-1;x>=0;x--){var cell=_cells[y][x];if(null!=cell.widget){cell.autoColSpan&&(cell.colSpan=w-x);break}}for(var x=0;w>x;x++)for(var y=h-1;y>=0;y--){var cell=_cells[y][x];if(null!=cell.widget){cell.autoRowSpan&&(cell.rowSpan=h-y);break}}},loadFromXML:function(_node){this.template_node=_node;var rowsElems=et2_directChildrenByTagName(_node,"rows"),columnsElems=et2_directChildrenByTagName(_node,"columns");if(1!=rowsElems.length||1!=columnsElems.length)throw"Error while parsing grid, none or multiple rows or columns tags!";var columns=columnsElems[0],rows=rowsElems[0],colData=[],rowData=[];this._fetchRowColData(columns,rows,colData,rowData);var cells=this._initCells(colData,rowData);this._fillCells(cells,columns,rows),this._expandLastCells(cells),this.createTableFromCells(cells,colData,rowData)},createTableFromCells:function(_cells,_colData,_rowData){this.managementArray=[],this.cells=_cells,this.colData=_colData,this.rowData=_rowData;for(var h=this.rowCount=_cells.length,w=this.columnCount=h>0?_cells[0].length:0,y=0;h>y;y++){var parent=(_cells[y],this.tbody);switch(this.rowData[y].part){case"header":this.tbody.children().length||this.tfoot.children().length||(parent=this.thead);break;case"footer":this.tbody.children().length||(parent=this.tfoot)}var tr=$j(document.createElement("tr")).appendTo(parent).addClass(this.rowData[y].class);this.rowData[y].disabled&&tr.hide(),"auto"!=this.rowData[y].height&&tr.height(this.rowData[y].height),this.rowData[y].valign&&tr.attr("valign",this.rowData[y].valign),this.rowData[y].id&&tr.attr("id",this.rowData[y].id);for(var x=0;w>x;){var cell=this._getCell(_cells,x,y);if(null==cell.td&&null!=cell.widget){var td=$j(document.createElement("td")).appendTo(tr).addClass(cell.class);cell.disabled&&(td.hide(),cell.widget.options=cell.disabled),"auto"!=cell.width&&td.width(cell.width),cell.align&&td.attr("align",cell.align),this.managementArray.push({cell:td[0],widget:cell.widget,disabled:cell.disabled});var cs=x==w-1?w-x:Math.min(w-x,cell.colSpan),rs=y==h-1?h-y:Math.min(h-y,cell.rowSpan);cs>1&&td.attr("colspan",cs),rs>1&&td.attr("rowspan",rs);for(var sx=x;x+cs>sx;sx++)for(var sy=y;y+rs>sy;sy++)this._getCell(_cells,sx,sy).td=td;x+=cell.colSpan}else x++}}},getDOMNode:function(_sender){if(_sender==this||"undefined"==typeof _sender)return null!=this.wrapper?this.wrapper[0]:this.table[0];for(var i=0;i<this.managementArray.length;i++)if(this.managementArray[i].widget==_sender)return this.managementArray[i].cell;return null},isInTree:function(_sender){var vis=!0;if("undefined"!=typeof _sender&&_sender!=this){vis=!1;for(var i=0;i<this.managementArray.length;i++)if(this.managementArray[i].widget==_sender){vis=!this.managementArray[i].disabled;break}}return this._super(this,vis)},set_overflow:function(_value){var wrapper=this.wrapper||this.table.parent('[id$="_grid_wrapper"]');this.overflow=_value,0==wrapper.length&&_value&&"visible"!==_value&&(this.wrapper=wrapper=this.table.wrap('<div id="'+this.id+'_grid_wrapper"></div>').parent(),this.height&&wrapper.css("height",this.height)),wrapper.css("overflow",_value),!wrapper.length||_value&&null!=_value&&"visible"!==_value||this.table.unwrap()},set_align:function(_value){this.align=_value},get_align:function(_value){return this.align},set_value:function(_value){for(var i=0;i<this.managementArray.length;i++){var cell=this.managementArray[i];cell.widget&&cell.widget.destroy()}this.managementArray=[],this.thead.empty(),this.tfoot.empty(),this.tbody.empty();for(var key in _value)this.getArrayMgr(key).data=_value[key];this.loadFromXML(this.template_node),this.loadingFinished()},set_sortable:function(sortable){if(!sortable)return void this.tbody.sortable("destroy");$j("tr",this.tbody).each(function(index){var $this=$j(this);$this.hasClass("th")||$this.attr("id")||$this.attr("id",index)});var self=this;this.tbody.sortable({items:"tr:not(.th)",distance:15,stop:function(event,ui){self.egw(window).json(sortable,[self.tbody.sortable("toArray"),self.id],null,self,!0).sendRequest()}})},_link_actions:function(actions){var objectManager=egw_getAppObjectManager(!0);objectManager=objectManager.getObjectById(this.getInstanceManager().uniqueId,2)||objectManager;var widget_object=objectManager.getObjectById(this.id);null==widget_object&&(widget_object=objectManager.insertObject(!1,new egwActionObject(this.id,objectManager,new et2_action_object_impl(this),this._actionManager||objectManager.manager.getActionById(this.id)||objectManager.manager))),widget_object.clear();for(var action_links=this._get_action_links(actions),i=0;i<this.rowData.length;i++){var row=$j("tr",this.tbody)[i],aoi=new et2_action_object_impl(this,row),id="row_"+i,content=this.getArrayMgr("content").getEntry(i);content&&content.id&&(id=content.id);var obj=widget_object.addObject(id,aoi);content&&(obj.data=content),obj.updateActionLinks(action_links)}},getDetachedAttributes:function(_attrs){},getDetachedNodes:function(){return[this.getDOMNode()]},setDetachedAttributes:function(_nodes,_values){},_getColumnName:function(){for(var ids=[],r=0;r<this.cells.length;++r)for(var cols=this.cells[r],c=0;c<cols.length;++c)cols[c].nm_id&&ids.push(cols[c].nm_id);return ids.join("_")},resize:function(_height){"undefined"!=typeof this.options&&_height&&"undefined"!=typeof this.options.resize_ratio&&this.options.resize_ratio&&(_height=""!=this.options.resize_ratio?_height*this.options.resize_ratio:_height,0!=_height&&(this.wrapper?this.wrapper.height(this.wrapper.height()+_height):this.table.height(this.table.height()+_height)))},getRow:function(_sender){if(_sender&&this.cells)for(var r=0;r<this.cells.length;++r)for(var row=this.cells[r],c=0;c<row.length;++c)if(row[c].widget){var found=row[c].widget===_sender;if(found||row[c].widget.iterateOver(function(_widget){_widget===_sender&&(found=!0)}),found){for(var row_obj=new et2_widget(this,{}),c=0;c<row.length;++c)row[c].widget&&row_obj._children.push(row[c].widget);return row_obj.isInTree=jQuery.proxy(this.isInTree,this),row_obj.destroy=function(){delete row_obj._children},row_obj}}}})}.call(this);et2_register_widget(et2_grid,["grid"]);var et2_baseWidget=function(){"use strict";return et2_DOMWidget.extend(et2_IAligned,{attributes:{statustext:{name:"Tooltip",type:"string",description:"Tooltip which is shown for this element",translate:!0},align:{name:"Align",type:"string",default:"left",description:"Position of this element in the parent hbox"},onclick:{name:"onclick",type:"js",default:et2_no_init,description:"JS code which is executed when the element is clicked."}},init:function(){this.align="left",this._super.apply(this,arguments),this.node=null,this.statustext="",this._messageDiv=null,this._tooltipElem=null},destroy:function(){this._super.apply(this,arguments),this.node=null,this._messageDiv=null},showMessage:function(_text,_type,_floating,_prepend){"undefined"==typeof _type&&(_type="hint"),"undefined"==typeof _floating&&(_floating=!0),"undefined"==typeof _prepend&&(_prepend=!1);var surr=this.getSurroundings();this.hideMessage(!1,!0),this._messageDiv=$j(document.createElement("div")).addClass("message").addClass(_type).addClass(_floating?"floating":"").text(_text.valueOf()+""),_prepend?surr.prependDOMNode(this._messageDiv[0]):surr.appendDOMNode(this._messageDiv[0]),surr.update()},hideMessage:function(_fade,_noUpdate){if("undefined"==typeof _fade&&(_fade=!0),"undefined"==typeof _noUpdate&&(_noUpdate=!1),null!=this._messageDiv){var surr=this.getSurroundings(),self=this,messageDiv=this._messageDiv;self._messageDiv=null;var _done=function(){surr.removeDOMNode(messageDiv[0]),_noUpdate||surr.update()};_fade?messageDiv.fadeOut("fast",_done):_done()}},detachFromDOM:function(){this._tooltipElem&&(this.egw().tooltipUnbind(this._tooltipElem),this._tooltipElem=null),this.node&&$j(this.node).unbind("click.et2_baseWidget"),this._super.apply(this,arguments)},attachToDOM:function(){this._super.apply(this,arguments),this.node&&($j(this.node).bind("click.et2_baseWidget",this,function(e){return e.data.click.call(e.data,e,this)}),"function"==typeof this.onclick&&$j(this.node).addClass("et2_clickable")),this.set_statustext(this.statustext)},setDOMNode:function(_node){return _node!=this.node?(this.detachFromDOM(),this.node=_node,this.attachToDOM()):!1},getDOMNode:function(){return this.node},getTooltipElement:function(){return this.getDOMNode(this)},click:function(_ev){if("function"==typeof this.onclick){var args=Array.prototype.slice.call(arguments);return-1==args.indexOf(this)&&args.splice(1,0,this),this.onclick.apply(this,args)}return!0},set_statustext:function(_value){if(""!=_value||this._tooltipElem){this.statustext=_value;var elem=$j(this.getTooltipElement());elem&&(this._tooltipElem&&(this.egw().tooltipUnbind(this._tooltipElem),this._tooltipElem=null),_value&&""!=_value&&(this.egw().tooltipBind(elem,_value),this._tooltipElem=elem))}},set_align:function(_value){this.align=_value},get_align:function(_value){return this.align}})}.call(this),et2_container=function(){"use strict";return et2_baseWidget.extend({init:function(){this._super.apply(this,arguments),this.setDOMNode(document.createElement("div"))},destroy:function(){for(var i=this._children.length-1;i>=0;i--)this._children[i].free();for(var key in this._mgrs)this._mgrs[key]&&this._mgrs[key].owner==this&&this._mgrs[key].free()}})}.call(this),et2_placeholder=function(){"use strict";return et2_baseWidget.extend([et2_IDetachedDOM],{init:function(){this._super.apply(this,arguments),this.attrNodes={},this.visible=!1,this.placeDiv=$j(document.createElement("span")).addClass("et2_placeholder");var headerNode=$j(document.createElement("span")).text(this._type||"").addClass("et2_caption").appendTo(this.placeDiv),attrsCntr=$j(document.createElement("span")).appendTo(this.placeDiv).hide();headerNode.click(this,function(e){e.data.visible=!e.data.visible,e.data.visible?attrsCntr.show():attrsCntr.hide()});for(var key in this.options)"undefined"!=typeof this.options[key]&&("undefined"==typeof this.attrNodes[key]&&(this.attrNodes[key]=$j(document.createElement("span")).addClass("et2_attr"),attrsCntr.append(this.attrNodes[key])),this.attrNodes[key].text(key+"="+this.options[key]));this.setDOMNode(this.placeDiv[0])},getDetachedAttributes:function(_attrs){_attrs.push("value")},getDetachedNodes:function(){return[this.placeDiv[0]]},setDetachedAttributes:function(_nodes,_values){this.placeDiv=jQuery(_nodes[0])}})}.call(this),et2_box=function(){"use strict";return et2_baseWidget.extend([et2_IDetachedDOM],{attributes:{rows:{ignore:!0},cols:{ignore:!0}},createNamespace:!0,init:function(){this._super.apply(this,arguments),this.div=$j(document.createElement("div")).addClass("et2_"+this._type).addClass("et2_box_widget"),this.setDOMNode(this.div[0])},loadFromXML:function(_node){if("box"!=this._type)return this._super.apply(this,arguments);for(var childIndex=0,repeatNode=null,i=0;i<_node.childNodes.length;i++){var node=_node.childNodes[i],widgetType=node.nodeName.toLowerCase();if("#comment"!=widgetType)if("#text"!=widgetType){var id=et2_readAttrWithDefault(node,"id","");id.indexOf("$")<0||"box"!=widgetType?(this.createElementFromNode(node),childIndex++):repeatNode=node}else node.data.replace(/^\s+|\s+$/g,"")&&this.loadContent(node.data)}if(null!=repeatNode){var currentPerspective=this.getArrayMgr("content").perspectiveData;for(childIndex;"undefined"!=typeof this.getArrayMgr("content").data[childIndex]&&this.getArrayMgr("content").data[childIndex];childIndex++){var mgrs=this.getArrayMgrs();for(var name in mgrs)this.getArrayMgr(name).getEntry(childIndex)&&(this.getArrayMgr(name).perspectiveData.row=childIndex);this.createElementFromNode(repeatNode)}for(var name in this.getArrayMgrs())this.getArrayMgr(name).perspectiveData=currentPerspective}},getDetachedAttributes:function(_attrs){_attrs.push("data")},getDetachedNodes:function(){return[this.getDOMNode()]},setDetachedAttributes:function(_nodes,_values){if(_values.data)for(var pairs=_values.data.split(/,/g),i=0;i<pairs.length;++i){var name_value=pairs[i].split(":");$j(_nodes[0]).attr("data-"+name_value[0],name_value[1])}}})}.call(this);et2_register_widget(et2_box,["vbox","box"]);var et2_details=function(){"use strict";return et2_box.extend({attributes:{toggle_align:{name:"Toggle button alignment",description:" Defines where to align the toggle button, default is right alignment",type:"string",default:"right"},title:{name:"title",description:"Set a header title for box and shows it next to toggle button, default is no title",type:"string",default:""}},init:function(){this._super.apply(this,arguments),this.div=jQuery(document.createElement("div")).addClass("et2_details"),this.title=jQuery(document.createElement("span")).addClass("et2_label et2_details_title").appendTo(this.div),this.span=jQuery(document.createElement("span")).addClass("et2_details_toggle").appendTo(this.div),this.wrapper=jQuery(document.createElement("div")).addClass("et2_details_wrapper").appendTo(this.div),this._createWidget()},_toggle:function(){this.div.toggleClass("et2_details_expanded")},_createWidget:function(){var self=this;this.span.on("click",function(e){self._toggle()}),this.options.title&&this.title.click(function(){self._toggle()}).text(this.options.title),"left"===this.options.toggle_align&&this.span.css({float:"left"})},getDOMNode:function(_sender){return _sender&&_sender!==this?this.wrapper[0]:this.div[0]}})}.call(this);et2_register_widget(et2_details,["details"]);var et2_hbox=function(){"use strict";return et2_baseWidget.extend({createNamespace:!0,init:function(){this._super.apply(this,arguments),this.alignData={hasAlign:!1,hasLeft:!1,hasCenter:!1,hasRight:!1,lastAlign:"left"},this.leftDiv=null,this.rightDiv=null,this.div=$j(document.createElement("div")).addClass("et2_"+this._type).addClass("et2_box_widget"),this.setDOMNode(this.div[0])},_buildAlignCells:function(){if(this.alignData.hasAlign){var mto=this.alignData.hasLeft&&this.alignData.hasRight||this.alignData.hasLeft&&this.alignData.hasCenter||this.alignData.hasCenter&&this.alignData.hasRight;mto?(this.alignData.hasRight&&(this.rightDiv=$j(document.createElement("div")).addClass("et2_hbox_right").appendTo(this.div)),this.alignData.hasCenter&&(this.leftDiv=$j(document.createElement("div")).addClass("et2_hbox_left").appendTo(this.div),this.div.addClass("et2_hbox_al_center"))):"left"!=this.alignData.lastAlign&&this.div.addClass("et2_hbox_al_"+this.alignData.lastAlign)}},loadFromXML:function(_node){et2_filteredNodeIterator(_node,function(_node){var align=_node.getAttribute("align");switch(align||(align="left"),"left"!=align&&(this.alignData.hasAlign=!0),this.alignData.lastAlign=align,align){case"left":this.alignData.hasLeft=!0;break;case"right":this.alignData.hasRight=!0;break;case"center":this.alignData.hasCenter=!0}},this),this._buildAlignCells(),this._super.apply(this,arguments)},assign:function(_obj){this.alignData=et2_cloneObject(_obj.alignData),this._buildAlignCells(),this._super.apply(this,arguments)},getDOMNode:function(_sender){if(_sender!=this&&this.alignData.hasAlign){var align=_sender.implements(et2_IAligned)?_sender.get_align():"left";if("left"==align&&null!=this.leftDiv)return this.leftDiv[0];if("right"==align&&null!=this.rightDiv)return this.rightDiv[0]}return this._super.apply(this,arguments)},addChild:function(child){this._super.apply(this,arguments),(child.instanceOf&&child.instanceOf(et2_grid)||"et2_grid"==child._type)&&jQuery(child.getDOMNode(child)).css("display","inline-table")}})}.call(this);et2_register_widget(et2_hbox,["hbox"]);var et2_groupbox=function(){"use strict";return et2_baseWidget.extend({init:function(){this._super.apply(this,arguments),this.setDOMNode(document.createElement("fieldset"))}})}.call(this);et2_register_widget(et2_groupbox,["groupbox"]);var et2_groupbox_legend=function(){"use strict";return et2_baseWidget.extend({attributes:{
label:{name:"Label",type:"string",default:"",description:"Label for group box",translate:!0}},init:function(){this._super.apply(this,arguments);var legend=jQuery(document.createElement("legend")).text(this.options.label);this.setDOMNode(legend[0])}})}.call(this);et2_register_widget(et2_groupbox_legend,["caption"]),function($){var splitterCounter=0;$.fn.splitter=function(args){return args=args||{},this.each(function(){function setBarState(state){bar.removeClass(opts.barStateClasses).addClass(state)}function startSplitMouse(evt){1==evt.which&&(bar.removeClass(opts.barHoverClass),opts.outline&&(zombie=zombie||bar.clone(!1).insertAfter(A),bar.removeClass(opts.barDockedClass)),setBarState(opts.barActiveClass),panes.css("-webkit-user-select","none").find("iframe").andSelf().filter("iframe").addClass(opts.iframeClass),A._posSplit=A[0][opts.pxSplit]-evt[opts.eventPos],$(document).bind("mousemove"+opts.eventNamespace,doSplitMouse).bind("mouseup"+opts.eventNamespace,endSplitMouse))}function doSplitMouse(evt){var pos=A._posSplit+evt[opts.eventPos],range=Math.max(0,Math.min(pos,splitter._DA-bar._DA)),limit=Math.max(A._min,splitter._DA-B._max,Math.min(pos,A._max,splitter._DA-bar._DA-B._min));opts.outline?(opts.dockPane==A&&pos<Math.max(A._min,bar._DA)||opts.dockPane==B&&pos>Math.min(pos,A._max,splitter._DA-bar._DA-B._min)?bar.addClass(opts.barDockedClass).css(opts.origin,range):bar.removeClass(opts.barDockedClass).css(opts.origin,limit),bar._DA=bar[0][opts.pxSplit]):resplit(pos),setBarState(pos==limit?opts.barActiveClass:opts.barLimitClass)}function endSplitMouse(evt){setBarState(opts.barNormalClass),bar.addClass(opts.barHoverClass);var pos=A._posSplit+evt[opts.eventPos];opts.outline&&(zombie.remove(),zombie=null,resplit(pos)),panes.css("-webkit-user-select","text").find("iframe").andSelf().filter("iframe").removeClass(opts.iframeClass),$(document).unbind("mousemove"+opts.eventNamespace+" mouseup"+opts.eventNamespace)}function resplit(pos){bar._DA=bar[0][opts.pxSplit],opts.dockPane==A&&pos<Math.max(A._min,bar._DA)||opts.dockPane==B&&pos>Math.min(pos,A._max,splitter._DA-bar._DA-B._min)?(bar.addClass(opts.barDockedClass),bar._DA=bar[0][opts.pxSplit],pos=opts.dockPane==A?0:splitter._DA-bar._DA,null==bar._pos&&(bar._pos=A[0][opts.pxSplit])):(bar.removeClass(opts.barDockedClass),bar._DA=bar[0][opts.pxSplit],bar._pos=null,pos=Math.max(A._min,splitter._DA-B._max,Math.min(pos,A._max,splitter._DA-bar._DA-B._min))),bar.css(opts.origin,pos).css(opts.fixed,splitter._DF),A.css(opts.origin,0).css(opts.split,pos).css(opts.fixed,splitter._DF),B.css(opts.origin,pos+bar._DA).css(opts.split,splitter._DA-bar._DA-pos).css(opts.fixed,splitter._DF),panes.trigger("resize"+opts.eventNamespace)}function dimSum(jq,dims){for(var sum=0,i=1;i<arguments.length;i++)sum+=Math.max(parseInt(jq.css(arguments[i]),10)||0,0);return sum}if(!$(this).is(".splitter")){var zombie,vh=(args.splitHorizontal?"h":args.splitVertical?"v":args.type)||"v",opts=$.extend({splitterClass:"splitter ui-widget ui-widget-content",paneClass:"splitter-pane",barClass:"splitter-bar",barNormalClass:"ui-state-default",barHoverClass:"ui-state-hover",barActiveClass:"ui-state-highlight",barLimitClass:"ui-state-error",iframeClass:"splitter-iframe-hide",eventNamespace:".splitter"+ ++splitterCounter,pxPerKey:8,tabIndex:0,accessKey:""},{v:{keyLeft:39,keyRight:37,cursor:"e-resize",barStateClass:"splitter-bar-vertical",barDockedClass:"splitter-bar-vertical-docked"},h:{keyTop:40,keyBottom:38,cursor:"n-resize",barStateClass:"splitter-bar-horizontal",barDockedClass:"splitter-bar-horizontal-docked"}}[vh],args,{v:{type:"v",eventPos:"pageX",origin:"left",split:"width",pxSplit:"offsetWidth",side1:"Left",side2:"Right",fixed:"height",pxFixed:"offsetHeight",side3:"Top",side4:"Bottom"},h:{type:"h",eventPos:"pageY",origin:"top",split:"height",pxSplit:"offsetHeight",side1:"Top",side2:"Bottom",fixed:"width",pxFixed:"offsetWidth",side3:"Left",side4:"Right"}}[vh]);opts.barStateClasses=[opts.barNormalClass,opts.barHoverClass,opts.barActiveClass,opts.barLimitClass].join(" ");var splitter=$(this).css({position:"relative"}).addClass(opts.splitterClass),panes=$(">*",splitter[0]).addClass(opts.paneClass).css({position:"absolute","z-index":"1","-moz-outline-style":"none"}),A=$(panes[0]),B=$(panes[1]);opts.dockPane=opts.dock&&(/right|bottom/.test(opts.dock)?B:A);var focuser=$('<a href="javascript:void(0)"></a>').attr({accessKey:opts.accessKey,tabIndex:opts.tabIndex,title:opts.splitbarClass}).bind("focus"+opts.eventNamespace,function(){this.focus(),bar.addClass(opts.barActiveClass)}).bind("keydown"+opts.eventNamespace,function(e){var key=e.which||e.keyCode,dir=key==opts["key"+opts.side1]?1:key==opts["key"+opts.side2]?-1:0;dir&&resplit(A[0][opts.pxSplit]+dir*opts.pxPerKey,!1)}).bind("blur"+opts.eventNamespace,function(){bar.removeClass(opts.barActiveClass)}),bar=$("<div></div>").insertAfter(A).addClass(opts.barClass).addClass(opts.barStateClass).append(focuser).attr({unselectable:"on"}).css({position:"absolute","user-select":"none","-webkit-user-select":"none","-khtml-user-select":"none","-moz-user-select":"none","z-index":"100"}).bind("mousedown"+opts.eventNamespace,startSplitMouse).bind("mouseover"+opts.eventNamespace,function(){$(this).addClass(opts.barHoverClass)}).bind("mouseout"+opts.eventNamespace,function(){$(this).removeClass(opts.barHoverClass)});/^(auto|default|)$/.test(bar.css("cursor"))&&bar.css("cursor",opts.cursor),bar._DA=bar[0][opts.pxSplit],splitter._PBF=dimSum(splitter,"border"+opts.side3+"Width","border"+opts.side4+"Width"),splitter._PBA=dimSum(splitter,"border"+opts.side1+"Width","border"+opts.side2+"Width"),A._pane=opts.side1,B._pane=opts.side2,$.each([A,B],function(){this._splitter_style=this.style,this._min=opts["min"+this._pane]||dimSum(this,"min-"+opts.split),this._max=opts["max"+this._pane]||dimSum(this,"max-"+opts.split)||9999,this._init=opts["size"+this._pane]===!0?parseInt($.curCSS(this[0],opts.split),10):opts["size"+this._pane]});var initPos=A._init;isNaN(B._init)||(initPos=splitter[0][opts.pxSplit]-splitter._PBA-B._init-bar._DA),opts.cookie&&($.cookie||alert("jQuery.splitter(): jQuery cookie plugin required"),initPos=parseInt($.cookie(opts.cookie),10),$(window).bind("unload"+opts.eventNamespace,function(){var state=String(bar.css(opts.origin));$.cookie(opts.cookie,state,{expires:opts.cookieExpires||365,path:opts.cookiePath||document.location.pathname})})),isNaN(initPos)&&(initPos=Math.round((splitter[0][opts.pxSplit]-splitter._PBA-bar._DA)/2)),opts.anchorToWindow&&(opts.resizeTo=window),opts.resizeTo?(splitter._hadjust=dimSum(splitter,"borderTopWidth","borderBottomWidth","marginBottom"),splitter._hmin=Math.max(dimSum(splitter,"minHeight"),20),$(window).bind("resize"+opts.eventNamespace,function(){var top=splitter.offset().top,eh=$(opts.resizeTo).height();splitter.css("height",Math.max(eh-top-splitter._hadjust,splitter._hmin)+"px"),splitter.trigger("resize")}).trigger("resize"+opts.eventNamespace)):opts.resizeToWidth&&$(window).bind("resize"+opts.eventNamespace,function(){splitter.trigger("resize")}),opts.dock&&(splitter.bind("toggleDock"+opts.eventNamespace,function(){var pw=opts.dockPane[0][opts.pxSplit];splitter.trigger(pw?"dock":"undock")}).bind("dock"+opts.eventNamespace,function(){var pw=A[0][opts.pxSplit];if(pw&&!bar.hasClass("splitter-bar-horizontal-docked")&&!bar.hasClass("splitter-bar-vertical-docked")){bar._pos=pw;var x={};x[opts.origin]=opts.dockPane==A?0:splitter[0][opts.pxSplit]-splitter._PBA-bar[0][opts.pxSplit],bar.animate(x,opts.dockSpeed||1,opts.dockEasing,function(){bar.addClass(opts.barDockedClass),resplit(x[opts.origin]+1)})}}).bind("undock"+opts.eventNamespace,function(){var pw=opts.dockPane[0][opts.pxSplit];if(!pw){(null==bar._pos||Math.abs(bar._pos-splitter._DA-bar._DA)<20)&&(bar._pos=splitter._DA/2);var x={};x[opts.origin]=bar._pos+"px",bar.removeClass(opts.barDockedClass).animate(x,opts.undockSpeed||opts.dockSpeed||1,opts.undockEasing||opts.dockEasing,function(){resplit(bar._pos),bar._pos=null})}}),opts.dockKey&&$('<a title="'+opts.splitbarClass+' toggle dock" href="javascript:void(0)"></a>').attr({accessKey:opts.dockKey,tabIndex:-1}).appendTo(bar).bind("focus",function(){splitter.trigger("toggleDock"),this.blur()}),bar.bind("dblclick",function(){splitter.trigger("toggleDock")})),splitter.bind("destroy"+opts.eventNamespace,function(){$([window,document]).unbind(opts.eventNamespace),bar.unbind().remove(),panes.removeClass(opts.paneClass),splitter.removeClass(opts.splitterClass).add(panes).unbind(opts.eventNamespace).attr("style",function(el){return this._splitter_style||""}),splitter=bar=focuser=panes=A=B=opts=args=null}).bind("resize"+opts.eventNamespace,function(e,size){e.target==this&&(splitter._DF=splitter[0][opts.pxFixed]-splitter._PBF,splitter._DA=splitter[0][opts.pxSplit]-splitter._PBA,splitter._DF<=0||splitter._DA<=0||(resplit(isNaN(size)?opts.sizeRight||opts.sizeBottom?splitter._DA-B[0][opts.pxSplit]-bar._DA:A[0][opts.pxSplit]:size),setBarState(opts.barNormalClass)))}).trigger("resize",[initPos])}})}}(jQuery);var et2_split=function(){"use strict";return et2_DOMWidget.extend([et2_IResizeable,et2_IPrint],{attributes:{orientation:{name:"Orientation",description:"Horizontal or vertical (v or h)",default:"v",type:"string"},outline:{name:"Outline",description:"Use a 'ghosted' copy of the splitbar and does not resize the panes until the mouse button is released. Reduces flickering or unwanted re-layout during resize",default:!1,type:"boolean"},dock_side:{name:"Dock",description:"Allow the user to 'Dock' the splitbar to one side of the splitter, essentially hiding one pane and using the entire splitter area for the other pane. One of leftDock, rightDock, topDock, bottomDock.",default:et2_no_init,type:"string"},width:{default:"100%"},overflow:{ignore:!0},no_lang:{ignore:!0},rows:{ignore:!0},cols:{ignore:!0}},DOCK_TOLERANCE:15,init:function(){this._super.apply(this,arguments),this.div=$j(document.createElement("div")).addClass("et2_split"),this.dynheight=new et2_dynheight(this.getParent().getDOMNode()||this.getInstanceManager().DOMContainer,this.div,100),this.left=$j("<div>Top / Left</div>").appendTo(this.div),this.right=$j("<div>Bottom / Right</div>").appendTo(this.div),this.loading=jQuery.Deferred(),this.stop_resize=!1},destroy:function(){this.left.next().off("mouseup"),this.div.trigger("destroy"),this.dynheight.free(),this._super.apply(this,arguments),0==this._children.length&&this.div.empty(),this.div.remove()},loadFromXML:function(){this._super.apply(this,arguments),this._children.length>0&&(this._children[0]&&(this.left.detach(),this.left=$j(this._children[0].getDOMNode(this._children[0])).appendTo(this.div)),this._children[1]&&(this.right.detach(),this.right=$j(this._children[1].getDOMNode(this._children[1])).appendTo(this.div)));for(var i=0;i<this._children.length;i++)this._children[i].dynheight&&(this._children[i].dynheight.outerNode=0==i?this.left:this.right,this._children[i].dynheight.initialized=!1)},doLoadingFinished:function(){this._super.apply(this,arguments);var self=this;return window.setTimeout(function(){self._init_splitter()},1),this.loading.promise()},_init_splitter:function(){if(this.isAttached()&&this.div.is(":visible")){var options={type:this.orientation,dock:this.dock_side,splitterClass:"et2_split",outline:!0,eventNamespace:".et2_split."+this.id,sizeTop:this.dynheight.outerNode.height()/2,sizeLeft:this.dynheight.outerNode.width()/2},widget=this,per2pix=function(_size){var size=_size.replace("%",""),pix=0;return pix="v"==widget.orientation?size*widget.dynheight.outerNode.width()/100:size*widget.dynheight.outerNode.height()/100,pix.toFixed(2)},pix2per=function(_size){var per=0;return per="v"==widget.orientation?100*_size/widget.dynheight.outerNode.width():100*_size/widget.dynheight.outerNode.height(),per.toFixed(2)+"%"};if(this.id){var pref=this.egw().preference("splitter-size-"+this.id,this.egw().getAppName());pref&&(pref[Object.keys(pref)].toString().match(/%/g)&&(pref[Object.keys(pref)]=per2pix(pref[Object.keys(pref)])),("v"==this.orientation&&pref.sizeLeft<this.dynheight.outerNode.width()||"h"==this.orientation&&pref.sizeTop<this.dynheight.outerNode.height())&&(options=$j.extend(options,pref),this.prefSize=pref["v"==this.orientation?"sizeLeft":"sizeTop"])),"undefined"!=typeof this.prefSize&&this.prefSize||(this.prefSize="v"==this.orientation?options.sizeLeft:options.sizeTop)}this.div.hasClass(options.splitterClass)&&this.div.trigger("destroy"),this.div.splitter(options),this.div.trigger("resize",[options.sizeTop||options.sizeLeft||0]),options.dock&&("bottomDock"==options.dock&&Math.abs(options.sizeTop-this.div.height())<et2_split.DOCK_TOLERANCE||"topDock"==options.dock&&0==options.sizeTop||!this.div.is(":visible"))&&this.dock();var icon="ui-icon-grip-"+(this.dock_side?"solid":"dotted")+"-"+("h"==this.orientation?"horizontal":"vertical");if($j(document.createElement("div")).addClass("ui-icon").addClass(icon).appendTo(this.left.next()),this.id&&this.egw().getAppName()){var self=this;this.left.on("resize"+options.eventNamespace,function(e){var display=this.style.display;if(this.style.display="none",this.offsetHeight,this.style.display=display,e.namespace==options.eventNamespace.substr(1)&&!self.isDocked()){var size="v"==self.orientation?{sizeLeft:self.left.width()}:{sizeTop:self.left.height()};self.prefSize=size["v"==self.orientation?"sizeLeft":"sizeTop"];var prefInPercent="v"==self.orientation?{sizeLeft:pix2per(size.sizeLeft)}:{sizeTop:pix2per(size.sizeTop)};parseInt("v"==self.orientation?prefInPercent.sizeLeft:prefInPercent.sizeTop)<100&&self.egw().set_preference(self.egw().getAppName(),"splitter-size-"+self.id,prefInPercent)}self.iterateOver(function(widget){window.setTimeout(jQuery.proxy(function(){this.resize()},widget),200)},self,et2_IResizeable)})}this.loading.resolve()}},resize:function(){if(this.div.children().length<=2&&this._init_splitter(),this.dynheight&&!this.stop_resize){var old={w:this.div.width(),h:this.div.height()};this.dynheight.update(function(w,h){"v"==this.orientation&&(this.left.height(h),this.right.height(h)),"h"==this.orientation&&(this.left.width(w),this.right.width(w),this.isDocked()&&("topDock"==this.dock_side?(this.right.height(h),this.left.height(0)):(this.left.height(h),this.right.height(0)))),w==old.w&&h==old.h||this.div.trigger("resize.et2_split."+this.id,this.prefSize)},this)}},getDOMNode:function(){return this.div[0]},set_orientation:function(orient){this.orientation=orient,this._init_splitter()},set_dock_side:function(dock){this.dock_side=dock,this._init_splitter()},set_outline:function(outline){this.outline=outline,this._init_splitter()},dock:function(){this.isDocked()||this.div.trigger("dock")},undock:function(){this.div.trigger("undock")},isDocked:function(){var bar=$j(".splitter-bar",this.div);return bar.hasClass("splitter-bar-horizontal-docked")||bar.hasClass("splitter-bar-vertical-docked")},toggleDock:function(){this.div.trigger("toggleDock")},beforePrint:function(){this.stop_resize=!0,this.div.addClass("print")},afterPrint:function(){this.div.removeClass("print"),this.stop_resize=!1}})}.call(this);et2_register_widget(et2_split,["split"]);var et2_button=function(){"use strict";return et2_baseWidget.extend([et2_IInput,et2_IDetachedDOM],{attributes:{label:{name:"caption",type:"string",description:"Label of the button",translate:!0},image:{name:"Icon",type:"string",description:"Use an icon instead of label (when available)"},ro_image:{name:"Read-only Icon",type:"string",description:"Use this icon instead of hiding for read-only"},onclick:{description:"JS code which gets executed when the button is clicked"},accesskey:{name:"Access Key",type:"string",default:et2_no_init,description:"Alt + <key> activates widget"},tabindex:{name:"Tab index",type:"integer",default:et2_no_init,description:"Specifies the tab order of a widget when the 'tab' button is used for navigating."},background_image:{name:"Add image in front of text",type:"boolean",description:"Adds image in front of text instead of just using an image with text as tooltip",default:et2_no_init},novalidate:{name:"Do NOT validate form",type:"boolean",description:"Do NOT validate form before submitting it",default:!1},needed:{ignore:!0}},legacyOptions:["image","ro_image"],init:function(){return this._super.apply(this,arguments),this.label="",this.clicked=!1,this.btn=null,this.image=null,this.options.background_image||!this.options.image&&!this.options.ro_image?(this.options.readonly||(this.btn=$j(document.createElement("button")).addClass("et2_button").attr({type:"button"}),this.setDOMNode(this.btn[0])),void(this.options.image&&this.set_image(this.options.image))):(this.image=jQuery(document.createElement("img")).addClass("et2_button et2_button_icon"),void this.setDOMNode(this.image[0]))},transformAttributes:function(_attrs){if(this.id&&"undefined"==typeof _attrs.background_image&&!_attrs.image)for(var image in et2_button.default_background_images)if(this.id.match(et2_button.default_background_images[image])){_attrs.image=image,_attrs.background_image=!0;break}for(var name in et2_button.default_classes)if(this.id.match(et2_button.default_classes[name])){_attrs.class=("undefined"==typeof _attrs.class?"":_attrs.class+" ")+name;break}this._super.apply(this,arguments)},set_accesskey:function(key){jQuery(this.node).attr("accesskey",key)},set_image:function(_image){this.options.image=_image,this.update_image()},set_ro_image:function(_image){this.options.ro_image=_image,this.update_image()},update_image:function(_image){if(this.isInTree()&&(this.options.background_image||null!=this.image)){"undefined"==typeof _image&&(_image=this.options.readonly?this.options.ro_image:this.options.image),_image.match(/^[0-9]+\%$/)&&(_image="");var found_image=!1;if(""!=_image){var src=this.egw().image(_image);src?found_image=!0:"/"!=_image[0]&&"http"!=_image.substr(0,4)||(src=image,found_image=!0),found_image&&(null!=this.image?this.image.attr("src",src):this.options.background_image&&(this.btn.css("background-image","url("+src+")"),this.btn.addClass("et2_button_with_image")))}found_image||(this.set_label(this.label),this.btn&&(this.btn.css("background-image",""),this.btn.removeClass("et2_button_with_image")))}},set_readonly:function(_ro){_ro!=this.options.readonly&&(this.options.readonly=_ro,this.image&&this.update_image(),(this.btn||this.image)&&(this.btn||this.image).toggleClass("et2_clickable",!_ro).toggleClass("et2_button_ro",_ro).css("cursor",_ro?"default":"pointer"))},attachToDOM:function(){this._super.apply(this,arguments),this.options.readonly&&(this.btn||this.image)&&(this.btn||this.image).removeClass("et2_clickable").addClass("et2_button_ro").css("cursor","default")},getDOMNode:function(){return this.btn?this.btn[0]:this.image?this.image[0]:null},click:function(_ev){return this.options.readonly?!1:(this.clicked=!0,this._super.apply(this,arguments)?("buttononly"!=this._type&&this.getInstanceManager().submit(this,!1,this.options.novalidate),this.clicked=!1,!0):(this.clicked=!1,!1))},set_label:function(_value){this.btn&&(this.label=_value,this.btn.text(_value),_value&&!this.image?this.btn.addClass("et2_button_text"):this.btn.removeClass("et2_button_text")),this.image&&(this.image.attr("alt",_value),this.options.statustext||this.image.attr("title",_value))},set_tabindex:function(index){jQuery(this.btn).attr("tabindex",index)},isDirty:function(){return!1},resetDirty:function(){},getValue:function(){return this.clicked?!0:null},isValid:function(){return!0},getDetachedAttributes:function(_attrs){_attrs.push("label","value","class","image","ro_image","onclick","background_image")},getDetachedNodes:function(){return[null!=this.btn?this.btn[0]:null,null!=this.image?this.image[0]:null]},setDetachedAttributes:function(_nodes,_values){this.btn="#"!=_nodes[0].nodeName[0]?jQuery(_nodes[0]):null,this.image=jQuery(_nodes[1]),"undefined"!=typeof _values.id&&this.set_id(_values.id),"undefined"!=typeof _values.label&&this.set_label(_values.label),"undefined"!=typeof _values.value,"undefined"!=typeof _values.image&&this.set_image(_values.image),"undefined"!=typeof _values.ro_image&&this.set_ro_image(_values.ro_image),"undefined"!=typeof _values.class&&this.set_class(_values.class),"undefined"!=typeof _values.onclick&&(this.options.onclick=_values.onclick);var type=this._type,attrs=jQuery.extend(_values,this.options),parent=this._parent;jQuery(this.getDOMNode()).bind("click.et2_baseWidget",this,function(e){var widget=et2_createWidget(type,attrs,parent);return e.data=widget,e.data.set_id(_values.id),e.data.click.call(e.data,e)})}})}.call(this);et2_register_widget(et2_button,["button","buttononly"]),jQuery.extend(et2_button,{default_background_images:{save:/save(&|\]|$)/,apply:/apply(&|\]|$)/,cancel:/cancel(&|\]|$)/,delete:/delete(&|\]|$)/,edit:/edit(&|\[\]|$)/,next:/(next|continue)(&|\]|$)/,finish:/finish(&|\]|$)/,back:/(back|previous)(&|\]|$)/,copy:/copy(&|\]|$)/,more:/more(&|\]|$)/,check:/(yes|check)(&|\]|$)/,cancelled:/no(&|\]|$)/,ok:/ok(&|\]|$)/,close:/close(&|\]|$)/,add:/(add(&|\]|$)|create)/},default_classes:{et2_button_cancel:/cancel(&|\]|$)/,et2_button_question:/(yes|no)(&|\]|$)/,et2_button_delete:/delete(&|\]|$)/}});var et2_valueWidget=function(){"use strict";return et2_baseWidget.extend({attributes:{label:{name:"Label",default:"",type:"string",description:"The label is displayed by default in front (for radiobuttons behind) each widget (if not empty). If you want to specify a different position, use a '%s' in the label, which gets replaced by the widget itself. Eg. '%s Name' to have the label Name behind a checkbox. The label can contain variables, as descript for name. If the label starts with a '@' it is replaced by the value of the content-array at this index (with the '@'-removed and after expanding the variables).",translate:!0},value:{name:"Value",description:"The value of the widget",type:"rawstring",default:et2_no_init}},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),this.id){var contentMgr=this.getArrayMgr("content");if(null!=contentMgr){var val=contentMgr.getEntry(this.id,!1,!0);null!==val&&(_attrs.value=val)}this.createNamespace&&this.getArrayMgr("content").perspectiveData.owner==this&&(_attrs.value=this.getArrayMgr("content").data)}},set_label:function(_value){if(_value!=this.label){if(_value){null==this._labelContainer&&(this._labelContainer=$j(document.createElement("label")).addClass("et2_label"),this.getSurroundings().insertDOMNode(this._labelContainer[0])),this._labelContainer.empty();var ph=document.createElement("span");this.getSurroundings().setWidgetPlaceholder(ph);for(var parts=et2_csvSplit(_value,2,"%s"),i=0;i<parts.length;i++)parts[i]&&this._labelContainer.append(document.createTextNode(parts[i])),0==i&&this._labelContainer.append(ph)}else this._labelContainer&&this.getSurroundings().removeDOMNode(this._labelContainer[0]),this._labelContainer=null;this.getSurroundings().update(),this.label=_value}}})}.call(this),et2_inputWidget=function(){"use strict";return et2_valueWidget.extend([et2_IInput,et2_ISubmitListener],{attributes:{needed:{name:"Required",default:!1,type:"boolean",description:"If required, the user must enter a value before the form can be submitted"},onchange:{name:"onchange",type:"js",default:et2_no_init,description:"JS code which is executed when the value changes."},onfocus:{name:"onfocus",type:"js",default:et2_no_init,description:"JS code which get executed when wiget receives focus."},validation_error:{name:"Validation Error",type:"string",default:et2_no_init,description:"Used internally to store the validation error that came from the server."},tabindex:{name:"Tab index",type:"integer",default:et2_no_init,description:"Specifies the tab order of a widget when the 'tab' button is used for navigating."},readonly:{name:"readonly",type:"boolean",default:!1,description:"Does NOT allow user to enter data, just displays existing data"}},init:function(){this._super.apply(this,arguments),this._oldValue=et2_no_init,this._labelContainer=null},destroy:function(){var node=this.getInputNode();node&&($j(node).unbind("change.et2_inputWidget"),$j(node).unbind("focus")),this._super.apply(this,arguments),this._labelContainer=null},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),this.id&&this.getArrayMgr("validation_errors")){var val=this.getArrayMgr("validation_errors").getEntry(this.id);val&&(_attrs.validation_error=val)}},attachToDOM:function(){var node=this.getInputNode();node&&$j(node).off(".et2_inputWidget").bind("change.et2_inputWidget",this,function(e){e.data.change.call(e.data,this)}).bind("focus.et2_inputWidget",this,function(e){e.data.focus.call(e.data,this)}),this._super.apply(this,arguments)},detatchFromDOM:function(){this._super.apply(this,arguments)},change:function(_node){var messages=[],valid=this.isValid(messages);if(this.set_validation_error(valid?!1:messages),valid&&this.onchange){if("function"==typeof this.onchange){var args=Array.prototype.slice.call(arguments);return-1==args.indexOf(this)&&args.push(this),this.onchange.apply(this,args)}return et2_compileLegacyJS(this.options.onchange,this,_node)()}return valid},focus:function(_node){if("function"==typeof this.options.onfocus){var args=Array.prototype.slice.call(arguments);return-1==args.indexOf(this)&&args.push(this),this.options.onfocus.apply(this,args)}},set_value:function(_value){var node=this.getInputNode();node&&($j(node).val(_value),this.isAttached()&&this._oldValue!==et2_no_init&&this._oldValue!==_value&&$j(node).change()),this._oldValue=_value},set_id:function(_value){this.id=_value,this.dom_id=_value&&this.getInstanceManager()?this.getInstanceManager().uniqueId+"_"+this.id:_value;var node=this.getInputNode();node&&(""!=_value?(node.setAttribute("id",this.dom_id),node.setAttribute("name",_value)):(node.removeAttribute("id"),node.removeAttribute("name")))},set_needed:function(_value){var node=this.getInputNode();node&&(_value&&!this.options.readonly?$j(node).attr("required","required"):node.removeAttribute("required"))},set_validation_error:function(_value){var node=this.getInputNode();if(node)if(_value===!1)this.hideMessage(),$j(node).removeClass("invalid");else{this.showMessage(_value,"validation_error"),$j(node).addClass("invalid");for(var widget=this;widget._parent&&"tabbox"!=widget._type;)widget=widget._parent;"tabbox"==widget._type&&widget.activateTab(this)}},set_tabindex:function(index){jQuery(this.getInputNode()).attr("tabindex",index)},getInputNode:function(){return this.node},get_value:function(){return this.getValue()},getValue:function(){var node=this.getInputNode();if(node){var val=$j(node).val();return val}return this._oldValue},isDirty:function(){return this._oldValue!=this.getValue()},resetDirty:function(){this._oldValue=this.getValue()},isValid:function(messages){var ok=!0;return!this.options||!this.options.needed||this.options.readonly||this.disabled||null!=this.getValue()&&""!=this.getValue().valueOf()||(messages.push(this.egw().lang("Field must not be empty !!!")),ok=!1),ok},submit:function(_values){var messages=[],valid=this.isValid(messages);return this.set_validation_error(valid?!1:messages),valid}})}.call(this);!function($,version){Math.precision=function(value,precision){return void 0===precision&&(precision=0),Math.round(value*Math.pow(10,precision))/Math.pow(10,precision)};var Slider=function(bar,options){var offset,timeout,$this=this,arrow=bar.find("img:first"),minX=0,maxX=100,rangeX=100,minY=0,maxY=100,rangeY=100,x=0,y=0,changeEvents=new Array,fireChangeEvents=function(context){for(var i=0;i<changeEvents.length;i++)changeEvents[i].call($this,$this,context)},mouseDown=function(e){var off=bar.offset();offset={l:0|off.left,t:0|off.top},clearTimeout(timeout),timeout=setTimeout(function(){setValuesFromMousePosition.call($this,e)},0),$(document).bind("mousemove",mouseMove).bind("mouseup",mouseUp),e.preventDefault()},mouseMove=function(e){return clearTimeout(timeout),timeout=setTimeout(function(){setValuesFromMousePosition.call($this,e)},0),e.stopPropagation(),e.preventDefault(),!1},mouseUp=function(e){return $(document).unbind("mouseup",mouseUp).unbind("mousemove",mouseMove),e.stopPropagation(),e.preventDefault(),!1},setValuesFromMousePosition=function(e){var locX=e.pageX-offset.l,locY=e.pageY-offset.t,barW=bar.w,barH=bar.h;0>locX?locX=0:locX>barW&&(locX=barW),0>locY?locY=0:locY>barH&&(locY=barH),val.call($this,"xy",{x:locX/barW*rangeX+minX,y:locY/barH*rangeY+minY})},draw=function(){var arrowOffsetX=0,arrowOffsetY=0,barW=bar.w,barH=bar.h,arrowW=arrow.w,arrowH=arrow.h;setTimeout(function(){rangeX>0&&(arrowOffsetX=x==maxX?barW:x/rangeX*barW|0),rangeY>0&&(arrowOffsetY=y==maxY?barH:y/rangeY*barH|0),arrowW>=barW?arrowOffsetX=(barW>>1)-(arrowW>>1):arrowOffsetX-=arrowW>>1,arrowH>=barH?arrowOffsetY=(barH>>1)-(arrowH>>1):arrowOffsetY-=arrowH>>1,arrow.css({left:arrowOffsetX+"px",top:arrowOffsetY+"px"})},0)},val=function(name,value,context){var set=void 0!==value;if(!set)switch(void 0!==name&&null!=name||(name="xy"),name.toLowerCase()){case"x":return x;case"y":return y;case"xy":default:return{x:x,y:y}}if(null==context||context!=$this){var newX,newY,changed=!1;switch(null==name&&(name="xy"),name.toLowerCase()){case"x":newX=value&&(value.x&&0|value.x||0|value)||0;break;case"y":newY=value&&(value.y&&0|value.y||0|value)||0;break;case"xy":default:newX=value&&value.x&&0|value.x||0,newY=value&&value.y&&0|value.y||0}null!=newX&&(minX>newX?newX=minX:newX>maxX&&(newX=maxX),x!=newX&&(x=newX,changed=!0)),null!=newY&&(minY>newY?newY=minY:newY>maxY&&(newY=maxY),y!=newY&&(y=newY,changed=!0)),changed&&fireChangeEvents.call($this,context||$this)}},range=function(name,value){var set=void 0!==value;if(!set)switch(void 0!==name&&null!=name||(name="all"),name.toLowerCase()){case"minx":return minX;case"maxx":return maxX;case"rangex":return{minX:minX,maxX:maxX,rangeX:rangeX};case"miny":return minY;case"maxy":return maxY;case"rangey":return{minY:minY,maxY:maxY,rangeY:rangeY};case"all":default:return{minX:minX,maxX:maxX,rangeX:rangeX,minY:minY,maxY:maxY,rangeY:rangeY}}var newMinX,newMaxX,newMinY,newMaxY;switch(null==name&&(name="all"),name.toLowerCase()){case"minx":newMinX=value&&(value.minX&&0|value.minX||0|value)||0;break;case"maxx":newMaxX=value&&(value.maxX&&0|value.maxX||0|value)||0;break;case"rangex":newMinX=value&&value.minX&&0|value.minX||0,newMaxX=value&&value.maxX&&0|value.maxX||0;break;case"miny":newMinY=value&&(value.minY&&0|value.minY||0|value)||0;break;case"maxy":newMaxY=value&&(value.maxY&&0|value.maxY||0|value)||0;break;case"rangey":newMinY=value&&value.minY&&0|value.minY||0,newMaxY=value&&value.maxY&&0|value.maxY||0;break;case"all":default:newMinX=value&&value.minX&&0|value.minX||0,newMaxX=value&&value.maxX&&0|value.maxX||0,newMinY=value&&value.minY&&0|value.minY||0,newMaxY=value&&value.maxY&&0|value.maxY||0}null!=newMinX&&minX!=newMinX&&(minX=newMinX,rangeX=maxX-minX),null!=newMaxX&&maxX!=newMaxX&&(maxX=newMaxX,rangeX=maxX-minX),null!=newMinY&&minY!=newMinY&&(minY=newMinY,rangeY=maxY-minY),null!=newMaxY&&maxY!=newMaxY&&(maxY=newMaxY,rangeY=maxY-minY)},bind=function(callback){$.isFunction(callback)&&changeEvents.push(callback)},unbind=function(callback){if($.isFunction(callback))for(var i;-1!=(i=$.inArray(callback,changeEvents));)changeEvents.splice(i,1)},destroy=function(){$(document).unbind("mouseup",mouseUp).unbind("mousemove",mouseMove),bar.unbind("mousedown",mouseDown),bar=null,arrow=null,changeEvents=null};$.extend(!0,$this,{val:val,range:range,bind:bind,unbind:unbind,destroy:destroy}),arrow.src=options.arrow&&options.arrow.image,arrow.w=options.arrow&&options.arrow.width||arrow.width(),arrow.h=options.arrow&&options.arrow.height||arrow.height(),bar.w=options.map&&options.map.width||bar.width(),bar.h=options.map&&options.map.height||bar.height(),bar.bind("mousedown",mouseDown),bind.call($this,draw)},ColorValuePicker=function(picker,color,bindedHex,alphaPrecision){var $this=this,inputs=picker.find("td.Text input"),red=inputs.eq(3),green=inputs.eq(4),blue=inputs.eq(5),alpha=inputs.length>7?inputs.eq(6):null,hue=inputs.eq(0),saturation=inputs.eq(1),value=inputs.eq(2),hex=inputs.eq(inputs.length>7?7:6),ahex=inputs.length>7?inputs.eq(8):null,keyDown=function(e){
if(""!=e.target.value||e.target==hex.get(0)||(null==bindedHex||e.target==bindedHex.get(0))&&null!=bindedHex){if(!validateKey(e))return e;switch(e.target){case red.get(0):switch(e.keyCode){case 38:return red.val(setValueInRange.call($this,(red.val()<<0)+1,0,255)),color.val("r",red.val(),e.target),!1;case 40:return red.val(setValueInRange.call($this,(red.val()<<0)-1,0,255)),color.val("r",red.val(),e.target),!1}break;case green.get(0):switch(e.keyCode){case 38:return green.val(setValueInRange.call($this,(green.val()<<0)+1,0,255)),color.val("g",green.val(),e.target),!1;case 40:return green.val(setValueInRange.call($this,(green.val()<<0)-1,0,255)),color.val("g",green.val(),e.target),!1}break;case blue.get(0):switch(e.keyCode){case 38:return blue.val(setValueInRange.call($this,(blue.val()<<0)+1,0,255)),color.val("b",blue.val(),e.target),!1;case 40:return blue.val(setValueInRange.call($this,(blue.val()<<0)-1,0,255)),color.val("b",blue.val(),e.target),!1}break;case alpha&&alpha.get(0):switch(e.keyCode){case 38:return alpha.val(setValueInRange.call($this,parseFloat(alpha.val())+1,0,100)),color.val("a",Math.precision(255*alpha.val()/100,alphaPrecision),e.target),!1;case 40:return alpha.val(setValueInRange.call($this,parseFloat(alpha.val())-1,0,100)),color.val("a",Math.precision(255*alpha.val()/100,alphaPrecision),e.target),!1}break;case hue.get(0):switch(e.keyCode){case 38:return hue.val(setValueInRange.call($this,(hue.val()<<0)+1,0,360)),color.val("h",hue.val(),e.target),!1;case 40:return hue.val(setValueInRange.call($this,(hue.val()<<0)-1,0,360)),color.val("h",hue.val(),e.target),!1}break;case saturation.get(0):switch(e.keyCode){case 38:return saturation.val(setValueInRange.call($this,(saturation.val()<<0)+1,0,100)),color.val("s",saturation.val(),e.target),!1;case 40:return saturation.val(setValueInRange.call($this,(saturation.val()<<0)-1,0,100)),color.val("s",saturation.val(),e.target),!1}break;case value.get(0):switch(e.keyCode){case 38:return value.val(setValueInRange.call($this,(value.val()<<0)+1,0,100)),color.val("v",value.val(),e.target),!1;case 40:return value.val(setValueInRange.call($this,(value.val()<<0)-1,0,100)),color.val("v",value.val(),e.target),!1}}}},keyUp=function(e){if(""!=e.target.value||e.target==hex.get(0)||(null==bindedHex||e.target==bindedHex.get(0))&&null!=bindedHex){if(!validateKey(e))return e;switch(e.target){case red.get(0):red.val(setValueInRange.call($this,red.val(),0,255)),color.val("r",red.val(),e.target);break;case green.get(0):green.val(setValueInRange.call($this,green.val(),0,255)),color.val("g",green.val(),e.target);break;case blue.get(0):blue.val(setValueInRange.call($this,blue.val(),0,255)),color.val("b",blue.val(),e.target);break;case alpha&&alpha.get(0):alpha.val(setValueInRange.call($this,alpha.val(),0,100)),color.val("a",Math.precision(255*alpha.val()/100,alphaPrecision),e.target);break;case hue.get(0):hue.val(setValueInRange.call($this,hue.val(),0,360)),color.val("h",hue.val(),e.target);break;case saturation.get(0):saturation.val(setValueInRange.call($this,saturation.val(),0,100)),color.val("s",saturation.val(),e.target);break;case value.get(0):value.val(setValueInRange.call($this,value.val(),0,100)),color.val("v",value.val(),e.target);break;case hex.get(0):hex.val(hex.val().replace(/[^a-fA-F0-9]/g,"").toLowerCase().substring(0,6)),bindedHex&&bindedHex.val(hex.val()),color.val("hex",""!=hex.val()?hex.val():null,e.target);break;case bindedHex&&bindedHex.get(0):bindedHex.val(bindedHex.val().replace(/[^a-fA-F0-9]/g,"").toLowerCase().substring(0,6)),hex.val(bindedHex.val()),color.val("hex",""!=bindedHex.val()?bindedHex.val():null,e.target);break;case ahex&&ahex.get(0):ahex.val(ahex.val().replace(/[^a-fA-F0-9]/g,"").toLowerCase().substring(0,2)),color.val("a",null!=ahex.val()?parseInt(ahex.val(),16):null,e.target)}}},blur=function(e){if(null!=color.val())switch(e.target){case red.get(0):red.val(color.val("r"));break;case green.get(0):green.val(color.val("g"));break;case blue.get(0):blue.val(color.val("b"));break;case alpha&&alpha.get(0):alpha.val(Math.precision(100*color.val("a")/255,alphaPrecision));break;case hue.get(0):hue.val(color.val("h"));break;case saturation.get(0):saturation.val(color.val("s"));break;case value.get(0):value.val(color.val("v"));break;case hex.get(0):case bindedHex&&bindedHex.get(0):hex.val(color.val("hex")),bindedHex&&bindedHex.val(color.val("hex"));break;case ahex&&ahex.get(0):ahex.val(color.val("ahex").substring(6))}},validateKey=function(e){switch(e.keyCode){case 9:case 16:case 29:case 37:case 39:return!1;case"c".charCodeAt():case"v".charCodeAt():if(e.ctrlKey)return!1}return!0},setValueInRange=function(value,min,max){return""==value||isNaN(value)?min:value>max?max:min>value?min:value},colorChanged=function(ui,context){var all=ui.val("all");context!=red.get(0)&&red.val(null!=all?all.r:""),context!=green.get(0)&&green.val(null!=all?all.g:""),context!=blue.get(0)&&blue.val(null!=all?all.b:""),alpha&&context!=alpha.get(0)&&alpha.val(null!=all?Math.precision(100*all.a/255,alphaPrecision):""),context!=hue.get(0)&&hue.val(null!=all?all.h:""),context!=saturation.get(0)&&saturation.val(null!=all?all.s:""),context!=value.get(0)&&value.val(null!=all?all.v:""),context!=hex.get(0)&&(bindedHex&&context!=bindedHex.get(0)||!bindedHex)&&hex.val(null!=all?all.hex:""),bindedHex&&context!=bindedHex.get(0)&&context!=hex.get(0)&&bindedHex.val(null!=all?all.hex:""),ahex&&context!=ahex.get(0)&&ahex.val(null!=all?all.ahex.substring(6):"")},destroy=function(){red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).add(hex).add(bindedHex).add(ahex).unbind("keyup",keyUp).unbind("blur",blur),red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).unbind("keydown",keyDown),color.unbind(colorChanged),red=null,green=null,blue=null,alpha=null,hue=null,saturation=null,value=null,hex=null,ahex=null};$.extend(!0,$this,{destroy:destroy}),red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).add(hex).add(bindedHex).add(ahex).bind("keyup",keyUp).bind("blur",blur),red.add(green).add(blue).add(alpha).add(hue).add(saturation).add(value).bind("keydown",keyDown),color.bind(colorChanged)};$.jPicker={List:[],Color:function(init){var r,g,b,a,h,s,v,$this=this,changeEvents=new Array,fireChangeEvents=function(context){for(var i=0;i<changeEvents.length;i++)changeEvents[i].call($this,$this,context)},val=function(name,value,context){var set=void 0!==value;if(!set){if(void 0!==name&&null!=name&&""!=name||(name="all"),null==r)return null;switch(name.toLowerCase()){case"ahex":return ColorMethods.rgbaToHex({r:r,g:g,b:b,a:a});case"hex":return val("ahex").substring(0,6);case"all":return{r:r,g:g,b:b,a:a,h:h,s:s,v:v,hex:val.call($this,"hex"),ahex:val.call($this,"ahex")};default:for(var ret={},i=0;i<name.length;i++)switch(name.charAt(i)){case"r":1==name.length?ret=r:ret.r=r;break;case"g":1==name.length?ret=g:ret.g=g;break;case"b":1==name.length?ret=b:ret.b=b;break;case"a":1==name.length?ret=a:ret.a=a;break;case"h":1==name.length?ret=h:ret.h=h;break;case"s":1==name.length?ret=s:ret.s=s;break;case"v":1==name.length?ret=v:ret.v=v}return ret=={}?val.call($this,"all"):ret}}if(null==context||context!=$this){var changed=!1;if(null==name&&(name=""),null==value)return null!=r&&(r=null,changed=!0),null!=g&&(g=null,changed=!0),null!=b&&(b=null,changed=!0),null!=a&&(a=null,changed=!0),null!=h&&(h=null,changed=!0),null!=s&&(s=null,changed=!0),null!=v&&(v=null,changed=!0),void(changed&&fireChangeEvents.call($this,context||$this));switch(name.toLowerCase()){case"ahex":case"hex":var ret=ColorMethods.hexToRgba(value&&(value.ahex||value.hex)||value||"00000000");val.call($this,"rgba",{r:ret.r,g:ret.g,b:ret.b,a:"ahex"==name?ret.a:null!=a?a:255},context);break;default:if(value&&(null!=value.ahex||null!=value.hex))return void val.call($this,"ahex",value.ahex||value.hex||"00000000",context);var newV={},rgb=!1,hsv=!1;void 0!==value.r&&-1==!name.indexOf("r")&&(name+="r"),void 0!==value.g&&-1==!name.indexOf("g")&&(name+="g"),void 0!==value.b&&-1==!name.indexOf("b")&&(name+="b"),void 0!==value.a&&-1==!name.indexOf("a")&&(name+="a"),void 0!==value.h&&-1==!name.indexOf("h")&&(name+="h"),void 0!==value.s&&-1==!name.indexOf("s")&&(name+="s"),void 0!==value.v&&-1==!name.indexOf("v")&&(name+="v");for(var i=0;i<name.length;i++)switch(name.charAt(i)){case"r":if(hsv)continue;rgb=!0,newV.r=value&&value.r&&0|value.r||value&&0|value||0,newV.r<0?newV.r=0:newV.r>255&&(newV.r=255),r!=newV.r&&(r=newV.r,changed=!0);break;case"g":if(hsv)continue;rgb=!0,newV.g=value&&value.g&&0|value.g||value&&0|value||0,newV.g<0?newV.g=0:newV.g>255&&(newV.g=255),g!=newV.g&&(g=newV.g,changed=!0);break;case"b":if(hsv)continue;rgb=!0,newV.b=value&&value.b&&0|value.b||value&&0|value||0,newV.b<0?newV.b=0:newV.b>255&&(newV.b=255),b!=newV.b&&(b=newV.b,changed=!0);break;case"a":newV.a=value&&null!=value.a?0|value.a:null!=value?0|value:255,newV.a<0?newV.a=0:newV.a>255&&(newV.a=255),a!=newV.a&&(a=newV.a,changed=!0);break;case"h":if(rgb)continue;hsv=!0,newV.h=value&&value.h&&0|value.h||value&&0|value||0,newV.h<0?newV.h=0:newV.h>360&&(newV.h=360),h!=newV.h&&(h=newV.h,changed=!0);break;case"s":if(rgb)continue;hsv=!0,newV.s=value&&null!=value.s?0|value.s:null!=value?0|value:100,newV.s<0?newV.s=0:newV.s>100&&(newV.s=100),s!=newV.s&&(s=newV.s,changed=!0);break;case"v":if(rgb)continue;hsv=!0,newV.v=value&&null!=value.v?0|value.v:null!=value?0|value:100,newV.v<0?newV.v=0:newV.v>100&&(newV.v=100),v!=newV.v&&(v=newV.v,changed=!0)}if(changed){if(rgb){r=r||0,g=g||0,b=b||0;var ret=ColorMethods.rgbToHsv({r:r,g:g,b:b});h=ret.h,s=ret.s,v=ret.v}else if(hsv){h=h||0,s=null!=s?s:100,v=null!=v?v:100;var ret=ColorMethods.hsvToRgb({h:h,s:s,v:v});r=ret.r,g=ret.g,b=ret.b}a=null!=a?a:255,fireChangeEvents.call($this,context||$this)}}}},bind=function(callback){$.isFunction(callback)&&changeEvents.push(callback)},unbind=function(callback){if($.isFunction(callback))for(var i;-1!=(i=$.inArray(callback,changeEvents));)changeEvents.splice(i,1)},destroy=function(){changeEvents=null};$.extend(!0,$this,{val:val,bind:bind,unbind:unbind,destroy:destroy}),init&&(null!=init.ahex?val("ahex",init):null!=init.hex?val((null!=init.a?"a":"")+"hex",null!=init.a?{ahex:init.hex+ColorMethods.intToHex(init.a)}:init):null!=init.r&&null!=init.g&&null!=init.b?val("rgb"+(null!=init.a?"a":""),init):null!=init.h&&null!=init.s&&null!=init.v&&val("hsv"+(null!=init.a?"a":""),init))},ColorMethods:{hexToRgba:function(hex){if(hex=this.validateHex(hex),""==hex)return{r:null,g:null,b:null,a:null};var r="00",g="00",b="00",a="255";return 6==hex.length&&(hex+="ff"),hex.length>6?(r=hex.substring(0,2),g=hex.substring(2,4),b=hex.substring(4,6),a=hex.substring(6,hex.length)):(hex.length>4&&(r=hex.substring(4,hex.length),hex=hex.substring(0,4)),hex.length>2&&(g=hex.substring(2,hex.length),hex=hex.substring(0,2)),hex.length>0&&(b=hex.substring(0,hex.length))),{r:this.hexToInt(r),g:this.hexToInt(g),b:this.hexToInt(b),a:this.hexToInt(a)}},validateHex:function(hex){return hex=hex.toLowerCase().replace(/[^a-f0-9]/g,""),hex.length>8&&(hex=hex.substring(0,8)),hex},rgbaToHex:function(rgba){return this.intToHex(rgba.r)+this.intToHex(rgba.g)+this.intToHex(rgba.b)+this.intToHex(rgba.a)},intToHex:function(dec){var result=(0|dec).toString(16);return 1==result.length&&(result="0"+result),result.toLowerCase()},hexToInt:function(hex){return parseInt(hex,16)},rgbToHsv:function(rgb){var delta,r=rgb.r/255,g=rgb.g/255,b=rgb.b/255,hsv={h:0,s:0,v:0},min=0,max=0;return r>=g&&r>=b?(max=r,min=g>b?b:g):g>=b&&g>=r?(max=g,min=r>b?b:r):(max=b,min=g>r?r:g),hsv.v=max,hsv.s=max?(max-min)/max:0,hsv.s?(delta=max-min,r==max?hsv.h=(g-b)/delta:g==max?hsv.h=2+(b-r)/delta:hsv.h=4+(r-g)/delta,hsv.h=parseInt(60*hsv.h),hsv.h<0&&(hsv.h+=360)):hsv.h=0,hsv.s=100*hsv.s|0,hsv.v=100*hsv.v|0,hsv},hsvToRgb:function(hsv){var rgb={r:0,g:0,b:0,a:100},h=hsv.h,s=hsv.s,v=hsv.v;if(0==s)0==v?rgb.r=rgb.g=rgb.b=0:rgb.r=rgb.g=rgb.b=255*v/100|0;else{360==h&&(h=0),h/=60,s/=100,v/=100;var i=0|h,f=h-i,p=v*(1-s),q=v*(1-s*f),t=v*(1-s*(1-f));switch(i){case 0:rgb.r=v,rgb.g=t,rgb.b=p;break;case 1:rgb.r=q,rgb.g=v,rgb.b=p;break;case 2:rgb.r=p,rgb.g=v,rgb.b=t;break;case 3:rgb.r=p,rgb.g=q,rgb.b=v;break;case 4:rgb.r=t,rgb.g=p,rgb.b=v;break;case 5:rgb.r=v,rgb.g=p,rgb.b=q}rgb.r=255*rgb.r|0,rgb.g=255*rgb.g|0,rgb.b=255*rgb.b|0}return rgb}}};var Color=$.jPicker.Color,List=$.jPicker.List,ColorMethods=$.jPicker.ColorMethods;$.fn.jPicker=function(options){var $arguments=arguments;return this.each(function(){var $this=this,settings=$.extend(!0,{},$.fn.jPicker.defaults,options);"input"==$($this).get(0).nodeName.toLowerCase()&&($.extend(!0,settings,{window:{bindToInput:!0,expandable:!0,input:$($this)}}),""==$($this).val()?(settings.color.active=new Color({hex:null}),settings.color.current=new Color({hex:null})):ColorMethods.validateHex($($this).val())&&(settings.color.active=new Color({hex:$($this).val(),a:settings.color.active.val("a")}),settings.color.current=new Color({hex:$($this).val(),a:settings.color.active.val("a")}))),settings.window.expandable?$($this).after('<span class="jPicker"><span class="Icon"><span class="Color">&nbsp;</span><span class="Alpha">&nbsp;</span><span class="Image" title="Click To Open Color Picker">&nbsp;</span><span class="Container">&nbsp;</span></span></span>'):settings.window.liveUpdate=!1;var isLessThanIE7=parseFloat(navigator.appVersion.split("MSIE")[1])<7&&document.body.filters,container=null,colorMapDiv=null,colorBarDiv=null,colorMapL1=null,colorMapL2=null,colorMapL3=null,colorBarL1=null,colorBarL2=null,colorBarL3=null,colorBarL4=null,colorBarL5=null,colorBarL6=null,colorMap=null,colorBar=null,colorPicker=null,elementStartX=null,elementStartY=null,pageStartX=null,pageStartY=null,activePreview=null,currentPreview=null,okButton=null,cancelButton=null,grid=null,iconColor=null,iconAlpha=null,iconImage=null,moveBar=null,setColorMode=function(colorMode){var rgbMap,rgbBar,active=color.active,hex=(images.clientPath,active.val("hex"));switch(settings.color.mode=colorMode,colorMode){case"h":if(setTimeout(function(){setBG.call($this,colorMapDiv,"transparent"),setImgLoc.call($this,colorMapL1,0),setAlpha.call($this,colorMapL1,100),setImgLoc.call($this,colorMapL2,260),setAlpha.call($this,colorMapL2,100),setBG.call($this,colorBarDiv,"transparent"),setImgLoc.call($this,colorBarL1,0),setAlpha.call($this,colorBarL1,100),setImgLoc.call($this,colorBarL2,260),setAlpha.call($this,colorBarL2,100),setImgLoc.call($this,colorBarL3,260),setAlpha.call($this,colorBarL3,100),setImgLoc.call($this,colorBarL4,260),setAlpha.call($this,colorBarL4,100),setImgLoc.call($this,colorBarL6,260),setAlpha.call($this,colorBarL6,100)},0),colorMap.range("all",{minX:0,maxX:100,minY:0,maxY:100}),colorBar.range("rangeY",{minY:0,maxY:360}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("s"),y:100-active.val("v")},colorMap),colorBar.val("y",360-active.val("h"),colorBar);break;case"s":if(setTimeout(function(){setBG.call($this,colorMapDiv,"transparent"),setImgLoc.call($this,colorMapL1,-260),setImgLoc.call($this,colorMapL2,-520),setImgLoc.call($this,colorBarL1,-260),setImgLoc.call($this,colorBarL2,-520),setImgLoc.call($this,colorBarL6,260),setAlpha.call($this,colorBarL6,100)},0),colorMap.range("all",{minX:0,maxX:360,minY:0,maxY:100}),colorBar.range("rangeY",{minY:0,maxY:100}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("h"),y:100-active.val("v")},colorMap),colorBar.val("y",100-active.val("s"),colorBar);break;case"v":if(setTimeout(function(){setBG.call($this,colorMapDiv,"000000"),setImgLoc.call($this,colorMapL1,-780),setImgLoc.call($this,colorMapL2,260),setBG.call($this,colorBarDiv,hex),setImgLoc.call($this,colorBarL1,-520),setImgLoc.call($this,colorBarL2,260),setAlpha.call($this,colorBarL2,100),setImgLoc.call($this,colorBarL6,260),setAlpha.call($this,colorBarL6,100)},0),colorMap.range("all",{minX:0,maxX:360,minY:0,maxY:100}),colorBar.range("rangeY",{minY:0,maxY:100}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("h"),y:100-active.val("s")},colorMap),colorBar.val("y",100-active.val("v"),colorBar);break;case"r":if(rgbMap=-1040,rgbBar=-780,colorMap.range("all",{minX:0,maxX:255,minY:0,maxY:255}),colorBar.range("rangeY",{minY:0,maxY:255}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("b"),y:255-active.val("g")},colorMap),colorBar.val("y",255-active.val("r"),colorBar);break;case"g":if(rgbMap=-1560,rgbBar=-1820,colorMap.range("all",{minX:0,maxX:255,minY:0,maxY:255}),colorBar.range("rangeY",{minY:0,maxY:255}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("b"),y:255-active.val("r")},colorMap),colorBar.val("y",255-active.val("g"),colorBar);break;case"b":if(rgbMap=-2080,rgbBar=-2860,colorMap.range("all",{minX:0,maxX:255,minY:0,maxY:255}),colorBar.range("rangeY",{minY:0,maxY:255}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("r"),y:255-active.val("g")},colorMap),colorBar.val("y",255-active.val("b"),colorBar);break;case"a":if(setTimeout(function(){setBG.call($this,colorMapDiv,"transparent"),setImgLoc.call($this,colorMapL1,-260),setImgLoc.call($this,colorMapL2,-520),setImgLoc.call($this,colorBarL1,260),setImgLoc.call($this,colorBarL2,260),setAlpha.call($this,colorBarL2,100),setImgLoc.call($this,colorBarL6,0),setAlpha.call($this,colorBarL6,100)},0),colorMap.range("all",{minX:0,maxX:360,minY:0,maxY:100}),colorBar.range("rangeY",{minY:0,maxY:255}),null==active.val("ahex"))break;colorMap.val("xy",{x:active.val("h"),y:100-active.val("v")},colorMap),colorBar.val("y",255-active.val("a"),colorBar);break;default:throw"Invalid Mode"}switch(colorMode){case"h":break;case"s":case"v":case"a":setTimeout(function(){setAlpha.call($this,colorMapL1,100),setAlpha.call($this,colorBarL1,100),setImgLoc.call($this,colorBarL3,260),setAlpha.call($this,colorBarL3,100),setImgLoc.call($this,colorBarL4,260),setAlpha.call($this,colorBarL4,100)},0);break;case"r":case"g":case"b":setTimeout(function(){setBG.call($this,colorMapDiv,"transparent"),setBG.call($this,colorBarDiv,"transparent"),setAlpha.call($this,colorBarL1,100),setAlpha.call($this,colorMapL1,100),setImgLoc.call($this,colorMapL1,rgbMap),setImgLoc.call($this,colorMapL2,rgbMap-260),setImgLoc.call($this,colorBarL1,rgbBar-780),setImgLoc.call($this,colorBarL2,rgbBar-520),setImgLoc.call($this,colorBarL3,rgbBar),setImgLoc.call($this,colorBarL4,rgbBar-260),setImgLoc.call($this,colorBarL6,260),setAlpha.call($this,colorBarL6,100)},0)}null!=active.val("ahex")&&activeColorChanged.call($this,active)},activeColorChanged=function(ui,context){(null==context||context!=colorBar&&context!=colorMap)&&positionMapAndBarArrows.call($this,ui,context),setTimeout(function(){updatePreview.call($this,ui),updateMapVisuals.call($this,ui),updateBarVisuals.call($this,ui)},0)},mapValueChanged=function(ui,context){var active=color.active;if(context==colorMap||null!=active.val()){var xy=ui.val("all");switch(settings.color.mode){case"h":active.val("sv",{s:xy.x,v:100-xy.y},context);break;case"s":case"a":active.val("hv",{h:xy.x,v:100-xy.y},context);break;case"v":active.val("hs",{h:xy.x,s:100-xy.y},context);break;case"r":active.val("gb",{g:255-xy.y,b:xy.x},context);break;case"g":active.val("rb",{r:255-xy.y,b:xy.x},context);break;case"b":active.val("rg",{r:xy.x,g:255-xy.y},context)}}},colorBarValueChanged=function(ui,context){var active=color.active;if(context==colorBar||null!=active.val())switch(settings.color.mode){case"h":active.val("h",{h:360-ui.val("y")},context);break;case"s":active.val("s",{s:100-ui.val("y")},context);break;case"v":active.val("v",{v:100-ui.val("y")},context);break;case"r":active.val("r",{r:255-ui.val("y")},context);break;case"g":active.val("g",{g:255-ui.val("y")},context);break;case"b":active.val("b",{b:255-ui.val("y")},context);break;case"a":active.val("a",255-ui.val("y"),context)}},positionMapAndBarArrows=function(ui,context){if(context!=colorMap)switch(settings.color.mode){case"h":var sv=ui.val("sv");colorMap.val("xy",{x:null!=sv?sv.s:100,y:100-(null!=sv?sv.v:100)},context);break;case"s":case"a":var hv=ui.val("hv");colorMap.val("xy",{x:hv&&hv.h||0,y:100-(null!=hv?hv.v:100)},context);break;case"v":var hs=ui.val("hs");colorMap.val("xy",{x:hs&&hs.h||0,y:100-(null!=hs?hs.s:100)},context);break;case"r":var bg=ui.val("bg");colorMap.val("xy",{x:bg&&bg.b||0,y:255-(bg&&bg.g||0)},context);break;case"g":var br=ui.val("br");colorMap.val("xy",{x:br&&br.b||0,y:255-(br&&br.r||0)},context);break;case"b":var rg=ui.val("rg");colorMap.val("xy",{x:rg&&rg.r||0,y:255-(rg&&rg.g||0)},context)}if(context!=colorBar)switch(settings.color.mode){case"h":colorBar.val("y",360-(ui.val("h")||0),context);break;case"s":var s=ui.val("s");colorBar.val("y",100-(null!=s?s:100),context);break;case"v":var v=ui.val("v");colorBar.val("y",100-(null!=v?v:100),context);break;case"r":colorBar.val("y",255-(ui.val("r")||0),context);break;case"g":colorBar.val("y",255-(ui.val("g")||0),context);break;case"b":colorBar.val("y",255-(ui.val("b")||0),context);break;case"a":var a=ui.val("a");colorBar.val("y",255-(null!=a?a:255),context)}},updatePreview=function(ui){try{var all=ui.val("all");activePreview.css({backgroundColor:all&&"#"+all.hex||"transparent"}),setAlpha.call($this,activePreview,all&&Math.precision(100*all.a/255,4)||0)}catch(e){}},updateMapVisuals=function(ui){switch(settings.color.mode){case"h":setBG.call($this,colorMapDiv,new Color({h:ui.val("h")||0,s:100,v:100}).val("hex"));break;case"s":case"a":var s=ui.val("s");setAlpha.call($this,colorMapL2,100-(null!=s?s:100));break;case"v":var v=ui.val("v");setAlpha.call($this,colorMapL1,null!=v?v:100);break;case"r":setAlpha.call($this,colorMapL2,Math.precision((ui.val("r")||0)/255*100,4));break;case"g":setAlpha.call($this,colorMapL2,Math.precision((ui.val("g")||0)/255*100,4));break;case"b":setAlpha.call($this,colorMapL2,Math.precision((ui.val("b")||0)/255*100))}var a=ui.val("a");setAlpha.call($this,colorMapL3,Math.precision(100*(255-(a||0))/255,4))},updateBarVisuals=function(ui){switch(settings.color.mode){case"h":var a=ui.val("a");setAlpha.call($this,colorBarL5,Math.precision(100*(255-(a||0))/255,4));break;case"s":var hva=ui.val("hva"),saturatedColor=new Color({h:hva&&hva.h||0,s:100,v:null!=hva?hva.v:100});setBG.call($this,colorBarDiv,saturatedColor.val("hex")),setAlpha.call($this,colorBarL2,100-(null!=hva?hva.v:100)),setAlpha.call($this,colorBarL5,Math.precision(100*(255-(hva&&hva.a||0))/255,4));break;case"v":var hsa=ui.val("hsa"),valueColor=new Color({h:hsa&&hsa.h||0,s:null!=hsa?hsa.s:100,v:100});setBG.call($this,colorBarDiv,valueColor.val("hex")),setAlpha.call($this,colorBarL5,Math.precision(100*(255-(hsa&&hsa.a||0))/255,4));break;case"r":case"g":case"b":var hValue=0,vValue=0,rgba=ui.val("rgba");"r"==settings.color.mode?(hValue=rgba&&rgba.b||0,vValue=rgba&&rgba.g||0):"g"==settings.color.mode?(hValue=rgba&&rgba.b||0,vValue=rgba&&rgba.r||0):"b"==settings.color.mode&&(hValue=rgba&&rgba.r||0,vValue=rgba&&rgba.g||0);var middle=vValue>hValue?hValue:vValue;setAlpha.call($this,colorBarL2,hValue>vValue?Math.precision((hValue-vValue)/(255-vValue)*100,4):0),setAlpha.call($this,colorBarL3,vValue>hValue?Math.precision((vValue-hValue)/(255-hValue)*100,4):0),setAlpha.call($this,colorBarL4,Math.precision(middle/255*100,4)),setAlpha.call($this,colorBarL5,Math.precision(100*(255-(rgba&&rgba.a||0))/255,4));break;case"a":var a=ui.val("a");setBG.call($this,colorBarDiv,ui.val("hex")||"000000"),setAlpha.call($this,colorBarL5,null!=a?0:100),setAlpha.call($this,colorBarL6,null!=a?100:0)}},setBG=function(el,c){el.css({backgroundColor:c&&6==c.length&&"#"+c||"transparent"})},setImg=function(img,src){!isLessThanIE7||-1==src.indexOf("AlphaBar.png")&&-1==src.indexOf("Bars.png")&&-1==src.indexOf("Maps.png")?img.css({backgroundImage:"url('"+src+"')"}):(img.attr("pngSrc",src),img.css({backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')"}))},setImgLoc=function(img,y){img.css({top:y+"px"})},setAlpha=function(obj,alpha){if(obj.css({visibility:alpha>0?"visible":"hidden"}),alpha>0&&100>alpha)if(isLessThanIE7){var src=obj.attr("pngSrc");null==src||-1==src.indexOf("AlphaBar.png")&&-1==src.indexOf("Bars.png")&&-1==src.indexOf("Maps.png")?obj.css({opacity:Math.precision(alpha/100,4)}):obj.css({filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale') progid:DXImageTransform.Microsoft.Alpha(opacity="+alpha+")"})}else obj.css({opacity:Math.precision(alpha/100,4)});else if(0==alpha||100==alpha)if(isLessThanIE7){var src=obj.attr("pngSrc");null==src||-1==src.indexOf("AlphaBar.png")&&-1==src.indexOf("Bars.png")&&-1==src.indexOf("Maps.png")?obj.css({opacity:""}):obj.css({filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+src+"', sizingMethod='scale')"})}else obj.css({opacity:""})},revertColor=function(){color.active.val("ahex",color.current.val("ahex"))},commitColor=function(){color.current.val("ahex",color.active.val("ahex"))},radioClicked=function(e){$(this).parents("tbody:first").find('input:radio[value!="'+e.target.value+'"]').removeAttr("checked"),setColorMode.call($this,e.target.value)},currentClicked=function(){revertColor.call($this)},cancelClicked=function(){revertColor.call($this),settings.window.expandable&&hide.call($this),$.isFunction(cancelCallback)&&cancelCallback.call($this,color.active,cancelButton)},okClicked=function(){commitColor.call($this),settings.window.expandable&&hide.call($this),$.isFunction(commitCallback)&&commitCallback.call($this,color.active,okButton)},iconImageClicked=function(){show.call($this)},currentColorChanged=function(ui,context){var hex=ui.val("hex");currentPreview.css({backgroundColor:hex&&"#"+hex||"transparent"}),setAlpha.call($this,currentPreview,Math.precision(100*(ui.val("a")||0)/255,4))},expandableColorChanged=function(ui,context){var hex=ui.val("hex"),va=ui.val("va");iconColor.css({backgroundColor:hex&&"#"+hex||"transparent"}),setAlpha.call($this,iconAlpha,Math.precision(100*(255-(va&&va.a||0))/255,4)),settings.window.bindToInput&&settings.window.updateInputColor&&settings.window.input.css({backgroundColor:hex&&"#"+hex||"transparent",color:null==va||va.v>75?"#000000":"#ffffff"})},moveBarMouseDown=function(e){settings.window.element,settings.window.page;elementStartX=parseInt(container.css("left")),elementStartY=parseInt(container.css("top")),pageStartX=e.pageX,pageStartY=e.pageY,$(document).bind("mousemove",documentMouseMove).bind("mouseup",documentMouseUp),e.preventDefault()},documentMouseMove=function(e){return container.css({left:elementStartX-(pageStartX-e.pageX)+"px",top:elementStartY-(pageStartY-e.pageY)+"px"}),settings.window.expandable&&!$.support.boxModel&&container.prev().css({left:container.css("left"),top:container.css("top")}),e.stopPropagation(),e.preventDefault(),!1},documentMouseUp=function(e){return $(document).unbind("mousemove",documentMouseMove).unbind("mouseup",documentMouseUp),e.stopPropagation(),e.preventDefault(),!1},quickPickClicked=function(e){return e.preventDefault(),e.stopPropagation(),color.active.val("ahex",$(this).attr("title")||null,e.target),!1},commitCallback=$.isFunction($arguments[1])&&$arguments[1]||null,liveCallback=$.isFunction($arguments[2])&&$arguments[2]||null,cancelCallback=$.isFunction($arguments[3])&&$arguments[3]||null,show=function(){color.current.val("ahex",color.active.val("ahex"));var attachIFrame=function(){if(settings.window.expandable&&!$.support.boxModel){var table=container.find("table:first");container.before("<iframe/>"),container.prev().css({width:table.width(),height:container.height(),opacity:0,position:"absolute",left:container.css("left"),top:container.css("top")})}};switch(settings.window.expandable&&($(document.body).children("div.jPicker.Container").css({zIndex:10}),container.css({zIndex:20})),settings.window.effects.type){case"fade":container.fadeIn(settings.window.effects.speed.show,attachIFrame);break;case"slide":container.slideDown(settings.window.effects.speed.show,attachIFrame);break;case"show":default:container.show(settings.window.effects.speed.show,attachIFrame)}},hide=function(){var removeIFrame=function(){settings.window.expandable&&container.css({zIndex:10}),settings.window.expandable&&!$.support.boxModel&&container.prev().remove()};switch(settings.window.effects.type){case"fade":container.fadeOut(settings.window.effects.speed.hide,removeIFrame);break;case"slide":container.slideUp(settings.window.effects.speed.hide,removeIFrame);break;case"show":default:container.hide(settings.window.effects.speed.hide,removeIFrame)}},initialize=function(){var win=settings.window,popup=win.expandable?$($this).next().find(".Container:first"):null;container=$(win.expandable?"<div/>":$this),container.addClass("jPicker Container"),win.expandable&&container.hide(),container.get(0).onselectstart=function(event){return"input"!==event.target.nodeName.toLowerCase()?!1:void 0};var all=color.active.val("all");win.alphaPrecision<0?win.alphaPrecision=0:win.alphaPrecision>2&&(win.alphaPrecision=2);var controlHtml='<table class="jPicker" cellpadding="0" cellspacing="0"><tbody>'+(win.expandable?'<tr><td class="Move" colspan="5">&nbsp;</td></tr>':"")+'<tr><td rowspan="9"><h2 class="Title">'+(win.title||localization.text.title)+'</h2><div class="Map"><span class="Map1">&nbsp;</span><span class="Map2">&nbsp;</span><span class="Map3">&nbsp;</span><img src="'+images.clientPath+images.colorMap.arrow.file+'" class="Arrow"/></div></td><td rowspan="9"><div class="Bar"><span class="Map1">&nbsp;</span><span class="Map2">&nbsp;</span><span class="Map3">&nbsp;</span><span class="Map4">&nbsp;</span><span class="Map5">&nbsp;</span><span class="Map6">&nbsp;</span><img src="'+images.clientPath+images.colorBar.arrow.file+'" class="Arrow"/></div></td><td colspan="2" class="Preview">'+localization.text.newColor+'<div><span class="Active" title="'+localization.tooltips.colors.newColor+'">&nbsp;</span><span class="Current" title="'+localization.tooltips.colors.currentColor+'">&nbsp;</span></div>'+localization.text.currentColor+'</td><td rowspan="9" class="Button"><input type="button" class="Ok" value="'+localization.text.ok+'" title="'+localization.tooltips.buttons.ok+'"/><input type="button" class="Cancel" value="'+localization.text.cancel+'" title="'+localization.tooltips.buttons.cancel+'"/><hr/><div class="Grid">&nbsp;</div></td></tr><tr class="Hue"><td class="Radio"><label title="'+localization.tooltips.hue.radio+'"><input type="radio" value="h"'+("h"==settings.color.mode?' checked="checked"':"")+'/>H:</label></td><td class="Text"><input type="text" maxlength="3" value="'+(null!=all?all.h:"")+'" title="'+localization.tooltips.hue.textbox+'"/>&nbsp;&deg;</td></tr><tr class="Saturation"><td class="Radio"><label title="'+localization.tooltips.saturation.radio+'"><input type="radio" value="s"'+("s"==settings.color.mode?' checked="checked"':"")+'/>S:</label></td><td class="Text"><input type="text" maxlength="3" value="'+(null!=all?all.s:"")+'" title="'+localization.tooltips.saturation.textbox+'"/>&nbsp;%</td></tr><tr class="Value"><td class="Radio"><label title="'+localization.tooltips.value.radio+'"><input type="radio" value="v"'+("v"==settings.color.mode?' checked="checked"':"")+'/>V:</label><br/><br/></td><td class="Text"><input type="text" maxlength="3" value="'+(null!=all?all.v:"")+'" title="'+localization.tooltips.value.textbox+'"/>&nbsp;%<br/><br/></td></tr><tr class="Red"><td class="Radio"><label title="'+localization.tooltips.red.radio+'"><input type="radio" value="r"'+("r"==settings.color.mode?' checked="checked"':"")+'/>R:</label></td><td class="Text"><input type="text" maxlength="3" value="'+(null!=all?all.r:"")+'" title="'+localization.tooltips.red.textbox+'"/></td></tr><tr class="Green"><td class="Radio"><label title="'+localization.tooltips.green.radio+'"><input type="radio" value="g"'+("g"==settings.color.mode?' checked="checked"':"")+'/>G:</label></td><td class="Text"><input type="text" maxlength="3" value="'+(null!=all?all.g:"")+'" title="'+localization.tooltips.green.textbox+'"/></td></tr><tr class="Blue"><td class="Radio"><label title="'+localization.tooltips.blue.radio+'"><input type="radio" value="b"'+("b"==settings.color.mode?' checked="checked"':"")+'/>B:</label></td><td class="Text"><input type="text" maxlength="3" value="'+(null!=all?all.b:"")+'" title="'+localization.tooltips.blue.textbox+'"/></td></tr><tr class="Alpha"><td class="Radio">'+(win.alphaSupport?'<label title="'+localization.tooltips.alpha.radio+'"><input type="radio" value="a"'+("a"==settings.color.mode?' checked="checked"':"")+"/>A:</label>":"&nbsp;")+'</td><td class="Text">'+(win.alphaSupport?'<input type="text" maxlength="'+(3+win.alphaPrecision)+'" value="'+(null!=all?Math.precision(100*all.a/255,win.alphaPrecision):"")+'" title="'+localization.tooltips.alpha.textbox+'"/>&nbsp;%':"&nbsp;")+'</td></tr><tr class="Hex"><td colspan="2" class="Text"><label title="'+localization.tooltips.hex.textbox+'">#:<input type="text" maxlength="6" class="Hex" value="'+(null!=all?all.hex:"")+'"/></label>'+(win.alphaSupport?'<input type="text" maxlength="2" class="AHex" value="'+(null!=all?all.ahex.substring(6):"")+'" title="'+localization.tooltips.hex.alpha+'"/></td>':"&nbsp;")+"</tr></tbody></table>";
win.expandable?(container.html(controlHtml),0==$(document.body).children("div.jPicker.Container").length?$(document.body).prepend(container):$(document.body).children("div.jPicker.Container:last").after(container),container.mousedown(function(){$(document.body).children("div.jPicker.Container").css({zIndex:10}),container.css({zIndex:20})}),container.css({left:"left"==win.position.x?popup.offset().left-530-("center"==win.position.y?25:0)+"px":"center"==win.position.x?popup.offset().left-260+"px":"right"==win.position.x?popup.offset().left-10+("center"==win.position.y?25:0)+"px":"screenCenter"==win.position.x?($(document).width()>>1)-260+"px":popup.offset().left+parseInt(win.position.x)+"px",position:"absolute",top:"top"==win.position.y?popup.offset().top-312+"px":"center"==win.position.y?popup.offset().top-156+"px":"bottom"==win.position.y?popup.offset().top+25+"px":popup.offset().top+parseInt(win.position.y)+"px"})):(container=$($this),container.html(controlHtml));var tbody=container.find("tbody:first");colorMapDiv=tbody.find("div.Map:first"),colorBarDiv=tbody.find("div.Bar:first");var MapMaps=colorMapDiv.find("span"),BarMaps=colorBarDiv.find("span");colorMapL1=MapMaps.filter(".Map1:first"),colorMapL2=MapMaps.filter(".Map2:first"),colorMapL3=MapMaps.filter(".Map3:first"),colorBarL1=BarMaps.filter(".Map1:first"),colorBarL2=BarMaps.filter(".Map2:first"),colorBarL3=BarMaps.filter(".Map3:first"),colorBarL4=BarMaps.filter(".Map4:first"),colorBarL5=BarMaps.filter(".Map5:first"),colorBarL6=BarMaps.filter(".Map6:first"),colorMap=new Slider(colorMapDiv,{map:{width:images.colorMap.width,height:images.colorMap.height},arrow:{image:images.clientPath+images.colorMap.arrow.file,width:images.colorMap.arrow.width,height:images.colorMap.arrow.height}}),colorMap.bind(mapValueChanged),colorBar=new Slider(colorBarDiv,{map:{width:images.colorBar.width,height:images.colorBar.height},arrow:{image:images.clientPath+images.colorBar.arrow.file,width:images.colorBar.arrow.width,height:images.colorBar.arrow.height}}),colorBar.bind(colorBarValueChanged),colorPicker=new ColorValuePicker(tbody,color.active,win.expandable&&win.bindToInput?win.input:null,win.alphaPrecision);var hex=null!=all?all.hex:null,preview=tbody.find(".Preview"),button=tbody.find(".Button");if(activePreview=preview.find(".Active:first").css({backgroundColor:hex&&"#"+hex||"transparent"}),currentPreview=preview.find(".Current:first").css({backgroundColor:hex&&"#"+hex||"transparent"}).bind("click",currentClicked),setAlpha.call($this,currentPreview,Math.precision(100*color.current.val("a"))/255,4),okButton=button.find(".Ok:first").bind("click",okClicked),cancelButton=button.find(".Cancel:first").bind("click",cancelClicked),grid=button.find(".Grid:first"),setTimeout(function(){setImg.call($this,colorMapL1,images.clientPath+"Maps.png"),setImg.call($this,colorMapL2,images.clientPath+"Maps.png"),setImg.call($this,colorMapL3,images.clientPath+"map-opacity.png"),setImg.call($this,colorBarL1,images.clientPath+"Bars.png"),setImg.call($this,colorBarL2,images.clientPath+"Bars.png"),setImg.call($this,colorBarL3,images.clientPath+"Bars.png"),setImg.call($this,colorBarL4,images.clientPath+"Bars.png"),setImg.call($this,colorBarL5,images.clientPath+"bar-opacity.png"),setImg.call($this,colorBarL6,images.clientPath+"AlphaBar.png"),setImg.call($this,preview.find("div:first"),images.clientPath+"preview-opacity.png")},0),tbody.find("td.Radio input").bind("click",radioClicked),color.quickList&&color.quickList.length>0){var html="";for(i=0;i<color.quickList.length;i++){"string"==(typeof color.quickList[i]).toString().toLowerCase()&&(color.quickList[i]=new Color({hex:color.quickList[i]}));var alpha=color.quickList[i].val("a"),ahex=color.quickList[i].val("ahex");!win.alphaSupport&&ahex&&(ahex=ahex.substring(0,6)+"ff");var quickHex=color.quickList[i].val("hex");html+='<span class="QuickColor"'+(ahex&&' title="#'+ahex+'"'||"")+' style="background-color:'+(quickHex&&"#"+quickHex||"")+";"+(quickHex?"":"background-image:url("+images.clientPath+"NoColor.png)")+(win.alphaSupport&&alpha&&255>alpha?";opacity:"+Math.precision(alpha/255,4)+";filter:Alpha(opacity="+Math.precision(alpha/2.55,4)+")":"")+'">&nbsp;</span>'}setImg.call($this,grid,images.clientPath+"bar-opacity.png"),grid.html(html),grid.find(".QuickColor").click(quickPickClicked)}setColorMode.call($this,settings.color.mode),color.active.bind(activeColorChanged),$.isFunction(liveCallback)&&color.active.bind(liveCallback),color.current.bind(currentColorChanged),win.expandable?($this.icon=popup.parents(".Icon:first"),iconColor=$this.icon.find(".Color:first").css({backgroundColor:hex&&"#"+hex||"transparent"}),iconAlpha=$this.icon.find(".Alpha:first"),setImg.call($this,iconAlpha,images.clientPath+"bar-opacity.png"),setAlpha.call($this,iconAlpha,Math.precision(100*(255-(null!=all?all.a:0))/255,4)),iconImage=$this.icon.find(".Image:first").css({backgroundImage:"url('"+images.clientPath+images.picker.file+"')"}).bind("click",iconImageClicked),win.bindToInput&&win.updateInputColor&&win.input.css({backgroundColor:hex&&"#"+hex||"transparent",color:null==all||all.v>75?"#000000":"#ffffff"}),moveBar=tbody.find(".Move:first").bind("mousedown",moveBarMouseDown),color.active.bind(expandableColorChanged)):show.call($this)},destroy=function(){for(container.find("td.Radio input").unbind("click",radioClicked),currentPreview.unbind("click",currentClicked),cancelButton.unbind("click",cancelClicked),okButton.unbind("click",okClicked),settings.window.expandable&&(iconImage.unbind("click",iconImageClicked),moveBar.unbind("mousedown",moveBarMouseDown),$this.icon=null),container.find(".QuickColor").unbind("click",quickPickClicked),colorMapDiv=null,colorBarDiv=null,colorMapL1=null,colorMapL2=null,colorMapL3=null,colorBarL1=null,colorBarL2=null,colorBarL3=null,colorBarL4=null,colorBarL5=null,colorBarL6=null,colorMap.destroy(),colorMap=null,colorBar.destroy(),colorBar=null,colorPicker.destroy(),colorPicker=null,activePreview=null,currentPreview=null,okButton=null,cancelButton=null,grid=null,commitCallback=null,cancelCallback=null,liveCallback=null,container.remove(),i=0;i<List.length;i++)List[i]==$this&&List.splice(i,1)},images=settings.images,localization=settings.localization,color={active:new Color("string"==(typeof settings.color.active).toString().toLowerCase()?{ahex:!settings.window.alphaSupport&&settings.color.active?settings.color.active.substring(0,6)+"ff":settings.color.active}:{ahex:!settings.window.alphaSupport&&settings.color.active.val("ahex")?settings.color.active.val("ahex").substring(0,6)+"ff":settings.color.active.val("ahex")}),current:new Color("string"==(typeof settings.color.active).toString().toLowerCase()?{ahex:!settings.window.alphaSupport&&settings.color.active?settings.color.active.substring(0,6)+"ff":settings.color.active}:{ahex:!settings.window.alphaSupport&&settings.color.active.val("ahex")?settings.color.active.val("ahex").substring(0,6)+"ff":settings.color.active.val("ahex")}),quickList:settings.color.quickList};$.extend(!0,$this,{commitCallback:commitCallback,liveCallback:liveCallback,cancelCallback:cancelCallback,color:color,show:show,hide:hide,destroy:destroy}),List.push($this),setTimeout(function(){initialize.call($this)},0)})},$.fn.jPicker.defaults={window:{title:null,effects:{type:"slide",speed:{show:"slow",hide:"fast"}},position:{x:"screenCenter",y:"top"},expandable:!1,liveUpdate:!0,alphaSupport:!1,alphaPrecision:0,updateInputColor:!0},color:{mode:"h",active:new Color({ahex:"#ffcc00ff"}),quickList:[new Color({h:360,s:33,v:100}),new Color({h:360,s:66,v:100}),new Color({h:360,s:100,v:100}),new Color({h:360,s:100,v:75}),new Color({h:360,s:100,v:50}),new Color({h:180,s:0,v:100}),new Color({h:30,s:33,v:100}),new Color({h:30,s:66,v:100}),new Color({h:30,s:100,v:100}),new Color({h:30,s:100,v:75}),new Color({h:30,s:100,v:50}),new Color({h:180,s:0,v:90}),new Color({h:60,s:33,v:100}),new Color({h:60,s:66,v:100}),new Color({h:60,s:100,v:100}),new Color({h:60,s:100,v:75}),new Color({h:60,s:100,v:50}),new Color({h:180,s:0,v:80}),new Color({h:90,s:33,v:100}),new Color({h:90,s:66,v:100}),new Color({h:90,s:100,v:100}),new Color({h:90,s:100,v:75}),new Color({h:90,s:100,v:50}),new Color({h:180,s:0,v:70}),new Color({h:120,s:33,v:100}),new Color({h:120,s:66,v:100}),new Color({h:120,s:100,v:100}),new Color({h:120,s:100,v:75}),new Color({h:120,s:100,v:50}),new Color({h:180,s:0,v:60}),new Color({h:150,s:33,v:100}),new Color({h:150,s:66,v:100}),new Color({h:150,s:100,v:100}),new Color({h:150,s:100,v:75}),new Color({h:150,s:100,v:50}),new Color({h:180,s:0,v:50}),new Color({h:180,s:33,v:100}),new Color({h:180,s:66,v:100}),new Color({h:180,s:100,v:100}),new Color({h:180,s:100,v:75}),new Color({h:180,s:100,v:50}),new Color({h:180,s:0,v:40}),new Color({h:210,s:33,v:100}),new Color({h:210,s:66,v:100}),new Color({h:210,s:100,v:100}),new Color({h:210,s:100,v:75}),new Color({h:210,s:100,v:50}),new Color({h:180,s:0,v:30}),new Color({h:240,s:33,v:100}),new Color({h:240,s:66,v:100}),new Color({h:240,s:100,v:100}),new Color({h:240,s:100,v:75}),new Color({h:240,s:100,v:50}),new Color({h:180,s:0,v:20}),new Color({h:270,s:33,v:100}),new Color({h:270,s:66,v:100}),new Color({h:270,s:100,v:100}),new Color({h:270,s:100,v:75}),new Color({h:270,s:100,v:50}),new Color({h:180,s:0,v:10}),new Color({h:300,s:33,v:100}),new Color({h:300,s:66,v:100}),new Color({h:300,s:100,v:100}),new Color({h:300,s:100,v:75}),new Color({h:300,s:100,v:50}),new Color({h:180,s:0,v:0}),new Color({h:330,s:33,v:100}),new Color({h:330,s:66,v:100}),new Color({h:330,s:100,v:100}),new Color({h:330,s:100,v:75}),new Color({h:330,s:100,v:50}),new Color]},images:{clientPath:"/jPicker/images/",colorMap:{width:256,height:256,arrow:{file:"mappoint.gif",width:15,height:15}},colorBar:{width:20,height:256,arrow:{file:"rangearrows.gif",width:20,height:7}},picker:{file:"picker.gif",width:25,height:24}},localization:{text:{title:"Drag Markers To Pick A Color",newColor:"new",currentColor:"current",ok:"OK",cancel:"Cancel"},tooltips:{colors:{newColor:"New Color - Press &ldquo;OK&rdquo; To Commit",currentColor:"Click To Revert To Original Color"},buttons:{ok:"Commit To This Color Selection",cancel:"Cancel And Revert To Original Color"},hue:{radio:"Set To &ldquo;Hue&rdquo; Color Mode",textbox:"Enter A &ldquo;Hue&rdquo; Value (0-360&deg;)"},saturation:{radio:"Set To &ldquo;Saturation&rdquo; Color Mode",textbox:"Enter A &ldquo;Saturation&rdquo; Value (0-100%)"},value:{radio:"Set To &ldquo;Value&rdquo; Color Mode",textbox:"Enter A &ldquo;Value&rdquo; Value (0-100%)"},red:{radio:"Set To &ldquo;Red&rdquo; Color Mode",textbox:"Enter A &ldquo;Red&rdquo; Value (0-255)"},green:{radio:"Set To &ldquo;Green&rdquo; Color Mode",textbox:"Enter A &ldquo;Green&rdquo; Value (0-255)"},blue:{radio:"Set To &ldquo;Blue&rdquo; Color Mode",textbox:"Enter A &ldquo;Blue&rdquo; Value (0-255)"},alpha:{radio:"Set To &ldquo;Alpha&rdquo; Color Mode",textbox:"Enter A &ldquo;Alpha&rdquo; Value (0-100)"},hex:{textbox:"Enter A &ldquo;Hex&rdquo; Color Value (#000000-#ffffff)",alpha:"Enter A &ldquo;Alpha&rdquo; Value (#00-#ff)"}}}}}(jQuery,"1.1.6");var et2_color=function(){"use strict";return et2_inputWidget.extend({attributes:{alphaSupport:{name:"Transparancy",type:"boolean",default:!1,description:"Allow selection of alpha channel as well as color"}},defaults:{window:{expandable:!0,effects:{type:"none"},position:{x:"screenCenter",y:"screenCenter"}},images:{clientPath:egw_webserverUrl+"/phpgwapi/js/jquery/jpicker/images/"},color:{active:new jQuery.jPicker.Color}},init:function(){this._super.apply(this,arguments),this.egw().includeCSS("phpgwapi/js/jquery/jpicker/css/jPicker-1.1.6.min.css"),this.input=this.$node=jQuery(document.createElement("span"));for(var key in jQuery.fn.jPicker.defaults.localization.text)jQuery.fn.jPicker.defaults.localization.text[key]&&(jQuery.fn.jPicker.defaults.localization.text[key]=this.egw().lang(jQuery.fn.jPicker.defaults.localization.text[key]));for(var key in jQuery.fn.jPicker.defaults.localization.tooltips)jQuery.fn.jPicker.defaults.localization.tooltips[key].ok&&(jQuery.fn.jPicker.defaults.localization.tooltips[key].ok=this.egw().lang(jQuery.fn.jPicker.defaults.localization.tooltips[key].ok)),jQuery.fn.jPicker.defaults.localization.tooltips[key].cancel&&(jQuery.fn.jPicker.defaults.localization.tooltips[key].cancel=this.egw().lang(jQuery.fn.jPicker.defaults.localization.tooltips[key].cancel));this.options=jQuery.extend({},this.defaults,this.options),this.setDOMNode(this.$node[0])},destroy:function(){this.get_jPicker()&&(this.get_jPicker().destroy(),jQuery("table.jPicker").dialog("destroy"),jQuery("table.jPicker").remove(),this.$node.next("span").remove()),this._super.call(this,arguments)},doLoadingFinished:function(){if(!this.get_jPicker()){this._super.apply(this,arguments);var self=this;this.options.color.active=new jQuery.jPicker.Color(this.value?{hex:this.value}:{});var list_id=jQuery.jPicker.List.length?jQuery.jPicker.List.length:0;this.$node.jPicker(this.options,function(value){self.set_value(value),jQuery("table.jPicker").dialog("close")},null,function(color){jQuery("table.jPicker").dialog("close")});return jQuery.jPicker.List[list_id].id=this.id+"_jPicker",setTimeout(function(){var regExClassName=/[\[\]']+/g;jQuery("div.jPicker :button").addClass("et2_button et2_button_text"),jQuery("table.jPicker").dialog({title:self.options.statustext?self.options.statustext:self.egw().lang("Select color"),autoOpen:!1,resizable:!1,width:"auto"}),jQuery("table.jPicker").each(function(){return this.getAttribute("class").match(/jPickerColorIden/)?void 0:(jQuery(this).addClass("jPickerColorIden-"+self.id.replace(regExClassName,"_")),!1)}),jQuery("table.jPicker .Move").hide(),jQuery(".Image",self.$node.next()).click(function(){jQuery("table.jPickerColorIden-"+self.id.replace(regExClassName,"_")).dialog("open")})},500),!0}},get_jPicker:function(){for(var i=0;i<jQuery.jPicker.List.length;++i){var node=jQuery.jPicker.List[i];if(node&&(node.id==this.id+"_jPicker"||node.id==this.dom_id))return node}return null},getValue:function(){return this.value},set_value:function(color){if("string"==typeof color)this.value=color;else if("object"==typeof color&&color.val){var hex=color.val("hex");hex?hex="#"+hex:this.value!=hex&&(hex=""),this.value=hex}if(jQuery.jPicker.List.length){var self=this,picker=this.get_jPicker();picker&&(picker.color.active=new jQuery.jPicker.Color(self.options.value))}}})}.call(this);et2_register_widget(et2_color,["colorpicker"]);var et2_color_ro=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{init:function(){this._super.apply(this,arguments),this.value="",this.$node=$j(document.createElement("div")).addClass("et2_color"),this.setDOMNode(this.$node[0])},set_value:function(_value){this.value=_value,_value||(_value="inherit"),this.$node.css("background-color",_value)},getDetachedAttributes:function(_attrs){_attrs.push("value")},getDetachedNodes:function(){return[this.node]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_color_ro,["colorpicker_ro"]),function(factory){"use strict";"function"==typeof define&&define.amd?define(["./blueimp-helper"],factory):(window.blueimp=window.blueimp||{},window.blueimp.Gallery=factory(window.blueimp.helper||window.jQuery))}(function($){"use strict";function Gallery(list,options){return void 0===document.body.style.maxHeight?null:this&&this.options===Gallery.prototype.options?list&&list.length?(this.list=list,this.num=list.length,this.initOptions(options),void this.initialize()):void this.console.log("blueimp Gallery: No or empty list provided as first argument.",list):new Gallery(list,options)}return $.extend(Gallery.prototype,{options:{container:"#blueimp-gallery",slidesContainer:"div",titleElement:"h3",displayClass:"blueimp-gallery-display",controlsClass:"blueimp-gallery-controls",singleClass:"blueimp-gallery-single",leftEdgeClass:"blueimp-gallery-left",rightEdgeClass:"blueimp-gallery-right",playingClass:"blueimp-gallery-playing",slideClass:"slide",slideLoadingClass:"slide-loading",slideErrorClass:"slide-error",slideContentClass:"slide-content",toggleClass:"toggle",prevClass:"prev",nextClass:"next",closeClass:"close",playPauseClass:"play-pause",fullscreenClass:"fullscreen",downloadClass:"download",typeProperty:"type",titleProperty:"title",urlProperty:"href",displayTransition:!0,clearSlides:!0,stretchImages:!1,toggleControlsOnReturn:!0,toggleSlideshowOnSpace:!0,toggleFullscreenOnSlideShow:!1,enableKeyboardNavigation:!0,closeOnEscape:!0,hideControlsOnSlideshow:!1,closeOnSlideClick:!0,closeOnSwipeUpOrDown:!0,emulateTouchEvents:!0,stopTouchEventsPropagation:!1,hidePageScrollbars:!0,disableScroll:!0,carousel:!1,continuous:!0,unloadElements:!0,startSlideshow:!1,slideshowInterval:5e3,index:0,preloadRange:2,transitionSpeed:400,slideshowTransitionSpeed:void 0,event:void 0,onopen:void 0,onopened:void 0,onslide:void 0,onslideend:void 0,onslidecomplete:void 0,onclose:void 0,onclosed:void 0},carouselOptions:{hidePageScrollbars:!1,toggleControlsOnReturn:!1,toggleSlideshowOnSpace:!1,enableKeyboardNavigation:!1,closeOnEscape:!1,closeOnSlideClick:!1,closeOnSwipeUpOrDown:!1,disableScroll:!1,startSlideshow:!0},console:window.console&&"function"==typeof window.console.log?window.console:{log:function(){}},support:function(element){var support={touch:void 0!==window.ontouchstart||window.DocumentTouch&&document instanceof DocumentTouch},transitions={webkitTransition:{end:"webkitTransitionEnd",prefix:"-webkit-"},MozTransition:{end:"transitionend",prefix:"-moz-"},OTransition:{end:"otransitionend",prefix:"-o-"},transition:{end:"transitionend",prefix:""}},elementTests=function(){var prop,translateZ,transition=support.transition;document.body.appendChild(element),transition&&(prop=transition.name.slice(0,-9)+"ransform",void 0!==element.style[prop]&&(element.style[prop]="translateZ(0)",translateZ=window.getComputedStyle(element).getPropertyValue(transition.prefix+"transform"),support.transform={prefix:transition.prefix,name:prop,translate:!0,translateZ:!!translateZ&&"none"!==translateZ})),void 0!==element.style.backgroundSize&&(support.backgroundSize={},element.style.backgroundSize="contain",support.backgroundSize.contain="contain"===window.getComputedStyle(element).getPropertyValue("background-size"),element.style.backgroundSize="cover",support.backgroundSize.cover="cover"===window.getComputedStyle(element).getPropertyValue("background-size")),document.body.removeChild(element)};return function(support,transitions){var prop;for(prop in transitions)if(transitions.hasOwnProperty(prop)&&void 0!==element.style[prop]){support.transition=transitions[prop],support.transition.name=prop;break}}(support,transitions),document.body?elementTests():$(document).on("DOMContentLoaded",elementTests),support}(document.createElement("div")),requestAnimationFrame:window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame,initialize:function(){return this.initStartIndex(),this.initWidget()===!1?!1:(this.initEventListeners(),this.onslide(this.index),this.ontransitionend(),void(this.options.startSlideshow&&this.play()))},slide:function(to,speed){window.clearTimeout(this.timeout);var direction,naturalDirection,diff,index=this.index;if(index!==to&&1!==this.num){if(speed||(speed=this.options.transitionSpeed),this.support.transform){for(this.options.continuous||(to=this.circle(to)),direction=Math.abs(index-to)/(index-to),this.options.continuous&&(naturalDirection=direction,direction=-this.positions[this.circle(to)]/this.slideWidth,direction!==naturalDirection&&(to=-direction*this.num+to)),diff=Math.abs(index-to)-1;diff;)diff-=1,this.move(this.circle((to>index?to:index)-diff-1),this.slideWidth*direction,0);to=this.circle(to),this.move(index,this.slideWidth*direction,speed),this.move(to,0,speed),this.options.continuous&&this.move(this.circle(to-direction),-(this.slideWidth*direction),0)}else to=this.circle(to),this.animate(index*-this.slideWidth,to*-this.slideWidth,speed);this.onslide(to)}},getIndex:function(){return this.index},getNumber:function(){return this.num},prev:function(){(this.options.continuous||this.index)&&this.slide(this.index-1)},next:function(){(this.options.continuous||this.index<this.num-1)&&this.slide(this.index+1)},play:function(time){var that=this;this.options.hideControlsOnSlideshow&&this.container.removeClass(this.options.controlsClass),window.clearTimeout(this.timeout),this.interval=time||this.options.slideshowInterval,this.elements[this.index]>1&&(this.timeout=this.setTimeout(!this.requestAnimationFrame&&this.slide||function(to,speed){that.animationFrameId=that.requestAnimationFrame.call(window,function(){that.slide(to,speed)})},[this.index+1,this.options.slideshowTransitionSpeed],this.interval)),this.container.addClass(this.options.playingClass)},pause:function(){window.clearTimeout(this.timeout),this.interval=null,this.container.removeClass(this.options.playingClass)},add:function(list){var i;for(list.concat||(list=Array.prototype.slice.call(list)),this.list.concat||(this.list=Array.prototype.slice.call(this.list)),this.list=this.list.concat(list),this.num=this.list.length,this.num>2&&null===this.options.continuous&&(this.options.continuous=!0,this.container.removeClass(this.options.leftEdgeClass)),this.container.removeClass(this.options.rightEdgeClass).removeClass(this.options.singleClass),i=this.num-list.length;i<this.num;i+=1)this.addSlide(i),this.positionSlide(i);this.positions.length=this.num,this.initSlides(!0)},resetSlides:function(){this.slidesContainer.empty(),this.slides=[]},handleClose:function(){var options=this.options;this.destroyEventListeners(),this.pause(),this.container[0].style.display="none",this.container.removeClass(options.displayClass).removeClass(options.singleClass).removeClass(options.leftEdgeClass).removeClass(options.rightEdgeClass),options.hidePageScrollbars&&(document.body.style.overflow=this.bodyOverflowStyle),this.options.clearSlides&&this.resetSlides(),this.options.onclosed&&this.options.onclosed.call(this)},close:function(){var that=this,closeHandler=function(event){event.target===that.container[0]&&(that.container.off(that.support.transition.end,closeHandler),that.handleClose())};this.options.onclose&&this.options.onclose.call(this),this.support.transition&&this.options.displayTransition?(this.container.on(this.support.transition.end,closeHandler),this.container.removeClass(this.options.displayClass)):this.handleClose()},circle:function(index){return(this.num+index%this.num)%this.num},move:function(index,dist,speed){this.translateX(index,dist,speed),this.positions[index]=dist},translate:function(index,x,y,speed){var style=this.slides[index].style,transition=this.support.transition,transform=this.support.transform;style[transition.name+"Duration"]=speed+"ms",style[transform.name]="translate("+x+"px, "+y+"px)"+(transform.translateZ?" translateZ(0)":"")},translateX:function(index,x,speed){this.translate(index,x,0,speed)},translateY:function(index,y,speed){this.translate(index,0,y,speed)},animate:function(from,to,speed){if(!speed)return void(this.slidesContainer[0].style.left=to+"px");var that=this,start=(new Date).getTime(),timer=window.setInterval(function(){var timeElap=(new Date).getTime()-start;return timeElap>speed?(that.slidesContainer[0].style.left=to+"px",that.ontransitionend(),void window.clearInterval(timer)):void(that.slidesContainer[0].style.left=(to-from)*(Math.floor(timeElap/speed*100)/100)+from+"px")},4)},preventDefault:function(event){event.preventDefault?event.preventDefault():event.returnValue=!1},stopPropagation:function(event){event.stopPropagation?event.stopPropagation():event.cancelBubble=!0},onresize:function(){this.initSlides(!0)},onmousedown:function(event){event.which&&1===event.which&&"VIDEO"!==event.target.nodeName&&(event.preventDefault(),(event.originalEvent||event).touches=[{pageX:event.pageX,pageY:event.pageY}],this.ontouchstart(event))},onmousemove:function(event){this.touchStart&&((event.originalEvent||event).touches=[{pageX:event.pageX,pageY:event.pageY}],this.ontouchmove(event))},onmouseup:function(event){this.touchStart&&(this.ontouchend(event),delete this.touchStart)},onmouseout:function(event){if(this.touchStart){var target=event.target,related=event.relatedTarget;related&&(related===target||$.contains(target,related))||this.onmouseup(event)}},ontouchstart:function(event){this.options.stopTouchEventsPropagation&&this.stopPropagation(event);var touches=(event.originalEvent||event).touches[0];this.touchStart={x:touches.pageX,y:touches.pageY,time:Date.now()},this.isScrolling=void 0,this.touchDelta={}},ontouchmove:function(event){this.options.stopTouchEventsPropagation&&this.stopPropagation(event);var touchDeltaX,indices,touches=(event.originalEvent||event).touches[0],scale=(event.originalEvent||event).scale,index=this.index;if(!(touches.length>1||scale&&1!==scale))if(this.options.disableScroll&&event.preventDefault(),this.touchDelta={x:touches.pageX-this.touchStart.x,y:touches.pageY-this.touchStart.y},touchDeltaX=this.touchDelta.x,void 0===this.isScrolling&&(this.isScrolling=this.isScrolling||Math.abs(touchDeltaX)<Math.abs(this.touchDelta.y)),this.isScrolling)this.options.closeOnSwipeUpOrDown&&this.translateY(index,this.touchDelta.y+this.positions[index],0);else for(event.preventDefault(),window.clearTimeout(this.timeout),this.options.continuous?indices=[this.circle(index+1),index,this.circle(index-1)]:(this.touchDelta.x=touchDeltaX/=!index&&touchDeltaX>0||index===this.num-1&&0>touchDeltaX?Math.abs(touchDeltaX)/this.slideWidth+1:1,indices=[index],index&&indices.push(index-1),index<this.num-1&&indices.unshift(index+1));indices.length;)index=indices.pop(),this.translateX(index,touchDeltaX+this.positions[index],0)},ontouchend:function(event){this.options.stopTouchEventsPropagation&&this.stopPropagation(event);var direction,indexForward,indexBackward,distanceForward,distanceBackward,index=this.index,speed=this.options.transitionSpeed,slideWidth=this.slideWidth,isShortDuration=Number(Date.now()-this.touchStart.time)<250,isValidSlide=isShortDuration&&Math.abs(this.touchDelta.x)>20||Math.abs(this.touchDelta.x)>slideWidth/2,isPastBounds=!index&&this.touchDelta.x>0||index===this.num-1&&this.touchDelta.x<0,isValidClose=!isValidSlide&&this.options.closeOnSwipeUpOrDown&&(isShortDuration&&Math.abs(this.touchDelta.y)>20||Math.abs(this.touchDelta.y)>this.slideHeight/2);this.options.continuous&&(isPastBounds=!1),direction=this.touchDelta.x<0?-1:1,this.isScrolling?isValidClose?this.close():this.translateY(index,0,speed):isValidSlide&&!isPastBounds?(indexForward=index+direction,indexBackward=index-direction,distanceForward=slideWidth*direction,distanceBackward=-slideWidth*direction,this.options.continuous?(this.move(this.circle(indexForward),distanceForward,0),this.move(this.circle(index-2*direction),distanceBackward,0)):indexForward>=0&&indexForward<this.num&&this.move(indexForward,distanceForward,0),this.move(index,this.positions[index]+distanceForward,speed),this.move(this.circle(indexBackward),this.positions[this.circle(indexBackward)]+distanceForward,speed),index=this.circle(indexBackward),this.onslide(index)):this.options.continuous?(this.move(this.circle(index-1),-slideWidth,speed),this.move(index,0,speed),this.move(this.circle(index+1),slideWidth,speed)):(index&&this.move(index-1,-slideWidth,speed),this.move(index,0,speed),index<this.num-1&&this.move(index+1,slideWidth,speed))},ontouchcancel:function(event){this.touchStart&&(this.ontouchend(event),delete this.touchStart)},ontransitionend:function(event){var slide=this.slides[this.index];event&&slide!==event.target||(this.interval&&this.play(),this.setTimeout(this.options.onslideend,[this.index,slide]))},oncomplete:function(event){var index,target=event.target||event.srcElement,parent=target&&target.parentNode;target&&parent&&(index=this.getNodeIndex(parent),$(parent).removeClass(this.options.slideLoadingClass),"error"===event.type?($(parent).addClass(this.options.slideErrorClass),this.elements[index]=3):this.elements[index]=2,target.clientHeight>this.container[0].clientHeight&&(target.style.maxHeight=this.container[0].clientHeight),this.interval&&this.slides[this.index]===parent&&this.play(),this.setTimeout(this.options.onslidecomplete,[index,parent]))},onload:function(event){this.oncomplete(event)},onerror:function(event){this.oncomplete(event)},onkeydown:function(event){switch(event.which||event.keyCode){case 13:this.options.toggleControlsOnReturn&&(this.preventDefault(event),this.toggleControls());break;case 27:this.options.closeOnEscape&&this.close();break;case 32:this.options.toggleSlideshowOnSpace&&(this.preventDefault(event),this.toggleSlideshow());break;case 37:this.options.enableKeyboardNavigation&&(this.preventDefault(event),this.prev());break;case 39:this.options.enableKeyboardNavigation&&(this.preventDefault(event),this.next())}},handleClick:function(event){var options=this.options,target=event.target||event.srcElement,parent=target.parentNode,isTarget=function(className){return $(target).hasClass(className)||$(parent).hasClass(className)};isTarget(options.toggleClass)?(this.preventDefault(event),this.toggleControls()):isTarget(options.prevClass)?(this.preventDefault(event),this.prev()):isTarget(options.nextClass)?(this.preventDefault(event),this.next()):isTarget(options.closeClass)?(this.preventDefault(event),this.close()):isTarget(options.playPauseClass)?(this.preventDefault(event),this.toggleSlideshow()):isTarget(options.fullscreenClass)?(this.preventDefault(event),this.toggleFullscreen()):isTarget(options.downloadClass)?(this.list[this.getIndex()]&&"undefined"!=typeof this.list[this.getIndex()].download_href?event.target.href=this.list[this.getIndex()].download_href:event.target.href=this.list[this.getIndex()].href,"undefined"!=typeof event.target.download&&(event.target.download=this.list[this.getIndex()].title)):parent===this.slidesContainer[0]?(this.preventDefault(event),options.closeOnSlideClick?this.close():this.toggleControls()):parent.parentNode&&parent.parentNode===this.slidesContainer[0]&&(this.preventDefault(event),this.toggleControls())},onclick:function(event){return this.options.emulateTouchEvents&&this.touchDelta&&(Math.abs(this.touchDelta.x)>20||Math.abs(this.touchDelta.y)>20)?void delete this.touchDelta:this.handleClick(event)},updateEdgeClasses:function(index){index?this.container.removeClass(this.options.leftEdgeClass):this.container.addClass(this.options.leftEdgeClass),index===this.num-1?this.container.addClass(this.options.rightEdgeClass):this.container.removeClass(this.options.rightEdgeClass)},handleSlide:function(index){this.options.continuous||this.updateEdgeClasses(index),this.loadElements(index),this.options.unloadElements&&this.unloadElements(index),this.setTitle(index)},onslide:function(index){this.index=index,this.handleSlide(index),this.setTimeout(this.options.onslide,[index,this.slides[index]])},setTitle:function(index){var text=this.slides[index].firstChild.title,titleElement=this.titleElement;titleElement.length&&(this.titleElement.empty(),text&&titleElement[0].appendChild(document.createTextNode(text)))},setTimeout:function(func,args,wait){var that=this;return func&&window.setTimeout(function(){func.apply(that,args||[])},wait||0)},imageFactory:function(obj,callback){var called,element,title,that=this,img=this.imagePrototype.cloneNode(!1),url=obj,backgroundSize=this.options.stretchImages,callbackWrapper=function(event){if(!called){if(event={type:event.type,target:element},!element.parentNode)return that.setTimeout(callbackWrapper,[event]);called=!0,$(img).off("load error",callbackWrapper),backgroundSize&&"load"===event.type&&(element.style.background='url("'+url+'") center no-repeat',element.style.backgroundSize=backgroundSize),callback(event)}};return"string"!=typeof url&&(url=this.getItemProperty(obj,this.options.urlProperty),title=this.getItemProperty(obj,this.options.titleProperty)),
backgroundSize===!0&&(backgroundSize="contain"),backgroundSize=this.support.backgroundSize&&this.support.backgroundSize[backgroundSize]&&backgroundSize,backgroundSize?element=this.elementPrototype.cloneNode(!1):(element=img,img.draggable=!1),title&&(element.title=title),$(img).on("load error",callbackWrapper),img.src=url,element},createElement:function(obj,callback){var type=obj&&this.getItemProperty(obj,this.options.typeProperty),factory=type&&this[type.split("/")[0]+"Factory"]||this.imageFactory,element=obj&&factory.call(this,obj,callback);return element||(element=this.elementPrototype.cloneNode(!1),this.setTimeout(callback,[{type:"error",target:element}])),$(element).addClass(this.options.slideContentClass),element},loadElement:function(index){this.elements[index]||(this.slides[index].firstChild?this.elements[index]=$(this.slides[index]).hasClass(this.options.slideErrorClass)?3:2:(this.elements[index]=1,$(this.slides[index]).addClass(this.options.slideLoadingClass),this.slides[index].appendChild(this.createElement(this.list[index],this.proxyListener))))},loadElements:function(index){var i,limit=Math.min(this.num,2*this.options.preloadRange+1),j=index;for(i=0;limit>i;i+=1)j+=i*(i%2===0?-1:1),j=this.circle(j),this.loadElement(j)},unloadElements:function(index){var i,slide,diff;for(i in this.elements)this.elements.hasOwnProperty(i)&&(diff=Math.abs(index-i),diff>this.options.preloadRange&&diff+this.options.preloadRange<this.num&&(slide=this.slides[i],slide.removeChild(slide.firstChild),delete this.elements[i]))},addSlide:function(index){var slide=this.slidePrototype.cloneNode(!1);slide.setAttribute("data-index",index),this.slidesContainer[0].appendChild(slide),this.slides.push(slide)},positionSlide:function(index){var slide=this.slides[index];slide.style.width=this.slideWidth+"px",this.support.transform&&(slide.style.left=index*-this.slideWidth+"px",this.move(index,this.index>index?-this.slideWidth:this.index<index?this.slideWidth:0,0))},initSlides:function(reload){var clearSlides,i;for(reload||(this.positions=[],this.positions.length=this.num,this.elements={},this.imagePrototype=document.createElement("img"),this.elementPrototype=document.createElement("div"),this.slidePrototype=document.createElement("div"),$(this.slidePrototype).addClass(this.options.slideClass),this.slides=this.slidesContainer[0].children,clearSlides=this.options.clearSlides||this.slides.length!==this.num),this.slideWidth=this.container[0].offsetWidth,this.slideHeight=this.container[0].offsetHeight,this.slidesContainer[0].style.width=this.num*this.slideWidth+"px",clearSlides&&this.resetSlides(),i=0;i<this.num;i+=1)clearSlides&&this.addSlide(i),this.positionSlide(i);this.options.continuous&&this.support.transform&&(this.move(this.circle(this.index-1),-this.slideWidth,0),this.move(this.circle(this.index+1),this.slideWidth,0)),this.support.transform||(this.slidesContainer[0].style.left=this.index*-this.slideWidth+"px")},toggleControls:function(){var controlsClass=this.options.controlsClass;this.container.hasClass(controlsClass)?this.container.removeClass(controlsClass):this.container.addClass(controlsClass)},toggleSlideshow:function(){this.interval?this.pause():(this.play(),this.options.toggleFullscreenOnSlideShow&&this.requestFullScreen(this.container[0]))},toggleFullscreen:function(){this.getFullScreenElement()?this.exitFullScreen():this.requestFullScreen(this.container[0])},getNodeIndex:function(element){return parseInt(element.getAttribute("data-index"),10)},getNestedProperty:function(obj,property){return property.replace(/\[(?:'([^']+)'|"([^"]+)"|(\d+))\]|(?:(?:^|\.)([^\.\[]+))/g,function(str,singleQuoteProp,doubleQuoteProp,arrayIndex,dotProp){var prop=dotProp||singleQuoteProp||doubleQuoteProp||arrayIndex&&parseInt(arrayIndex,10);str&&obj&&(obj=obj[prop])}),obj},getDataProperty:function(obj,property){if(obj.getAttribute){var prop=obj.getAttribute("data-"+property.replace(/([A-Z])/g,"-$1").toLowerCase());if("string"==typeof prop){if(/^(true|false|null|-?\d+(\.\d+)?|\{[\s\S]*\}|\[[\s\S]*\])$/.test(prop))try{return $.parseJSON(prop)}catch(ignore){}return prop}}},getItemProperty:function(obj,property){var prop=obj[property];return void 0===prop&&(prop=this.getDataProperty(obj,property),void 0===prop&&(prop=this.getNestedProperty(obj,property))),prop},initStartIndex:function(){var i,index=this.options.index,urlProperty=this.options.urlProperty;if(index&&"number"!=typeof index)for(i=0;i<this.num;i+=1)if(this.list[i]===index||this.getItemProperty(this.list[i],urlProperty)===this.getItemProperty(index,urlProperty)){index=i;break}this.index=this.circle(parseInt(index,10)||0)},initEventListeners:function(){var that=this,slidesContainer=this.slidesContainer,proxyListener=function(event){var type=that.support.transition&&that.support.transition.end===event.type?"transitionend":event.type;that["on"+type](event)};$(window).on("resize",proxyListener),$(document.body).on("keydown",proxyListener),this.container.on("click",proxyListener),this.support.touch?slidesContainer.on("touchstart touchmove touchend touchcancel",proxyListener):this.options.emulateTouchEvents&&this.support.transition&&slidesContainer.on("mousedown mousemove mouseup mouseout",proxyListener),this.support.transition&&slidesContainer.on(this.support.transition.end,proxyListener),this.proxyListener=proxyListener},destroyEventListeners:function(){var slidesContainer=this.slidesContainer,proxyListener=this.proxyListener;$(window).off("resize",proxyListener),$(document.body).off("keydown",proxyListener),this.container.off("click",proxyListener),this.support.touch?slidesContainer.off("touchstart touchmove touchend touchcancel",proxyListener):this.options.emulateTouchEvents&&this.support.transition&&slidesContainer.off("mousedown mousemove mouseup mouseout",proxyListener),this.support.transition&&slidesContainer.off(this.support.transition.end,proxyListener)},handleOpen:function(){this.options.onopened&&this.options.onopened.call(this)},initWidget:function(){var that=this,openHandler=function(event){event.target===that.container[0]&&(that.container.off(that.support.transition.end,openHandler),that.handleOpen())};return this.container=$(this.options.container),this.container.length?(this.slidesContainer=this.container.find(this.options.slidesContainer).first(),this.slidesContainer.length?(this.titleElement=this.container.find(this.options.titleElement).first(),1===this.num&&this.container.addClass(this.options.singleClass),this.options.onopen&&this.options.onopen.call(this),this.support.transition&&this.options.displayTransition?this.container.on(this.support.transition.end,openHandler):this.handleOpen(),this.options.hidePageScrollbars&&(this.bodyOverflowStyle=document.body.style.overflow,document.body.style.overflow="hidden"),this.container[0].style.display="block",this.initSlides(),void this.container.addClass(this.options.displayClass)):(this.console.log("blueimp Gallery: Slides container not found.",this.options.slidesContainer),!1)):(this.console.log("blueimp Gallery: Widget container not found.",this.options.container),!1)},initOptions:function(options){this.options=$.extend({},this.options),(options&&options.carousel||this.options.carousel&&(!options||options.carousel!==!1))&&$.extend(this.options,this.carouselOptions),$.extend(this.options,options),this.num<3&&(this.options.continuous=this.options.continuous?null:!1),this.support.transition||(this.options.emulateTouchEvents=!1),this.options.event&&this.preventDefault(this.options.event)}}),Gallery}),function(factory){"use strict";"function"==typeof define&&define.amd?define(["./blueimp-helper","./blueimp-gallery"],factory):factory(window.blueimp.helper||window.jQuery,window.blueimp.Gallery)}(function($,Gallery){"use strict";$.extend(Gallery.prototype.options,{fullScreen:!1});var initialize=Gallery.prototype.initialize,close=Gallery.prototype.close;return $.extend(Gallery.prototype,{getFullScreenElement:function(){return document.fullscreenElement||document.webkitFullscreenElement||document.mozFullScreenElement||document.msFullscreenElement},requestFullScreen:function(element){element.requestFullscreen?element.requestFullscreen():element.webkitRequestFullscreen?element.webkitRequestFullscreen():element.mozRequestFullScreen?element.mozRequestFullScreen():element.msRequestFullscreen&&element.msRequestFullscreen()},exitFullScreen:function(){document.exitFullscreen?document.exitFullscreen():document.webkitCancelFullScreen?document.webkitCancelFullScreen():document.mozCancelFullScreen?document.mozCancelFullScreen():document.msExitFullscreen&&document.msExitFullscreen()},initialize:function(){initialize.call(this),this.options.fullScreen&&!this.getFullScreenElement()&&this.requestFullScreen(this.container[0])},close:function(){this.getFullScreenElement()===this.container[0]&&this.exitFullScreen(),close.call(this)}}),Gallery}),function(factory){"use strict";"function"==typeof define&&define.amd?define(["./blueimp-helper","./blueimp-gallery"],factory):factory(window.blueimp.helper||window.jQuery,window.blueimp.Gallery)}(function($,Gallery){"use strict";$.extend(Gallery.prototype.options,{indicatorContainer:"ol",activeIndicatorClass:"active",thumbnailProperty:"thumbnail",thumbnailIndicators:!0,thumbnailsTagIndicators:"li",thumbnailWithImgTag:!1});var initSlides=Gallery.prototype.initSlides,addSlide=Gallery.prototype.addSlide,resetSlides=Gallery.prototype.resetSlides,handleClick=Gallery.prototype.handleClick,handleSlide=Gallery.prototype.handleSlide,handleClose=Gallery.prototype.handleClose;return $.extend(Gallery.prototype,{createIndicator:function(obj){var thumbnailUrl,thumbnail,indicator=this.indicatorPrototype.cloneNode(this.options.thumbnailWithImgTag),title=this.getItemProperty(obj,this.options.titleProperty),thumbnailProperty=this.options.thumbnailProperty;return this.options.thumbnailIndicators&&(thumbnail=obj.getElementsByTagName&&$(obj).find("img")[0],thumbnail?thumbnailUrl=thumbnail.src:thumbnailProperty&&(thumbnailUrl=this.getItemProperty(obj,thumbnailProperty)),thumbnailUrl&&("img"==this.options.thumbnailsTagIndicators?indicator.src=thumbnailUrl:this.options.thumbnailWithImgTag?indicator.children[0].src=thumbnailUrl:indicator.style.backgroundImage='url("'+thumbnailUrl+'")')),title&&(indicator.title=title),indicator},addIndicator:function(index){if(this.indicatorContainer.length){var indicator=this.createIndicator(this.list[index]);indicator.setAttribute("data-index",index),this.indicatorContainer[0].appendChild(indicator),this.indicators.push(indicator)}},setActiveIndicator:function(index){this.indicators&&(this.activeIndicator&&this.activeIndicator.removeClass(this.options.activeIndicatorClass),this.activeIndicator=$(this.indicators[index]),this.activeIndicator.addClass(this.options.activeIndicatorClass))},initSlides:function(reload){reload||(this.indicatorContainer=this.container.find(this.options.indicatorContainer),this.indicatorContainer.length&&(this.indicatorPrototype=document.createElement(this.options.thumbnailsTagIndicators),this.options.thumbnailWithImgTag&&this.indicatorPrototype.appendChild(document.createElement("img")),this.indicators=this.indicatorContainer[0].children)),initSlides.call(this,reload)},addSlide:function(index){addSlide.call(this,index),this.addIndicator(index)},resetSlides:function(){resetSlides.call(this),this.indicatorContainer.empty(),this.indicators=[]},handleClick:function(event){var target=event.target||event.srcElement,parent=target.parentNode;if(parent===this.indicatorContainer[0])this.preventDefault(event),this.slide(this.getNodeIndex(target));else{if(parent.parentNode!==this.indicatorContainer[0])return handleClick.call(this,event);this.preventDefault(event),this.slide(this.getNodeIndex(parent))}},handleSlide:function(index){handleSlide.call(this,index),this.setActiveIndicator(index)},handleClose:function(){this.activeIndicator&&this.activeIndicator.removeClass(this.options.activeIndicatorClass),handleClose.call(this)}}),Gallery}),function(factory){"use strict";"function"==typeof define&&define.amd?define(["./blueimp-helper","./blueimp-gallery"],factory):factory(window.blueimp.helper||window.jQuery,window.blueimp.Gallery)}(function($,Gallery){"use strict";$.extend(Gallery.prototype.options,{videoContentClass:"video-content",videoLoadingClass:"video-loading",videoPlayingClass:"video-playing",videoPosterProperty:"poster",videoSourcesProperty:"sources"});var handleSlide=Gallery.prototype.handleSlide;return $.extend(Gallery.prototype,{handleSlide:function(index){handleSlide.call(this,index),this.playingVideo&&this.playingVideo.pause()},videoFactory:function(obj,callback,videoInterface){var posterImage,source,playMediaControl,isLoading,hasControls,that=this,options=this.options,videoContainerNode=this.elementPrototype.cloneNode(!1),videoContainer=$(videoContainerNode),errorArgs=[{type:"error",target:videoContainerNode}],video=videoInterface||document.createElement("video"),url=this.getItemProperty(obj,options.urlProperty),type=this.getItemProperty(obj,options.typeProperty),title=this.getItemProperty(obj,options.titleProperty),posterUrl=this.getItemProperty(obj,options.videoPosterProperty),sources=this.getItemProperty(obj,options.videoSourcesProperty);if(videoContainer.addClass(options.videoContentClass),title&&(videoContainerNode.title=title),video.canPlayType)if(url&&type&&video.canPlayType(type))video.src=url;else for(;sources&&sources.length;)if(source=sources.shift(),url=this.getItemProperty(source,options.urlProperty),type=this.getItemProperty(source,options.typeProperty),url&&type&&video.canPlayType(type)){video.src=url;break}return posterUrl&&(video.poster=posterUrl,posterImage=this.imagePrototype.cloneNode(!1),$(posterImage).addClass(options.toggleClass),posterImage.src=posterUrl,posterImage.draggable=!1,videoContainerNode.appendChild(posterImage)),playMediaControl=document.createElement("a"),playMediaControl.setAttribute("target","_blank"),videoInterface||playMediaControl.setAttribute("download",title),playMediaControl.href=url,video.src&&(video.controls=!0,(videoInterface||$(video)).on("error",function(){that.setTimeout(callback,errorArgs)}).on("pause",function(){isLoading=!1,videoContainer.removeClass(that.options.videoLoadingClass).removeClass(that.options.videoPlayingClass),hasControls&&that.container.addClass(that.options.controlsClass),delete that.playingVideo,that.interval&&that.play()}).on("playing",function(){isLoading=!1,videoContainer.removeClass(that.options.videoLoadingClass).addClass(that.options.videoPlayingClass),that.container.hasClass(that.options.controlsClass)?(hasControls=!0,that.container.removeClass(that.options.controlsClass)):hasControls=!1}).on("play",function(){window.clearTimeout(that.timeout),isLoading=!0,videoContainer.addClass(that.options.videoLoadingClass),that.playingVideo=video}),$(playMediaControl).on("click",function(event){that.preventDefault(event),isLoading?video.pause():video.play()}),videoContainerNode.appendChild(videoInterface&&videoInterface.element||video)),videoContainerNode.appendChild(playMediaControl),this.setTimeout(callback,[{type:"load",target:videoContainerNode}]),videoContainerNode}}),Gallery}),function(factory){"use strict";"function"==typeof define&&define.amd?define(["./blueimp-helper","./blueimp-gallery-video"],factory):factory(window.blueimp.helper||window.jQuery,window.blueimp.Gallery)}(function($,Gallery){"use strict";if(!window.postMessage)return Gallery;$.extend(Gallery.prototype.options,{youTubeVideoIdProperty:"youtube",youTubePlayerVars:{wmode:"transparent"},youTubeClickToPlay:!0});var textFactory=Gallery.prototype.textFactory||Gallery.prototype.imageFactory,YouTubePlayer=function(videoId,playerVars,clickToPlay){this.videoId=videoId,this.playerVars=playerVars,this.clickToPlay=clickToPlay,this.element=document.createElement("div"),this.listeners={}};return $.extend(YouTubePlayer.prototype,{canPlayType:function(){return!0},on:function(type,func){return this.listeners[type]=func,this},loadAPI:function(){var scriptTag,that=this,onYouTubeIframeAPIReady=window.onYouTubeIframeAPIReady,apiUrl="//www.youtube.com/iframe_api",scriptTags=document.getElementsByTagName("script"),i=scriptTags.length;for(window.onYouTubeIframeAPIReady=function(){onYouTubeIframeAPIReady&&onYouTubeIframeAPIReady.apply(this),that.playOnReady&&that.play()};i;)if(i-=1,scriptTags[i].src===apiUrl)return;scriptTag=document.createElement("script"),scriptTag.src=apiUrl,scriptTags[0].parentNode.insertBefore(scriptTag,scriptTags[0])},onReady:function(){this.ready=!0,this.playOnReady&&this.play()},onPlaying:function(){this.playStatus<2&&(this.listeners.playing(),this.playStatus=2)},onPause:function(){Gallery.prototype.setTimeout.call(this,this.checkSeek,null,2e3)},checkSeek:function(){this.stateChange!==YT.PlayerState.PAUSED&&this.stateChange!==YT.PlayerState.ENDED||(this.listeners.pause(),delete this.playStatus)},onStateChange:function(event){switch(event.data){case YT.PlayerState.PLAYING:this.hasPlayed=!0,this.onPlaying();break;case YT.PlayerState.PAUSED:case YT.PlayerState.ENDED:this.onPause()}this.stateChange=event.data},onError:function(event){this.listeners.error(event)},play:function(){var that=this;this.playStatus||(this.listeners.play(),this.playStatus=1),this.ready?!this.hasPlayed&&(this.clickToPlay||window.navigator&&/iP(hone|od|ad)/.test(window.navigator.platform))?this.onPlaying():this.player.playVideo():(this.playOnReady=!0,window.YT&&YT.Player?this.player||(this.player=new YT.Player(this.element,{videoId:this.videoId,playerVars:this.playerVars,events:{onReady:function(){that.onReady()},onStateChange:function(event){that.onStateChange(event)},onError:function(event){that.onError(event)}}})):this.loadAPI())},pause:function(){this.ready?this.player.pauseVideo():this.playStatus&&(delete this.playOnReady,this.listeners.pause(),delete this.playStatus)}}),$.extend(Gallery.prototype,{YouTubePlayer:YouTubePlayer,textFactory:function(obj,callback){var options=this.options,videoId=this.getItemProperty(obj,options.youTubeVideoIdProperty);return videoId?(void 0===this.getItemProperty(obj,options.urlProperty)&&(obj[options.urlProperty]="//www.youtube.com/watch?v="+videoId),void 0===this.getItemProperty(obj,options.videoPosterProperty)&&(obj[options.videoPosterProperty]="//img.youtube.com/vi/"+videoId+"/maxresdefault.jpg"),this.videoFactory(obj,callback,new YouTubePlayer(videoId,options.youTubePlayerVars,options.youTubeClickToPlay))):textFactory.call(this,obj,callback)}}),Gallery}),function(factory){"use strict";"function"==typeof define&&define.amd?define(["./blueimp-helper","./blueimp-gallery-video"],factory):factory(window.blueimp.helper||window.jQuery,window.blueimp.Gallery)}(function($,Gallery){"use strict";if(!window.postMessage)return Gallery;$.extend(Gallery.prototype.options,{vimeoVideoIdProperty:"vimeo",vimeoPlayerUrl:"//player.vimeo.com/video/VIDEO_ID?api=1&player_id=PLAYER_ID",vimeoPlayerIdPrefix:"vimeo-player-",vimeoClickToPlay:!0});var textFactory=Gallery.prototype.textFactory||Gallery.prototype.imageFactory,VimeoPlayer=function(url,videoId,playerId,clickToPlay){this.url=url,this.videoId=videoId,this.playerId=playerId,this.clickToPlay=clickToPlay,this.element=document.createElement("div"),this.listeners={}},counter=0;return $.extend(VimeoPlayer.prototype,{canPlayType:function(){return!0},on:function(type,func){return this.listeners[type]=func,this},loadAPI:function(){for(var scriptTag,called,that=this,apiUrl="//"+("https"===location.protocol?"secure-":"")+"a.vimeocdn.com/js/froogaloop2.min.js",scriptTags=document.getElementsByTagName("script"),i=scriptTags.length,callback=function(){!called&&that.playOnReady&&that.play(),called=!0};i;)if(i-=1,scriptTags[i].src===apiUrl){scriptTag=scriptTags[i];break}scriptTag||(scriptTag=document.createElement("script"),scriptTag.src=apiUrl),$(scriptTag).on("load",callback),scriptTags[0].parentNode.insertBefore(scriptTag,scriptTags[0]),/loaded|complete/.test(scriptTag.readyState)&&callback()},onReady:function(){var that=this;this.ready=!0,this.player.addEvent("play",function(){that.hasPlayed=!0,that.onPlaying()}),this.player.addEvent("pause",function(){that.onPause()}),this.player.addEvent("finish",function(){that.onPause()}),this.playOnReady&&this.play()},onPlaying:function(){this.playStatus<2&&(this.listeners.playing(),this.playStatus=2)},onPause:function(){this.listeners.pause(),delete this.playStatus},insertIframe:function(){var iframe=document.createElement("iframe");iframe.src=this.url.replace("VIDEO_ID",this.videoId).replace("PLAYER_ID",this.playerId),iframe.id=this.playerId,this.element.parentNode.replaceChild(iframe,this.element),this.element=iframe},play:function(){var that=this;this.playStatus||(this.listeners.play(),this.playStatus=1),this.ready?!this.hasPlayed&&(this.clickToPlay||window.navigator&&/iP(hone|od|ad)/.test(window.navigator.platform))?this.onPlaying():this.player.api("play"):(this.playOnReady=!0,window.$f?this.player||(this.insertIframe(),this.player=$f(this.element),this.player.addEvent("ready",function(){that.onReady()})):this.loadAPI())},pause:function(){this.ready?this.player.api("pause"):this.playStatus&&(delete this.playOnReady,this.listeners.pause(),delete this.playStatus)}}),$.extend(Gallery.prototype,{VimeoPlayer:VimeoPlayer,textFactory:function(obj,callback){var options=this.options,videoId=this.getItemProperty(obj,options.vimeoVideoIdProperty);return videoId?(void 0===this.getItemProperty(obj,options.urlProperty)&&(obj[options.urlProperty]="//vimeo.com/"+videoId),counter+=1,this.videoFactory(obj,callback,new VimeoPlayer(options.vimeoPlayerUrl,videoId,options.vimeoPlayerIdPrefix+counter,options.vimeoClickToPlay))):textFactory.call(this,obj,callback)}}),Gallery}),function(){"use strict";function extend(obj1,obj2){var prop;for(prop in obj2)obj2.hasOwnProperty(prop)&&(obj1[prop]=obj2[prop]);return obj1}function Helper(query){if(!this||this.find!==Helper.prototype.find)return new Helper(query);if(this.length=0,query)if("string"==typeof query&&(query=this.find(query)),query.nodeType||query===query.window)this.length=1,this[0]=query;else{var i=query.length;for(this.length=i;i;)i-=1,this[i]=query[i]}}Helper.extend=extend,Helper.contains=function(container,element){do if(element=element.parentNode,element===container)return!0;while(element);return!1},Helper.parseJSON=function(string){return window.JSON&&JSON.parse(string)},extend(Helper.prototype,{find:function(query){var container=this[0]||document;return"string"==typeof query&&(query=container.querySelectorAll?container.querySelectorAll(query):"#"===query.charAt(0)?container.getElementById(query.slice(1)):container.getElementsByTagName(query)),new Helper(query)},hasClass:function(className){return this[0]?new RegExp("(^|\\s+)"+className+"(\\s+|$)").test(this[0].className):!1},addClass:function(className){for(var element,i=this.length;i;){if(i-=1,element=this[i],!element.className)return element.className=className,this;if(this.hasClass(className))return this;element.className+=" "+className}return this},removeClass:function(className){for(var element,regexp=new RegExp("(^|\\s+)"+className+"(\\s+|$)"),i=this.length;i;)i-=1,element=this[i],element.className=element.className.replace(regexp," ");return this},on:function(eventName,handler){for(var i,element,eventNames=eventName.split(/\s+/);eventNames.length;)for(eventName=eventNames.shift(),i=this.length;i;)i-=1,element=this[i],element.addEventListener?element.addEventListener(eventName,handler,!1):element.attachEvent&&element.attachEvent("on"+eventName,handler);return this},off:function(eventName,handler){for(var i,element,eventNames=eventName.split(/\s+/);eventNames.length;)for(eventName=eventNames.shift(),i=this.length;i;)i-=1,element=this[i],element.removeEventListener?element.removeEventListener(eventName,handler,!1):element.detachEvent&&element.detachEvent("on"+eventName,handler);return this},empty:function(){for(var element,i=this.length;i;)for(i-=1,element=this[i];element.hasChildNodes();)element.removeChild(element.lastChild);return this},first:function(){return new Helper(this[0])}}),"function"==typeof define&&define.amd?define(function(){return Helper}):(window.blueimp=window.blueimp||{},window.blueimp.helper=Helper)}();var et2_IExposable=new Interface({getMedia:function(_attrs){}}),et2_description=function(){"use strict";return expose(et2_baseWidget.extend([et2_IDetachedDOM],{attributes:{label:{name:"Label",default:"",type:"string",description:"The label is displayed by default in front (for radiobuttons behind) each widget (if not empty). If you want to specify a different position, use a '%s' in the label, which gets replaced by the widget itself. Eg. '%s Name' to have the label Name behind a checkbox. The label can contain variables, as descript for name. If the label starts with a '@' it is replaced by the value of the content-array at this index (with the '@'-removed and after expanding the variables).",translate:!0},value:{name:"Value",type:"string",description:"Displayed text",translate:"!no_lang",default:""},font_style:{name:"Font Style",type:"string",description:'Style may be a compositum of "b" and "i" which renders the text bold and/or italic.'},href:{name:"Link URL",type:"string",description:"Link URL, empty if you don't wan't to display a link."},activate_links:{name:"Replace URLs",type:"boolean",default:!1,description:"If set, URLs in the text are automatically replaced by links"},for:{name:"Label for widget",type:"string",description:"Marks the text as label for the given widget."},extra_link_target:{name:"Link target",type:"string",default:"_browser",description:"Link target for href attribute"},extra_link_popup:{name:"Popup",type:"string",description:"widthxheight, if popup should be used, eg. 640x480"},extra_link_title:{name:"Link Title",type:"string",description:"Link title which is displayed on mouse over.",translate:!0},expose_view:{name:"Expose view",type:"boolean",default:!1,description:"Clicking on description with href value would popup an expose view, and will show content referenced by href."},mime:{name:"Mime type",type:"string",default:"",description:"Mime type of the registered link"},mime_data:{name:"Mime data",type:"string",default:"",description:"hash for data stored on service-side with egw_link::(get|set)_data()"}},legacyOptions:["font_style","href","activate_links","for","extra_link_target","extra_link_popup","extra_link_title"],init:function(){this._super.apply(this,arguments),this.span=$j(document.createElement(this.options.for?"label":"span")).addClass("et2_label"),this.options.for&&this.span.attr("for",this.options.for),et2_insertLinkText(this._parseText(this.options.value),this.span[0],this.options.href?this.options.extra_link_target:"_blank"),this.setDOMNode(this.span[0])},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),this.id){var val=this.getArrayMgr("content").getEntry(this.id);val&&(_attrs.value=val)}},set_label:function(_value){if(_value!=this.label){if(_value){null==this._labelContainer&&(this._labelContainer=$j(document.createElement("label")).addClass("et2_label"),this.getSurroundings().insertDOMNode(this._labelContainer[0])),this._labelContainer.empty();var ph=document.createElement("span");this.getSurroundings().setWidgetPlaceholder(ph);for(var parts=et2_csvSplit(_value,2,"%s"),i=0;i<parts.length;i++)parts[i]&&this._labelContainer.append(document.createTextNode(parts[i])),0==i&&this._labelContainer.append(ph)}else this._labelContainer&&this.getSurroundings().removeDOMNode(this._labelContainer[0]),this._labelContainer=null;this.getSurroundings().update(),this.label=_value}},getMedia:function(_value){var base_url=egw.webserverUrl.match(/^\//,"ig")?egw(window).window.location.origin:"",mediaContent=[];return _value&&(mediaContent=[{title:this.options.label,href:base_url+_value,type:this.options.type+"/*",thumbnail:base_url+_value}],_value.match(/\/webdav.php/,"ig")&&(mediaContent[0].download_href=base_url+_value+"?download")),mediaContent},set_value:function(_value){if(_value||(_value=""),this.options.no_lang||(_value=this.egw().lang(_value)),this.options.value&&-1!=(this.options.value+"").indexOf("%s")&&(_value=this.options.value.replace(/%s/g,_value)),et2_insertLinkText(this._parseText(_value),this.span[0],this.options.href?this.options.extra_link_target:"_blank"),this.options.extra_link_popup||this.options.mime){var href=this.options.href,mime_data=this.options.mime_data,self=this,$span=this.options.mime_data?jQuery(this.span):jQuery("a",this.span);$span.click(function(e){return self.options.expose_view&&"undefined"!=typeof self.options.mime&&self.options.mime.match(self.mime_regexp,"ig")?self._init_blueimp_gallery(e,href):egw(window).open_link(mime_data||href,self.options.extra_link_target,self.options.extra_link_popup,null,null,self.options.mime),e.preventDefault(),!1})}},_parseText:function(_value){if(this.options.href){var href=this.options.href;return-1==href.indexOf("/")&&href.split(".").length>=3&&-1==href.indexOf("mailto:")&&-1==href.indexOf("://")&&-1==href.indexOf("javascript:")&&(href="/index.php?menuaction="+href),"/"==href.charAt(0)&&(href=egw.link(href)),[{href:href,text:_value}]}return this.options.activate_links?et2_activateLinks(_value):[_value]},set_font_style:function(_value){this.font_style=_value,this.span.toggleClass("et2_bold",_value.indexOf("b")>=0),this.span.toggleClass("et2_italic",_value.indexOf("i")>=0)},getDetachedAttributes:function(_attrs){_attrs.push("value","class","href")},getDetachedNodes:function(){return[this.span[0]]},setDetachedAttributes:function(_nodes,_values){var updateLink=!1;"undefined"!=typeof _values.href&&(updateLink=!0,this.options.href=_values.href),("undefined"!=typeof _values.value||updateLink&&(_values.value||this.options.value))&&(this.span=jQuery(_nodes[0]),this.set_value(_values.value)),"undefined"!=typeof _values.class&&_nodes[0].setAttribute("class",_values.class)}}))}.call(this);et2_register_widget(et2_description,["description","label"]);var et2_entry=function(){"use strict";return et2_valueWidget.extend({attributes:{field:{name:"Fields",description:'Which entry field to display, or "sum" to add up the alternate_fields',type:"string"},compare:{name:"Compare",description:"if given, the selected field is compared with its value and an X is printed on equality, nothing otherwise",default:et2_no_init,type:"string"},alternate_fields:{name:"Alternate fields",description:"colon (:) separated list of alternative fields. The first non-empty one is used if the selected field is empty, (-) used for subtraction",type:"string",default:et2_no_init},precision:{name:"Decimals to be shown",description:"Specifies the number of decimals for sum of alternates, the default is 2",type:"string",default:"2"},value:{type:"any"},readonly:{default:!0}},legacyOptions:["field","compare","alternate_fields"],prefix:"~",init:function(parent,attrs){attrs.id&&attrs.id.indexOf(this.prefix)<0&&(attrs.id=this.prefix+attrs.id);var value=attrs.value;this._super.apply(this,arguments),value&&(this.options.value=value),this.widget=null,this.setDOMNode(document.createElement("span"))},loadFromXML:function(_node){this._super.apply(this,arguments),this.loadField()},loadField:function(){var attrs={id:this.id+"["+this.options.field+"]",type:"label",readonly:this.options.readonly},modifications=this.getArrayMgr("modifications");modifications&&this.options.field&&jQuery.extend(attrs,modifications.getEntry(attrs.id)),"template"==attrs.type&&this.options.label&&(this.egw().debug("log","Surpressed label on <"+this._type+' label="'+this.options.label+'" id="'+this.id+'"...>'),this.options.label="");var widget=et2_createWidget(attrs.type,attrs,this);if("string"==typeof this.options.value&&(widget.options.value=this.getRoot().getArrayMgr("content").getEntry(this.prefix+this.options.value+"["+this.options.field+"]")),this.options.compare&&(widget.options.value=widget.options.value==this.options.compare?"X":""),this.options.alternate_fields){for(var sum=0,fields=this.options.alternate_fields.split(":"),i=0;i<fields.length;i++){
var value="-"==fields[i][0]?-1*this.getArrayMgr("content").getEntry(fields[i].replace("-","")):this.getArrayMgr("content").getEntry(fields[i]);if(sum+=parseFloat(value),value&&"sum"!==this.options.field){widget.options.value=value;break}}"sum"==this.options.field&&(this.options.precision&&jQuery.isNumeric(sum)&&(sum=parseFloat(sum).toFixed(this.options.precision)),widget.options.value=sum)}}})}.call(this);et2_register_widget(et2_entry,["entry","contact-value","contact-account","contact-template","infolog-value","tracker-value","records-value"]);var et2_textbox=function(){"use strict";return et2_inputWidget.extend([et2_IResizeable],{attributes:{multiline:{name:"multiline",type:"boolean",default:!1,description:"If true, the textbox is a multiline edit field."},size:{name:"Size",type:"integer",default:et2_no_init,description:"Field width"},maxlength:{name:"Maximum length",type:"integer",default:et2_no_init,description:"Maximum number of characters allowed"},blur:{name:"Placeholder",type:"string",default:"",description:"This text get displayed if an input-field is empty and does not have the input-focus (blur). It can be used to show a default value or a kind of help-text."},rows:{name:"Rows",type:"integer",default:-1,description:"Multiline field height - better to use CSS"},cols:{name:"Size",type:"integer",default:-1,description:"Multiline field width - better to use CSS"},validator:{name:"Validator",type:"string",default:et2_no_init,description:"Perl regular expression eg. '/^[0-9][a-f]{4}$/i'"},autocomplete:{name:"Autocomplete",type:"string",default:"",description:"Weither or not browser should autocomplete that field: 'on', 'off', 'default' (use attribute from form). Default value for type password is set to off."},onkeypress:{name:"onKeypress",type:"js",default:et2_no_init,description:"JS code or app.$app.$method called when key is pressed, return false cancels it."}},legacyOptions:["size","maxlength","validator"],init:function(){this._super.apply(this,arguments),this.input=null,this.createInputWidget()},createInputWidget:function(){if(this.options.multiline||this.options.rows>1||this.options.cols>1)this.input=$j(document.createElement("textarea")),this.options.rows>0&&this.input.attr("rows",this.options.rows),this.options.cols>0&&this.input.attr("cols",this.options.cols);else{switch(this.input=$j(document.createElement("input")),this.options.type){case"passwd":this.input.attr("type","password"),""===this.options.autocomplete&&(this.options.autocomplete="off");break;case"hidden":this.input.attr("type","hidden")}this.options.autocomplete&&this.input.attr("autocomplete",this.options.autocomplete)}if(this.options.size&&this.set_size(this.options.size),this.options.blur&&this.set_blur(this.options.blur),this.options.readonly&&this.set_readonly(!0),this.input.addClass("et2_textbox"),this.setDOMNode(this.input[0]),this.options.value&&this.set_value(this.options.value),this.options.onkeypress&&"function"==typeof this.options.onkeypress){var self=this;this.input.keypress(function(_ev){return self.options.onkeypress.call(this,_ev,self)})}},set_id:function(_value){this._super.apply(this,arguments),"passwd"===this.options.type&&"off"===this.options.autocomplete&&this.input.removeAttr("name")},destroy:function(){var node=this.getInputNode();node&&$j(node).unbind("keypress"),this._super.apply(this,arguments)},getValue:function(){return this.options&&this.options.blur&&this.input.val()==this.options.blur?"":this._super.apply(this,arguments)},isValid:function(_messages){var ok=!0;if(this.options&&this.options.validator&&!this.options.readonly&&!this.disabled){if("string"==typeof this.options.validator){var parts=this.options.validator.split("/"),flags=parts.pop();if(parts.length<2||""!==parts[0])return _messages.push(this.egw().lang("'%1' has an invalid format !!!",this.options.validator)),!1;parts.shift(),this.options.validator=new RegExp(parts.join("/"),flags)}var value=this.getValue();(ok=this.options.validator.test(value))||_messages.push(this.egw().lang("'%1' has an invalid format !!!",value))}return this._super.apply(this,arguments)&&ok},set_size:function(_size){this.options.multiline||this.options.rows>1||this.options.cols>1?this.input.css("width",_size+"em"):"undefined"!=typeof _size&&_size!=this.input.attr("size")&&(this.size=_size,this.input.attr("size",this.size))},set_maxlength:function(_size){"undefined"!=typeof _size&&_size!=this.input.attr("maxlength")&&(this.maxLength=_size,this.input.attr("maxLength",this.maxLength))},set_readonly:function(_readonly){this.input.attr("readonly",_readonly)},set_blur:function(_value){_value?(this.input.attr("placeholder",this.egw().lang(_value)+""),this.input[0].placeholder||(""==this.input.val()&&this.input.val(this.egw().lang(this.options.blur)),this.input.focus(this,function(e){e.data.input.val()==e.data.egw().lang(e.data.options.blur)&&e.data.input.val("")}).blur(this,function(e){""==e.data.input.val()&&e.data.input.val(e.data.egw().lang(e.data.options.blur))}))):(this.getValue()||this.input.val(""),this.input.removeAttr("placeholder")),this.options.blur=_value},set_autocomplete:function(_value){this.options.autocomplete=_value,this.input.attr("autocomplete",_value)},resize:function(_height){_height&&this.options.multiline&&(_height=""!=this.options.resize_ratio?_height*this.options.resize_ratio:_height,0!=_height&&(this.input.height(this.input.height()+_height),this.input.parent().height(this.input.parent().height()+_height)))}})}.call(this);et2_register_widget(et2_textbox,["textbox","passwd","hidden"]);var et2_textbox_ro=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{multiline:{ignore:!0},maxlength:{ignore:!0},onchange:{ignore:!0},rows:{ignore:!0},cols:{ignore:!0},size:{ignore:!0},needed:{ignore:!0}},init:function(){this._super.apply(this,arguments),this.value="",this.span=$j(document.createElement("label")).addClass("et2_label"),this.value_span=$j(document.createElement("span")).addClass("et2_textbox_ro").appendTo(this.span),this.setDOMNode(this.span[0])},set_label:function(label){this.span.contents().filter(function(){return 3==this.nodeType}).remove();var parts=et2_csvSplit(label,2,"%s");this.span.prepend(parts[0]),this.span.append(parts[1]),this.label=label},set_value:function(_value){this.value=_value,_value||(_value=""),""!=this.label?this.span.removeClass("et2_label_empty"):this.span.addClass("et2_label_empty"),this.value_span.text(_value)},getDetachedAttributes:function(_attrs){_attrs.push("value","label")},getDetachedNodes:function(){return[this.span[0],this.value_span[0]]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),this.value_span=jQuery(_nodes[1]),"undefined"!=typeof _values.label&&this.set_label(_values.label),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_textbox_ro,["textbox_ro"]);var et2_searchbox=function(){"use strict";return et2_textbox.extend({attributes:{overlay:{name:"Overlay searchbox",type:"boolean",default:!1,description:"Define wheter the searchbox overlays while it's open (true) or stay as solid box infront of the search button (false). Default is false."},fix:{name:"Fix searchbox",type:"boolean",default:!0,description:"Define wheter the searchbox should be a fix input field or flexible search button. Default is true (fix)."}},init:function(){this.value="",this.div=jQuery(document.createElement("div")).addClass("et2_searchbox"),this.flex=jQuery(document.createElement("div")).addClass("flex").appendTo(this.div),this._super.apply(this,arguments),this.setDOMNode(this.div[0]),this._createWidget()},_createWidget:function(){var self=this;this.options.overlay&&this.flex.addClass("overlay"),this.options.fix||(this.button=et2_createWidget("button",{image:"search",background_image:"1"},this),this.button.onclick=function(){self._show_hide(jQuery(self.flex).hasClass("hide")),self.search.input.focus()},this.div.prepend(this.button.getDOMNode())),this.search=et2_createWidget("textbox",{blur:egw.lang("search"),onkeypress:function(event){13==event.which&&(event.preventDefault(),self.getInstanceManager().autocomplete_fixer(),window.setTimeout(function(){self.set_value(self.search.input.val()),self.change()},0))}},this),this.search.input.on({keyup:function(event){self.clear.toggle(""!=self.get_value()||!self.options.fix),27==event.which&&self.set_value("")},blur:function(event){event.relatedTarget&&jQuery(event.relatedTarget.parentNode).hasClass("et2_searchbox")||self._show_hide(!self.options.overlay&&self.get_value()),"undefined"!=typeof self.oldValue&&self._oldValue!=self.get_value()&&self.change()},mousedown:function(event){"span"==event.target.type&&event.stopImmidatePropagation()}}),this.flex.append(this.search.getDOMNode()),this.clear=jQuery(document.createElement("span")).addClass("ui-icon clear").toggle(!this.options.fix||""!=this._oldValue&&!jQuery.isEmptyObject(this._oldValue)).on("mousedown",function(event){event.preventDefault()}).on("click",function(event){self.get_value()?(self.search.input.val(""),self.search.input.focus(),self._show_hide(!0),self._oldValue&&self.change()):self._show_hide(!1),self.options.fix&&self.clear.hide()}).appendTo(this.flex)},_show_hide:function(_stat){this.options.fix||(jQuery(this.flex).toggleClass("hide",!_stat),jQuery(this.getDOMNode()).toggleClass("expanded",_stat))},_searchToggleState:function(){this.options.fix||(this.get_value()?(jQuery(this.button.getDOMNode()).addClass("toolbar_toggled"),this.button.set_statustext(egw.lang("search for '%1'",this.get_value()))):(jQuery(this.button.getDOMNode()).removeClass("toolbar_toggled"),this.button.set_statustext("")))},change:function(){this._searchToggleState(),this._super.apply(this,arguments)},get_value:function(){return this.search.input.val()},set_value:function(_value){this._super.apply(this,arguments),this.search&&this.search.input.val(_value)},doLoadingFinished:function(){this._super.apply(this,arguments),this.get_value()?(this._show_hide(!this.options.overlay),this._searchToggleState()):this._show_hide(!1)},attachToDOM:function(){this._super.apply(this,arguments);var node=this.getInputNode();node&&$j(node).off(".et2_inputWidget")}})}.call(this);et2_register_widget(et2_searchbox,["searchbox"]);var et2_number=function(){"use strict";return et2_textbox.extend({attributes:{value:{type:"float"},size:{default:5},min:{name:"Minimum",type:"integer",default:et2_no_init,description:"Minimum allowed value"},max:{name:"Maximum",type:"integer",default:et2_no_init,description:"Maximum allowed value"},precision:{name:"Precision",type:"integer",default:et2_no_init,description:"Allowed precision - # of decimal places",ignore:!0}},init:function(){this._super.apply(this,arguments)},transformAttributes:function(_attrs){this._super.apply(this,arguments),"undefined"==typeof _attrs.validator&&(_attrs.validator="float"==_attrs.type?"/^-?[0-9]*[,.]?[0-9]*$/":"/^-?[0-9]*$/")},isValid:function(_messages){var ok=!0;return this.input&&this.input[0]&&this.input[0].validationMessage&&!this.input[0].validity.stepMismatch&&(_messages.push(this.input[0].validationMessage),ok=!1),this._super.apply(this,arguments)&&ok},createInputWidget:function(){if(this.input=$j(document.createElement("input")),this.input.attr("type","number"),this.input.addClass("et2_textbox"),this.input.on("invalid",jQuery.proxy(this.change,this)),this.options.onkeypress&&"function"==typeof this.options.onkeypress){var self=this;this.input.keypress(function(_ev){return self.options.onkeypress.call(this,_ev,self)})}this.setDOMNode(this.input[0])},set_size:function(_size){"undefined"!=typeof _size&&_size!=this.input.attr("size")&&(this.size=_size,this.input.attr("size",this.size),"undefined"!=typeof this.options.class&&-1!=this.options.class.search("et2_fullWidth")||this.input.css("width",_size+"em"))},set_min:function(_value){this.min=_value,null==this.min?this.input.removeAttr("min"):this.input.attr("min",this.min)},set_max:function(_value){this.max=_value,null==this.max?this.input.removeAttr("max"):this.input.attr("max",this.max)}})}.call(this);et2_register_widget(et2_number,["int","integer","float"]);var et2_number_ro=function(){"use strict";return et2_textbox_ro.extend({attributes:{min:{ignore:!0},max:{ignore:!0},precision:{name:"Precision",type:"integer",default:et2_no_init,description:"Allowed precision - # of decimal places",ignore:!0},value:{type:"float"}},set_value:function(_value){"undefined"!=typeof this.options.precision&&""+_value!=""&&(_value=parseFloat(_value).toFixed(this.options.precision)),this._super.call(this,_value)}})}.call(this);et2_register_widget(et2_number_ro,["int_ro","integer_ro","float_ro"]),function($){var keyString="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",uTF8Encode=function(string){string=string.replace(/\x0d\x0a/g,"\n");for(var output="",n=0;n<string.length;n++){var c=string.charCodeAt(n);128>c?output+=String.fromCharCode(c):c>127&&2048>c?(output+=String.fromCharCode(c>>6|192),output+=String.fromCharCode(63&c|128)):(output+=String.fromCharCode(c>>12|224),output+=String.fromCharCode(c>>6&63|128),output+=String.fromCharCode(63&c|128))}return output},uTF8Decode=function(input){for(var string="",i=0,c=c1=c2=0;i<input.length;)c=input.charCodeAt(i),128>c?(string+=String.fromCharCode(c),i++):c>191&&224>c?(c2=input.charCodeAt(i+1),string+=String.fromCharCode((31&c)<<6|63&c2),i+=2):(c2=input.charCodeAt(i+1),c3=input.charCodeAt(i+2),string+=String.fromCharCode((15&c)<<12|(63&c2)<<6|63&c3),i+=3);return string};$.extend({base64Encode:function(input){var chr1,chr2,chr3,enc1,enc2,enc3,enc4,output="",i=0;for(input=uTF8Encode(input);i<input.length;)chr1=input.charCodeAt(i++),chr2=input.charCodeAt(i++),chr3=input.charCodeAt(i++),enc1=chr1>>2,enc2=(3&chr1)<<4|chr2>>4,enc3=(15&chr2)<<2|chr3>>6,enc4=63&chr3,isNaN(chr2)?enc3=enc4=64:isNaN(chr3)&&(enc4=64),output=output+keyString.charAt(enc1)+keyString.charAt(enc2)+keyString.charAt(enc3)+keyString.charAt(enc4);return output},base64Decode:function(input){var chr1,chr2,chr3,enc1,enc2,enc3,enc4,output="",i=0;for(input=input.replace(/[^A-Za-z0-9\+\/\=]/g,"");i<input.length;)enc1=keyString.indexOf(input.charAt(i++)),enc2=keyString.indexOf(input.charAt(i++)),enc3=keyString.indexOf(input.charAt(i++)),enc4=keyString.indexOf(input.charAt(i++)),chr1=enc1<<2|enc2>>4,chr2=(15&enc2)<<4|enc3>>2,chr3=(3&enc3)<<6|enc4,output+=String.fromCharCode(chr1),64!=enc3&&(output+=String.fromCharCode(chr2)),64!=enc4&&(output+=String.fromCharCode(chr3));return output=uTF8Decode(output)}})}(jQuery);var et2_url=function(){"use strict";return et2_textbox.extend({attributes:{multiline:{ignore:!0}},EMAIL_PREG:new RegExp(/^(([^\042',<][^,<]+|\042[^\042]+\042|\'[^\']+\'|)\s?<)?[^\x00-\x20()<>@,;:\042\[\]]+@([a-z0-9ÄÖÜäöüß](|[a-z0-9ÄÖÜäöüß_-]*[a-z0-9ÄÖÜäöüß])\.)+[a-z]{2,}>?$/i),createInputWidget:function(){this.input=$j(document.createElement("input")).blur(this,this.validate).blur(this,function(e){e.data.set_value(e.data.getValue())}),this._button=null,this.size&&this.set_size(this.size),this.setDOMNode(this.input[0])},destroy:function(){this.input&&this.input.unbind(),this._button=null,this._super.apply(this)},set_value:function(_value){this.update_button(_value),this._super.apply(this,arguments)},update_button:function(_value){if(this.value!=_value)if(_value)switch(null==this._button&&(this._button=$j(document.createElement("a")).addClass("et2_url"),this.getSurroundings().insertDOMNode(this._button[0]),this.getSurroundings().update()),this._button.removeClass("url phone email").removeAttr("href"),_value=this.get_link(this._type,_value),this._type){case"url":this._button.attr("href",_value).attr("target","_blank").addClass("url");break;case"url-phone":_value?"function"==typeof _value?this._button.click(this,_value).addClass("phone").show():this._button.attr("href",_value).addClass("phone").show():_value===!1&&this._button.hide();break;case"url-email":"function"==typeof _value?this._button.click(this,_value).addClass("email"):this._button.attr("href",_value).addClass("email")}else this._button&&this._button.hide(),this._button&&this.getSurroundings&&this.getSurroundings().removeDOMNode&&this.getSurroundings().removeDOMNode(this._button[0]),this._button=null},get_link:function(type,value){if(!value)return!1;switch(type){case"url":-1==value.indexOf("://")&&(value="http://"+value);break;case"url-phone":if(value=value.replace("&#9829;","").replace("(0)",""),value=value.replace(/[abc]/gi,2).replace(/[def]/gi,3).replace(/[ghi]/gi,4).replace(/[jkl]/gi,5).replace(/[mno]/gi,6),value=value.replace(/[pqrs]/gi,7).replace(/[tuv]/gi,8).replace(/[wxyz]/gi,9),value=value.replace(/[^0-9+]/g,""),-1===navigator.userAgent.indexOf("AppleWebKit")||-1===navigator.userAgent.indexOf("iPhone")&&-1===navigator.userAgent.indexOf("Android")||-1!=value.indexOf("tel:")){if(!this.egw().config("call_link"))return!1;var link=this.egw().config("call_link").replace("%1",encodeURIComponent(value)).replace("%u",this.egw().user("account_lid")).replace("%t",this.egw().user("account_phone")),popup=this.egw().config("call_popup");value=function(){egw.open_link(link,"phonecall",popup)}}else value="tel:"+value;break;case"url-email":if(-1==value.indexOf("mailto:")&&(value="mailto:"+value),(this.egw().user("apps").mail||this.egw().user("apps").felamimail)&&"1"!=this.egw().preference("force_mailto","addressbook"))return function(){egw.open_link(value)}}return value},validate:function(e){e.data.hideMessage(),e.data._super&&e.data._super.apply(this,arguments);var value=jQuery.trim(e.data.getValue());if(""!=value)switch(e.data._type){case"url":-1==value.indexOf("://")&&(e.data.set_value("http://"+value),e.data.showMessage(e.data.egw().lang("Protocol is required"),"hint",!0));break;case"url-email":(!e.data.EMAIL_PREG.test(value)||value.indexOf("<")>0&&value.indexOf(">")!=value.length-1||value.indexOf(">")>0&&value.indexOf("<")<0)&&e.data.showMessage("Invalid email","validation_error",!0)}},attachToDOM:function(){this._super.apply(this,arguments),this.input[0].parentNode&&jQuery(this.input[0].parentNode).addClass("et2_url_span")}})}.call(this);et2_register_widget(et2_url,["url","url-email","url-phone"]);var et2_url_ro=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{contact_plus:{name:"Add contact button",type:"boolean",default:!1,description:"Allow to add email as contact to addressbook"}},init:function(){this._super.apply(this,arguments),this.value="",this.span=$j(document.createElement("a")).addClass("et2_textbox readonly"),"url-email"==this._type&&this.span.addClass("et2_email"),this.setDOMNode(this.span[0])},set_value:function(_value){this.value=_value;var link=et2_url.prototype.get_link(this._type,_value);if(!link)return this.span.text(_value),void this.span.removeAttr("href");switch(this.span.text(_value),this._type){case"url":this.span.attr("href",link).attr("target","_blank");break;case"url-phone":"function"==typeof link?(this.span.off("click.et2_url"),this.span.on("click.et2_url",link),this.span.attr("href","#")):link&&this.span.attr("href",link);break;case"url-email":if("function"==typeof link?(this.span.off("click.et2_url"),this.span.on("click.et2_url",link),this.span.removeAttr("href")):(this.span.attr("href",link),this.span.attr("target")||this.span.attr("target","_blank")),this.span.text()&&this.span.text().split("<")){var val=this.span.text().split("<");val=""!=val[0]?val[0]:val[2],this.span.attr("title",_value),this.span.text(val.replace(/"/g,""))}if(this.options.contact_plus){if(!egw.app("addressbook"))return;this.span.on({mouseenter:function(event){event.stopImmediatePropagation();jQuery(this).tooltip({items:"a.et2_email",position:{my:"right top",at:"left top",collision:"flipfit"},tooltipClass:"et2_email_popup",content:function(){var extra={"presets[email]":jQuery(this).attr("title")};return jQuery('<a href="#" class= "et2_url_email_contactPlus" title="'+egw.lang("Add a new contact")+'"><img src="'+egw.image("new")+'"/></a>').on("click",function(){egw.open("","addressbook","add",extra)})},close:function(event,ui){ui.tooltip.hover(function(){jQuery(this).stop(!0).fadeTo(400,1)},function(){jQuery(this).fadeOut("400",function(){jQuery(this).remove()})})}}).tooltip("open")}})}}},getDetachedAttributes:function(_attrs){_attrs.push("value","class")},getDetachedNodes:function(){return[this.span[0]]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),"undefined"!=typeof _values.value&&this.set_value(_values.value),"undefined"!=typeof _values.class&&_nodes[0].setAttribute("class",_values.class)}})}.call(this);et2_register_widget(et2_url_ro,["url_ro","url-email_ro","url-phone_ro"]);var et2_selectbox=function(){"use strict";return et2_inputWidget.extend({attributes:{multiple:{name:"multiple",type:"boolean",default:!1,description:"Allow selecting multiple options"},expand_multiple_rows:{name:"Expand multiple",type:"integer",default:et2_no_init,description:"Shows single select widget, with a button. If the user clicks the button, the input will toggle to a multiselect,with this many rows. "},rows:{name:"Rows",type:"any",default:1,description:"Number of rows to display"},empty_label:{name:"Empty label",type:"string",default:"",description:"Textual label for first row, eg: 'All' or 'None'. ID will be ''",translate:!0},select_options:{type:"any",name:"Select options",default:{},description:"Internaly used to hold the select options."},selected_first:{name:"Selected options first",type:"boolean",default:!0,description:"For multi-selects, put the selected options at the top of the list when first loaded"},search:{name:"Search",type:"boolean",default:!1,description:"For single selects, add a search box to the drop-down list"},tags:{name:"Tag style",type:"boolean",default:!1,description:"For multi-selects, displays selected as a list of tags instead of a big list"},value:{type:"any"},other:{ignore:!0,type:"any"}},legacyOptions:["rows","other"],init:function(){this._super.apply(this,arguments),this.input=null,this.value="",this.supportedWidgetClasses=[],"string"==typeof this.options.rows&&(isNaN(this.options.rows)?(this.options.empty_label=this.egw().lang(this.options.rows),this.options.rows=1):this.options.rows=parseInt(this.options.rows)),this.options.rows>1?(this.options.multiple=!0,this.options.tags?this.createInputWidget():this.createMultiSelect()):this.createInputWidget()},destroy:function(){null!=this.input&&this.input.unchosen(),this.expand_button&&(this.expand_button.off(),this.expand_button.remove(),this.expand_button=null),this._super.apply(this,arguments),this.input=null},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),!(this.options&&this.options.select_options&&!jQuery.isEmptyObject(this.options.select_options)||_attrs.select_options&&!jQuery.isEmptyObject(_attrs.select_options)||"undefined"==typeof _attrs.select_options||null===_attrs.select_options)){var sel_options=et2_selectbox.find_select_options(this,_attrs.select_options,_attrs);jQuery.isEmptyObject(sel_options)||(_attrs.select_options=sel_options)}},set_multiple:function(_multiple,_size){this.options.multiple=_multiple,this.input&&(_multiple?(this.input.attr("size",_size||3),this.input.attr("multiple",!0),this.input.attr("name",this.id+"[]"),this.input[0].options.length&&""===this.input[0].options[0].value&&(this.input[0].options[0]=null)):(this.input.attr("multiple",!1),this.input.removeAttr("size"),this.input.attr("name",this.id),this.options.empty_label&&""!==this.input[0].options[0].value&&this._appendOptionElement("",this.options.empty_label)),this.expand_button&&(_multiple?this.expand_button.addClass("ui-icon-minus").removeClass("ui-icon-plus"):this.expand_button.removeClass("ui-icon-minus").addClass("ui-icon-plus")))},_appendOptionElement:function(_value,_label,_title,dom_element){if(""!=_value||null!=_label&&""!=_label){if(null==this.input)return this._appendMultiOption(_value,_label,_title,dom_element);var option=$j(document.createElement("option")).attr("value",_value).text(_label+"");"undefined"!=typeof _title&&_title&&option.attr("title",_title),_label==this.options.empty_label||""==this.options.empty_label&&""===_value?option.prependTo(this.input):option.appendTo(dom_element||this.input)}},_appendMultiOption:function(_value,_label,_title,dom_element){var option_data=null;if("object"==typeof _label&&(option_data=_label,_label=option_data.label),_label!=this.options.empty_label){var opt_id=this.dom_id+"_opt_"+_value,label=jQuery(document.createElement("label")).attr("for",opt_id).hover(function(){jQuery(this).addClass("ui-state-hover")},function(){jQuery(this).removeClass("ui-state-hover")}),option=jQuery(document.createElement("input")).attr("type","checkbox").attr("id",opt_id).attr("value",_value).appendTo(label);if("undefined"!=typeof _title&&option.attr("title",_title),option_data){if(option_data.icon){var img=this.egw().image(option_data.icon);jQuery(document.createElement(img?"img":"div")).attr("src",img).addClass("cat_icon cat_"+_value).appendTo(label)}option_data.color&&label.css("background-color",option_data.color).addClass("cat_"+_value)}label.append(jQuery("<span>"+_label+"</span>"));var li=jQuery(document.createElement("li")).append(label);li.appendTo(dom_element||this.multiOptions)}},createInputWidget:function(){this.input=$j(document.createElement("select")).addClass("et2_selectbox").attr("size",this.options.rows),this.setDOMNode(this.input[0]),this.options.empty_label&&this._appendOptionElement("",this.options.empty_label),this.options.multiple&&this.input.attr("multiple","multiple")},createMultiSelect:function(){var node=jQuery(document.createElement("div")).addClass("et2_selectbox"),header=jQuery(document.createElement("div")).addClass("ui-widget-header ui-helper-clearfix").appendTo(node),controls=jQuery(document.createElement("ul")).addClass("ui-helper-reset").appendTo(header);this.options.empty_label&&jQuery(document.createElement("span")).text(this.options.empty_label).addClass("ui-multiselect-header").appendTo(header);var options=this.multiOptions=jQuery(document.createElement("ul"));if(this.multiOptions.addClass("ui-multiselect-checkboxes ui-helper-reset").css("height",1.9*this.options.rows+"em").appendTo(node),this.options.rows>=5){var header_controls={check:{icon_class:"ui-icon-check",label:"Check all",click:function(e){var all_set=jQuery("input[type='checkbox']",e.data).prop("checked");jQuery("input[type='checkbox']",e.data).prop("checked",!all_set)}}};for(var key in header_controls)jQuery(document.createElement("li")).addClass("et2_clickable").click(options,header_controls[key].click).attr("title",header_controls[key].label).append('<span class="ui-icon '+header_controls[key].icon_class+'"/>').appendTo(controls)}this.setDOMNode(node[0])},doLoadingFinished:function(){return this._super.apply(this,arguments),this.set_tags(this.options.tags,this.options.width),!0},loadFromXML:function(_node){var legacy=_node.getAttribute("options");if(legacy){var legacy=legacy.split(",");legacy.length&&isNaN(legacy[0])&&(this.options.empty_label=legacy[0])}for(var options=et2_directChildrenByTagName(_node,"options"),i=0;i<options.length;i++)this.options.select_options[et2_readAttrWithDefault(options[i],"value",options[i].textContent)]={label:options[i].textContent,title:et2_readAttrWithDefault(options[i],"title","")};this.set_select_options(this.options.select_options)},_is_multiple_regexp:/^[,0-9A-Za-z\/_-]+$/,set_value:function(_value){if("number"==typeof _value&&(_value=""+_value),"string"==typeof _value&&(this.options.multiple||this.options.expand_multiple_rows)&&null!==_value.match(this._is_multiple_regexp)&&(_value=_value.split(",")),null!==this.input&&this.options.select_options&&(!jQuery.isEmptyObject(this.options.select_options)||this.options.select_options.length>0)&&0==this.input.children().length&&this.set_select_options(this.options.select_options),this._oldValue=this.value,null!==this.input&&(this.options.tags||this.options.search))return this.input.val("object"==typeof _value&&null!=_value?jQuery.map(_value,function(value,index){return[value]}):_value),this.input.trigger("liszt:updated"),void(this.value=this.input.val());if(null==this.input)return this.set_multi_value(_value);if(this.options.expand_multiple_rows&&!this.options.multiple&&jQuery.isArray(_value)&&_value.length>1&&this.set_multiple(!0,this.options.expand_multiple_rows),jQuery("option",this.input).prop("selected",!1),"array"==typeof _value)for(var i=0;i<_value.length;i++)jQuery("option[value='"+_value[i]+"']",this.input).prop("selected",!0);else if("object"==typeof _value)for(var i in _value)jQuery("option[value='"+_value[i]+"']",this.input).prop("selected",!0);else if(_value&&0==jQuery("option[value='"+_value+"']",this.input).prop("selected",!0).length){if(this.options.select_options[_value]||this.options.select_options.filter&&this.options.select_options.filter(function(value){return value==_value}))return this.set_select_options(this.options.select_options);if(jQuery.isEmptyObject(this.options.select_options))this.egw().debug("warn","Can't set value to '%s', widget has no options set",_value,this);else{var debug_value=_value;this.egw().debug("warn","Tried to set value '%s' that isn't an option",debug_value,this)}return}this.value=_value,this.isAttached()&&this._oldValue!==et2_no_init&&this._oldValue!==_value&&this.input.change()},set_multi_value:function(_value){if(jQuery("input",this.multiOptions).prop("checked",!1),"array"==typeof _value)for(var i=0;i<_value.length;i++)jQuery("input[value='"+_value[i]+"']",this.multiOptions).prop("checked",!0);else if("object"==typeof _value)for(var i in _value)jQuery("input[value='"+_value[i]+"']",this.multiOptions).prop("checked",!0);else if(0==jQuery("input[value='"+_value+"']",this.multiOptions).prop("checked",!0).length){var debug_value=_value;this.egw().debug("warn","Tried to set value '%s' that isn't an option",debug_value,this)}this.selected_first&&this.multiOptions.find("li:has(input:checked)").prependTo(this.multiOptions),this.value=_value},set_expand_multiple_rows:function(_rows){this.options.expand_multiple_rows=_rows;var surroundings=this.getSurroundings();if(1>=_rows&&this.expand_button)surroundings.removeDOMNode(this.expand_button.get(0));else{if(!this.expand_button){var button_id=this.getInstanceManager().uniqueId+"_"+this.id.replace(/\./g,"-")+"_expand";this.expand_button=$j("<button class='et2_button et2_button_icon et2_selectbox_expand ui-icon' id='"+button_id+"'/>").addClass(this.options.multiple?"ui-icon-minus":"ui-icon-plus").on("click",jQuery.proxy(function(e){"undefined"!=typeof this.input.attr("size")&&1!=this.input.attr("size")?(this.set_multiple(!1,1),this.expand_button.removeClass("ui-icon-minus").addClass("ui-icon-plus")):(this.set_multiple(!0,this.options.expand_multiple_rows),this.expand_button.addClass("ui-icon-minus").removeClass("ui-icon-plus"))},this))}surroundings.appendDOMNode(this.expand_button.get(0))}surroundings.update()},set_tags:function(_tags,_width){if(this.options.tags=_tags,this.isAttached()){if(null!=this.input&&!this.options.tags&&!this.options.search)return void this.input.unchosen().css("width","");if(null!=this.input&&(this.options.search||this.options.tags)&&!this.options.disabled){if(this.options.empty_label&&(this.input.attr("data-placeholder",this.options.empty_label),this.options.multiple&&this.input.children('[value=""]').remove()),this.input.hasClass("chzn-done"))return;var size=egw.getHiddenDimensions(this.input);this.input.chosen({inherit_select_classes:!0,search_contains:!0,width:_width||size.w+"px"}).change(this.onchange)}}},set_select_options:function(_options){this.input?this.input.empty():this.multiOptions&&this.multiOptions.empty(),!this.options.empty_label||this.options.tags||this.options.search||this._appendOptionElement("",this.egw().lang(this.options.empty_label));for(var key in _options)if(this.options.no_lang||("object"==typeof _options[key]&&null!==_options[key]?(_options[key].label&&(_options[key].label=this.egw().lang(_options[key].label)),
_options[key].title&&(_options[key].title=this.egw().lang(_options[key].title))):_options[key]=this.egw().lang(_options[key])),"object"==typeof _options[key]&&null!==_options[key])if("undefined"==typeof _options[key].label&&"undefined"==typeof _options[key].title){var group=$j(document.createElement("optgroup")).attr("label",this.options.no_lang?key:this.egw().lang(key)).appendTo(this.input);null==this.input&&(group=jQuery(document.createElement("ul")).append('<li class="ui-widget-header"><span>'+key+"</span></li>").appendTo(this.multiOptions));for(var sub in _options[key])"object"==typeof _options[key][sub]&&null!==_options[key][sub]?this._appendOptionElement(sub,_options[key][sub].label?_options[key][sub].label:"",_options[key][sub].title?_options[key][sub].title:"",group):this._appendOptionElement(sub,_options[key][sub],void 0,group)}else null==this.input?(_options[key].label=_options[key].label?_options[key].label:"",this._appendMultiOption("undefined"!=typeof _options[key].value?_options[key].value:key,_options[key],_options[key].title)):this._appendOptionElement("undefined"!=typeof _options[key].value?_options[key].value:key,_options[key].label?_options[key].label:"",_options[key].title?_options[key].title:"");else this._appendOptionElement(key,_options[key]);(this.value||this.options.empty_label)&&this.set_value(this.value)},getValue:function(){if(null==this.input){var value=[];jQuery("input:checked",this.multiOptions).each(function(){value.push(this.value)}),this.value=value}else this.value=this._super.apply(this,arguments),null===this.value&&(this.value=[]);return this.value},isDirty:function(){if(null==this.input){var value=this.getValue();return!(0==$j(this._oldValue).not(value).length&&0==$j(value).not(this._oldValue).length)}return this._super.apply(this,arguments)}})}.call(this);et2_register_widget(et2_selectbox,["menupopup","listbox","select","select-cat","select-percent","select-priority","select-country","select-state","select-year","select-month","select-day","select-dow","select-hour","select-number","select-app","select-lang","select-bool","select-timezone"]),jQuery.extend(et2_selectbox,{type_cache:{},find_select_options:function(widget,attr_options,attrs){var name_parts=widget.id.replace(/&#x5B;/g,"[").replace(/]|&#x5D;/g,"").split("["),type_options={},content_options={},type=widget.instanceOf(et2_nextmatch_filterheader)?attrs.widget_type||"":widget._type,type_function=type.replace("select-","").replace("_ro","")+"_options";if("function"==typeof this[type_function]){var old_type=widget._type;widget._type=type,"string"==typeof attrs.other&&(attrs.other=attrs.other.split(",")),type_options=this[type_function].call(this,widget,attrs);try{type_options=JSON.parse(JSON.stringify(type_options))}catch(e){egw.debug(e)}widget._type=old_type}if(widget.getArrayMgr("sel_options")){if(content_options=widget.getArrayMgr("sel_options").getEntry(widget.id),content_options&&1==content_options.length&&"string"==typeof content_options[0]&&""==content_options[0].trim()&&(content_options=null),content_options&&!isNaN(name_parts[name_parts.length-1])&&content_options.label&&content_options.title&&(name_parts.pop(),content_options=widget.getArrayMgr("sel_options").getEntry(name_parts.join("[")),delete content_options.$row),content_options&&0!=content_options.length||(content_options=widget.getArrayMgr("sel_options").getRoot().getEntry(name_parts[name_parts.length-1])),content_options&&0!=content_options.length||(content_options=widget.getArrayMgr("sel_options").getEntry(name_parts[name_parts.length-1])),name_parts.length>1&&(!content_options||0==content_options.length))for(var pop_that=jQuery.extend([],name_parts);pop_that.length>0&&(!content_options||0==content_options.length);){var last=pop_that.pop();content_options=widget.getArrayMgr("sel_options").getEntry(pop_that.join("[")),content_options&&"undefined"!=typeof content_options[last]&&content_options[last]&&(content_options=content_options[last])}for(var row_stuck=["${row}","{$row}"],i=0;i<row_stuck.length&&(!content_options||0==content_options.length);i++)if(widget.getArrayMgr("sel_options").perspectiveData.row||widget.getArrayMgr("sel_options").data[row_stuck[i]]){var row_id=widget.id.replace(/[0-9]+/,row_stuck[i]);content_options=widget.getArrayMgr("sel_options").getEntry(row_id),content_options&&0!=content_options.length||(content_options=widget.getArrayMgr("sel_options").getEntry(row_stuck[i]+"["+widget.id+"]"))}attr_options&&!jQuery.isEmptyObject(attr_options)&&content_options&&(content_options=jQuery.extend(!0,{},attr_options,content_options))}if(jQuery.isEmptyObject(content_options)&&null!=widget.getArrayMgr("content")){content_options&&(attr_options=content_options);var content_mgr=widget.getArrayMgr("content");content_mgr&&(content_options||(content_options=content_mgr.getEntry("options-"+widget.id)),content_options||(content_options=content_mgr.getRoot().getEntry("options-"+name_parts[name_parts.length-1])))}if(null==content_options&&(content_options={}),type_options.length||!jQuery.isEmptyObject(type_options)){for(var i in content_options){var value="object"==typeof content_options[i]&&"undefined"!=typeof content_options[i].value?content_options[i].value:i,added=!1;for(var j in type_options)if(""+type_options[j].value==""+value){added=!0,type_options[j]=content_options[i];break}added||type_options.splice(i,0,content_options[i])}content_options=type_options}return content_options},priority_options:function(widget){return[{value:1,label:"low"},{value:2,label:"normal"},{value:3,label:"high"},{value:0,label:"undefined"}]},bool_options:function(widget){return[{value:0,label:"no"},{value:1,label:"yes"}]},month_options:function(widget){return[{value:1,label:"January"},{value:2,label:"February"},{value:3,label:"March"},{value:4,label:"April"},{value:5,label:"May"},{value:6,label:"June"},{value:7,label:"July"},{value:8,label:"August"},{value:9,label:"September"},{value:10,label:"October"},{value:11,label:"November"},{value:12,label:"December"}]},number_options:function(widget,attrs){"object"!=typeof attrs.other&&(attrs.other=[]);var options=[],min="undefined"==typeof attrs.other[0]?1:parseInt(attrs.other[0]),max="undefined"==typeof attrs.other[1]?10:parseInt(attrs.other[1]),interval="undefined"==typeof attrs.other[2]?1:parseInt(attrs.other[2]),format="%d";attrs.other[2]&&"0"==attrs.other[2][0]&&(format="%0"+(""+interval).length+"d"),attrs.other[3]&&(format+=widget.egw().lang(attrs.other[3])),max>=min!=interval>0&&(interval=-interval);for(var i=0,n=min;max>=n&&100>=i;n+=interval,++i)options.push({value:n,label:sprintf(format,n)});return options},percent_options:function(widget,attrs){return"object"!=typeof attrs.other&&(attrs.other=[]),attrs.other[0]=0,attrs.other[1]=100,attrs.other[2]="undefined"==typeof attrs.other[2]?10:parseInt(attrs.other[2]),attrs.other[3]="%%",this.number_options(widget,attrs)},year_options:function(widget,attrs){"object"!=typeof attrs.other&&(attrs.other=[]);var t=new Date;return attrs.other[0]=t.getFullYear()-("undefined"==typeof attrs.other[0]?3:parseInt(attrs.other[0])),attrs.other[1]=t.getFullYear()+("undefined"==typeof attrs.other[1]?2:parseInt(attrs.other[1])),attrs.other[2]="undefined"==typeof attrs.other[2]?1:parseInt(attrs.other[2]),this.number_options(widget,attrs)},day_options:function(widget,attrs){return attrs.other=[1,31,1],this.number_options(widget,attrs)},hour_options:function(widget,attrs){for(var options=[],timeformat=egw.preference("common","timeformat"),h=0;23>=h;++h)options.push({value:h,label:12==timeformat?h%12+" "+(12>h?egw.lang("am"):egw.lang("pm")):sprintf("%02d",h)});return options},app_options:function(widget,attrs){var options=","+(attrs.other||[]).join(",");return this.cached_server_side_options(widget,options,attrs)},cat_options:function(widget,attrs){"undefined"==typeof attrs.other&&(attrs.other=new Array(4)),"undefined"==typeof attrs.other[3]&&(attrs.other[3]=attrs.application||widget.getInstanceManager().app);var options=(attrs.other||[]).join(",");return this.cached_server_side_options(widget,options,attrs)},country_options:function(widget,attrs){var options=",";return this.cached_server_side_options(widget,options,attrs)},dow_options:function(widget,attrs){var options=","+(attrs.other||[]).join(",");return this.cached_server_side_options(widget,options,attrs)},lang_options:function(widget,attrs){var options=","+(attrs.other||[]).join(",");return this.cached_server_side_options(widget,options,attrs)},timezone_options:function(widget,attrs){var options=","+(attrs.other||[]).join(",");return this.cached_server_side_options(widget,options,attrs)},cached_server_side_options:function(widget,options_string,attrs){options_string=options_string.replace(/,+$/,"");var cache_id=widget._type+"_"+options_string,cache=egw.window.et2_selectbox.type_cache[cache_id];if("undefined"==typeof cache&&(egw.window.et2_selectbox.type_cache[cache_id]=egw.json(widget.getInstanceManager().app+".etemplate_widget_menupopup.ajax_get_options.etemplate",[widget._type,options_string,attrs.value]).sendRequest(!0)),cache=egw.window.et2_selectbox.type_cache[cache_id],"function"==typeof cache.done)return cache.done(jQuery.proxy(function(response){egw.window.et2_selectbox.type_cache[this.cache_id]=response.response[0].data||void 0,attrs.select_options=egw.window.et2_selectbox.type_cache[this.cache_id],egw.window.setTimeout(jQuery.proxy(function(){this.widget&&"undefined"!=typeof this.widget.id&&this.widget.set_select_options(et2_selectbox.find_select_options(this.widget,{},this.widget.options))},this),1)},{widget:widget,cache_id:cache_id})),[];if(attrs.value&&""!=attrs.value&&"0"!=attrs.value&&"select-timezone"==attrs.type){for(var missing_option=!0,i=0;i<cache.length&&missing_option;i++)cache[i].value==attrs.value&&(missing_option=!1);if(missing_option)return delete egw.window.et2_selectbox.type_cache[cache_id],this.cached_server_side_options(widget,options_string,attrs)}return cache}});var et2_selectbox_ro=function(){"use strict";return et2_selectbox.extend([et2_IDetachedDOM],{init:function(){this._super.apply(this,arguments),this.supportedWidgetClasses=[],this.optionValues={},this.options.select_options&&this.set_select_options(this.options.select_options)},createInputWidget:function(){this.span=$j(document.createElement("span")).addClass("et2_selectbox readonly").text(this.options.empty_label),this.setDOMNode(this.span[0])},createMultiSelect:function(){this.span=$j(document.createElement("ul")).addClass("et2_selectbox readonly"),this.setDOMNode(this.span[0])},loadFromXML:function(_node){for(var options=et2_directChildrenByTagName(_node,"options"),i=0;i<options.length;i++)this.optionValues[et2_readAttrWithDefault(options[i],"value",0)]={label:options[i].textContent,title:et2_readAttrWithDefault(options[i],"title","")}},set_select_options:function(_options){for(var key in _options)this.options.no_lang||("object"==typeof _options[key]&&null!=_options[key]?(_options[key].label&&(_options[key].label=this.egw().lang(_options[key].label)),_options[key].title&&(_options[key].title=this.egw().lang(_options[key].title))):_options[key]=this.egw().lang(_options[key]));this.optionValues=_options},set_value:function(_value){if(this.value=_value,"string"==typeof _value?_value=null!==_value.match(this._is_multiple_regexp)?_value.split(","):[_value]:"number"==typeof _value&&(_value=[_value]),this.span.empty(),_value)for(var i=0;i<_value.length;i++)for(var o in this.optionValues){var option=this.optionValues[o],key="object"==typeof option&&null!=option&&"undefined"!=typeof option.value?option.value:o;if(key==_value[i]){var label="object"==typeof option?option.label:option;if(1==_value.length){this.span.text(label),"object"==typeof option&&option.title&&this.set_statustext(option.title);break}$j("<li>").text(label).attr("data-value",_value[i]).appendTo(this.span);break}}else this.options.empty_label&&this.span.text(this.options.empty_label)},getValue:function(){return null},getDetachedAttributes:function(_attrs){_attrs.push("value")},getDetachedNodes:function(){return[this.span[0]]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_selectbox_ro,["menupopup_ro","listbox_ro","select_ro","select-cat_ro","select-percent_ro","select-priority_ro","select-access_ro","select-country_ro","select-state_ro","select-year_ro","select-month_ro","select-day_ro","select-dow_ro","select-hour_ro","select-number_ro","select-app_ro","select-lang_ro","select-bool_ro","select-timezone_ro"]);var et2_menulist=function(){"use strict";return et2_DOMWidget.extend({init:function(){this._super.apply(this,arguments),this.supportedWidgetClasses=[et2_selectbox,et2_selectbox_ro]},getDOMNode:function(_sender){return _sender!=this?this._parent.getDOMNode(this):null},getChildren:function(){return this._parent.getChildren()}})}.call(this);et2_register_widget(et2_menulist,["menulist"]);var et2_checkbox=function(){"use strict";return et2_inputWidget.extend({attributes:{selected_value:{name:"Set value",type:"string",default:"true",description:"Value when checked"},unselected_value:{name:"Unset value",type:"string",default:"",description:"Value when not checked"},ro_true:{name:"Read only selected",type:"string",default:"X ",description:"What should be displayed when readonly and selected"},ro_false:{name:"Read only unselected",type:"string",default:"",description:"What should be displayed when readonly and not selected"},value:{type:"any"},toggle_on:{name:"Toggle on caption",type:"string",default:"",description:"String caption to show for ON status"},toggle_off:{name:"Toggle off caption",type:"string",default:"",description:"String caption to show OFF status"}},legacyOptions:["selected_value","unselected_value","ro_true","ro_false"],init:function(){this._super.apply(this,arguments),this.input=null,this.createInputWidget()},createInputWidget:function(){if(this.input=$j(document.createElement("input")).attr("type","checkbox"),this.input.addClass("et2_checkbox"),this.options.toggle_on||this.options.toggle_off){var self=this;this.toggle=$j(document.createElement("span")).addClass("et2_checkbox_slideSwitch").append(this.input),this.input.change(function(){return self.getValue(),!0});var area=jQuery(document.createElement("span")).addClass("slideSwitch_container").appendTo(this.toggle),on=jQuery(document.createElement("span")).addClass("on").appendTo(area),off=jQuery(document.createElement("span")).addClass("off").appendTo(area);on.text(this.options.toggle_on),off.text(this.options.toggle_off);jQuery(document.createElement("a")).appendTo(area);this.setDOMNode(this.toggle[0])}else this.setDOMNode(this.input[0])},set_label:function(label){label.length&&label.indexOf("%s")<0&&(label="%s"+label),this._super.apply(this,[label]),jQuery(this.getSurroundings()._widgetSurroundings).addClass("et2_checkbox_label")},set_value:function(_value){_value!=this.value&&(_value==this.options.selected_value||_value&&this.options.selected_value==this.attributes.selected_value.default&&_value!=this.options.unselected_value?((this.options.toggle_on||this.options.toggle_off)&&this.toggle.addClass("switchOn"),this.input.prop("checked",!0)):(this.input.prop("checked",!1),(this.options.toggle_on||this.options.toggle_off)&&this.toggle.removeClass("switchOn")))},set_readonly:function(_ro){jQuery(this.getDOMNode()).attr("disabled",_ro)},getValue:function(){return this.input.prop("checked")?((this.options.toggle_on||this.options.toggle_off)&&this.toggle.addClass("switchOn"),this.options.selected_value):((this.options.toggle_on||this.options.toggle_off)&&this.toggle.removeClass("switchOn"),this.options.unselected_value)}})}.call(this);et2_register_widget(et2_checkbox,["checkbox"]);var et2_checkbox_ro=function(){"use strict";return et2_checkbox.extend({attributes:{unselected_value:{ignore:!0}},init:function(){this._super.apply(this,arguments),this.value="",this.span=$j(document.createElement("span")).addClass("et2_checkbox_ro"),this.setDOMNode(this.span[0])},set_value:function(_value){_value==this.options.selected_value||_value&&this.options.selected_value==this.attributes.selected_value.default&&_value!=this.options.unselected_value?(this.span.text(this.options.ro_true),this.value=_value):this.span.text(this.options.ro_false)}})}.call(this);et2_register_widget(et2_checkbox_ro,["checkbox_ro"]);var et2_radiobox=function(){"use strict";return et2_inputWidget.extend({attributes:{set_value:{name:"Set value",type:"string",default:"true",description:"Value when selected"},ro_true:{name:"Read only selected",type:"string",default:"x",description:"What should be displayed when readonly and selected"},ro_false:{name:"Read only unselected",type:"string",default:"",description:"What should be displayed when readonly and not selected"}},legacyOptions:["set_value","ro_true","ro_false"],init:function(){this._super.apply(this,arguments),this.input=null,this.id="",this.createInputWidget()},createInputWidget:function(){this.input=$j(document.createElement("input")).val(this.options.set_value).attr("type","radio"),this.input.addClass("et2_radiobox"),this.setDOMNode(this.input[0])},set_id:function(_id){this._super.apply(this,arguments),this.dom_id=this.dom_id.replace("[]","")+"-"+this.options.set_value,this.input&&this.input.attr("id",this.dom_id)},set_label:function(_label){_label.length>0&&-1==_label.indexOf("%s")&&(_label="%s"+_label),this._super.apply(this,[_label])},set_value:function(_value){this.getRoot().iterateOver(function(radio){radio.id==this.id&&radio.input.prop("checked",_value==radio.options.set_value)},this,et2_radiobox)},getValue:function(){var val=this.options.value;return this.getRoot().iterateOver(function(radio){radio.id==this.id&&radio.input&&radio.input.prop("checked")&&(val=radio.options.set_value)},this,et2_radiobox),val==this.options.set_value?this.options.set_value:null},isValid:function(messages){var ok=!0;return!this.options||!this.options.needed||this.options.readonly||this.disabled||null!=this.getValue()&&""!=this.getValue().valueOf()||jQuery.isEmptyObject(this.getInstanceManager().getValues(this.getInstanceManager().widgetContainer)[this.id.replace("[]","")])&&(messages.push(this.egw().lang("Field must not be empty !!!")),ok=!1),ok}})}.call(this);et2_register_widget(et2_radiobox,["radio"]);var et2_radiobox_ro=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{set_value:{name:"Set value",type:"string",default:"true",description:"Value when selected"},ro_true:{name:"Read only selected",type:"string",default:"x",description:"What should be displayed when readonly and selected"},ro_false:{name:"Read only unselected",type:"string",default:"",description:"What should be displayed when readonly and not selected"},label:{name:"Label",default:"",type:"string"}},legacyOptions:["set_value","ro_true","ro_false"],init:function(){this._super.apply(this,arguments),this.value="",this.span=$j(document.createElement("span")).addClass("et2_radiobox"),this.setDOMNode(this.span[0])},set_value:function(_value){this.value=_value,_value==this.options.set_value?this.span.text(this.options.ro_true):this.span.text(this.options.ro_false)},set_label:function(_label){},getDetachedAttributes:function(_attrs){this.options.ro_true=this.options.label,_attrs.push("value")},getDetachedNodes:function(){return[this.span[0]]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_radiobox_ro,["radio_ro"]);var et2_radioGroup=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{label:{name:"Label",default:"",type:"string",description:"The label is displayed above the list of radio buttons. The label can contain variables, as descript for name. If the label starts with a '@' it is replaced by the value of the content-array at this index (with the '@'-removed and after expanding the variables).",translate:!0},value:{name:"Value",type:"string",default:"true",description:"Value for each radio button"},ro_true:{name:"Read only selected",type:"string",default:"x",description:"What should be displayed when readonly and selected"},ro_false:{name:"Read only unselected",type:"string",default:"",description:"What should be displayed when readonly and not selected"},options:{name:"Radio options",type:"any",default:{},description:"Options for radio buttons. Should be {value: label, ...}"},needed:{name:"Required",default:!1,type:"boolean",description:"If required, the user must select one of the options before the form can be submitted"}},createNamespace:!1,init:function(parent,attrs){this._super.apply(this,arguments),this.node=$j(document.createElement("div")).addClass("et2_vbox").addClass("et2_box_widget"),this.options.needed&&this.node.attr("required","required"),this.setDOMNode(this.node[0]),this.supportedWidgetClasses=[et2_radiobox,et2_radiobox_ro]},set_value:function(_value){this.value=_value;for(var i=0;i<this._children.length;i++){var radio=this._children[i];radio.set_value(_value)}},getValue:function(){return jQuery("input:checked",this.getDOMNode()).val()},set_options:function(_options){for(var i=this._children.length-1;i>=0;i--)this._children[i].free();this._children=[];for(var key in _options){var attrs={id:this.options.readonly?this.id:this.id+"[]",set_value:key,label:_options[key],ro_true:this.options.ro_true,ro_false:this.options.ro_false,readonly:this.options.readonly};attrs.readonly===!1&&(attrs.needed=this.options.needed);et2_createWidget("radio",attrs,this)}this.set_value(this.value)},set_label:function(_value){if(_value!=this.label)if(_value){null==this._labelContainer&&(this._labelContainer=$j(document.createElement("label")),this.getSurroundings().insertDOMNode(this._labelContainer[0])),this._labelContainer.empty();var ph=document.createElement("span");this.getSurroundings().setWidgetPlaceholder(ph),this._labelContainer.append(document.createTextNode(_value)).append(ph)}else this._labelContainer&&this.getSurroundings().removeDOMNode(this._labelContainer[0]),this._labelContainer=null},getDetachedAttributes:function(_attrs){},getDetachedNodes:function(){return[this.getDOMNode()]},setDetachedAttributes:function(_nodes,_values){}})}.call(this);et2_register_widget(et2_radioGroup,["radiogroup"]);var et2_date=function(){"use strict";return et2_inputWidget.extend({attributes:{value:{type:"any"},type:{ignore:!1},blur:{name:"Placeholder",type:"string",default:"",description:"This text get displayed if an input-field is empty and does not have the input-focus (blur). It can be used to show a default value or a kind of help-text."},data_format:{ignore:!0,description:"Date/Time format. Can be set as an options to date widget",default:""},year_range:{name:"Year range",type:"string",default:"c-10:c+10",description:'The range of years displayed in the year drop-down: either relative to today\'s year ("-nn:+nn"), relative to the currently selected year ("c-nn:c+nn"), absolute ("nnnn:nnnn"), or combinations of these formats ("nnnn:-nn"). Note that this option only affects what appears in the drop-down, to restrict which dates may be selected use the min and/or max options.'},min:{name:"Minimum",type:"any",default:et2_no_init,description:'Minimum allowed date. Multiple types supported:Date: A date object containing the minimum date.Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.String: A string in the user\'s date format, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.'},max:{name:"Maximum",type:"any",default:et2_no_init,description:'Maximum allowed date. Multiple types supported:Date: A date object containing the maximum date.Number: A number of days from today. For example 2 represents two days from today and -1 represents yesterday.String: A string in the user\'s date format, or a relative date. Relative dates must contain value and period pairs; valid periods are "y" for years, "m" for months, "w" for weeks, and "d" for days. For example, "+1m +7d" represents one month and seven days from today.'},inline:{name:"Inline",type:"boolean",default:!1,description:"Instead of an input field with a popup calendar, the calendar is displayed inline, with no input field"}},legacyOptions:["data_format"],init:function(){this._super.apply(this,arguments),this.date=new Date,this.date.setUTCHours(0),this.date.setMinutes(0),this.date.setSeconds(0),this.input=null,this.createInputWidget()},createInputWidget:function(){if(this.span=$j(document.createElement(this.options.inline?"div":"span")).addClass("et2_date"),this.input_date=$j(document.createElement(this.options.inline?"div":"input")),this.options.blur&&this.input_date.attr("placeholder",this.egw().lang(this.options.blur)),this.input_date.addClass("et2_date").attr("type","text").attr("size",7).appendTo(this.span),this.setDOMNode(this.span[0]),this.is_mobile=egwIsMobile()&&!this.options.inline,this.is_mobile)switch(this.dateFormat="yy-mm-dd",this.timeFormat="HH:mm",this._type){case"date":this.input_date.attr("type","date");break;case"date-time":this.input_date.attr("type","datetime-local");break;case"date-timeonly":this.input_date.addClass("et2_time"),this.input_date.attr("type","time")}else this.dateFormat=this.egw().dateTimeFormat(this.egw().preference("dateformat")),this.timeFormat=12==this.egw().preference("timeformat")?"h:mmtt":"HH:mm","date-timeonly"!=this._type?this.egw().calendar(this.input_date,"date-time"==this._type):(this.input_date.addClass("et2_time"),this.egw().time(this.input_date)),this.input_date.datepicker("option","beforeShow",function(input,inst){var cal=inst.dpDiv;setTimeout(function(){var $input=jQuery(input),inputOffset=$input.offset();cal.height()+inputOffset.top>window.innerHeight&&cal.position({my:"left center",at:"right bottom",collision:"flip fit",of:input})},0)});var self=this;this.input_date.bind("change",function(e){return self.set_value(this.value),!1}),null==this.options.value&&this.set_value(null)},set_type:function(_type){_type!=this._type&&(this._type=_type,this.createInputWidget())},set_readonly:function(_ro){this.input_date&&!this.input_date.attr("disabled")!=!_ro&&this.input_date.attr("disabled",!!_ro).datepicker("option","disabled",!!_ro)},set_year:function(_value){this.date.setUTCFullYear(_value),this.set_value(this.date)},set_month:function(_value){this.date.setUTCMonth(_value-1),this.set_value(this.date)},set_date:function(_value){this.date.setUTCDate(_value),this.set_value(this.date)},set_hours:function(_value){this.date.setUTCHours(_value),this.set_value(this.date)},set_minutes:function(_value){this.date.setUTCMinutes(_value),this.set_value(this.date)},get_year:function(){return""==this.input_date.val()?null:this.date.getUTCFullYear()},get_month:function(){return""==this.input_date.val()?null:this.date.getUTCMonth()+1},get_date:function(){return""==this.input_date.val()?null:this.date.getUTCDate()},get_hours:function(){return""==this.input_date.val()?null:this.date.getUTCHours()},get_minutes:function(){return""==this.input_date.val()?null:this.date.getUTCMinutes()},get_time:function(){return""==this.input_date.val()?null:this.date.getTime()},set_year_range:function(_value){this.input_date&&"date"==this._type&&!this.is_mobile&&this.input_date.datepicker("option","yearRange",_value),this.options.year_range=_value},set_min:function(_value){this.input_date&&(this.is_mobile?this.input_date.attr("min",this._relativeDate(_value)):this.input_date.datepicker("option","minDate",_value)),this.options.min=_value},_relativeDate:function(_value){return"string"==typeof _value&&_value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/)?_value:jQuery.datepicker._determineDate(jQuery.datepicker,_value,this.date).toJSON()},set_max:function(_value){this.input_date&&(this.is_mobile?this.input_date.attr("max",this._relativeDate(_value)):this.input_date.datepicker("option","maxDate",_value)),this.options.max=_value},set_value:function(_value){var old_value=this._oldValue;if(null===_value||""===_value||void 0===_value||0==_value&&("date-time"==this._type||"date"==this._type))return this.input_date&&this.input_date.val(""),this._oldValue!==et2_no_init&&old_value!==_value&&this.change(this.input_date),void(this._oldValue=_value);if(("number"==typeof _value||"string"==typeof _value&&!isNaN(_value)&&"+"!=_value[0]&&"-"!=_value[0])&&(_value=date("Y-m-d\\TH:i:s\\Z",_value)),"string"==typeof _value&&_value.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})(?:\.\d{3})?(?:Z|[+-](\d{2})\:(\d{2}))/)&&(_value=new Date(_value)),"string"==typeof _value&&isNaN(_value))try{var fix_reg=new RegExp(("date-timeonly"==this._type?"^":" ")+"([0-9]+)(:[0-9]*)?( ?(a|p)m?)?$","i"),matches=_value.match(fix_reg);if(matches&&(matches[1].length<2||void 0===matches[2]||matches[2].length<3||matches[3]&&"am"!=matches[3]&&"pm"!=matches[3])){for(matches[1].length<2&&!matches[3]&&(matches[1]="0"+matches[1]),void 0===matches[2]&&(matches[2]=":00");matches[2].length<3;)matches[2]=":0"+matches[2].substr(1);_value=_value.replace(fix_reg,("date-timeonly"==this._type?"":" ")+matches[1]+matches[2]+matches[3]),void 0!==matches[4]&&(matches[3]="a"==matches[4].toLowerCase()?"am":"pm")}switch(this._type){case"date-timeonly":var parsed=jQuery.datepicker.parseTime(this.timeFormat,_value);return parsed?(this.set_validation_error(!1),this.date.setDate(1),this.date.setMonth(0),this.date.setFullYear(1970),this.date.setUTCHours(parsed.hour),this.date.setMinutes(parsed.minute),this.input_date.val()!=_value&&(this.input_date.val(_value),this.input_date.timepicker("setTime",_value),this._oldValue!==et2_no_init&&this.change(this.input_date)),void(this._oldValue=this.date.toJSON())):void this.set_validation_error(this.egw().lang("'%1' has an invalid format !!!",_value));default:if(this.id.match(/^#/g)&&this.options.value==_value||this.options.data_format&&this.options.value==_value)switch(this._type){case"date":var parsed=jQuery.datepicker.parseDate(this.egw().dateTimeFormat(this.options.data_format),_value);break;case"date-time":var DTformat=this.options.data_format.split(" "),parsed=jQuery.datepicker.parseDateTime(this.egw().dateTimeFormat(DTformat[0]),this.egw().dateTimeFormat(DTformat[1]),_value)}else{var parsed=jQuery.datepicker.parseDateTime(this.dateFormat,this.timeFormat,_value.replace("T"," "));if(!parsed)return void this.set_validation_error(this.egw().lang("%1' han an invalid format !!!",_value))}parsed&&(this.date=new Date(parsed.valueOf()-6e4*parsed.getTimezoneOffset())),this.set_validation_error(!1)}}catch(e){return this.set_value(null)}else"object"==typeof _value&&_value.date?this.date=_value.date:"object"==typeof _value&&_value.valueOf?this.date=_value:this.date.setTime(this.date.getTime()+1e3*parseInt(_value));_value="";var formatDate=new Date(this.date.valueOf()+60*this.date.getTimezoneOffset()*1e3);"date-timeonly"!=this._type&&(_value=jQuery.datepicker.formatDate(this.dateFormat,formatDate)),"date"!=this._type&&("date-timeonly"!=this._type&&(_value+=this.is_mobile?"T":" "),_value+=jQuery.datepicker.formatTime(this.timeFormat,{hour:formatDate.getHours(),minute:formatDate.getMinutes(),seconds:0,timezone:0})),this.options.inline?this.input_date.datepicker("setDate",formatDate):this.input_date.val(_value),this._oldValue!==et2_no_init&&old_value!=this.getValue()&&this.change(this.input_date),this._oldValue=_value},getValue:function(){return""==this.input_date.val()?null:("date-timeonly"==this._type?(this.date.setDate(1),this.date.setMonth(0),this.date.setFullYear(1970)):"date"==this._type&&(this.date.setUTCHours(0),this.date.setUTCMinutes(0)),this.date.setSeconds(0,0),this.date&&"undefined"!=typeof this.date.toJSON&&this.date.toJSON()?this.date.toJSON().replace(/\.\d{3}Z$/,"Z"):this.date)}})}.call(this);et2_register_widget(et2_date,["date","date-time","date-timeonly"]);
var et2_date_duration=function(){"use strict";return et2_date.extend({attributes:{data_format:{name:"Data format",default:"m",type:"string",description:"Units to read/store the data. 'd' = days (float), 'h' = hours (float), 'm' = minutes (int)."},display_format:{name:"Display format",default:"dhm",type:"string",description:"Permitted units for displaying the data. 'd' = days, 'h' = hours, 'm' = minutes. Use combinations to give a choice. Default is 'dh' = days or hours with selectbox."},percent_allowed:{name:"Percent allowed",default:!1,type:"boolean",description:"Allows to enter a percentage."},hours_per_day:{name:"Hours per day",default:8,type:"integer",description:"Number of hours in a day, for converting between hours and (working) days."},empty_not_0:{name:"0 or empty",default:!1,type:"boolean",description:"Should the widget differ between 0 and empty, which get then returned as NULL"},short_labels:{name:"Short labels",default:!1,type:"boolean",description:"use d/h/m instead of day/hour/minute"}},legacyOptions:["data_format","display_format","hours_per_day","empty_not_0","short_labels"],time_formats:{d:"d",h:"h",m:"m"},init:function(){this._super.apply(this,arguments),this.input=null,-1!=this.options.display_format.indexOf("%")&&(this.options.percent_allowed=!0,this.options.display_format=this.options.display_format.replace("%","")),this.options.display_format=this.options.display_format.replace(/[^dhm]/,""),this.options.display_format||(this.options.display_format=this.attributes.display_format.default),this.time_formats={d:this.options.short_labels?this.egw().lang("m"):this.egw().lang("Days"),h:this.options.short_labels?this.egw().lang("h"):this.egw().lang("Hours"),m:this.options.short_labels?this.egw().lang("m"):this.egw().lang("Minutes")},this.createInputWidget()},createInputWidget:function(){if(this.node=$j(document.createElement("span")).addClass("et2_date_duration"),this.duration=$j(document.createElement("input")).addClass("et2_date_duration").attr({type:"number",size:3}),this.node.append(this.duration),this.options.display_format.length>1){this.format=$j(document.createElement("select")).addClass("et2_date_duration"),this.node.append(this.format);for(var i=0;i<this.options.display_format.length;i++)this.format.append("<option value='"+this.options.display_format[i]+"'>"+this.time_formats[this.options.display_format[i]]+"</option>")}else this.time_formats[this.options.display_format]?this.format=$j("<span>"+this.time_formats[this.options.display_format]+"</span>").appendTo(this.node):this.format=$j("<span>"+this.time_formats.m+"</span>").appendTo(this.node)},attachToDOM:function(){var node=this.getInputNode();node&&$j(node).bind("change.et2_inputWidget",this,function(e){e.data.change(this)}),et2_DOMWidget.prototype.attachToDOM.apply(this,arguments)},getDOMNode:function(){return this.node[0]},getInputNode:function(){return this.duration[0]},set_id:function(_value){this.id=_value;var node=this.getDOMNode(this);node&&(""!=_value?node.setAttribute("id",this.getInstanceManager().uniqueId+"_"+this.id):node.removeAttribute("id"))},set_value:function(_value){this.options.value=_value;var display=this._convert_to_display(_value);"INPUT"==this.duration[0].nodeName?this.duration.val(display.value):this.duration.text(display.value+" "),display.unit!=this.options.display_format&&(this.format&&this.format.children().length>1?$j("option[value='"+display.unit+"']",this.format).attr("selected","selected"):this.format.text(this.time_formats[display.unit]))},_convert_to_display:function(_value){if(_value)switch(this.options.data_format){case"d":_value*=this.options.hours_per_day;case"h":_value*=60}var _unit="d"==this.options.display_format?"d":"h";this.options.display_format.indexOf("m")>-1&&_value&&60>_value?_unit="m":this.options.display_format.indexOf("d")>-1&&_value>=60*this.options.hours_per_day&&(_unit="d"),_value=this.options.empty_not_0&&""===_value||!this.options.empty_not_0&&!_value?"":"m"==_unit?parseInt(_value):Math.round(_value/60/("d"==_unit?this.options.hours_per_day:1)*100)/100,""===_value&&(_unit="");var format=this.egw().preference("number_format"),sep=format?format[0]:".";return"string"==typeof _value&&format&&sep&&"."!=sep&&(_value=_value.replace(".",sep)),{value:_value,unit:_unit}},getValue:function(){var value=this.duration.val().replace(",",".");if(""===value)return this.options.empty_not_0?"":0;switch(this.format&&this.format.val()?this.format.val():this.options.display_format){case"d":value*=this.options.hours_per_day;case"h":value*=60}switch(value=Math.round(value),this.options.data_format){case"d":value/=this.options.hours_per_day;case"h":value/=60}return value}})}.call(this);et2_register_widget(et2_date_duration,["date-duration"]);var et2_date_duration_ro=function(){"use strict";return et2_date_duration.extend([et2_IDetachedDOM],{createInputWidget:function(){this.node=$j(document.createElement("span")),this.duration=$j(document.createElement("span")).appendTo(this.node),this.format=$j(document.createElement("span")).appendTo(this.node)},getDetachedAttributes:function(_attrs){_attrs.push("value")},getDetachedNodes:function(){return[this.duration[0],this.format[0]]},setDetachedAttributes:function(_nodes,_values){for(var i=0;i<_nodes.length;i++)for(var j=_nodes[i].childNodes.length-1;j>=0;j--)_nodes[i].removeChild(_nodes[i].childNodes[j]);if("undefined"!=typeof _values.value&&(_values.value=parseFloat(_values.value)),_values.value){var display=this._convert_to_display(_values.value);_nodes[0].appendChild(document.createTextNode(display.value)),_nodes[1].appendChild(document.createTextNode(display.unit))}}})}.call(this);et2_register_widget(et2_date_duration_ro,["date-duration_ro"]);var et2_date_ro=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{value:{type:"string"},type:{ignore:!1},data_format:{ignore:!0,description:"Format data is in. This is not used client-side because it's always a timestamp client side."},min:{ignore:!0},max:{ignore:!0},year_range:{ignore:!0}},legacyOptions:["data_format"],date:new Date,init:function(){this._super.apply(this,arguments),this._labelContainer=$j(document.createElement("label")).addClass("et2_label"),this.value="",this.span=$j(document.createElement("date-since"==this._type||"date-time_today"==this._type?"span":"time")).addClass("et2_date_ro et2_label").appendTo(this._labelContainer),this.setDOMNode(this._labelContainer[0])},set_value:function(_value){if("undefined"==typeof _value&&(_value=0),this.value=_value,0==_value||null==_value)return void this.span.attr("datetime","").text("");if("string"==typeof _value&&_value.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})(?:\.\d{3})?(?:Z|[+-](\d{2})\:(\d{2}))/))this.date=new Date(_value),this.date=new Date(this.date.valueOf()+60*this.date.getTimezoneOffset()*1e3);else if("string"==typeof _value&&isNaN(_value)){try{var parsed="undefined"!=typeof jQuery.datepicker.parseDateTime("yy-mm-dd","hh:mm:ss",_value)?jQuery.datepicker.parseDateTime("yy-mm-dd","hh:mm:ss",_value):jQuery.datepicker.parseDateTime(this.egw().preference("dateformat"),"24"==this.egw().preference("timeformat")?"H:i":"g:i a",_value)}catch(e){return void this.span.attr("datetime","").text("")}var text=new Date(parsed);parsed&&(this.date=new Date(text.valueOf()-60*text.getTimezoneOffset()*1e3)),this.date.setTime(text.valueOf())}else this.date=_value;var display=this.date.toString();switch(this._type){case"time_or_date":case"date-time_today":display=date("Y-m-d",this.date)==date("Y-m-d")?date("24"==this.egw().preference("timeformat")?"H:i":"g:i a",this.date):"time_or_date"===this._type?date(this.egw().preference("dateformat"),this.date):date(this.egw().preference("dateformat")+" "+("24"==this.egw().preference("timeformat")?"H:i":"g:i a"),this.date);break;case"date":display=date(this.egw().preference("dateformat"),this.date);break;case"date-timeonly":display=date("24"==this.egw().preference("timeformat")?"H:i":"g:i a",this.date);break;case"date-time":display=date(this.egw().preference("dateformat")+" "+("24"==this.egw().preference("timeformat")?"H:i":"g:i a"),this.date);break;case"date-since":var unit2label={Y:"years",m:"month",d:"days",H:"hours",i:"minutes",s:"seconds"},unit2s={Y:31536e3,m:2628e3,d:86400,H:3600,i:60,s:1},d=new Date,diff=Math.round(d.valueOf()/1e3)-Math.round(this.date.valueOf()/1e3);display="";for(var unit in unit2s){var unit_s=unit2s[unit];if(diff>=unit_s||"s"==unit){display=Math.round(diff/unit_s,1)+" "+this.egw().lang(unit2label[unit]);break}}}this.span.attr("datetime",date("Y-m-d H:i:s",this.date)).text(display)},set_label:function(label){this._labelContainer.contents().filter(function(){return 3==this.nodeType}).remove();var parts=et2_csvSplit(label,2,"%s");this._labelContainer.prepend(parts[0]),this._labelContainer.append(parts[1]),this.label=label},getDetachedAttributes:function(_attrs){_attrs.push("label","value","class")},getDetachedNodes:function(){return[this._labelContainer[0],this.span[0]]},setDetachedAttributes:function(_nodes,_values){this._labelContainer=jQuery(_nodes[0]),this.span=jQuery(_nodes[1]),this.set_value(_values.value),_values.label&&this.set_label(_values.label),_values.class&&this.span.addClass(_values.class)}})}.call(this);et2_register_widget(et2_date_ro,["date_ro","date-time_ro","date-since","date-time_today","time_or_date","date-timeonly_ro"]);var et2_date_range=function(){"use strict";return et2_inputWidget.extend({attributes:{value:{type:"any",description:"An object with keys 'from' and 'to' for absolute ranges, or a relative range string"},relative:{name:"Relative",type:"boolean",description:"Is the date range relative (this week) or absolute (2016-02-15 - 2016-02-21). This will affect the value returned."}},init:function(){this._super.apply(this,arguments),this.div=jQuery(document.createElement("div")).attr({class:"et2_date_range"}),this.from=null,this.to=null,this.select=null,this.set_id(this.id),this.setDOMNode(this.div[0]),this._createWidget(),this.set_relative(this.options.relative||!1)},_createWidget:function(){var widget=this;this.from=et2_createWidget("date",{id:this.id+"[from]",blur:egw.lang("From"),onchange:function(){widget.to.set_min(widget.from.getValue())}},this),this.to=et2_createWidget("date",{id:this.id+"[to]",blur:egw.lang("To"),onchange:function(){widget.from.set_max(widget.to.getValue())}},this),this.select=et2_createWidget("select",{id:this.id+"[relative]",select_options:et2_date_range.relative_dates,empty_label:this.options.blur||"All"},this),this.select.loadingFinished()},iterateOver:function(_callback,_context,_type){"undefined"==typeof _type&&(_type=et2_widget),this.isInTree()&&this.instanceOf(_type)&&_callback.call(_context,this)},set_relative:function(_value){this.options.relative=_value,this.options.relative?($j(this.from.getDOMNode()).hide(),$j(this.to.getDOMNode()).hide()):$j(this.select.getDOMNode()).hide()},set_value:function(value){value&&"null"!=typeof value||(this.select.set_value(""),this.from.set_value(null),this.to.set_value(null)),value&&"string"==typeof value?this._set_relative_value(value):value&&"undefined"==typeof value.from&&value[0]?value={from:value[0],to:value[1]||(new Date).valueOf()/1e3}:value&&value.from&&value.to&&(this.from.set_value(value.from),this.to.set_value(value.to))},getValue:function(){return this.options.relative?this.select.getValue():{from:this.from.getValue(),to:this.to.getValue()}},_set_relative_value:function(_value){this.options.relative&&$j(this.select.getDOMNode()).show(),this.select.set_value(_value);var now=new Date;now.setUTCMinutes(-now.getTimezoneOffset()),now.setUTCHours(0),now.setUTCSeconds(0),this.from.set_value(now.toJSON()),this.to.set_value(now.toJSON());var relative=null;for(var index in et2_date_range.relative_dates)if(et2_date_range.relative_dates[index].value===_value){relative=et2_date_range.relative_dates[index];break}if(relative)for(var dates=["from","to"],value=now.toJSON(),i=0;i<dates.length;i++){var date=dates[i];value="function"==typeof relative[date]?relative[date](new Date(value)):this[date]._relativeDate(relative[date]),this[date].set_value(value)}}})}.call(this);et2_register_widget(et2_date_range,["date-range"]),jQuery.extend(et2_date_range,{relative_dates:[{value:"Today",label:"Today",from:"",to:"+1d"},{label:"Yesterday",value:"Yesterday",from:"-1d",to:""},{label:"This week",value:"This week",from:function(date){return egw.week_start(date)},to:function(date){return date.setUTCDate(date.getUTCDate()+6),date}},{label:"Last week",value:"Last week",from:function(date){var d=egw.week_start(date);return d.setUTCDate(d.getUTCDate()-7),d},to:function(date){return date.setUTCDate(date.getUTCDate()+6),date}},{label:"This month",value:"This month",from:"",to:"+1m"},{label:"Last month",value:"Last month",from:"-1m",to:""},{label:"Last 3 months",value:"Last 3 months",from:"-3m",to:""},{label:"This year",value:"This year",from:function(d){return d.setUTCMonth(0),d.setUTCDate(1),d},to:function(d){return d.setUTCMonth(11),d.setUTCDate(31),d}},{label:"Last year",value:"Last year",from:function(d){return d.setUTCMonth(0),d.setUTCDate(1),d.setUTCYear(d.getUTCYear()-1),d},to:function(d){return d.setUTCMonth(11),d.setUTCDate(31),d.setUTCYear(d.getUTCYear()-1),d}}]});var et2_dialog=function(){"use strict";return et2_widget.extend({attributes:{callback:{name:"Callback",type:"js",description:"Callback function is called with the value when the dialog is closed",default:function(button_id){egw.debug("log","Button ID: %d",button_id)}},message:{name:"Message",type:"string",description:"Dialog message (plain text, no html)",default:"Somebody forgot to set this..."},dialog_type:{name:"Dialog type",type:"integer",description:"To use a pre-defined dialog style, use et2_dialog.ERROR_MESSAGE, INFORMATION_MESSAGE,WARNING_MESSAGE,QUESTION_MESSAGE,PLAIN_MESSAGE constants. Default is et2_dialog.PLAIN_MESSAGE",default:0},buttons:{name:"Buttons",type:"any",default:0,description:"Buttons that appear at the bottom of the dialog. You can use the constants et2_dialog.BUTTONS_OK, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_OK_CANCEL, or pass in an array for full control"},icon:{name:"Icon",type:"string",description:"URL of an icon for the dialog. If omitted, an icon based on dialog_type will be used.",default:""},title:{name:"Title",type:"string",description:"Title for the dialog box (plain text, no html)",default:""},modal:{name:"Modal",type:"boolean",description:"Prevent the user from interacting with the page",default:!0},resizable:{name:"Resizable",type:"boolean",description:"Allow the user to resize the dialog",default:!0},value:{name:"Value",description:"The (default) value of the dialog. Use with template.",type:"any",default:et2_no_init},template:{name:"Template",description:"Instead of displaying a simple message, a full template can be loaded instead. Set defaults with value.",type:"string",default:et2_no_init}},_dialog_types:["","dialog_info","dialog_help","dialog_warning","dialog_error"],_buttons:[[{button_id:1,text:"ok",id:"dialog[ok]",image:"check",default:!0}],[{button_id:1,text:"ok",id:"dialog[ok]",image:"check",default:!0},{button_id:0,text:"cancel",id:"dialog[cancel]",image:"cancel"}],[{button_id:2,text:"yes",id:"dialog[yes]",image:"check",default:!0},{button_id:3,text:"no",id:"dialog[no]",image:"cancelled"}],[{button_id:2,text:"yes",id:"dialog[yes]",image:"check",default:!0},{button_id:3,text:"no",id:"dialog[no]",image:"cancelled"},{button_id:0,text:"cancel",id:"dialog[cancel]",image:"cancel"}]],_parent:null,init:function(){this._super.apply(this,arguments);for(var self=this,i=0;i<this._buttons.length;i++)for(var j=0;j<this._buttons[i].length;j++)this._buttons[i][j].click=function(id){return function(event){self.click(event.target,id)}}(this._buttons[i][j].button_id),this._buttons[i][j].text=egw.lang(this._buttons[i][j].text);this.div=$j(document.createElement("div")),this._createDialog()},destroy:function(){null!=this.div&&(this.div.dialog("destroy"),this.template&&(this.template.clear(),this.template=null),this.div=null),this._super.apply(this,arguments)},click:function(target,button_id){this.options.callback&&this.options.callback.call(this,button_id,this.get_value()),this.div.dialog("close")},get_value:function(){var value=this.options.value;return this.template&&(value=this.template.getValues(this.template.widgetContainer)),value},set_message:function(message){this.options.message=message,this.div.empty().append("<img class='dialog_icon' />").append($j("<div/>").text(message))},set_dialog_type:function(type){this.options.dialog_type!=type&&"string"==typeof this._dialog_types[type]&&(this.options.dialog_type=type),this.set_icon(this._dialog_types[type]?egw.image(this._dialog_types[type]):"")},set_icon:function(icon_url){""==icon_url?$j("img.dialog_icon",this.div).hide():$j("img.dialog_icon",this.div).show().attr("src",icon_url)},set_buttons:function(buttons){if(this.options.buttons=buttons,buttons instanceof Array)for(var i=0;i<buttons.length;i++){var button=buttons[i];if(button.click||(button.click=jQuery.proxy(this.click,this,null,button.id)),button.id&&"undefined"==typeof button.class)for(var name in et2_button.default_classes)if(button.id.match(et2_button.default_classes[name])){button.class=("undefined"==typeof button.class?"":button.class+" ")+name;break}if(button.id&&"undefined"==typeof button.image&&"undefined"==typeof button.style)for(var name in et2_button.default_background_images)if(button.id.match(et2_button.default_background_images[name])){button.image=name;break}button.image&&(button.style="background-image: url("+this.egw().image(button.image)+")",delete button.image)}this.div.data("ui-dialog")&&(this.div.dialog("option","buttons",buttons),$j(".ui-dialog-buttonpane button[default]",this.div.parent()).focus())},set_title:function(title){this.options.title=title,this.div.dialog("option","title",title)},set_modal:function(modal){this.options.modal=modal,this.div.dialog("option","modal",modal)},set_template:function(template){this.template&&this.options.template!=template&&this.template.clear(),this.template=new etemplate2(this.div[0],!1),template.indexOf(".xet")>0?this.template.load("",template,this.options.value||{},jQuery.proxy(function(){$j("input",this.div).first().focus()},this)):this.template.load(template,"",this.options.value||{})},_createDialog:function(){this.options.template?this.set_template(this.options.template):(this.set_message(this.options.message),this.set_dialog_type(this.options.dialog_type)),this.set_buttons("number"==typeof this.options.buttons?this._buttons[this.options.buttons]:this.options.buttons),this.div.dialog({buttons:this.options.buttons,modal:this.options.modal,resizable:this.options.resizable,width:"auto",maxWidth:640,title:this.options.title,open:function(){$j(this).parents(".ui-dialog-buttonpane button[default]").focus()},close:jQuery.proxy(function(){this.destroy()},this)})}})}.call(this);et2_register_widget(et2_dialog,["dialog"]),jQuery.extend(et2_dialog,{PLAIN_MESSAGE:0,INFORMATION_MESSAGE:1,QUESTION_MESSAGE:2,WARNING_MESSAGE:3,ERROR_MESSAGE:4,BUTTONS_OK:0,BUTTONS_OK_CANCEL:1,BUTTONS_YES_NO:2,BUTTONS_YES_NO_CANCEL:3,CANCEL_BUTTON:0,OK_BUTTON:1,YES_BUTTON:2,NO_BUTTON:3,_create_parent:function(_egw_or_appname){"undefined"==typeof _egw_or_appname&&(_egw_or_appname=egw_appName);var parent=new et2_widget;return"string"!=typeof _egw_or_appname?parent._egw=_egw_or_appname:(parent._egw=egw(_egw_or_appname),parent._egw.langRequireApp(parent._egw.window,_egw_or_appname)),parent},show_dialog:function(_callback,_message,_title,_value,_buttons,_type,_icon,_egw_or_appname){var parent=et2_dialog._create_parent(_egw_or_appname);return et2_createWidget("dialog",{callback:_callback||function(){},message:_message,title:_title||parent._egw.lang("Confirmation required"),buttons:"undefined"!=typeof _buttons?_buttons:et2_dialog.BUTTONS_YES_NO,dialog_type:"undefined"!=typeof _type?_type:et2_dialog.QUESTION_MESSAGE,icon:_icon,value:_value},parent)},alert:function(_message,_title,_type){var parent=et2_dialog._create_parent(et2_dialog._create_parent()._egw);et2_createWidget("dialog",{callback:function(){},message:_message,title:_title,buttons:et2_dialog.BUTTONS_OK,dialog_type:_type||et2_dialog.INFORMATION_MESSAGE},parent)},show_prompt:function(_callback,_message,_title,_value,_buttons,_egw_or_appname){var callback=_callback;return et2_createWidget("dialog",{callback:function(_button_id,_value){"function"==typeof callback&&callback.call(this,_button_id,_value.value)},title:_title||egw.lang("Input required"),buttons:_buttons||et2_dialog.BUTTONS_OK_CANCEL,value:{content:{value:_value,message:_message}},template:egw.webserverUrl+"/etemplate/templates/default/prompt.xet",class:"et2_prompt"},et2_dialog._create_parent(_egw_or_appname))},confirm:function(_senders,_dialogMsg,_titleMsg){var senders=_senders,buttonId=_senders.id,dialogMsg="undefined"!=typeof _dialogMsg?_dialogMsg:"",titleMsg="undefined"!=typeof _titleMsg?_titleMsg:"",egw=_senders instanceof et2_widget?_senders.egw():et2_dialog._create_parent()._egw,callbackDialog=function(button_id){button_id==et2_dialog.YES_BUTTON&&senders.getRoot().getInstanceManager().submit(buttonId)};et2_dialog.show_dialog(callbackDialog,egw.lang(dialogMsg),egw.lang(titleMsg),{},et2_dialog.BUTTON_YES_NO,et2_dialog.WARNING_MESSAGE,void 0,egw)},long_task:function(_callback,_message,_title,_menuaction,_list,_egw_or_appname){var parent=et2_dialog._create_parent(_egw_or_appname),egw=parent._egw,buttons=[{button_id:et2_dialog.OK_BUTTON,text:egw.lang("ok"),default:!0,disabled:!0},{button_id:et2_dialog.CANCEL_BUTTON,text:egw.lang("cancel"),click:function(){cancel=!0,$j("button[button_id="+et2_dialog.CANCEL_BUTTON+"]",dialog.div.parent()).button("disable"),update.call(_list.length,"")}}],dialog=et2_createWidget("dialog",{template:egw.webserverUrl+"/etemplate/templates/default/long_task.xet",value:{content:{message:_message}},callback:function(_button_id,_value){_button_id==et2_dialog.CANCEL_BUTTON&&(cancel=!0),"function"==typeof _callback&&_callback.call(this,_button_id,_value.value)},title:_title||egw.lang("please wait..."),buttons:buttons},parent);$j("button[button_id="+et2_dialog.OK_BUTTON+"]",dialog.div.parent()).button("disable");var log=null,progressbar=null,cancel=!1,update=function(response){var index=this||0;switch(progressbar.set_value(100*(index/_list.length)),response.type){case"error":log.append("<div class='message error'>"+response.data+"</div>");break;default:response&&log.append("<div class='message'>"+response+"</div>")}var height=log[0].scrollHeight;if(log.scrollTop(height),!cancel&&index<_list.length){var parameters=_list[index];"object"!=typeof parameters&&(parameters=[parameters]),egw.json(_menuaction,parameters,update,index+1,!0,index+1).sendRequest()}else cancel||progressbar.set_value(100),$j("button[button_id="+et2_dialog.CANCEL_BUTTON+"]",dialog.div.parent()).button("disable"),$j("button[button_id="+et2_dialog.OK_BUTTON+"]",dialog.div.parent()).button("enable"),cancel||"function"!=typeof _callback||_callback.call(dialog,!0,response)};return $j(dialog.template.DOMContainer).on("load",function(){log=$j(dialog.template.widgetContainer.getWidgetById("log").getDOMNode()),progressbar=dialog.template.widgetContainer.getWidgetById("progressbar"),window.setTimeout(function(){update.call(0,"")},0)}),dialog}}),__whitespace={" ":!0," ":!0,"\n":!0,"\f":!0,"\r":!0},difflib={defaultJunkFunction:function(c){return __whitespace.hasOwnProperty(c)},stripLinebreaks:function(str){return str.replace(/^[\n\r]*|[\n\r]*$/g,"")},stringAsLines:function(str){for(var lfpos=str.indexOf("\n"),crpos=str.indexOf("\r"),linebreak=lfpos>-1&&crpos>-1||0>crpos?"\n":"\r",lines=str.split(linebreak),i=0;i<lines.length;i++)lines[i]=difflib.stripLinebreaks(lines[i]);return lines},__reduce:function(func,list,initial){if(null!=initial)var value=initial,idx=0;else{if(!list)return null;var value=list[0],idx=1}for(;idx<list.length;idx++)value=func(value,list[idx]);return value},__ntuplecomp:function(a,b){for(var mlen=Math.max(a.length,b.length),i=0;mlen>i;i++){if(a[i]<b[i])return-1;if(a[i]>b[i])return 1}return a.length==b.length?0:a.length<b.length?-1:1},__calculate_ratio:function(matches,length){return length?2*matches/length:1},__isindict:function(dict){return function(key){return dict.hasOwnProperty(key)}},__dictget:function(dict,key,defaultValue){return dict.hasOwnProperty(key)?dict[key]:defaultValue},SequenceMatcher:function(a,b,isjunk){this.set_seqs=function(a,b){this.set_seq1(a),this.set_seq2(b)},this.set_seq1=function(a){a!=this.a&&(this.a=a,this.matching_blocks=this.opcodes=null)},this.set_seq2=function(b){b!=this.b&&(this.b=b,this.matching_blocks=this.opcodes=this.fullbcount=null,this.__chain_b())},this.__chain_b=function(){for(var b=this.b,n=b.length,b2j=this.b2j={},populardict={},i=0;i<b.length;i++){var elt=b[i];if(b2j.hasOwnProperty(elt)){var indices=b2j[elt];n>=200&&100*indices.length>n?(populardict[elt]=1,delete b2j[elt]):indices.push(i)}else b2j[elt]=[i]}for(var elt in populardict)populardict.hasOwnProperty(elt)&&delete b2j[elt];var isjunk=this.isjunk,junkdict={};if(isjunk){for(var elt in populardict)populardict.hasOwnProperty(elt)&&isjunk(elt)&&(junkdict[elt]=1,delete populardict[elt]);for(var elt in b2j)b2j.hasOwnProperty(elt)&&isjunk(elt)&&(junkdict[elt]=1,delete b2j[elt])}this.isbjunk=difflib.__isindict(junkdict),this.isbpopular=difflib.__isindict(populardict)},this.find_longest_match=function(alo,ahi,blo,bhi){for(var a=this.a,b=this.b,b2j=this.b2j,isbjunk=this.isbjunk,besti=alo,bestj=blo,bestsize=0,j=null,j2len={},nothing=[],i=alo;ahi>i;i++){var newj2len={},jdict=difflib.__dictget(b2j,a[i],nothing);for(var jkey in jdict)if(jdict.hasOwnProperty(jkey)){if(j=jdict[jkey],blo>j)continue;if(j>=bhi)break;newj2len[j]=k=difflib.__dictget(j2len,j-1,0)+1,k>bestsize&&(besti=i-k+1,bestj=j-k+1,bestsize=k)}j2len=newj2len}for(;besti>alo&&bestj>blo&&!isbjunk(b[bestj-1])&&a[besti-1]==b[bestj-1];)besti--,bestj--,bestsize++;for(;ahi>besti+bestsize&&bhi>bestj+bestsize&&!isbjunk(b[bestj+bestsize])&&a[besti+bestsize]==b[bestj+bestsize];)bestsize++;for(;besti>alo&&bestj>blo&&isbjunk(b[bestj-1])&&a[besti-1]==b[bestj-1];)besti--,bestj--,bestsize++;for(;ahi>besti+bestsize&&bhi>bestj+bestsize&&isbjunk(b[bestj+bestsize])&&a[besti+bestsize]==b[bestj+bestsize];)bestsize++;return[besti,bestj,bestsize]},this.get_matching_blocks=function(){if(null!=this.matching_blocks)return this.matching_blocks;for(var alo,ahi,blo,bhi,qi,i,j,k,x,la=this.a.length,lb=this.b.length,queue=[[0,la,0,lb]],matching_blocks=[];queue.length;)qi=queue.pop(),alo=qi[0],ahi=qi[1],blo=qi[2],bhi=qi[3],x=this.find_longest_match(alo,ahi,blo,bhi),i=x[0],j=x[1],k=x[2],k&&(matching_blocks.push(x),i>alo&&j>blo&&queue.push([alo,i,blo,j]),ahi>i+k&&bhi>j+k&&queue.push([i+k,ahi,j+k,bhi]));matching_blocks.sort(difflib.__ntuplecomp);var i1=j1=k1=block=0,non_adjacent=[];for(var idx in matching_blocks)matching_blocks.hasOwnProperty(idx)&&(block=matching_blocks[idx],i2=block[0],j2=block[1],k2=block[2],i1+k1==i2&&j1+k1==j2?k1+=k2:(k1&&non_adjacent.push([i1,j1,k1]),i1=i2,j1=j2,k1=k2));return k1&&non_adjacent.push([i1,j1,k1]),non_adjacent.push([la,lb,0]),this.matching_blocks=non_adjacent,this.matching_blocks},this.get_opcodes=function(){if(null!=this.opcodes)return this.opcodes;var i=0,j=0,answer=[];this.opcodes=answer;var block,ai,bj,size,tag,blocks=this.get_matching_blocks();for(var idx in blocks)blocks.hasOwnProperty(idx)&&(block=blocks[idx],ai=block[0],bj=block[1],size=block[2],tag="",ai>i&&bj>j?tag="replace":ai>i?tag="delete":bj>j&&(tag="insert"),tag&&answer.push([tag,i,ai,j,bj]),i=ai+size,j=bj+size,size&&answer.push(["equal",ai,i,bj,j]));return answer},this.get_grouped_opcodes=function(n){n||(n=3);var codes=this.get_opcodes();codes||(codes=[["equal",0,1,0,1]]);var code,tag,i1,i2,j1,j2;"equal"==codes[0][0]&&(code=codes[0],tag=code[0],i1=code[1],i2=code[2],j1=code[3],j2=code[4],codes[0]=[tag,Math.max(i1,i2-n),i2,Math.max(j1,j2-n),j2]),"equal"==codes[codes.length-1][0]&&(code=codes[codes.length-1],tag=code[0],i1=code[1],i2=code[2],j1=code[3],j2=code[4],codes[codes.length-1]=[tag,i1,Math.min(i2,i1+n),j1,Math.min(j2,j1+n)]);var nn=n+n,groups=[];for(var idx in codes)codes.hasOwnProperty(idx)&&(code=codes[idx],tag=code[0],i1=code[1],i2=code[2],j1=code[3],j2=code[4],"equal"==tag&&i2-i1>nn&&(groups.push([tag,i1,Math.min(i2,i1+n),j1,Math.min(j2,j1+n)]),i1=Math.max(i1,i2-n),j1=Math.max(j1,j2-n)),groups.push([tag,i1,i2,j1,j2]));return groups&&"equal"==groups[groups.length-1][0]&&groups.pop(),groups},this.ratio=function(){return matches=difflib.__reduce(function(sum,triple){return sum+triple[triple.length-1]},this.get_matching_blocks(),0),difflib.__calculate_ratio(matches,this.a.length+this.b.length)},this.quick_ratio=function(){var fullbcount,elt;if(null==this.fullbcount){this.fullbcount=fullbcount={};for(var i=0;i<this.b.length;i++)elt=this.b[i],fullbcount[elt]=difflib.__dictget(fullbcount,elt,0)+1}fullbcount=this.fullbcount;for(var avail={},availhas=difflib.__isindict(avail),matches=numb=0,i=0;i<this.a.length;i++)elt=this.a[i],availhas(elt)?numb=avail[elt]:numb=difflib.__dictget(fullbcount,elt,0),avail[elt]=numb-1,numb>0&&matches++;return difflib.__calculate_ratio(matches,this.a.length+this.b.length)},this.real_quick_ratio=function(){var la=this.a.length,lb=this.b.length;return _calculate_ratio(Math.min(la,lb),la+lb)},this.isjunk=isjunk?isjunk:difflib.defaultJunkFunction,this.a=this.b=null,this.set_seqs(a,b)}},diffview={buildView:function(params){function celt(name,clazz){var e=document.createElement(name);return e.className=clazz,e}function telt(name,text){var e=document.createElement(name);return e.appendChild(document.createTextNode(text)),e}function ctelt(name,clazz,text){var e=document.createElement(name);return e.className=clazz,e.appendChild(document.createTextNode(text)),e}function addCells(row,tidx,tend,textLines,change){return tend>tidx?(row.appendChild(telt("th",(tidx+1).toString())),row.appendChild(ctelt("td",change,textLines[tidx].replace(/\t/g,"    "))),tidx+1):(row.appendChild(document.createElement("th")),row.appendChild(celt("td","empty")),tidx)}function addCellsInline(row,tidx,tidx2,textLines,change){row.appendChild(telt("th",null==tidx?"":(tidx+1).toString())),row.appendChild(telt("th",null==tidx2?"":(tidx2+1).toString())),row.appendChild(ctelt("td",change,textLines[null!=tidx?tidx:tidx2].replace(/\t/g,"    ")))}var baseTextLines=params.baseTextLines,newTextLines=params.newTextLines,opcodes=params.opcodes,baseTextName=params.baseTextName?params.baseTextName:"Base Text",newTextName=params.newTextName?params.newTextName:"New Text",contextSize=params.contextSize,inline=0==params.viewType||1==params.viewType?params.viewType:0;if(null==baseTextLines)throw"Cannot build diff view; baseTextLines is not defined.";if(null==newTextLines)throw"Cannot build diff view; newTextLines is not defined.";if(!opcodes)throw"Canno build diff view; opcodes is not defined.";var tdata=document.createElement("thead"),node=document.createElement("tr");tdata.appendChild(node),inline?(node.appendChild(document.createElement("th")),node.appendChild(document.createElement("th")),node.appendChild(ctelt("th","texttitle",baseTextName+" vs. "+newTextName))):(node.appendChild(document.createElement("th")),node.appendChild(ctelt("th","texttitle",baseTextName)),node.appendChild(document.createElement("th")),node.appendChild(ctelt("th","texttitle",newTextName))),tdata=[tdata];for(var node2,rows=[],idx=0;idx<opcodes.length;idx++){code=opcodes[idx],change=code[0];for(var b=code[1],be=code[2],n=code[3],ne=code[4],rowcnt=Math.max(be-b,ne-n),toprows=[],botrows=[],i=0;rowcnt>i;i++){if(contextSize&&opcodes.length>1&&(idx>0&&i==contextSize||0==idx&&0==i)&&"equal"==change){var jump=rowcnt-(0==idx?1:2)*contextSize;if(jump>1){if(toprows.push(node=document.createElement("tr")),b+=jump,n+=jump,i+=jump-1,node.appendChild(telt("th","...")),inline||node.appendChild(ctelt("td","skip","")),node.appendChild(telt("th","...")),
node.appendChild(ctelt("td","skip","")),idx+1==opcodes.length)break;continue}}toprows.push(node=document.createElement("tr")),inline?"insert"==change?addCellsInline(node,null,n++,newTextLines,change):"replace"==change?(botrows.push(node2=document.createElement("tr")),be>b&&addCellsInline(node,b++,null,baseTextLines,"delete"),ne>n&&addCellsInline(node2,null,n++,newTextLines,"insert")):"delete"==change?addCellsInline(node,b++,null,baseTextLines,change):addCellsInline(node,b++,n++,baseTextLines,change):(b=addCells(node,b,be,baseTextLines,change),n=addCells(node,n,ne,newTextLines,change))}for(var i=0;i<toprows.length;i++)rows.push(toprows[i]);for(var i=0;i<botrows.length;i++)rows.push(botrows[i])}rows.push(node=ctelt("th","author","diff view generated by ")),node.setAttribute("colspan",inline?3:4),node.appendChild(node2=telt("a","jsdifflib")),node2.setAttribute("href","http://github.com/cemerick/jsdifflib"),tdata.push(node=document.createElement("tbody"));for(var idx in rows)node.appendChild(rows[idx]);node=celt("table","diff"+(inline?" inlinediff":""));for(var idx in tdata)node.appendChild(tdata[idx]);return node}};var et2_diff=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{value:{type:"any"}},init:function(){this._super.apply(this,arguments),this.mini=!0,this.egw().includeCSS("etemplate/js/lib/jsdifflib/diffview.css"),this.div=document.createElement("div"),jQuery(this.div).addClass("diff")},set_value:function(value){if(jQuery(this.div).empty(),"string"==typeof value.old&&"string"==typeof value.new){var old_text=difflib.stringAsLines(value.old.toString()),new_text=difflib.stringAsLines(value.new.toString()),sm=new difflib.SequenceMatcher(old_text,new_text),opcodes=sm.get_opcodes(),view=diffview.buildView({baseTextLines:old_text,newTextLines:new_text,opcodes:opcodes,baseTextName:"",newTextName:"",viewType:1});if(jQuery(this.div).append(view),this.mini){view=jQuery(view),this.minify(view);var self=this;jQuery('<span class="ui-icon ui-icon-circle-plus">&nbsp;</span>').appendTo(self.div).css("cursor","pointer").click({diff:view,div:self.div},function(e){var diff=e.data.diff,div=e.data.div;self.un_minify(diff);var dialog_div=jQuery("<div>").append(diff);dialog_div.dialog({title:self.options.label,width:"auto",autoResize:!0,modal:!0,buttons:[{text:self.egw().lang("ok"),click:function(){jQuery(this).dialog("close")}}],close:function(event,ui){dialog_div.dialog("destroy"),self.minify(this),diff.prependTo(div)}})})}}else"object"!=typeof value&&jQuery(this.div).append(value)},set_label:function(_label){this.options.label=_label},minify:function(view){view=jQuery(view).addClass("mini").width("100%").css("height","inherit").show(),jQuery("th",view).hide(),jQuery("td.equal",view).hide().prevAll().hide()},un_minify:function(view){jQuery(view).removeClass("mini").show(),jQuery("th",view).show(),jQuery("td.equal",view).show()},getDetachedAttributes:function(_attrs){_attrs.push("value","label")},getDetachedNodes:function(){return[this.div]},setDetachedAttributes:function(_nodes,_values){this.div=_nodes[0],"undefined"!=typeof _values.label&&this.set_label(_values.label),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_diff,["diff"]);var et2_dropdown_button=function(){"use strict";return et2_inputWidget.extend({attributes:{label:{name:"caption",type:"string",description:"Label of the button",translate:!0,default:"Select..."},label_updates:{name:"Label updates",type:"boolean",description:"Button label updates when an option is selected from the menu",default:!0},image:{name:"Icon",type:"string",description:"Add an icon"},ro_image:{name:"Read-only Icon",type:"string",description:"Use this icon instead of hiding for read-only"},onclick:{description:"JS code which gets executed when the button is clicked"},select_options:{type:"any",name:"Select options",default:{},description:"Select options for dropdown. Can be a simple key => value list, or value can be full HTML",ignore:!0},accesskey:{name:"Access Key",type:"string",default:et2_no_init,description:"Alt + <key> activates widget"},tabindex:{name:"Tab index",type:"integer",default:et2_no_init,description:"Specifies the tab order of a widget when the 'tab' button is used for navigating."},required:{ignore:!0}},internal_ids:{div:"",button:"",menu:""},div:null,buttons:null,button:null,menu:null,default_menu:'<ul> <li data-id="opt_1.1"><a href="#">Option-1.1</a></li> <li data-id="opt_1.2"><a href="#">Option-1.2</a></li> <li data-id="opt_1.3"><a href="#">Option-1.3</a></li> <li data-id="opt_1.4"><a href="#">Option-1.4<br> <small>with second line</small> </a></li> <li data-id="opt_1.5"><a href="#">Option-1.5</a></li></ul>',init:function(){this._super.apply(this,arguments),this.clicked=!1;var self=this;this.menu=$j(this.default_menu).attr("id",this.internal_ids.menu).hide().menu({select:function(event,ui){self.onselect.call(self,event,ui.item)}}),this.buttons=$j(document.createElement("div")).addClass("et2_dropdown"),this.div=$j(document.createElement("div")).attr("id",this.internal_ids.div).append(this.buttons).append(this.menu),this.button=$j(document.createElement("button")).attr("id",this.internal_ids.button).attr("type","button").addClass("ui-widget ui-corner-left").removeClass("ui-corner-all").appendTo(this.buttons),this.arrow=$j(document.createElement("button")).addClass("ui-widget ui-corner-right").removeClass("ui-corner-all").attr("type","button").click(function(){if(self.menu.is(":visible"))return self.menu.hide(),!1;var menu=self.menu.show().position({my:"left top",at:"left bottom",of:self.buttons});return $j(document).one("click",function(){menu.hide()}),!1}).append("<div class='ui-icon ui-icon-triangle-1-s'/>").appendTo(this.buttons),this.buttons.children("button").addClass("ui-state-default").hover(function(){$j(this).addClass("ui-state-hover")},function(){$j(this).removeClass("ui-state-hover")}),this.image=jQuery(document.createElement("img")),this.setDOMNode(this.div[0])},destroy:function(){this.menu&&this.menu.data("ui-menu")&&this.menu.menu("destroy"),this.image=null,this.button=null,this.arrow=null,this.buttons=null,this.menu=null,this.div.empty().remove()},set_id:function(_id){this._super.apply(this,arguments),this.internal_ids={div:this.dom_id+"_wrapper",button:this.dom_id,menu:this.dom_id+"_menu"};for(var key in this.internal_ids)null!=this[key]&&this[key].attr("id",this.internal_ids[key])},set_label_updates:function(updates){this.label_updates=updates},set_accesskey:function(key){jQuery(this.node).attr("accesskey",key)},set_ro_image:function(_image){this.options.readonly&&this.set_image(_image)},set_image:function(_image){if(this.isInTree()&&null!=this.image){var found_image=!1;_image.trim()?this.image.show():this.image.hide();var src=this.egw().image(_image);src?(this.image.attr("src",src),found_image=!0):"/"==_image[0]||"http"==_image.substr(0,4)?(this.image.attr("src",_image),found_image=!0):this.image.hide()}},click:function(_ev){return this.clicked=!0,this._super.apply(this,arguments)?("buttononly"!=this._type&&this.getInstanceManager().submit(this),this.clicked=!1,!0):(this.clicked=!1,!1)},onselect:function(event,selected_node){this.set_value(selected_node.attr("data-id")),this.change(selected_node)},attachToDOM:function(){this._super.apply(this,arguments),$j(this.node).unbind("click.et2_baseWidget"),this.button.bind("click.et2_baseWidget",this,function(e){return e.data.click.call(e.data,this)})},set_label:function(_value){this.button&&(this.label=_value,this.button.text(_value).prepend(this.image))},set_select_options:function(options){if(this.menu.first().empty(),"string"==typeof options)this.menu.append(options);else{var add_complex=function(node,options){for(var key in options){var item;"string"==typeof options[key]?item=$j("<li data-id='"+key+"'><a href='#'>"+options[key]+"</a></li>"):options[key].label?item=$j("<li data-id='"+key+"'><a href='#'>"+options[key].label+"</a></li>"):(item=$j("<li><a href='#'>"+key+"</a></li>"),add_complex(node.append("<ul>"),options[key])),node.append(item),item&&options[key].icon&&$j("a",item).prepend('<img class="et2_button_icon" src="'+options[key].icon+'"/>')}};add_complex(this.menu.first(),options)}this.menu.menu("refresh")},set_tabindex:function(index){jQuery(this.button).attr("tabindex",index)},set_value:function(new_value){var menu_item=$j("[data-id='"+new_value+"']",this.menu);menu_item.length?(this.value=new_value,this.label_updates&&this.set_label(menu_item.text())):(this.value=null,this.label_updates&&this.set_label(this.options.label))},getValue:function(){return this.value}})}.call(this);et2_register_widget(et2_dropdown_button,["dropdown_button"]);var et2_styles=function(){"use strict";return et2_widget.extend({init:function(){this._super.apply(this,arguments),this.supportedWidgetClasses=[],this.styleNode=document.createElement("style"),this.styleNode.setAttribute("type","text/css"),this.head=this.egw().window.document.getElementsByTagName("head")[0],this.head.appendChild(this.styleNode)},destroy:function(){this.head.removeChild(this.styleNode),this._super.apply(this,arguments)},loadContent:function(_content){this.styleNode.styleSheet?this.styleNode.styleSheet.cssText+=_content:this.styleNode.appendChild(document.createTextNode(_content))},set_id:function(_value){this.id=_value,this.dom_id=_value?this.getInstanceManager().uniqueId+"_"+_value.replace(/\./g,"-"):_value,this.styleNode&&(""!=_value?this.styleNode.setAttribute("id",this.dom_id):this.styleNode.removeAttribute("id"))}})}.call(this);et2_register_widget(et2_styles,["styles"]);var et2_link_to=function(){"use strict";return et2_inputWidget.extend({attributes:{only_app:{name:"Application",type:"string",default:"",description:"Limit to just this one application - hides app selection"},application_list:{name:"Application list",type:"any",default:"",description:"Limit to the listed application or applications (comma seperated)"},blur:{name:"Placeholder",type:"string",default:"",description:"This text get displayed if an input-field is empty and does not have the input-focus (blur). It can be used to show a default value or a kind of help-text.",translate:!0},no_files:{name:"No files",type:"boolean",default:!1,description:"Suppress attach-files"},search_label:{name:"Search label",type:"string",default:"",description:"Label to use for search"},link_label:{name:"Link label",type:"string",default:"Link",description:"Label for the link button"},value:{type:"any"}},init:function(){this._super.apply(this,arguments),this.div=null,this.link_button=null,this.status_span=null,this.link_entry=null,this.file_upload=null,this.options.readonly||this.createInputWidget()},destroy:function(){this.link_button=null,this.status_span=null,this.link_entry&&(this.link_entry.destroy(),this.link_entry=null),this.file_upload&&(this.file_upload.destroy(),this.file_upload=null),this.div=null,this._super.apply(this,arguments)},getDOMNode:function(_sender){return _sender==this?this.div[0]:"link-entry"==_sender._type?this.link_div[0]:"file"==_sender._type?this.file_div[0]:"vfs-select"==_sender._type?this.filemanager_button[0]:void 0},createInputWidget:function(){this.div=$j(document.createElement("div")).addClass("et2_link_to"),this.link_button=$j(document.createElement("button")).text(this.egw().lang(this.options.link_label)).appendTo(this.div).hide().click(this,this.createLink),this.status_span=$j(document.createElement("span")).appendTo(this.div).addClass("status").hide(),this.link_div=$j(document.createElement("div")).css("margin-bottom","1ex").css("width","89%").appendTo(this.div),this.filemanager_button=$j(document.createElement("div")).appendTo(this.div),this.file_div=$j(document.createElement("div")).appendTo(this.div),this.setDOMNode(this.div[0])},doLoadingFinished:function(){this._super.apply(this,arguments);var self=this;if(this.link_entry&&this.vfs_select&&this.file_upload)return!1;var link_entry_attrs={id:this.id+"_link_entry",only_app:this.options.only_app,application_list:this.options.application_list,blur:this.options.search_label?this.options.search_label:this.egw().lang("Search..."),query:function(){return self.link_button.hide(),!0},select:function(){return self.link_button.show(),!0}};this.link_entry=et2_createWidget("link-entry",link_entry_attrs,this);var select_attrs={method:"etemplate_widget_link::link_existing",method_id:function(){return self.options.value.to_app+":"+self.options.value.to_id},button_label:egw.lang("Link")};this.vfs_select=et2_createWidget("vfs-select",select_attrs,this),$j(this.vfs_select.getDOMNode()).change(function(){var values=!0;if(!self.options.value.to_id||"object"==typeof self.options.value.to_id){values=self.options.value.to_id||{};for(var files=self.vfs_select.getValue(),i=0;i<files.length;i++)values["link:"+files[i]]={app:"link",id:files[i],type:"unknown",icon:"link",remark:"",title:files[i]}}self._link_result(values)});var file_attrs={multiple:!0,id:this.id+"_file",drop_target:this.getInstanceManager().DOMContainer.getAttribute("id"),onStart:function(event,file_count){var tabs=self;do tabs=tabs._parent;while(tabs!=self.getRoot()&&"tabbox"!=tabs._type);if(tabs!=self.getRoot())for(var i=0;i<tabs.tabData.length;i++)if(tabs.tabData[i].contentDiv.has(self.div).length){tabs.setActiveTab(i);break}return!0},onFinish:function(event,file_count){event.data=self,self.filesUploaded(event),self.createLink(event)}};return this.file_upload=et2_createWidget("file",file_attrs,this),!0},getValue:function(){return this.options.value},filesUploaded:function(event){this.link_button.show()},createLink:function(event){event.data.link_button.attr("disabled",!0);var values=event.data.options.value,self=event.data,links=[];if(event.data=self.link_entry,self.link_entry.createLink(event,links),!self.options.no_files)for(var file in self.file_upload.options.value)links.push({app:"file",id:file,name:self.file_upload.options.value[file].name,type:self.file_upload.options.value[file].type,remark:jQuery("li[file='"+self.file_upload.options.value[file].name+"'] > input",self.file_upload.progress).filter(function(){return jQuery(this).attr("placeholder")!=jQuery(this).val()}).val()});if(0!=links.length){var request=egw.json(self.egw().getAppName()+".etemplate_widget_link.ajax_link.etemplate",[values.to_app,values.to_id,links],self._link_result,self,!0,self);request.sendRequest()}},_link_result:function(success){if(success){this.link_button.hide().attr("disabled",!1),this.status_span.removeClass("error").addClass("success"),this.status_span.fadeIn().delay(1e3).fadeOut(),delete this.options.value.app,delete this.options.value.id;for(var file in this.file_upload.options.value)delete this.file_upload.options.value[file];if(this.file_upload.progress.empty(),"object"==typeof success){"object"!=typeof this.options.value&&(this.options.value={}),this.options.value.to_id=success;for(var link in success)"undefined"==typeof success[link].icon&&(success[link].icon=egw.link_get_registry(success[link].app,"icon"),0==success[link].icon&&success[link].id.type&&(success[link].type=success[link].id.type,success[link].icon=!0)),"file"==success[link].app&&"undefined"==typeof success[link].title&&(success[link].title=success[link].id.name||"")}var self=this,list_widget=null;if(this.getRoot().iterateOver(function(widget){widget.id==self.id&&(list_widget=widget,success===!0&&widget._get_links())},this,et2_link_list),list_widget&&success){list_widget.set_value(null);for(var link_id in success){var link=success[link_id];"undefined"==typeof link.title?egw.link_title(link.app,link.id,function(title){link.title=title,list_widget._add_link(link)}):list_widget._add_link(link)}}}else this.status_span.removeClass("success").addClass("error").fadeIn();this.div.trigger("link.et2_link_to",success)},set_no_files:function(no_files){no_files?(this.file_div.hide(),this.filemanager_button.hide()):(this.file_div.show(),this.filemanager_button.show()),this.options.no_files=no_files}})}.call(this);et2_register_widget(et2_link_to,["link-to"]);var et2_link_apps=function(){"use strict";return et2_selectbox.extend({attributes:{only_app:{name:"Application",type:"string",default:"",description:"Limit to just this one application - hides app selection"},application_list:{name:"Application list",type:"any",default:"",description:"Limit to the listed application or applications (comma seperated)"}},init:function(){if(this._super.apply(this,arguments),null!=this.options.select_options){this.options.value||this.set_value(egw.preference("link_app",this.egw().getAppName()));var self=this;this.input.bind("click",function(){if("undefined"!=typeof self.options.value)var appname=self.options.value.to_app;egw.set_preference(appname||self.egw().getAppName(),"link_app",self.getValue())})}},transformAttributes:function(_attrs){var select_options={};_attrs.only_app?select_options[_attrs.only_app]=this.egw().lang(_attrs.only_app):_attrs.application_list?select_options=_attrs.application_list:(select_options=egw.link_app_list("query"),"undefined"!=typeof select_options["addressbook-email"]&&delete select_options["addressbook-email"]),_attrs.select_options=select_options,this._super.apply(this,arguments)}})}.call(this);et2_register_widget(et2_link_apps,["link-apps"]);var et2_link_entry=function(){"use strict";return et2_inputWidget.extend({attributes:{value:{type:"any",default:{}},only_app:{name:"Application",type:"string",default:"",description:"Limit to just this one application - hides app selection"},application_list:{name:"Application list",type:"any",default:"",description:"Limit to the listed applications (comma seperated)"},blur:{name:"Placeholder",type:"string",default:et2_no_init,description:"This text get displayed if an input-field is empty and does not have the input-focus (blur). It can be used to show a default value or a kind of help-text.",translate:!0},query:{name:"Query callback",type:"js",default:et2_no_init,description:"Callback before query to server. It will be passed the request & et2_link_entry objects. Must return true, or false to abort query."},select:{name:"Select callback",type:"js",default:et2_no_init,description:"Callback when user selects an option. Must return true, or false to abort normal action."}},legacyOptions:["only_app","application_list"],search_timeout:500,minimum_characters:4,init:function(){this._super.apply(this,arguments),this.search=null,this.clear=null,this.app_select=null,this._oldValue={id:null,app:this.options.value&&this.options.value.app?this.options.value.app:this.options.only_app},"undefined"!=typeof this.options.value&&null!=this.options.value||(this.options.value={}),this.cache={},this.request=null,this.createInputWidget()},destroy:function(){this._super.apply(this,arguments),this.div=null,this.search.data("ui-autocomplete")&&this.search.autocomplete("destroy"),this.search=null,this.clear=null,this.app_select=null,this.request=null},createInputWidget:function(){var self=this;this.div=$j(document.createElement("div")).addClass("et2_link_entry"),this.app_select=$j(document.createElement("select")).appendTo(this.div).change(function(e){self.cache={},egw.set_preference(self.options.value.to_app||self.egw().getAppName(),"link_app",self.app_select.val()),"object"!=typeof self.options.value&&(self.options.value={}),self.options.value.app=self.app_select.val()});var opt_count=0;for(var key in this.options.select_options){opt_count++;var option=$j(document.createElement("option")).attr("value",key).text(this.options.select_options[key]);option.appendTo(this.app_select)}this.options.only_app?(this.app_select.val(this.options.only_app),this.app_select.hide(),this.div.addClass("no_app")):this.app_select.val(this.options.value.app||""),this.search=$j(document.createElement("input")).focus(function(){self.options.only_app||(self.div.removeClass("no_app"),self.app_select.show())}).appendTo(this.div),this.set_blur(this.options.blur?this.options.blur:this.egw().lang("search"),this.search),this.search.autocomplete({source:function(request,response){return self.query(request,response)},select:function(event,item){return event.data=self,item.item.value=item.item.value.trim(),self.select(event,item),!1},focus:function(event,item){return event.stopPropagation(),self.search.val(item.item.label),!1},minLength:self.minimum_characters,delay:self.search_timeout,disabled:self.options.disabled,appendTo:self.div}),this.search.data("uiAutocomplete")._renderItem=function(ul,item){var li=jQuery(document.createElement("li")).data("item.autocomplete",item),extra={};if("object"==typeof item.label&&(extra=item.label,item.label=extra.label?extra.label:extra,(extra["style.backgroundColor"]||extra.color)&&li.css("backgroundColor",extra.color?extra.color:extra["style.backgroundColor"]),extra.icon)){var img=self.egw().image(extra.icon);img&&jQuery(document.createElement("img")).attr("src",img).css("float","right").appendTo(li)}return li.append(jQuery("<a></a>").text(item.label)).appendTo(ul),li},this.search.keydown(function(e){var keycode=e.keyCode?e.keyCode:e.which;return"13"!=keycode||self.processing?void 0:(self.search.autocomplete("option","minLength",0),self.search.autocomplete("search"),self.search.autocomplete("option","minLength",self.minimum_characters),!1)}),this.clear=$j(document.createElement("span")).addClass("ui-icon ui-icon-close").click(function(e){self.search&&(self.last_search&&self.last_search!=self.search.val()?(self.search.val(self.last_search),self.last_search="",self.search.autocomplete("search")):(self.search.autocomplete("close"),self.set_value(null),self.search.val(""),window.setTimeout(function(){self.search.trigger("change")},0)),self.search.focus())}).appendTo(this.div).hide(),this.setDOMNode(this.div[0])},getDOMNode:function(){return this.div?this.div[0]:null},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),_attrs.select_options={},_attrs.application_list)for(var apps="string"==typeof _attrs.application_list?et2_csvSplit(_attrs.application_list,null,","):_attrs.application_list,i=0;i<apps.length;i++)_attrs.select_options[apps[i]]=this.egw().lang(apps[i]);else _attrs.select_options=this.egw().link_app_list("query"),"undefined"!=typeof _attrs.select_options["addressbook-email"]&&delete _attrs.select_options["addressbook-email"];null==_attrs.select_options&&(_attrs.select_options=this.getArrayMgr("content").getEntry("options-"+this.id)),null==_attrs.select_options&&(_attrs.select_options={})},doLoadingFinished:function(){return"object"!=typeof this.options.value||this.options.value.app||(this.options.value.app=egw.preference("link_app",this.options.value.to_app||this.egw().getAppName()),"undefined"!=typeof this.options.value.app&&this.options.value.app||(this.options.value.app=Object.keys(this.options.select_options)[0]),this.app_select.val(this.options.value.app)),this._super.apply(this,arguments)},getValue:function(){var value=this.options&&this.options.only_app?this.options.value.id:this.options?this.options.value:null;return this.options&&!this.options.only_app&&this.search&&(value.search=this.search.val()),value},set_value:function(_value){if("string"==typeof _value||"number"==typeof _value)if("string"==typeof _value&&_value.indexOf(",")>0&&(_value=_value.replace(",",":")),"string"==typeof _value&&_value.indexOf(":")>=0){var split=_value.split(":");_value={app:split.shift(),id:1==split.length?split[0]:split}}else _value&&this.options.only_app&&(_value={app:this.options.only_app,id:_value});if(this._oldValue=this.options.value,_value&&0!=_value.length&&null!=_value&&!jQuery.isEmptyObject(_value)||(this.search.val(""),this.clear.hide(),this.options.value=_value={id:null}),_value.app||(_value.app=this.options.only_app||this.app_select.val()),!_value.id)return void this.clear.hide();if(this.clear.css("display",""),"object"!=typeof _value||!_value.app&&!_value.id)return void console.warn("Bad value for link widget. Need an object with keys 'app', 'id', and optionally 'title'",_value);if(!_value.title){var title=this.egw().link_title(_value.app,_value.id);if(null!=title)_value.title=title;else{var title=this.egw().link_title(_value.app,_value.id,function(title){this.search.removeClass("loading").val(title+""),this.clear.css("display","")},this);this.search.addClass("loading")}}_value.title&&this.search.val(_value.title+""),this.options.value=_value,jQuery("option[value='"+_value.app+"']",this.app_select).prop("selected",!0),this.app_select.hide(),this.div.addClass("no_app")},set_blur:function(_value,input){"undefined"==typeof input&&(input=this.search),_value?(input.attr("placeholder",_value),input[0].placeholder||(""==input.val()&&input.val(_value),input.focus(input,function(e){var placeholder=_value;e.data.val()==placeholder&&e.data.val("")}).blur(input,function(e){var placeholder=_value;""==e.data.val()&&e.data.val(placeholder)}),""==input.val()&&input.val(_value))):this.search.removeAttr("placeholder")},set_query:function(f){this.options.query=f},set_select:function(f){this.options.select=f},query:function(request,response){return this.request&&(this.request.abort(),this.request=null),this.last_search=this.search.val(),this.options.query&&"function"==typeof this.options.query&&!this.options.query(request,this)?!1:"undefined"==typeof request.no_cache&&!request.no_cache&&request.term in this.cache?response(this.cache[request.term]):(this.response=response,this.search.addClass("loading"),this.clear.css("display",""),void(this.request=egw.json(egw_getAppName()+".etemplate_widget_link.ajax_link_search.etemplate",[this.app_select.val(),"",request.term,request.options],this._results,this,!0,this).sendRequest()))},select:function(event,selected){return null!==selected.item.value&&"string"==typeof selected.item.value&&(selected.item.value=selected.item.value.trim()),this.options.select&&"function"==typeof this.options.select&&!this.options.select(event,selected)?!1:("object"==typeof event.data.options.value&&null!=event.data.options.value||(event.data.options.value={}),event.data.options.value.id=selected.item.value,event.data.processing=!0,this.clear.css("display",""),event.data.search.val(selected.item.label),this.search.change(),void window.setTimeout(jQuery.proxy(function(){delete this.processing},event.data)))},_results:function(data){this.request&&(this.request=null),this.search.removeClass("loading");var result=[];for(var id in data)result.push({value:id,label:data[id]});this.cache[this.search.val()]=result,this.response(result)},createLink:function(event,_links){var values=event.data.options.value,self=event.data,links=[];if(links="undefined"==typeof _links?[]:_links,values.id&&(links.push({app:values.app,id:values.id}),self.search.val("")),"undefined"==typeof _links){var request=egw.json(self.egw().getAppName()+".etemplate_widget_link.ajax_link.etemplate",[values.to_app,values.to_id,links],self._link_result,this,!0);request.sendRequest()}},_link_result:function(success){success&&(this.link_button.hide().attr("disabled",!1),this.status_span.fadeIn().delay(1e3).fadeOut(),delete this.options.value.app,delete this.options.value.id)}})}.call(this);et2_register_widget(et2_link_entry,["link-entry"]);var et2_link=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{only_app:{name:"Application",type:"string",default:"",description:"Use the given application, so you can pass just the ID for value"},value:{description:"Array with keys app, id, and optionally title",type:"any"},needed:{ignore:!0}},legacyOptions:["only_app"],init:function(){this._super.apply(this,arguments),this.label_span=$j(document.createElement("label")).addClass("et2_label"),this.link=$j(document.createElement("span")).addClass("et2_link").appendTo(this.label_span),this.options.class&&this.label_span.addClass(this.options.class),this.setDOMNode(this.label_span[0])},destroy:function(){this.link&&this.link.unbind(),this.link=null,this._super.apply(this,arguments)},set_label:function(label){this.label_span.contents().filter(function(){return 3==this.nodeType}).remove();var parts=et2_csvSplit(label,2,"%s");this.label_span.prepend(parts[0]),this.label_span.append(parts[1]),this.label=label},set_value:function(_value){if("object"!=typeof _value&&_value&&!this.options.only_app){if(!(_value.indexOf(":")>=0))return void console.warn("Bad value for link widget. Need an object with keys 'app', 'id', and optionally 'title'",_value);var app=_value.split(":",1),id=_value.substr(app[0].length+1);_value={app:app[0],id:id}}else"object"!=typeof _value&&(_value={app:this.options.only_app,id:_value});if(!_value||jQuery.isEmptyObject(_value))return void this.link.text("").unbind();var self=this;if(this.link.unbind(),_value.id&&_value.app?(this.link.addClass("et2_link"),this.link.click(function(e){self.egw().open(_value,"","view",null,_value.app,_value.app),e.stopImmediatePropagation()})):this.link.removeClass("et2_link"),!_value.title){var self=this,node=this.link[0];if(_value.app&&_value.id){var title=this.egw().link_title(_value.app,_value.id,function(title){self.set_title(node,title)},this);if(null==title)return;_value.title=title}else _value.title=""}this.set_title(this.link,_value.title)},set_title:function(node,_value){_value!==!1&&null!==_value||(_value=""),jQuery(node).text(_value+"")},getDetachedAttributes:function(_attrs){_attrs.push("label","value")},getDetachedNodes:function(){return[this.node,this.link[0]]},setDetachedAttributes:function(_nodes,_values){this.node=_nodes[0],this.label_span=jQuery(_nodes[0]),this.link=jQuery(_nodes[1]),"undefined"!=typeof _values.id&&this.set_id(_values.id),"undefined"!=typeof _values.label&&this.set_label(_values.label),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_link,["link","link-entry_ro"]);var et2_link_string=function(){"use strict";return expose(et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{application:{name:"Application",type:"string",default:"",description:"Use the given application, so you can pass just the ID for value"},value:{description:"Either an array of link information (see egw_link::link()) or array with keys to_app and to_id",type:"any"},only_app:{name:"Application filter",type:"string",default:"",description:"Appname, eg. 'projectmananager' to list only linked projects"},link_type:{name:"Type filter",type:"string",default:"",description:"Sub-type key to list only entries of that type"},expose_view:{name:"Expose view",type:"boolean",default:!0,description:"Clicking on description with href value would popup an expose view, and will show content referenced by href."}},init:function(){this._super.apply(this,arguments),this.list=$j(document.createElement("ul")).addClass("et2_link_string"),this.options.class&&this.list.addClass(this.options.class),this.setDOMNode(this.list[0])},destroy:function(){this._super.apply(this,arguments),null!=this.node&&this.node.children().unbind()},set_value:function(_value){if(!_value||null==_value)return void this.list.empty();if("string"==typeof _value&&_value.indexOf(",")>0&&(_value=_value.split(",")),!_value.to_app&&"object"==typeof _value&&this.options.application&&(_value.to_app=this.options.application),"object"==typeof _value&&_value.to_app&&_value.to_id)return this.value=_value,void this._get_links();if(this.list.empty(),"object"==typeof _value&&_value.length>0)for(var i=0;i<_value.length;i++)(!this.options.only_app||this.options.only_app&&_value[i].app==this.options.only_app)&&this._add_link(_value[i].id?_value[i]:{id:_value[i],app:_value.to_app});else this.options.application&&this._add_link({id:_value,app:this.options.application})},_get_links:function(){var _value=this.value;this.options.only_app&&(_value.only_app=this.options.only_app),this.egw().jsonq(this.egw().getAppName()+".etemplate_widget_link.ajax_link_list",[_value],this.set_value,this)},getMedia:function(_value){var base_url=egw.webserverUrl.match(/^\//,"ig")?egw(window).window.location.origin+egw.webserverUrl:egw.webserverUrl,mediaContent=[];
return _value&&"undefined"!=typeof _value.type&&_value.type.match(/video\//,"ig")?mediaContent=[{title:_value.id,type:_value.type,poster:"",href:base_url+egw().mime_open(_value),download_href:base_url+egw().mime_open(_value)+"?download"}]:_value&&(mediaContent=[{title:_value.id,href:base_url+egw().mime_open(_value).url,download_href:base_url+egw().mime_open(_value).url+"?download",type:_value.type}]),mediaContent[0].href&&mediaContent[0].href.match(/\/webdav.php/,"ig")&&(mediaContent[0].download_href=mediaContent[0].href+"?download"),mediaContent},_add_link:function(_link_data){var self=this,link=$j(document.createElement("li")).appendTo(this.list).addClass("et2_link loading").click(function(e){self.options.expose_view&&"undefined"!=typeof _link_data.type&&_link_data.type.match(self.mime_regexp,"ig")?self._init_blueimp_gallery(e,_link_data):self.egw().open(_link_data,"","view",null,_link_data.app,_link_data.app),e.stopImmediatePropagation()});_link_data.title&&link.text(_link_data.title),_link_data.title||this.egw().link_title(_link_data.app,_link_data.id,function(title){title?this.removeClass("loading").text(title):this.remove()},link)},getDetachedAttributes:function(_attrs){null==this._labelContainer&&(this._labelContainer=$j(document.createElement("label")).addClass("et2_label"),this.getSurroundings().insertDOMNode(this._labelContainer[0]),this.getSurroundings().update()),_attrs.push("value","label")},getDetachedNodes:function(){return null==this._labelContainer&&(this._labelContainer=$j(document.createElement("label")).addClass("et2_label"),this.getSurroundings().insertDOMNode(this._labelContainer[0])),[this.list[0],this._labelContainer[0]]},setDetachedAttributes:function(_nodes,_values){this.list=$j(_nodes[0]),this.set_value(_values.value),this._labelContainer=_nodes.length>1?$j(_nodes[1]):null,_values.label?this.set_label(_values.label):this._labelContainer&&this._labelContainer.contents().not(this.list).remove()}}))}.call(this);et2_register_widget(et2_link_string,["link-string"]);var et2_link_list=function(){"use strict";return et2_link_string.extend({attributes:{show_deleted:{name:"Show deleted",type:"boolean",default:!1,description:"Show links that are marked as deleted, being held for purge"},onchange:{name:"onchange",type:"js",default:et2_no_init,description:"JS code which is executed when the links change."},readonly:{name:"readonly",type:"boolean",default:!1,description:"Does NOT allow user to enter data, just displays existing data"}},init:function(){this._super.apply(this,arguments),this.list=$j(document.createElement("table")).addClass("et2_link_list"),this.options.class&&this.list.addClass(this.options.class),this.setDOMNode(this.list[0]);var self=this;this.context=new egwMenu,this.context.addItem("comment",this.egw().lang("Comment"),"",function(){var link_id="number"==typeof self.context.data.link_id?self.context.data.link_id:self.context.data.link_id.replace(/[:\.]/g,"_");et2_dialog.show_prompt(function(button,comment){if(button==et2_dialog.OK_BUTTON){var remark=jQuery("#link_"+(self.context.data.dom_id?self.context.data.dom_id:link_id),self.list).children(".remark");if(isNaN(self.context.data.link_id)){if(remark.text(comment),self.context.data.link_id){var _widget=link_id.widget||null;self.getRoot().iterateOver(function(widget){widget.id==self.id&&(_widget=widget)},self,et2_link_to);var value=null!=_widget?_widget.getValue():!1;_widget&&value&&value.to_id&&(value.to_id[self.context.data.link_id].remark=comment)}}else{remark.addClass("loading");egw.json(self.egw().getAppName()+".etemplate_widget_link.ajax_link_comment.etemplate",[link_id,comment],function(){remark&&(remark.removeClass("loading").text(comment+""),self.context.data.remark=comment+"")},this,!0).sendRequest()}}},"",self.egw().lang("Comment"),self.context.data.remark||"")}),this.context.addItem("file_info",this.egw().lang("File information"),this.egw().image("edit"),function(menu_item){var link_data=self.context.data;if("file"==link_data.app){var url="/apps/"+link_data.app2+"/"+link_data.id2+"/"+decodeURIComponent(link_data.id);"string"==typeof url&&url.indexOf("webdav.php")?url=url.replace("/webdav.php",""):"object"==typeof url&&url.path&&(url=url.path),self.egw().open(url,"filemanager","edit")}}),this.context.addItem("-","-"),this.context.addItem("save",this.egw().lang("Save as"),this.egw().image("save"),function(menu_item){var link_data=self.context.data;if(link_data.download_url){var url=link_data.download_url;"/"==url[0]&&(url=egw.link(url));var a=document.createElement("a");if("undefined"==typeof a.download)return window.location=url+"?download",!1;a=$j(a).prop("href",url).prop("download",link_data.title||"").appendTo(self.getInstanceManager().DOMContainer);var evt=document.createEvent("MouseEvent");return evt.initMouseEvent("click",!0,!0,window,1,0,0,0,0,!1,!1,!1,!1,0,null),a[0].dispatchEvent(evt),a.remove(),!1}self.egw().open(link_data,"","view","download",link_data.target?link_data.target:link_data.app,link_data.app)}),this.context.addItem("zip",this.egw().lang("Save as Zip"),this.egw().image("save_zip"),function(menu_item){$j('[id^="link_-"]',this.list).effect("highlight",{},2e3),window.location=self.egw().link("/index.php",{menuaction:"etemplate.etemplate_widget_link.download_zip",app:self.value.to_app,id:self.value.to_id})}),this.context.addItem("-","-"),this.context.addItem("delete",this.egw().lang("Delete link"),this.egw().image("delete"),function(menu_item){var link_id=isNaN(self.context.data.link_id)?self.context.data:self.context.data.link_id,row=jQuery("#link_"+(self.context.data.dom_id?self.context.data.dom_id:self.context.data.link_id),self.list);et2_dialog.show_dialog(function(button){button==et2_dialog.YES_BUTTON&&self._delete_link(link_id,row)},egw.lang("Delete link?"))}),jQuery.event.props.push("dataTransfer")},destroy:function(){this._super.apply(this,arguments),this.context&&(this.context.clear(),delete this.context)},set_value:function(_value){if(this.list.empty(),_value&&"object"==typeof _value){var list=[];if(_value.to_id&&"object"==typeof _value.to_id?list=_value.to_id:_value.length&&(list=_value),list.length>0)for(var id in list){var link=list[id];link.app&&(link.link_id&&"number"!=typeof link.link_id&&(link.dom_id="temp_"+egw.uid()),link.icon||(link.icon=egw.link_get_registry(link.app,"icon"),0==link.icon&&link.id.type&&(link.type=link.id.type,link.icon=!0)),"object"!=typeof link.id||link.title||(link.title=link.id.name||""),this._add_link(link))}else this._super.apply(this,arguments)}},_add_link:function(_link_data){var row=$j(document.createElement("tr")).attr("id","link_"+(_link_data.dom_id?_link_data.dom_id:"string"==typeof _link_data.link_id?_link_data.link_id.replace(/[:\.]/g,"_"):_link_data.link_id||_link_data.id)).attr("draggable","file"==_link_data.app?"true":"").appendTo(this.list);if(!_link_data.link_id)for(var k in _link_data)row[0].dataset[k]=_link_data[k];var icon=$j(document.createElement("td")).appendTo(row).addClass("icon");if(_link_data.icon){var icon_widget=et2_createWidget("image"),src="";if(_link_data.type){var vfs_widget=et2_createWidget("vfs-mime");vfs_widget.set_value({download_url:_link_data.download_url,name:_link_data.title,mime:_link_data.type,path:_link_data.icon}),icon.append(vfs_widget.getDOMNode())}else src=this.egw().image(_link_data.icon),src&&icon_widget.set_src(src),icon.append(icon_widget.getDOMNode())}for(var columns=["title","remark"],self=this,i=0;i<columns.length;i++){var $td=$j(document.createElement("td")).appendTo(row).addClass(columns[i]).text(_link_data[columns[i]]?_link_data[columns[i]]+"":""),dirs=_link_data[columns[i]]?_link_data[columns[i]].split("/"):[];"title"==columns[i]&&_link_data.type&&dirs.length>1&&this._format_vfs($td,dirs,_link_data),!_link_data||"undefined"==typeof _link_data.download_url&&"egw-data"==_link_data.app||$td.click(function(){if("undefined"!=typeof _link_data.type&&_link_data.type.match(self.mime_regexp,"ig")){var $vfs_img_node=jQuery(this).parent().find(".vfsMimeIcon");$vfs_img_node.length>0&&$vfs_img_node.click()}else self.egw().open(_link_data,"","view",null,_link_data.target?_link_data.target:_link_data.app,_link_data.app)})}if("undefined"==typeof _link_data.title){$j("td.title",row).addClass("loading");this.egw().link_title(_link_data.app,_link_data.id,function(title){$j("td.title",this).removeClass("loading").text(title+"")},row)}if(!this.options.readonly){var delete_button=$j(document.createElement("td")).appendTo(row);$j("<div />").appendTo(delete_button).addClass("delete icon").bind("click",function(){et2_dialog.show_dialog(function(button){button==et2_dialog.YES_BUTTON&&self._delete_link(self.value&&"object"!=typeof self.value.to_id&&_link_data.link_id?_link_data.link_id:_link_data,row)},egw.lang("Delete link?"))})}row.bind("contextmenu",function(e){self.context.getItem("comment").set_enabled("undefined"!=typeof _link_data.link_id&&!self.options.readonly),self.context.getItem("file_info").set_enabled("object"!=typeof _link_data.id&&"file"==_link_data.app),self.context.getItem("save").set_enabled("object"!=typeof _link_data.id&&"file"==_link_data.app),self.context.getItem("zip").set_enabled($j('[id^="link_-"]',this.list).length>=2),self.context.getItem("delete").set_enabled(!self.options.readonly),self.context.data=_link_data,self.context.showAt(e.pageX,e.pageY,!0),e.preventDefault()}),navigator&&navigator.userAgent.indexOf("Chrome")>=0&&row.on("dragstart",_link_data,function(event){if(null!=event.dataTransfer){var data=event.data||{};if(data&&data.type&&data.download_url){event.dataTransfer.dropEffect="copy",event.dataTransfer.effectAllowed="copy";var url=data.download_url;"/"==url[0]&&(url=egw.link(url)),"/"==url[0]&&(url=window.location.origin+url),navigator&&navigator.userAgent.indexOf("Chrome")&&event.dataTransfer.setData("DownloadURL",data.type+":"+data.title+":"+url),event.dataTransfer.setData("text/uri-list",url)}if(0==event.dataTransfer.types.length)return void event.preventDefault();var div=$j(document.createElement("div")).attr("id","drag_helper").css({position:"absolute",top:"0px",left:"0px",width:"300px"});div.append(event.target.cloneNode(!0)),self.list.append(div),event.dataTransfer.setDragImage(div.get(0),0,0)}}).on("drag",function(){$j("#drag_helper",self.list).remove()})},_delete_link:function(link_id,row){if(row){var delete_button=jQuery(".delete",row);delete_button.removeClass("delete").addClass("loading"),row.off()}if(this.onchange&&this.onchange(this,link_id,row),"object"!=typeof link_id)egw.json(this.egw().getAppName()+".etemplate_widget_link.ajax_delete.etemplate",[link_id],function(data){data&&row.slideUp(row.remove)}).sendRequest();else if(row&&(row.slideUp(row.remove),link_id.link_id)){var self=this,_widget=link_id.widget||null;this.getRoot().iterateOver(function(widget){widget.id==self.id&&(_widget=widget)},this,et2_link_to);var value=null!=_widget?_widget.getValue():!1;_widget&&value&&value.to_id&&(delete value.to_id[link_id.link_id],_widget.set_value(value))}},_format_vfs:function($td,dirs,_link_data){$td.attr("data-title",_link_data.title);var reformat=!1,span_size=.3,prev=$j("td.title",$td.parent().prev("tr"));if(1===prev.length){var prev_dirs=(prev.attr("data-title")||"").split("/");if(prev_dirs.length>1&&prev_dirs.length==dirs.length)for(var i=0;i<dirs.length&&dirs[i]===prev_dirs[i];i++)reformat=!0,span_size+=dirs[i].length+1,dirs[i]=""}if(reformat)$td.html('<span style="display: inline-block; width:'+span_size+'ex;"></span> - '+dirs.join(""));else{var filename=dirs.pop();span_size+=dirs.join("/").length+1,$td.html('<span style="display: inline-block; width:'+span_size+'ex;">'+dirs.join("/")+":</span> - "+filename)}}})}.call(this);et2_register_widget(et2_link_list,["link-list"]);var et2_link_add=function(){"use strict";return et2_inputWidget.extend({attributes:{value:{description:"Either an array of link information (see egw_link::link()) or array with keys to_app and to_id",type:"any"},application:{name:"Application",type:"string",default:"",description:"Limit to the listed application or applications (comma seperated)"}},init:function(){this._super.apply(this,arguments),this.span=jQuery(document.createElement("span")).text(this.egw().lang("Add new")).addClass("et2_link_add_span"),this.div=jQuery(document.createElement("div")).append(this.span),this.setDOMNode(this.div[0])},doLoadingFinished:function(){if(this._super.apply(this,arguments),this.app_select&&this.button)return!1;this.app_select=et2_createWidget("link-apps",jQuery.extend({},this.options,{id:this.options.id+"app",value:this.options.application?this.options.application:this.options.value&&this.options.value.add_app?this.options.value.add_app:null,application_list:this.options.application?this.options.application:null}),this),this.div.append(this.app_select.getDOMNode()),this.button=et2_createWidget("button",{id:this.options.id+"_add",label:this.egw().lang("add")},this),this.button.set_label(this.egw().lang("add"));var self=this;return this.button.click=function(){self.egw().open(self.options.value.to_app+":"+self.options.value.to_id,self.app_select.get_value(),"add")},this.div.append(this.button.getDOMNode()),!0},getValue:function(){return null}})}.call(this);et2_register_widget(et2_link_add,["link-add"]);var et2_selectAccount=function(){"use strict";return et2_selectbox.extend({attributes:{account_type:{name:"Account type",default:"accounts",type:"string",description:"Limit type of accounts. One of {accounts,groups,both,owngroups}."}},legacyOptions:["empty_label","account_type"],account_types:["accounts","groups","both","owngroups"],init:function(_parent,_attrs){jQuery.inArray(_attrs.empty_label,this.account_types)>0&&(jQuery.inArray(_attrs.account_type,this.account_types)<0||_attrs.account_type==this.attributes.account_type.default)&&(_attrs.account_type=_attrs.empty_label,_attrs.empty_label=""),jQuery.inArray(_attrs.account_type,this.account_types)<0&&this.egw().debug("warn","Invalid account_type: %s Valid options:",_attrs.account_type,this.account_types),this.search=null,this.dialog=null,this._super.call(this,_parent,_attrs),this.supportedWidgetClasses=[et2_link_entry]},destroy:function(){this._super.apply(this,arguments)},createInputWidget:function(){var type=this.egw().preference("account_selection","common");switch(type){case"none":if("undefined"==typeof egw.user("apps").admin){this.options.select_options={};break}case"selectbox":case"groupmembers":default:this.options.select_options=this._get_accounts()}if(this._super.apply(this,arguments),"primary_group"==type){var button=jQuery(document.createElement("span")).addClass("et2_clickable").click(this,jQuery.proxy(function(e){this.options.expand_multiple_rows&&!this.options.multiple&&this.set_multiple(!0,this.options.expand_multiple_rows),this.options.multiple?this._open_multi_search(e):this._open_search(e)},this)).attr("title",egw.lang("popup with search")).append('<span class="ui-icon ui-icon-search" style="display:inline-block"/>');this.getSurroundings().insertDOMNode(button[0])}},createMultiSelect:function(){var type=this.egw().preference("account_selection","common");if(("none"!=type||"undefined"!=typeof egw.user("apps").admin)&&(this._super.apply(this,arguments),this.options.select_options=this._get_accounts(),"primary_group"==type)){this.supportedWidgetClasses=[et2_link_entry],this.options.multiple=!1,this._create_search();var old_select=this.search_widget.select,self=this;this.search_widget.select=function(e,selected){var current=self.getValue();selected.item.value=parseInt(selected.item.value),old_select.apply(this,arguments),current.push(selected.item.value),this.search.val(""),self.set_value(current)},this.search_widget.search.on("autocompleteopen",jQuery.proxy(function(){this.search_widget.search.data("ui-autocomplete").menu.element.appendTo(this.node).position({my:"left top",at:"left bottom",of:this.multiOptions.prev()})},this)),this.search=jQuery(document.createElement("li")).appendTo(this.multiOptions.prev().find("ul")),this.options.multiple=!0;var button=jQuery(document.createElement("li")).addClass("et2_clickable").click(this,this._open_multi_search).attr("title",egw.lang("popup with search")).append('<span class="ui-icon ui-icon-search"/>'),type=this.egw().preference("account_selection","common");this.multiOptions.prev().find("ul").append(button)}},set_value:function(_value){if("string"==typeof _value&&this.options.multiple&&null!==_value.match(this._is_multiple_regexp)&&(_value=_value.split(",")),_value){var search=_value;jQuery.isArray(search)||(search=[_value]);for(var update_options=!1,num_calls=0,current_call=0,j=0;j<search.length;j++){var found=!1;if(search[j]&&"0"!==search[j]){for(var i=0;!found&&i<this.options.select_options.length;i++)"object"==typeof this.options.select_options[i]?this.options.select_options[i].value==search[j]&&(found=!0):egw.debug("warn",this.id+" wrong option "+i+" this.options.select_options=",this.options.select_options);if(!found){var name=this.egw().link_title("home-accounts",search[j]);name?(update_options=!0,this.options.select_options.push({value:search[j],label:name})):(++num_calls,this._appendOptionElement(search[j],search[j]),this.egw().link_title("home-accounts",search[j],function(name){if(++current_call>=num_calls){for(var i=0;i<this.widget.options.select_options.length;i++){var opt=this.widget.options.select_options[i];if(opt&&opt.value&&opt.value==this.unknown&&opt.label==this.unknown){opt.label=name,this.widget.set_select_options(this.widget.options.select_options);break}}this.widget.set_value(_value)}},{widget:this,unknown:search[j]}))}}}update_options&&this.set_select_options(this.options.select_options)}this._super.apply(this,arguments)},_get_accounts:function(){if(!jQuery.isArray(this.options.select_options)){var options=jQuery.extend({},this.options.select_options);this.options.select_options=[];for(var key in options)"object"==typeof options[key]?("undefined"==typeof options[key].key&&(options[key].value=key),this.options.select_options.push(options[key])):this.options.select_options.push({value:key,label:options[key]})}var type=this.egw().preference("account_selection","common"),accounts=[];return"primary_group"==type&&"accounts"!=this.options.account_type?("both"==this.options.account_type&&(accounts=this.egw().accounts("accounts")),accounts=accounts.concat(this.egw().accounts("owngroups"))):accounts=this.egw().accounts(this.options.account_type),this.options.select_options.concat(accounts)},_open_search:function(e){var widget=e.data,search=widget._create_search(),ok_click=function(){jQuery(this).dialog("close"),widget.set_value([]),widget.input&&widget.input.trigger("change"),jQuery(this).dialog("destroy")};widget._create_dialog(search,ok_click)},_open_multi_search:function(e){var widget=e&&e.data?e.data:this,table=widget.search=jQuery('<table><tbody><tr valign="top"><td id="search_col"/><td id="selection_col"/></tr></tbody></table>');table.css("width","100%").css("height","100%");var search_col=jQuery("#search_col",table),select_col=jQuery("#selection_col",table);search_col.append(widget._create_search()),select_col.append(widget._create_selected());var ok_click=function(){jQuery(this).dialog("close");var ids=[];jQuery("#"+widget.getInstanceManager().uniqueId+"_selected li",select_col).each(function(){var id=$j(this).attr("data-id");ids.push(id),widget.options.multiple||0!=jQuery('input[id$="_opt_'+id+'"]',widget.multiOptions).length?widget.options.multiple&&0==jQuery('option[value="'+id+'"]',widget.node).length&&widget._appendOptionElement(id,jQuery("label",this).text()):widget._appendMultiOption(id,jQuery("label",this).text())}),widget.set_value(ids),jQuery(this).dialog("destroy"),widget.input&&widget.input.trigger("change")},container=jQuery(document.createElement("div")).append(table);return widget._create_dialog(container,ok_click)},_create_dialog:function(widgets,update_function){return this.dialog=widgets,widgets.dialog({title:this.options.label?this.options.label:this.egw().lang("Select"),modal:!0,width:"500",height:"350",buttons:[{text:this.egw().lang("ok"),click:update_function},{text:this.egw().lang("cancel"),click:function(){jQuery(this).dialog("close"),jQuery(this).dialog("destroy")}}]}),widgets},_create_search:function(){var self=this,search=this.search=jQuery(document.createElement("div")),search_widget=this.search_widget=et2_createWidget("link-entry",{only_app:"home-accounts",query:function(request,response){return request.options||search.find("#search_results").empty(),request.options&&request.options.filter||(request.options={account_type:self.options.account_type}),!0},select:function(e,selected){var already_there=!1,last_key=null;for(last_key in self.options.select_options){var option=self.options.select_options[last_key];already_there=already_there||"undefined"!=typeof option.value&&option.value==selected.item.value}return already_there||(self.options.select_options[parseInt(last_key)+1]=selected.item,self._appendOptionElement(selected.item.value,selected.item.label)),self.set_value(selected.item.value),self.dialog&&(self.dialog.dialog("close"),self.dialog.dialog("destroy")),self.input&&self.input.trigger("change"),!0}},this);if(search.append(search_widget.getDOMNode()),!this.options.multiple)return search;var results=jQuery(document.createElement("ul")).attr("id","search_results").css("height","230px").addClass("ui-multiselect-checkboxes ui-helper-reset");return jQuery(document.createElement("div")).addClass("et2_selectbox").css("height","100%").append(results).appendTo(search),search_widget.search.data("ui-autocomplete")._suggest=function(items){jQuery.each(items,function(index,item){item.value=parseInt(item.value),self._add_search_result(results,item)})},search},_add_search_result:function(list,item){var node=null,self=this;item.value&&(item.value=parseInt(item.value));var selected=jQuery("#"+this.getInstanceManager().uniqueId+"_selected",this.dialog);item.value&&item.value<0?(node=jQuery(document.createElement("ul")),"groups"!=this.options.account_type&&jQuery('<span class="ui-icon ui-icon-circlesmall-plus et2_clickable"/>').css("float","left").appendTo(node).click(function(){if(jQuery(this).hasClass("ui-icon-circlesmall-plus")){jQuery(this).removeClass("ui-icon-circlesmall-plus").addClass("ui-icon-circlesmall-minus");var group=jQuery(this).parent().addClass("expanded");0==group.children("li").length?self.search_widget.query({term:"",options:{filter:{group:item.value}},no_cache:!0},function(items){jQuery(items).each(function(index,item){self._add_search_result(node,item)})}):group.children("li").each(function(index,item){var j=jQuery(item);0==jQuery('[data-id="'+j.attr("data-id")+'"]',selected).length&&j.show()})}else{jQuery(this).addClass("ui-icon-circlesmall-plus").removeClass("ui-icon-circlesmall-minus");var group=jQuery(this).parent().children("li").hide()}})):item.value&&(node=jQuery(document.createElement("li"))),node.attr("data-id",item.value),jQuery('<span class="ui-icon ui-icon-arrow-1-e et2_clickable"/>').css("float","right").appendTo(node).click(function(){var button=jQuery(this);self._add_selected(selected,button.parent().attr("data-id")),button.parent().is("li")?button.parent().hide():button.hide()}),0!=jQuery('[data-id="'+item.value+'"]',selected).length&&node.hide();var label=jQuery(document.createElement("label")).addClass("loading").appendTo(node);this.egw().link_title("home-accounts",item.value,function(name){label.text(name).removeClass("loading")},label),node.appendTo(list)},_create_selected:function(){var node=jQuery(document.createElement("div")).addClass("et2_selectbox"),header=jQuery(document.createElement("div")).addClass("ui-widget-header ui-helper-clearfix").appendTo(node),selected=jQuery(document.createElement("ul")).addClass("ui-multiselect-checkboxes ui-helper-reset").attr("id",this.getInstanceManager().uniqueId+"_selected").css("height","230px").appendTo(node);jQuery(document.createElement("span")).text(this.egw().lang("Selection")).addClass("ui-multiselect-header").appendTo(header);var controls=jQuery(document.createElement("ul")).addClass("ui-helper-reset").appendTo(header);if(jQuery(document.createElement("li")).addClass("et2_clickable").click(selected,function(e){jQuery("li",e.data).remove()}).append('<span class="ui-icon ui-icon-closethick"/>').appendTo(controls),this.getValue())for(var value=this.getValue(),i=0;i<value.length;i++)this._add_selected(selected,value[i]);return node},_add_selected:function(list,value){var there=jQuery('[data-id="'+value+'"]',list);if(there.length)return void there.show();var option=jQuery(document.createElement("li")).attr("data-id",value).appendTo(list);jQuery('<div class="ui-icon ui-icon-close et2_clickable"/>').css("float","right").appendTo(option).click(function(){var id=jQuery(this).parent().attr("data-id");jQuery(this).parent().remove(),list.parents("tr").find("[data-id='"+id+"']").show().children("span").show()});var label=jQuery(document.createElement("label")).addClass("loading").appendTo(option);this.egw().link_title("home-accounts",value,function(name){this.text(name).removeClass("loading")},label)},attachToDOM:function(){this._super.apply(this,arguments),"primary_group"==this.egw().preference("account_selection","common")&&(jQuery(this.node).removeClass("chzn-done"),this.set_tags(this.options.tags,this.options.width))}})}.call(this);et2_register_widget(et2_selectAccount,["select-account"]);var et2_selectAccount_ro=function(){"use strict";return et2_link_string.extend([et2_IDetachedDOM],{attributes:{empty_label:{name:"Empty label",type:"string",default:"",description:"Textual label for first row, eg: 'All' or 'None'. ID will be ''",translate:!0}},legacyOptions:["empty_label"],init:function(_parent,options){_parent.supportedWidgetClasses.indexOf(et2_selectAccount_ro)<0&&_parent.supportedWidgetClasses.push(et2_selectAccount_ro),this._super.apply(this,arguments),"string"==typeof this.options.empty_label&&isNaN(this.options.empty_label)&&(this.options.empty_label=this.egw().lang(this.options.empty_label)),this.options.application="home-accounts";var options=et2_selectbox.find_select_options(this,options.select_options);jQuery.isEmptyObject(options)||(this.options.select_options=options),this.list.removeClass("et2_link_string").addClass("et2_selectbox")},transformAttributes:function(_attrs){et2_selectbox.prototype.transformAttributes.apply(this,arguments)},set_value:function(_value){if("string"==typeof _value&&_value.indexOf(",")>0&&(_value=_value.split(",")),"object"==typeof _value||!isNaN(_value)&&""!=_value)return this._super.apply(this,arguments),void jQuery("li",this.list).removeClass("et2_link et2_link_string").off();if(jQuery("li",this.list).removeClass("et2_link et2_link_string").off(),this.options.select_options&&!jQuery.isEmptyObject(this.options.select_options)||this.options.empty_label)if(_value)if("object"==typeof _value)for(var i=0;i<_value.length;i++){if(!_value[i]||!parseInt(_value[i]))return void this.list.append("<li>"+this.options.empty_label+"</li>");this.options.select_options[_value]&&this.list.append("<li>"+this.options.select_options[_value]+"</li>")}else{var search=_value;jQuery.isArray(search)||(search=[_value]);for(var j=0;j<search.length;j++){if(search[j])for(var i in this.options.select_options)if(this.options.select_options[i].value==search[j]){this.list.append("<li>"+this.options.select_options[i].label+"</li>");break}}}else this.list.append("<li>"+this.options.empty_label+"</li>")}})}.call(this);et2_register_widget(et2_selectAccount_ro,["select-account_ro"]);var et2_customfields_list=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM,et2_IInput],{attributes:{customfields:{name:"Custom fields",description:"Auto filled",type:"any"},fields:{name:"Custom fields",description:"Auto filled",type:"any"},value:{name:"Custom fields",description:"Auto filled",type:"any"},type_filter:{name:"Field filter",default:"",type:"any",description:"Filter displayed custom fields by their 'type2' attribute"},private:{ignore:!0,type:"boolean"}},legacyOptions:["type_filter","private","fields"],prefix:"#",DEFAULT_ID:"custom_fields",init:function(){if(arguments[1].id||(arguments[1].id=this.DEFAULT_ID),this._super.apply(this,arguments),"undefined"!=typeof this.options.prefix&&(this.prefix=this.options.prefix),this.tbody=$j(document.createElement("tbody")),this.table=$j(document.createElement("table")).addClass("et2_grid et2_customfield_list"),this.table.append(this.tbody),this.rows={},this.widgets={},this.detachedNodes=[],this.options.fields||(this.options.fields={}),this.options.type_filter&&"string"==typeof this.options.type_filter&&(this.options.type_filter=this.options.type_filter.split(",")),this.options.type_filter){var already_filtered=!jQuery.isEmptyObject(this.options.fields);for(var field_name in this.options.customfields)if(!already_filtered||this.options.fields[field_name])if(this.options.customfields[field_name].type2&&0!=this.options.customfields[field_name].type2.length&&"0"!=this.options.customfields[field_name].type2){var types="string"==typeof this.options.customfields[field_name].type2?this.options.customfields[field_name].type2.split(","):this.options.customfields[field_name].type2;this.options.fields[field_name]=!1;for(var i=0;i<types.length;i++)jQuery.inArray(types[i],this.options.type_filter)>-1&&(this.options.fields[field_name]=!0)}else this.options.fields[field_name]=!0}this.setDOMNode(this.table[0])},destroy:function(){this._super.apply(this,arguments),this.rows={},this.widgets={},this.detachedNodes=[],this.tbody=null},assign:function(_obj){this.loadFields()},getDOMNode:function(_sender){return this.rows&&_sender.id&&this.rows[_sender.id]?this.rows[_sender.id]:this._super.apply(this,arguments)},loadFields:function(){if(this.options&&this.options.customfields&&("customfields-list"!=this._type||this.isInTree())&&jQuery.isEmptyObject(this.widgets)){var global_data=this.getArrayMgr("modifications").getRoot().getEntry("~custom_fields~");global_data&&global_data.fields&&!this.options.fields&&(this.options.fields=global_data.fields);var apps=this.egw().link_app_list();for(var field_name in this.options.customfields)if("customfields-list"==this._type||jQuery.isEmptyObject(this.options.fields)||this.options.fields[field_name]){var field=this.options.customfields[field_name],id=this.prefix+field_name;if("$row"==this.id?id="{"+this.id+"}["+this.prefix+field_name+"]":this.id!=this.DEFAULT_ID&&(id=this.id+"["+id+"]"),!this.rows[id]){var row=jQuery(document.createElement("tr")).appendTo(this.tbody).addClass(this.id+"_"+id),cf=jQuery(document.createElement("td")).appendTo(row);field.type||(field.type='text";');var setup_function="_setup_"+(apps[field.type]?"link_entry":field.type.replace("-","_")),attrs={id:id,statustext:field.help,needed:field.needed,readonly:this.getArrayMgr("readonlys").isReadOnly(id,null,this.options.readonly),value:this.options.value[this.prefix+field_name]};if(attrs.readonly===!0&&delete attrs.needed,this[setup_function]){var no_skip=this[setup_function].call(this,field_name,field,attrs);if(!no_skip)continue}if("customfields-list"==this._type?(attrs.readonly=!0,row.attr("title",field.label),row.attr("data-label",field.label),row.attr("data-field",field_name),row.attr("data-help",field.help),this.detachedNodes.push(row[0])):(cf.text(field.label+""),cf=jQuery(document.createElement("td")).appendTo(row)),this.rows[id]=cf[0],-1==["select","radio","radiogroup","checkbox","button"].indexOf(field.type)&&!jQuery.isEmptyObject(field.values)){var w=et2_registry[attrs.type?attrs.type:field.type];for(var attr_name in field.values)"undefined"!=typeof w.prototype.attributes[attr_name]&&(attrs[attr_name]=field.values[attr_name])}this.widgets[field_name]=et2_createWidget(attrs.type?attrs.type:field.type,attrs,this)}!this.options.fields||jQuery.isEmptyObject(this.options.fields)||1==this.options.fields[field_name]?jQuery(this.rows[field_name]).show():jQuery(this.rows[field_name]).hide()}}},transformAttributes:function(_attrs){
this._super.apply(this,arguments);var data=this.getArrayMgr("modifications").getEntry(this.id),global_data=this.getArrayMgr("modifications").getRoot().getEntry("~custom_fields~",!0);if(global_data)for(var key in data)global_data[key]&&"fields"!==key&&(data[key]=jQuery.extend(!0,{},data[key],global_data[key]));for(var key in data)_attrs[key]=data[key];for(var key in global_data)"undefined"==typeof global_data[key]||_attrs[key]||(_attrs[key]=global_data[key]);if(this.id){var contentMgr=this.getArrayMgr("content");if(null!=contentMgr){var val=contentMgr.getEntry(this.id);if(_attrs.value={},null!==val)if(0===this.id.indexOf(this.prefix)&&"undefined"!=typeof data.fields&&data.fields[this.id.replace(this.prefix,"")]===!0)_attrs.value[this.id]=val;else for(var key in val)0==key.indexOf(this.prefix)&&(_attrs.value[key]=val[key]);else for(var key in _attrs.customfields)_attrs.value[this.prefix+key]=contentMgr.getEntry(this.prefix+key)}}},loadFromXML:function(_node){this.loadFields(),this._super.apply(this,arguments)},set_value:function(_value){if(this.options.customfields)for(var field_name in this.options.customfields)if((jQuery.isEmptyObject(this.options.fields)||this.options.fields[field_name])&&this.widgets[field_name]&&this.widgets[field_name].set_value){var value=_value[this.prefix+field_name]?_value[this.prefix+field_name]:null;switch(null==value&&this.id==this.DEFAULT_ID&&this.getArrayMgr("content").getEntry(this.prefix+field_name)&&(value=this.getArrayMgr("content").getEntry(this.prefix+field_name)),this.options.customfields[field_name].type){case"date":value&&isNaN(value)&&(value=jQuery.datepicker.parseDate("yy-mm-dd",value))}this.widgets[field_name].set_value(value)}},getValue:function(){if(this.id!=this.DEFAULT_ID)return null;var value={};for(var field_name in this.widgets)this.widgets[field_name].getValue&&!this.widgets[field_name].options.readonly&&(value[this.prefix+field_name]=this.widgets[field_name].getValue());return value},isDirty:function(){var dirty=!0;for(var field_name in this.widgets)this.widgets[field_name].isDirty&&(dirty=dirty&&this.widgets[field_name].isDirty());return dirty},resetDirty:function(){for(var field_name in this.widgets)this.widgets[field_name].resetDirty&&this.widgets[field_name].resetDirty()},isValid:function(){return!0},_setup_text:function(field_name,field,attrs){return delete attrs.label,field.type="textbox",attrs.rows=field.rows>1?field.rows:null,field.len&&(attrs.size=field.len,1==field.rows&&(attrs.maxlength=field.len)),!0},_setup_ajax_select:function(field_name,field,attrs){var attributes=["get_rows","get_title","id_field","template"];if(field.values)for(var i=0;i<attributes.length;i++)"undefined"!=typeof field.values[attributes[i]]&&(attrs[attributes[i]]=field.values[attributes[i]]);return!0},_setup_float:function(field_name,field,attrs){return delete attrs.label,field.type="float",field.len&&(attrs.size=field.len),!0},_setup_select:function(field_name,field,attrs){return delete attrs.label,attrs.rows=field.rows,attrs.tags=field.tags,!0},_setup_select_account:function(field_name,field,attrs){return attrs.empty_label=egw.lang("Select"),this._setup_select(field_name,field,attrs)},_setup_date:function(field_name,field,attrs){return attrs.data_format="Y-m-d",!0},_setup_date_time:function(field_name,field,attrs){return attrs.data_format="Y-m-d H:i:s",!0},_setup_htmlarea:function(field_name,field,attrs){attrs.config=field.config?field.config:{},attrs.config.toolbarStartupExpanded=!1,field.len&&(attrs.config.width=field.len+"px"),attrs.config.height=16*(field.rows>0&&"undefined"!=field.rows?field.rows:5)+"px";var data=this.getArrayMgr("modifications").getEntry(this.prefix+field_name);return data&&jQuery.extend(data.config,attrs.config),!0},_setup_radio:function(field_name,field,attrs){return delete attrs.label,field.values&&field.values[""]&&(attrs.label=field.values[""],delete field.values[""]),field.type="radiogroup",attrs.options=field.values,!0},_setup_checkbox:function(field_name,field,attrs){return attrs.readonly&&(attrs.ro_true=field.label),!0},_setup_button:function(field_name,field,attrs){if(delete attrs.label,attrs.label=field.label,"customfields-list"==this._type)return!1;if(field.values&&"object"==typeof field.values&&1!=Object.keys(field.values).length){var row=$j("tr",this.tbody).last(),cf=$j("td",row);cf.text(field.label+""),cf=jQuery(document.createElement("td")).appendTo(row);for(var key in field.values){var button_attrs=jQuery.extend({},attrs);button_attrs.label=key,button_attrs.onclick=field.values[key],button_attrs.id=attrs.id+"_"+key,this.rows[button_attrs.id]=cf[0],et2_createWidget(attrs.type?attrs.type:field.type,button_attrs,this)}return!1}for(var key in field.values)attrs.label=key,attrs.onclick=field.values[key];return attrs.label||(attrs.label='No "label=onclick" in values!',attrs.onclick=function(){return!1}),!attrs.readonly},_setup_link_entry:function(field_name,field,attrs){return"filemanager"===field.type?this._setup_filemanager(field_name,field,attrs):(delete attrs.label,attrs.type="link-entry",attrs.only_app=field.type,!0)},_setup_filemanager:function(field_name,field,attrs){if(attrs.type="vfs-upload",delete attrs.label,"customfields-list"==this._type)return!0;var row=$j("tr",this.tbody).last(),cf=$j("td",row);cf.text(field.label+""),cf=jQuery(document.createElement("td")).appendTo(row);var widget=this.widgets[field_name]=et2_createWidget(attrs.type?attrs.type:field.type,attrs,this);this.rows[attrs.id]=cf[0],$j(widget.getDOMNode(widget)).css("vertical-align","top");var select_attrs=jQuery.extend({},attrs,{label:"",method:"etemplate_widget_link::link_existing",method_id:attrs.path,button_label:egw.lang("Link")},{type:"vfs-select"});return select_attrs.id=attrs.id+"_vfs_select",this.rows[select_attrs.id]=cf[0],widget=et2_createWidget(select_attrs.type,select_attrs,this),$j(widget.getDOMNode(widget)).css("vertical-align","top").prependTo(cf),!1},set_visible:function(_fields){for(var name in _fields)this.rows[this.prefix+name]&&(_fields[name]?jQuery(this.rows[this.prefix+name]).show():jQuery(this.rows[this.prefix+name]).hide()),this.options.fields[name]=_fields[name]},getDetachedAttributes:function(_attrs){_attrs.push("value","class")},getDetachedNodes:function(){return this.detachedNodes?this.detachedNodes:[]},setDetachedAttributes:function(_nodes,_values){for(var i=0;i<_nodes.length;i++){var key=_nodes[i].getAttribute("data-field");$j(_nodes[i]).toggle(!(!_values.fields[key]||!_values.value[this.prefix+key]))}}})}.call(this);et2_register_widget(et2_customfields_list,["customfields","customfields-list"]);var et2_dataview_IInvalidatable=new Interface({invalidate:function(){}}),et2_dataview_IViewRange=new Interface({setViewRange:function(_range){}}),et2_IDataProvider=new Interface({dataFetch:function(_queriedRange,_lastModification,_callback,_context){},dataRegisterUID:function(_uid,_callback,_context){},dataUnregisterUID:function(_uid,_callback,_context){}}),et2_dataview_container=function(){"use strict";return Class.extend(et2_dataview_IInvalidatable,{init:function(_parent){this._parent=_parent,this._nodes=[],this._inTree=!1,this._attachData={node:null,prepend:!1},this._destroyCallback=null,this._destroyContext=null,this._height=!1,this._index=0,this._top=0},destroy:function(){this.removeFromTree(),this._destroyCallback&&this._destroyCallback.call(this._destroyContext,this)},setDestroyCallback:function(_callback,_context){this._destroyCallback=_callback,this._destroyContext=_context},insertIntoTree:function(_node,_prepend){if(!this._inTree&&null!=_node&&this._nodes.length>0){this._attachData={node:_node,prepend:_prepend},this._inTree=!0;for(var i=0;i<this._nodes.length;i++)0==i?_prepend?_node.before(this._nodes[0]):_node.after(this._nodes[0]):this._nodes[i-1].after(this._nodes[i]);this.invalidate()}},removeFromTree:function(){if(this._inTree){for(var i=0;i<this._nodes.length;i++)this._nodes[i].remove();this._inTree=!1,this._attachData={node:null,prepend:!1}}},appendNode:function(_node){this._nodes.push(_node),this._inTree&&(1===this._nodes.length?this._attachData.prepend?this._attachData.node.before(_node):this._attachData.node.after(_node):this._nodes[this._nodes.length-2].after(_node),this.invalidate())},removeNode:function(_node){var idx=this._nodes.indexOf(_node);idx>=0&&(this._inTree&&_node.parentNode.removeChild(_node),this._nodes.splice(idx,1))},getLastNode:function(){return this._nodes.length>0?this._nodes[this._nodes.length-1]:null},getFirstNode:function(){return this._nodes.length>0?this._nodes[0]:null},getHeight:function(){if(this._height===!1&&this._inTree){this._height=0;for(var i=0;i<this._nodes.length;i++)this._isVisible(this._nodes[i][0])&&(this._height+=this._nodeHeight(this._nodes[i][0]))}return this._height===!1?0:this._height},getAvgHeightData:function(){return{avgHeight:this.getHeight(),avgCount:1}},getTop:function(){return this._top},getBottom:function(){return this._top+this.getHeight()},getRange:function(){return et2_bounds(this.getTop(),this.getBottom())},getIndex:function(){return this._index},getCount:function(){return 1},setTop:function(_value){this._top=_value},setIndex:function(_value){this._index=_value},invalidate:function(){this._height!==!1&&(this._height=!1,this._parent.invalidate())},_isVisible:function(_obj){if(_obj.style&&("none"===_obj.style.display||"none"===_obj.style.visiblity))return!1;var style=window.getComputedStyle?window.getComputedStyle(_obj,null):_obj.currentStyle;return"none"!==style.display&&"none"!==style.visibility},_nodeHeight:function(_node){return _node.offsetHeight}})}.call(this),et2_dataview_row=function(){"use strict";return et2_dataview_container.extend(et2_dataview_IViewRange,{init:function(_parent){this._super(_parent),this.tr=$j(document.createElement("tr")),this.appendNode(this.tr),this.expansionContainer=null,this.expansionVisible=!1,this.expansionButton=null},destroy:function(){null!=this.expansionContainer&&this.expansionContainer.free(),this._super()},clear:function(){this.tr.empty()},makeExpandable:function(_expandable,_callback,_context){if(_expandable){this.expansionButton||(this.expansionButton=$j(document.createElement("span")),this.expansionButton.addClass("arrow closed"));var self=this;this.expansionButton.off("click").on("click",function(e){self._handleExpansionButtonClick(_callback,_context),e.stopImmediatePropagation()}),$j("td:first",this.tr).prepend(this.expansionButton)}else this.expansionButton&&this.expansionButton.remove(),this.expansionContainer&&this.expansionContainer.free(),this.expansionButton=null,this.expansionContainer=null},removeFromTree:function(){this.expansionContainer&&this.expansionContainer.removeFromTree(),this.expansionContainer=null,this.expansionButton=null,this._super()},getDOMNode:function(){return this.tr[0]},getJNode:function(){return this.tr},getHeight:function(){var h=this._super();return this.expansionContainer&&this.expansionVisible&&(h+=this.expansionContainer.getHeight()),h},getAvgHeightData:function(){this.expansionVisible=!1;var res={avgHeight:this.getHeight(),avgCount:1};return this.expansionVisible=!0,res},_handleExpansionButtonClick:function(_callback,_context){this.expansionContainer||(this.expansionContainer=_callback.call(_context),this.expansionContainer.insertIntoTree(this.tr),this.expansionVisible=!1),this.expansionVisible=!this.expansionVisible,$j(this.expansionContainer._nodes[0]).toggle(this.expansionVisible),this.expansionVisible?(this.expansionButton.addClass("opened"),this.expansionButton.removeClass("closed")):(this.expansionButton.addClass("closed"),this.expansionButton.removeClass("opened")),this.invalidate()},setViewRange:function(_range){if(this.expansionContainer&&this.expansionVisible&&this.expansionContainer.implements(et2_dataview_IViewRange)){var oh=$j(this._nodes[0]).height();_range.top-=oh,this.expansionContainer.setViewRange(_range)}}})}.call(this);!function(factory){"function"==typeof define&&define.amd&&define.amd.jQuery?define(["jquery"],factory):factory(jQuery)}(function($){"use strict";function init(options){return!options||void 0!==options.allowPageScroll||void 0===options.swipe&&void 0===options.swipeStatus||(options.allowPageScroll=NONE),void 0!==options.click&&void 0===options.tap&&(options.tap=options.click),options||(options={}),options=$.extend({},$.fn.swipe.defaults,options),this.each(function(){var $this=$(this),plugin=$this.data(PLUGIN_NS);plugin||(plugin=new TouchSwipe(this,options),$this.data(PLUGIN_NS,plugin))})}function TouchSwipe(element,options){function touchStart(jqEvent){if(!(getTouchInProgress()||$(jqEvent.target).closest(options.excludedElements,$element).length>0)){var ret,event=jqEvent.originalEvent?jqEvent.originalEvent:jqEvent,evt=SUPPORTS_TOUCH?event.touches[0]:event;return phase=PHASE_START,SUPPORTS_TOUCH?fingerCount=event.touches.length:jqEvent.preventDefault(),distance=0,direction=null,pinchDirection=null,duration=0,startTouchesDistance=0,endTouchesDistance=0,pinchZoom=1,pinchDistance=0,fingerData=createAllFingerData(),maximumsMap=createMaximumsData(),cancelMultiFingerRelease(),!SUPPORTS_TOUCH||fingerCount===options.fingers||options.fingers===ALL_FINGERS||hasPinches()?(createFingerData(0,evt),startTime=getTimeStamp(),2==fingerCount&&(createFingerData(1,event.touches[1]),startTouchesDistance=endTouchesDistance=calculateTouchesDistance(fingerData[0].start,fingerData[1].start)),(options.swipeStatus||options.pinchStatus)&&(ret=triggerHandler(event,phase))):ret=!1,ret===!1?(phase=PHASE_CANCEL,triggerHandler(event,phase),ret):(options.hold&&(holdTimeout=setTimeout($.proxy(function(){$element.trigger("hold",[event.target]),options.hold&&(ret=options.hold.call($element,event,event.target))},this),options.longTapThreshold)),setTouchInProgress(!0),null)}}function touchMove(jqEvent){var event=jqEvent.originalEvent?jqEvent.originalEvent:jqEvent;if(phase!==PHASE_END&&phase!==PHASE_CANCEL&&!inMultiFingerRelease()){var ret,evt=SUPPORTS_TOUCH?event.touches[0]:event,currentFinger=updateFingerData(evt);if(endTime=getTimeStamp(),SUPPORTS_TOUCH&&(fingerCount=event.touches.length),options.hold&&clearTimeout(holdTimeout),phase=PHASE_MOVE,2==fingerCount&&(0==startTouchesDistance?(createFingerData(1,event.touches[1]),startTouchesDistance=endTouchesDistance=calculateTouchesDistance(fingerData[0].start,fingerData[1].start)):(updateFingerData(event.touches[1]),endTouchesDistance=calculateTouchesDistance(fingerData[0].end,fingerData[1].end),pinchDirection=calculatePinchDirection(fingerData[0].end,fingerData[1].end)),pinchZoom=calculatePinchZoom(startTouchesDistance,endTouchesDistance),pinchDistance=Math.abs(startTouchesDistance-endTouchesDistance)),fingerCount===options.fingers||options.fingers===ALL_FINGERS||!SUPPORTS_TOUCH||hasPinches()){if(direction=calculateDirection(currentFinger.start,currentFinger.end),validateDefaultEvent(jqEvent,direction),distance=calculateDistance(currentFinger.start,currentFinger.end),duration=calculateDuration(),setMaxDistance(direction,distance),(options.swipeStatus||options.pinchStatus)&&(ret=triggerHandler(event,phase)),!options.triggerOnTouchEnd||options.triggerOnTouchLeave){var inBounds=!0;if(options.triggerOnTouchLeave){var bounds=getbounds(this);inBounds=isInBounds(currentFinger.end,bounds)}!options.triggerOnTouchEnd&&inBounds?phase=getNextPhase(PHASE_MOVE):options.triggerOnTouchLeave&&!inBounds&&(phase=getNextPhase(PHASE_END)),phase!=PHASE_CANCEL&&phase!=PHASE_END||triggerHandler(event,phase)}}else phase=PHASE_CANCEL,triggerHandler(event,phase);ret===!1&&(phase=PHASE_CANCEL,triggerHandler(event,phase))}}function touchEnd(jqEvent){var event=jqEvent.originalEvent;return SUPPORTS_TOUCH&&event.touches.length>0?(startMultiFingerRelease(),!0):(inMultiFingerRelease()&&(fingerCount=previousTouchFingerCount),endTime=getTimeStamp(),duration=calculateDuration(),didSwipeBackToCancel()||!validateSwipeDistance()?(phase=PHASE_CANCEL,triggerHandler(event,phase)):options.triggerOnTouchEnd||0==options.triggerOnTouchEnd&&phase===PHASE_MOVE?(jqEvent.preventDefault(),phase=PHASE_END,triggerHandler(event,phase)):!options.triggerOnTouchEnd&&hasTap()?(phase=PHASE_END,triggerHandlerForGesture(event,phase,TAP)):phase===PHASE_MOVE&&(phase=PHASE_CANCEL,triggerHandler(event,phase)),setTouchInProgress(!1),null)}function touchCancel(){fingerCount=0,endTime=0,startTime=0,startTouchesDistance=0,endTouchesDistance=0,pinchZoom=1,cancelMultiFingerRelease(),setTouchInProgress(!1)}function touchLeave(jqEvent){var event=jqEvent.originalEvent;options.triggerOnTouchLeave&&(phase=getNextPhase(PHASE_END),triggerHandler(event,phase))}function removeListeners(){$element.unbind(START_EV,touchStart),$element.unbind(CANCEL_EV,touchCancel),$element.unbind(MOVE_EV,touchMove),$element.unbind(END_EV,touchEnd),LEAVE_EV&&$element.unbind(LEAVE_EV,touchLeave),setTouchInProgress(!1)}function getNextPhase(currentPhase){var nextPhase=currentPhase,validTime=validateSwipeTime(),validDistance=validateSwipeDistance(),didCancel=didSwipeBackToCancel();return!validTime||didCancel?nextPhase=PHASE_CANCEL:!validDistance||currentPhase!=PHASE_MOVE||options.triggerOnTouchEnd&&!options.triggerOnTouchLeave?!validDistance&&currentPhase==PHASE_END&&options.triggerOnTouchLeave&&(nextPhase=PHASE_CANCEL):nextPhase=PHASE_END,nextPhase}function triggerHandler(event,phase){var ret=void 0;return didSwipe()||hasSwipes()?ret=triggerHandlerForGesture(event,phase,SWIPE):(didPinch()||hasPinches())&&ret!==!1&&(ret=triggerHandlerForGesture(event,phase,PINCH)),didDoubleTap()&&ret!==!1?ret=triggerHandlerForGesture(event,phase,DOUBLE_TAP):didLongTap()&&ret!==!1?ret=triggerHandlerForGesture(event,phase,LONG_TAP):didTap()&&ret!==!1&&(ret=triggerHandlerForGesture(event,phase,TAP)),phase===PHASE_CANCEL&&touchCancel(event),phase===PHASE_END&&(SUPPORTS_TOUCH?0==event.touches.length&&touchCancel(event):touchCancel(event)),ret}function triggerHandlerForGesture(event,phase,gesture){var ret=void 0;if(gesture==SWIPE){if($element.trigger("swipeStatus",[phase,direction||null,distance||0,duration||0,fingerCount,fingerData]),options.swipeStatus&&(ret=options.swipeStatus.call($element,event,phase,direction||null,distance||0,duration||0,fingerCount,fingerData),ret===!1))return!1;if(phase==PHASE_END&&validateSwipe()){if($element.trigger("swipe",[direction,distance,duration,fingerCount,fingerData]),options.swipe&&(ret=options.swipe.call($element,event,direction,distance,duration,fingerCount,fingerData),ret===!1))return!1;switch(direction){case LEFT:$element.trigger("swipeLeft",[direction,distance,duration,fingerCount,fingerData]),options.swipeLeft&&(ret=options.swipeLeft.call($element,event,direction,distance,duration,fingerCount,fingerData));break;case RIGHT:$element.trigger("swipeRight",[direction,distance,duration,fingerCount,fingerData]),options.swipeRight&&(ret=options.swipeRight.call($element,event,direction,distance,duration,fingerCount,fingerData));break;case UP:$element.trigger("swipeUp",[direction,distance,duration,fingerCount,fingerData]),options.swipeUp&&(ret=options.swipeUp.call($element,event,direction,distance,duration,fingerCount,fingerData));break;case DOWN:$element.trigger("swipeDown",[direction,distance,duration,fingerCount,fingerData]),options.swipeDown&&(ret=options.swipeDown.call($element,event,direction,distance,duration,fingerCount,fingerData))}}}if(gesture==PINCH){if($element.trigger("pinchStatus",[phase,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData]),options.pinchStatus&&(ret=options.pinchStatus.call($element,event,phase,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData),ret===!1))return!1;if(phase==PHASE_END&&validatePinch())switch(pinchDirection){case IN:$element.trigger("pinchIn",[pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData]),options.pinchIn&&(ret=options.pinchIn.call($element,event,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData));break;case OUT:$element.trigger("pinchOut",[pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData]),options.pinchOut&&(ret=options.pinchOut.call($element,event,pinchDirection||null,pinchDistance||0,duration||0,fingerCount,pinchZoom,fingerData))}}return gesture==TAP?phase!==PHASE_CANCEL&&phase!==PHASE_END||(clearTimeout(singleTapTimeout),clearTimeout(holdTimeout),hasDoubleTap()&&!inDoubleTap()?(doubleTapStartTime=getTimeStamp(),singleTapTimeout=setTimeout($.proxy(function(){doubleTapStartTime=null,$element.trigger("tap",[event.target]),options.tap&&(ret=options.tap.call($element,event,event.target))},this),options.doubleTapThreshold)):(doubleTapStartTime=null,$element.trigger("tap",[event.target]),options.tap&&(ret=options.tap.call($element,event,event.target)))):gesture==DOUBLE_TAP?phase!==PHASE_CANCEL&&phase!==PHASE_END||(clearTimeout(singleTapTimeout),doubleTapStartTime=null,$element.trigger("doubletap",[event.target]),options.doubleTap&&(ret=options.doubleTap.call($element,event,event.target))):gesture==LONG_TAP&&(phase!==PHASE_CANCEL&&phase!==PHASE_END||(clearTimeout(singleTapTimeout),doubleTapStartTime=null,$element.trigger("longtap",[event.target]),options.longTap&&(ret=options.longTap.call($element,event,event.target)))),ret}function validateSwipeDistance(){var valid=!0;return null!==options.threshold&&(valid=distance>=options.threshold),valid}function didSwipeBackToCancel(){var cancelled=!1;return null!==options.cancelThreshold&&null!==direction&&(cancelled=getMaxDistance(direction)-distance>=options.cancelThreshold),cancelled}function validatePinchDistance(){return null!==options.pinchThreshold?pinchDistance>=options.pinchThreshold:!0}function validateSwipeTime(){var result;return result=options.maxTimeThreshold?!(duration>=options.maxTimeThreshold):!0}function validateDefaultEvent(jqEvent,direction){if(options.allowPageScroll===NONE||hasPinches())jqEvent.preventDefault();else{var auto=options.allowPageScroll===AUTO;switch(direction){case LEFT:(options.swipeLeft&&auto||!auto&&options.allowPageScroll!=HORIZONTAL)&&jqEvent.preventDefault();break;case RIGHT:(options.swipeRight&&auto||!auto&&options.allowPageScroll!=HORIZONTAL)&&jqEvent.preventDefault();break;case UP:(options.swipeUp&&auto||!auto&&options.allowPageScroll!=VERTICAL)&&jqEvent.preventDefault();break;case DOWN:(options.swipeDown&&auto||!auto&&options.allowPageScroll!=VERTICAL)&&jqEvent.preventDefault()}}}function validatePinch(){var hasCorrectFingerCount=validateFingers(),hasEndPoint=validateEndPoint(),hasCorrectDistance=validatePinchDistance();return hasCorrectFingerCount&&hasEndPoint&&hasCorrectDistance}function hasPinches(){return!!(options.pinchStatus||options.pinchIn||options.pinchOut)}function didPinch(){return!(!validatePinch()||!hasPinches())}function validateSwipe(){var hasValidTime=validateSwipeTime(),hasValidDistance=validateSwipeDistance(),hasCorrectFingerCount=validateFingers(),hasEndPoint=validateEndPoint(),didCancel=didSwipeBackToCancel(),valid=!didCancel&&hasEndPoint&&hasCorrectFingerCount&&hasValidDistance&&hasValidTime;return valid}function hasSwipes(){return!!(options.swipe||options.swipeStatus||options.swipeLeft||options.swipeRight||options.swipeUp||options.swipeDown)}function didSwipe(){return!(!validateSwipe()||!hasSwipes())}function validateFingers(){return fingerCount===options.fingers||options.fingers===ALL_FINGERS||!SUPPORTS_TOUCH}function validateEndPoint(){return 0!==fingerData[0].end.x}function hasTap(){return!!options.tap}function hasDoubleTap(){return!!options.doubleTap}function hasLongTap(){return!!options.longTap}function validateDoubleTap(){if(null==doubleTapStartTime)return!1;var now=getTimeStamp();return hasDoubleTap()&&now-doubleTapStartTime<=options.doubleTapThreshold}function inDoubleTap(){return validateDoubleTap()}function validateTap(){return(1===fingerCount||!SUPPORTS_TOUCH)&&(isNaN(distance)||distance<options.threshold)}function validateLongTap(){return duration>options.longTapThreshold&&DOUBLE_TAP_THRESHOLD>distance}function didTap(){return!(!validateTap()||!hasTap())}function didDoubleTap(){return!(!validateDoubleTap()||!hasDoubleTap())}function didLongTap(){return!(!validateLongTap()||!hasLongTap())}function startMultiFingerRelease(){previousTouchEndTime=getTimeStamp(),previousTouchFingerCount=event.touches.length+1}function cancelMultiFingerRelease(){previousTouchEndTime=0,previousTouchFingerCount=0}function inMultiFingerRelease(){var withinThreshold=!1;if(previousTouchEndTime){var diff=getTimeStamp()-previousTouchEndTime;diff<=options.fingerReleaseThreshold&&(withinThreshold=!0)}return withinThreshold}function getTouchInProgress(){return!($element.data(PLUGIN_NS+"_intouch")!==!0)}function setTouchInProgress(val){val===!0?($element.bind(MOVE_EV,touchMove),$element.bind(END_EV,touchEnd),LEAVE_EV&&$element.bind(LEAVE_EV,touchLeave)):($element.unbind(MOVE_EV,touchMove,!1),$element.unbind(END_EV,touchEnd,!1),LEAVE_EV&&$element.unbind(LEAVE_EV,touchLeave,!1)),$element.data(PLUGIN_NS+"_intouch",val===!0)}function createFingerData(index,evt){var id=void 0!==evt.identifier?evt.identifier:0;return fingerData[index].identifier=id,fingerData[index].start.x=fingerData[index].end.x=evt.pageX||evt.clientX,fingerData[index].start.y=fingerData[index].end.y=evt.pageY||evt.clientY,fingerData[index]}function updateFingerData(evt){var id=void 0!==evt.identifier?evt.identifier:0,f=getFingerData(id);return f.end.x=evt.pageX||evt.clientX,f.end.y=evt.pageY||evt.clientY,f}function getFingerData(id){for(var i=0;i<fingerData.length;i++)if(fingerData[i].identifier==id)return fingerData[i]}function createAllFingerData(){for(var fingerData=[],i=0;5>=i;i++)fingerData.push({start:{x:0,y:0},end:{x:0,y:0},identifier:0});return fingerData}function setMaxDistance(direction,distance){distance=Math.max(distance,getMaxDistance(direction)),maximumsMap[direction].distance=distance}function getMaxDistance(direction){return maximumsMap[direction]?maximumsMap[direction].distance:void 0}function createMaximumsData(){var maxData={};return maxData[LEFT]=createMaximumVO(LEFT),maxData[RIGHT]=createMaximumVO(RIGHT),maxData[UP]=createMaximumVO(UP),maxData[DOWN]=createMaximumVO(DOWN),maxData}function createMaximumVO(dir){return{direction:dir,distance:0}}function calculateDuration(){return endTime-startTime}function calculateTouchesDistance(startPoint,endPoint){var diffX=Math.abs(startPoint.x-endPoint.x),diffY=Math.abs(startPoint.y-endPoint.y);return Math.round(Math.sqrt(diffX*diffX+diffY*diffY))}function calculatePinchZoom(startDistance,endDistance){var percent=endDistance/startDistance*1;return percent.toFixed(2)}function calculatePinchDirection(){return 1>pinchZoom?OUT:IN}function calculateDistance(startPoint,endPoint){return Math.round(Math.sqrt(Math.pow(endPoint.x-startPoint.x,2)+Math.pow(endPoint.y-startPoint.y,2)))}function calculateAngle(startPoint,endPoint){var x=startPoint.x-endPoint.x,y=endPoint.y-startPoint.y,r=Math.atan2(y,x),angle=Math.round(180*r/Math.PI);return 0>angle&&(angle=360-Math.abs(angle)),angle}function calculateDirection(startPoint,endPoint){var angle=calculateAngle(startPoint,endPoint);return 45>=angle&&angle>=0?LEFT:360>=angle&&angle>=315?LEFT:angle>=135&&225>=angle?RIGHT:angle>45&&135>angle?DOWN:UP}function getTimeStamp(){var now=new Date;return now.getTime()}function getbounds(el){el=$(el);var offset=el.offset(),bounds={left:offset.left,right:offset.left+el.outerWidth(),top:offset.top,bottom:offset.top+el.outerHeight()};return bounds}function isInBounds(point,bounds){return point.x>bounds.left&&point.x<bounds.right&&point.y>bounds.top&&point.y<bounds.bottom}var useTouchEvents=SUPPORTS_TOUCH||SUPPORTS_POINTER||!options.fallbackToMouseEvents,START_EV=useTouchEvents?SUPPORTS_POINTER?SUPPORTS_POINTER_IE10?"MSPointerDown":"pointerdown":"touchstart":"mousedown",MOVE_EV=useTouchEvents?SUPPORTS_POINTER?SUPPORTS_POINTER_IE10?"MSPointerMove":"pointermove":"touchmove":"mousemove",END_EV=useTouchEvents?SUPPORTS_POINTER?SUPPORTS_POINTER_IE10?"MSPointerUp":"pointerup":"touchend":"mouseup",LEAVE_EV=useTouchEvents?null:"mouseleave",CANCEL_EV=SUPPORTS_POINTER?SUPPORTS_POINTER_IE10?"MSPointerCancel":"pointercancel":"touchcancel",distance=0,direction=null,duration=0,startTouchesDistance=0,endTouchesDistance=0,pinchZoom=1,pinchDistance=0,pinchDirection=0,maximumsMap=null,$element=$(element),phase="start",fingerCount=0,fingerData=null,startTime=0,endTime=0,previousTouchEndTime=0,previousTouchFingerCount=0,doubleTapStartTime=0,singleTapTimeout=null,holdTimeout=null;try{$element.bind(START_EV,touchStart),$element.bind(CANCEL_EV,touchCancel)}catch(e){$.error("events not supported "+START_EV+","+CANCEL_EV+" on jQuery.swipe")}this.enable=function(){return $element.bind(START_EV,touchStart),$element.bind(CANCEL_EV,touchCancel),$element},this.disable=function(){return removeListeners(),$element},this.destroy=function(){return removeListeners(),$element.data(PLUGIN_NS,null),$element},this.option=function(property,value){if(void 0!==options[property]){if(void 0===value)return options[property];options[property]=value}else $.error("Option "+property+" does not exist on jQuery.swipe.options");return null}}var LEFT="left",RIGHT="right",UP="up",DOWN="down",IN="in",OUT="out",NONE="none",AUTO="auto",SWIPE="swipe",PINCH="pinch",TAP="tap",DOUBLE_TAP="doubletap",LONG_TAP="longtap",HORIZONTAL="horizontal",VERTICAL="vertical",ALL_FINGERS="all",DOUBLE_TAP_THRESHOLD=10,PHASE_START="start",PHASE_MOVE="move",PHASE_END="end",PHASE_CANCEL="cancel",SUPPORTS_TOUCH="ontouchstart"in window,SUPPORTS_POINTER_IE10=window.navigator.msPointerEnabled&&!window.navigator.pointerEnabled,SUPPORTS_POINTER=window.navigator.pointerEnabled||window.navigator.msPointerEnabled,PLUGIN_NS="TouchSwipe",defaults={fingers:1,threshold:75,cancelThreshold:null,pinchThreshold:20,maxTimeThreshold:null,fingerReleaseThreshold:250,longTapThreshold:500,doubleTapThreshold:200,swipe:null,swipeLeft:null,swipeRight:null,swipeUp:null,swipeDown:null,swipeStatus:null,pinchIn:null,pinchOut:null,pinchStatus:null,click:null,tap:null,doubleTap:null,longTap:null,hold:null,triggerOnTouchEnd:!0,triggerOnTouchLeave:!1,allowPageScroll:"auto",fallbackToMouseEvents:!0,excludedElements:"label, button, input, select, textarea, a, .noSwipe"};$.fn.swipe=function(method){var $this=$(this),plugin=$this.data(PLUGIN_NS);if(plugin&&"string"==typeof method){if(plugin[method])return plugin[method].apply(this,Array.prototype.slice.call(arguments,1));$.error("Method "+method+" does not exist on jQuery.swipe")}else if(!(plugin||"object"!=typeof method&&method))return init.apply(this,arguments);return $this},$.fn.swipe.defaults=defaults,$.fn.swipe.phases={PHASE_START:PHASE_START,PHASE_MOVE:PHASE_MOVE,PHASE_END:PHASE_END,PHASE_CANCEL:PHASE_CANCEL},$.fn.swipe.directions={LEFT:LEFT,RIGHT:RIGHT,UP:UP,DOWN:DOWN,IN:IN,OUT:OUT},$.fn.swipe.pageScroll={NONE:NONE,HORIZONTAL:HORIZONTAL,VERTICAL:VERTICAL,AUTO:AUTO},$.fn.swipe.fingers={ONE:1,TWO:2,THREE:3,ALL:ALL_FINGERS}});var EGW_SELECTMODE_DEFAULT=0,EGW_SELECTMODE_TOGGLE=1,et2_dataview_selectionManager=function(){"use strict";return Class.extend({init:function(_parent,_indexMap,_actionObjectManager,_queryRangeCallback,_makeVisibleCallback,_context){this._parent=_parent,this._indexMap=_indexMap,this._actionObjectManager=_actionObjectManager,this._queryRangeCallback=_queryRangeCallback,this._makeVisibleCallback=_makeVisibleCallback,this._context=_context,this._parent&&this._parent._children.push(this),this._registeredRows={},this._focusedEntry=null,this._invertSelection=!1,this._selectAll=!1,this._inUpdate=!1,this._total=0,this._children=[],this.select_callback=null},destroy:function(){if(this._parent){var idx=this._parent._children.indexOf(this);this._parent._children.splice(idx,1)}for(var i=this._children.length-1;i>=0;i--)this._children[i].free();for(var key in this._registeredRows)this.unregisterRow(key,this._registeredRows[key].tr);this.select_callback=null},clear:function(){for(var key in this._registeredRows)this.unregisterRow(key,this._registeredRows[key].tr),delete this._registeredRows[key];
this._indexMap={},this._total=0,this._focusedEntry=null,this._invertSelection=!1,this._selectAll=!1,this._inUpdate=!1},setIndexMap:function(_indexMap){this._indexMap=_indexMap},setTotalCount:function(_total){this._total=_total},registerRow:function(_uid,_idx,_tr,_links){var entry=this._getRegisteredRowsEntry(_uid);entry.tr&&entry.tr!==_tr&&this.unregisterRow(_uid,entry.tr,!0),!entry.tr&&_links&&(this._attachActionObjectInterface(entry,_tr,_uid),this._attachActionObject(entry,_tr,_uid,_links,_idx)),entry.ao&&entry.ao._index,entry.idx=_idx,entry.tr=_tr,this._updateEntryState(entry,entry.state)},unregisterRow:function(_uid,_tr,_noDelete){_noDelete=!!_noDelete,"undefined"!=typeof this._registeredRows[_uid]&&this._registeredRows[_uid].tr===_tr&&(this._inUpdate=!0,this._registeredRows[_uid].tr=null,this._registeredRows[_uid].aoi=null,this._registeredRows[_uid].ao&&(this._registeredRows[_uid].ao.remove(),this._registeredRows[_uid].ao=null),_noDelete||this._registeredRows[_uid].state!==EGW_AO_STATE_NORMAL||delete this._registeredRows[_uid],this._inUpdate=!1)},resetSelection:function(){this._invertSelection=!1,this._selectAll=!1,this._actionObjectManager.setAllSelected(!1);for(var key in this._registeredRows)this.setSelected(key,!1);for(var i=0;i<this._children.length;i++)this._children[i].resetSelection()},setSelected:function(_uid,_selected){this._selectAll=!1;var entry=this._getRegisteredRowsEntry(_uid);this._updateEntryState(entry,egwSetBit(entry.state,EGW_AO_STATE_SELECTED,_selected))},setFocused:function(_uid,_focused){if(this._focusedEntry&&(this._updateEntryState(this._focusedEntry,egwSetBit(this._focusedEntry.state,EGW_AO_STATE_FOCUSED,!1)),this._focusedEntry=null),_focused){var entry=this._focusedEntry=this._getRegisteredRowsEntry(_uid);this._updateEntryState(entry,egwSetBit(entry.state,EGW_AO_STATE_FOCUSED,!0))}},selectAll:function(){this.resetSelection(),this._selectAll=!0,this._actionObjectManager.setAllSelected(!0);for(var key in this._registeredRows){var entry=this._registeredRows[key];this._updateEntryState(entry,entry.state)}},getSelected:function(){var ids=[];for(var key in this._registeredRows)egwBitIsSet(this._registeredRows[key].state,EGW_AO_STATE_SELECTED)&&ids.push(key);for(var i=0;i<this._children.length;i++)ids=ids.concat(this._children[i].getSelected().ids);return{all:this._selectAll,ids:ids}},_attachActionObjectInterface:function(_entry,_tr,_uid){_entry.aoi=new et2_dataview_rowAOI(_tr),_entry.aoi.setStateChangeCallback(function(_newState,_changedBit,_shiftState){_changedBit===EGW_AO_STATE_SELECTED&&this._handleSelect(_uid,_entry,egwBitIsSet(_shiftState,EGW_AO_SHIFT_STATE_BLOCK),egwBitIsSet(_shiftState,EGW_AO_SHIFT_STATE_MULTI))},this)},_getDummyAOI:function(_entry,_tr,_uid,_idx){var dummyAOI=new egwActionObjectInterface,self=this;return dummyAOI.doSetState=function(_state){self._inUpdate||(self.setFocused(_uid,egwBitIsSet(_state,EGW_AO_STATE_FOCUSED)),self._updateState(_uid,_state))},dummyAOI.doMakeVisible=function(){self._makeVisibleCallback.call(self._context,_idx)},dummyAOI.doTriggerEvent=_entry.aoi.doTriggerEvent,dummyAOI.getDOMNode=function(){return _tr},dummyAOI},_attachActionObject:function(_entry,_tr,_uid,_links,_idx){function getIndexAO(_idx){return"undefined"!=typeof self._indexMap[_idx]&&self._indexMap[_idx].uid?self._getRegisteredRowsEntry(self._indexMap[_idx].uid).ao:null}function getElementRelatively(_step){for(var max_index=(self._total||Object.keys(self._indexMap).length,Math.max.apply(Math,Object.keys(self._indexMap))),count=Math.max(1,Math.min(self._total,50)),element=null,idx=_entry.idx;null==element&&count>0&&max_index>0;)count--,element=getIndexAO(Math.max(0,Math.min(max_index,idx+=_step)));return element}var dummyAOI=this._getDummyAOI(_entry,_tr,_uid,_idx);_entry.ao=this._actionObjectManager.addObject(_uid,dummyAOI),_entry.ao._context=this._context,_entry.ao.updateActionLinks(_links),_entry.ao._index=_idx;var self=this;_entry.ao.getPrevious=function(_step){return getElementRelatively(-_step)},_entry.ao.getNext=function(_step){return getElementRelatively(_step)},_entry.ao.traversePath=function(_obj){for(var s=Math.min(this._index,_obj._index),e=Math.max(this._index,_obj._index),result=[],i=s;e>i;i++){var ao=getIndexAO(i);ao&&result.push(ao)}return result}},_updateState:function(_uid,_state){var entry=this._getRegisteredRowsEntry(_uid);return this._updateEntryState(entry,_state),entry},_updateEntryState:function(_entry,_state){this._selectAll?_state|=EGW_AO_STATE_SELECTED:this._invertSelection&&(_state^=EGW_AO_STATE_SELECTED),(_entry.aoi&&_entry.aoi.getState()!==_state||_entry.state!=_state)&&(this._inUpdate=!0,_entry.ao&&(_entry.ao.setSelected(egwBitIsSet(_state,EGW_AO_STATE_SELECTED)),_entry.ao.setFocused(egwBitIsSet(_state,EGW_AO_STATE_FOCUSED))),this._inUpdate=!1,_state!==EGW_AO_STATE_NORMAL||_entry.tr||delete this._registeredRows[_entry.uid]),_entry.aoi&&_entry.aoi.doSetState&&_entry.aoi.doSetState(_state),_entry.state=_state},_getRegisteredRowsEntry:function(_uid){return"undefined"==typeof this._registeredRows[_uid]&&(this._registeredRows[_uid]={uid:_uid,idx:null,state:EGW_AO_STATE_NORMAL,tr:null,aoi:null,ao:null}),this._registeredRows[_uid]},_handleSelect:function(_uid,_entry,_shift,_ctrl){if(!_ctrl){for(var top=this;null!==top._parent;)top=top._parent;top.resetSelection(),this._actionObjectManager.setAllSelected(!1)}var entry=this._getRegisteredRowsEntry(_uid);this.setSelected(_uid,!_ctrl||!egwBitIsSet(entry.state,EGW_AO_STATE_SELECTED)),_shift?this._focusedEntry&&this._selectRange(this._focusedEntry.idx,_entry.idx):this.setFocused(_uid,!0),this.select_callback&&"function"==typeof this.select_callback&&this.select_callback.apply(this._context,arguments)},_selectRange:function(_start,_stop){for(var queryRanges=[],naStart=!1,s=Math.min(_start,_stop),e=Math.max(_stop,_start),i=s;e>=i;i++)"undefined"!=typeof this._indexMap[i]&&this._indexMap[i].uid?(naStart!==!1&&(queryRanges.push(et2_bounds(naStart,i-1)),naStart=!1),this.setSelected(this._indexMap[i].uid,!0)):naStart===!1&&(naStart=i);naStart!==!1&&(queryRanges.push(et2_bounds(naStart,i-1)),naStart=!1);for(var i=0;i<queryRanges.length;i++)this._queryRangeCallback.call(this._context,queryRanges[i],function(_order){for(var j=0;j<_order.length;j++)this.setSelected(_order[j],!0)},this)}})}.call(this),ET2_DATAVIEW_FETCH_TIMEOUT=50,ET2_DATAVIEW_STEPSIZE=50,et2_dataview_controller=function(){"use strict";return Class.extend({init:function(_parentController,_grid,_dataProvider,_rowCallback,_linkCallback,_context,_actionObjectManager){this._parentController=_parentController,this._grid=_grid,this._dataProvider=_dataProvider,this._rowCallback=_rowCallback,this._linkCallback=_linkCallback,this._context=_context,this._children=[],this._indexMap={},this._queueTimer=null,this._queue={},this._grid.setDataCallback(this._gridCallback,this),this._selectionMgr=new et2_dataview_selectionManager(this._parentController?this._parentController._selectionMgr:null,this._indexMap,_actionObjectManager,this._selectionFetchRange,this._makeIndexVisible,this),null!=this._parentController&&this._parentController._children.push(this)},destroy:function(){if(this._selectionMgr.free(),this._clearTimer(),null!=this._parentController){var idx=this._parentController._children.indexOf(this);idx>=0&&(this._parentController._children.splice(idx,1),this._parentController=null)}},update:function(clear){this._grid.doInvalidate=!1,clear&&(this._grid.makeIndexVisible(0),this._grid.clear(),this._selectionMgr.clear(),this._indexMap={},this._selectionMgr.setIndexMap(this._indexMap),this._queue={},this._lastModification=0),this._grid.cleanup();var range=this._grid.getIndexRange();range.top===!1&&(range.top=range.bottom=0),this._queueFetch(et2_bounds(range.top,clear?0:range.bottom+1),0,!0)},reset:function(){this._indexMap={},this._grid.clear(),this._queue={},this.update()},loadInitialOrder:function(order){for(var i=0;i<order.length;i++)this._getIndexEntry(i).uid=order[i]},loadInitialData:function(uid_prefix,uid_key,data){var idx=0;for(var key in data)if("object"==typeof data[key]&&null!=data[key]&&"undefined"!=typeof data[key][uid_key]){var entry=this._getIndexEntry(idx++);entry.uid=data[key][uid_key]+"",entry.uid.indexOf(uid_prefix)<0&&(entry.uid=uid_prefix+"::"+entry.uid),egw.dataStoreUID(entry.uid,data[key])}0==idx&&this._emptyRow()},getDepth:function(){return this._parentController?this._parentController.getDepth()+1:0},setPrefix:function(prefix){this.dataStorePrefix=prefix},getRowByNode:function(node){var row_node=$j(node).closest("tr"),row=!1,indexed=this._getIndexEntry(row_node.index());if(indexed&&indexed.row&&indexed.row.getDOMNode()==row_node[0])row=indexed;else for(var index in this._indexMap)if(indexed=this._indexMap[index],indexed&&indexed.row&&indexed.row.getDOMNode()==row_node[0]){row=indexed;break}for(var i=0;!row&&i<this._children.length;i++){var child_row=this._children[i].getRowByNode(node);child_row!==!1&&(row=child_row)}return row&&!row.controller&&(row.controller=this),row},_getIndexEntry:function(_idx){return"undefined"==typeof this._indexMap[_idx]&&(this._indexMap[_idx]={row:null,uid:null}),this._indexMap[_idx].idx=_idx,this._indexMap[_idx]},_insertDataRow:function(_entry,_update){if(_entry.row&&!_update)return!0;var ctx={self:this,entry:_entry},createdRow=!1;if(_entry.row||(createdRow=!0,_entry.row=this._createRow(ctx),_entry.row.setDestroyCallback(this._destroyCallback,ctx)),this.hasData=!1,_entry.uid&&this._dataProvider.dataRegisterUID(_entry.uid,this._dataCallback,ctx),!this.hasData){var avg=Math.round(this._grid.getAverageHeight()-5)+"px",prototype=this._grid.getRowProvider().getPrototype("loading");$j("div",prototype).css("height",avg);var node=_entry.row.getJNode();node.empty(),node.append(prototype.children())}return createdRow&&_entry.row&&this._grid.insertRow(_entry.idx,_entry.row),this.hasData},_createRow:function(ctx){return new et2_dataview_row(this._grid)},_gridCallback:function(_idxStart,_idxEnd){for(var needsData=!1,i=_idxStart;_idxEnd>=i;i++){var entry=this._getIndexEntry(i);this._insertDataRow(entry,!1)||needsData!==!1||(needsData=i)}needsData!==!1&&this._queueFetch(et2_bounds(needsData,_idxEnd+1),needsData==_idxStart?0:needsData>_idxStart?1:-1,!1)},_queueFetch:function(_range,_direction,_isUpdate){_isUpdate=_isUpdate?_isUpdate:!1;for(var start=Math.max(0,_range.top),end=Math.min(this._grid.getTotalCount(),_range.bottom),i=start;end>i;i++)"undefined"==typeof this._queue[i]&&(this._queue[i]=_direction);if(null===this._queueTimer&&!_isUpdate){var self=this;egw.debug("log","Dataview queue: ",_range),this._queueTimer=window.setTimeout(function(){self._flushQueue(!1)},ET2_DATAVIEW_FETCH_TIMEOUT)}_isUpdate&&this._flushQueue(!0)},_flushQueue:function(_isUpdate){this._clearTimer();var marked={},r=_isUpdate?0:Math.floor(ET2_DATAVIEW_STEPSIZE/2),total=this._grid.getTotalCount();for(var key in this._queue)if(!(this._queue[key]>1)){key=parseInt(key);for(var b=Math.max(0,key-r+r*this._queue[key]),t=Math.min(key+r+r*this._queue[key],total-1),c=0,i=b;t>=i&&ET2_DATAVIEW_STEPSIZE>c;i++)("undefined"==typeof this._queue[i]||this._queue[i]<=1)&&(this._queue[i]=2,marked[i]=!0,c++)}for(var fetchList=[],entry=null,last=0,arr=et2_arrayIntKeys(marked).sort(function(a,b){return a>b?1:a==b?0:-1}),i=0;i<arr.length;i++)0==i||arr[i]-last>1?(entry&&fetchList.push(entry),entry={start:arr[i],count:1}):entry.count++,last=arr[i];entry&&fetchList.push(entry),0===fetchList.length&&_isUpdate&&(fetchList.push({start:0,count:0}),this._grid.doInvalidate=!1),egw.debug("log","Dataview flush",fetchList);for(var i=0;i<fetchList.length;i++){var query={start:fetchList[i].start,num_rows:fetchList[i].count,refresh:!1},ctx={self:this,start:query.start,count:query.num_rows,lastModification:this._lastModification};this.dataStorePrefix&&(ctx.prefix=this.dataStorePrefix),this._dataProvider.dataFetch(query,this._fetchCallback,ctx)}},_clearTimer:function(){this._queueTimer&&(window.clearTimeout(this._queueTimer),this._queueTimer=null)},_dataCallback:function(_data){if(this.self.hasData=!0,this.self._rowCallback){if(this.entry.row.clear(),"undefined"==typeof _data||null==_data)return void this.self._destroyCallback.call(this,this.entry.row);this.self._rowCallback.call(this.self._context,_data,this.entry.row,this.entry.idx,this.entry);var tr=this.entry.row.getDOMNode(),d=this.self.getDepth();if(d>0&&($j(tr).addClass("subentry"),$j("td:first",tr).children("div").last().addClass("level_"+d+" indentation"),0==this.entry.idx)){var indent=$j("<span class='indentation'/>").appendTo("body");egw.css(".subentry td div.innerContainer.level_"+d,"margin-right:"+parseInt(indent.css("margin-right"))*d+"px"),indent.remove()}var links=null;_data.no_actions||(this.self._linkCallback&&(links=this.self._linkCallback.call(this.self._context,_data,this.entry.idx,this.entry.uid)),this.self._selectionMgr.registerRow(this.entry.uid,this.entry.idx,tr,links)),this.entry.row.invalidate()}},_destroyCallback:function(_row){var selection=this.self._selectionMgr._getRegisteredRowsEntry(this.entry.uid);if(this.entry.row&&selection&&!egwBitIsSet(selection.state,EGW_AO_STATE_SELECTED)){var tr=this.entry.row.getDOMNode();this.self._selectionMgr._updateState(this.entry.uid,EGW_AO_STATE_NORMAL),this.self._selectionMgr.unregisterRow(this.entry.uid,tr)}this.entry.row=null,this.self._dataProvider.dataUnregisterUID(this.entry.uid,this.self._dataCallback,this)},_getIndexMapping:function(_start,_count){for(var result=[],i=_start;_start+_count>i;i++)result.push(this._getIndexEntry(i));return result},_updateOrder:function(_start,_count,_idxMap,_order){for(var result=[],mapIdx=0,idx=_start,i=0;i<_order.length;i++,idx++){var current=_idxMap[mapIdx];if(current.row&&current.uid)if(current.uid!==_order[i]){var entry={idx:idx,uid:_order[i],row:null};this._insertDataRow(entry,!0),result.push(entry)}else current.idx=idx,mapIdx++;else current.uid=_order[i],current.idx=idx,current.row&&this._insertDataRow(current,!0),mapIdx++}for(var i=mapIdx;i<_idxMap.length;i++)"undefined"!=typeof _idxMap[i]&&(_idxMap[i].uid=null);return result},_mergeResult:function(_newEntries,_invalidStartIdx,_diff,_total){if(_newEntries.length>0||_diff>0){for(var newMap={},i=0;i<_newEntries.length;i++)newMap[_newEntries[i].idx]=_newEntries[i];for(var key in this._indexMap){var entry=this._indexMap[key],newIdx=entry.idx>=_invalidStartIdx?entry.idx-_diff:entry.idx;newIdx>=0&&_total>newIdx&&"undefined"==typeof newMap[newIdx]?(entry.idx=newIdx,newMap[newIdx]=entry):(entry.idx=null,entry.row=null)}this._indexMap=newMap,this._selectionMgr.setIndexMap(newMap)}},_fetchCallback:function(_response){if(this.self._lastModification=_response.lastModification,_response.order){var order=0!=this.count?_response.order.splice(0,this.count):_response.order;if(_response.total<this.count)this.self._queue={};else for(var i=this.start;i<this.start+order.length;i++)delete this.self._queue[i];var idxMap=this.self._getIndexMapping(this.start,order.length),res=this.self._updateOrder(this.start,this.count,idxMap,order);if(this.self._mergeResult(res,this.start+order.length,idxMap.length-order.length,_response.total),0==_response.total)this.self._emptyRow();else{var row=$j(".egwGridView_empty",this.self._grid.innerTbody).remove();this.self._selectionMgr.unregisterRow("",0,row.get(0))}this.self._grid.doInvalidate=!0,this.self._grid.setTotalCount(_response.total),this.self._selectionMgr.setTotalCount(_response.total),this.self._grid.invalidate()}},_emptyRow:function(){if($j(".egwGridView_empty",this._grid.innerTbody).remove(),"undefined"!=typeof this._grid._rowProvider&&this._grid._rowProvider.getPrototype("empty")){var placeholder=this._grid._rowProvider.getPrototype("empty");1==$j("td",placeholder).length&&$j("td",placeholder).css("width",this._grid.outerCell.width()+"px"),placeholder.appendTo(this._grid.innerTbody);var links=null;this._linkCallback&&(links=this._linkCallback.call(this._context,{},0,"")),this._selectionMgr.registerRow("",0,placeholder.get(0),links)}},_selectionFetchRange:function(_range,_callback,_context){this._dataProvider.dataFetch({start:_range.top,num_rows:_range.bottom-_range.top+1,no_data:!0},function(_response){_callback.call(_context,_response.order)})},_makeIndexVisible:function(_idx){this._grid.makeIndexVisible(_idx)}})}.call(this),et2_dataview_tile=function(){"use strict";return et2_dataview_row.extend([],{columns:4,init:function(_parent){this._super(_parent),this.tr.addClass("tile")},makeExpandable:function(_expandable,_callback,_context){},getAvgHeightData:function(){var res={avgHeight:this.getHeight()/this.columns,avgCount:this.columns};return res},getHeight:function(){return this._index%this.columns==0?this._super():0},invalidate:function(){if(this._inTree&&this.tr){var template_width=$j(".innerContainer",this.tr).children().outerWidth(!0);template_width&&this.tr.css("width",template_width+(this.tr.outerWidth(!0)-this.tr.width()))}this._recalculate_columns(),this._super()},_recalculate_columns:function(){this._inTree&&this.tr&&this.tr.parent()&&(this.columns=Math.max(1,parseInt(this.tr.parent().innerWidth()/this.tr.outerWidth(!0))))}})}.call(this),nm_popup_action,nm_popup_ids=null,et2_nextmatch_controller=function(){"use strict";return et2_dataview_controller.extend(et2_IDataProvider,{VIEW_ROW:"row",VIEW_TILE:"tile",init:function(_parentController,_egw,_execId,_widget,_parentId,_grid,_rowProvider,_actionLinks,_objectManager,_actions){this.egw=_egw,this._widget=_widget,this._actionLinks=_actionLinks,this._execId=_execId,this._widgetId=_widget.id,this._parentId=_parentId,this._rowProvider=_rowProvider,_objectManager?(this._actionManager=null,this._objectManager=_objectManager):this._initActions(_actions);var self=this;this._objectManager.setSelectedCallback=function(){self._selectCallback.apply(self,[this,arguments])},this._super(_parentController,_grid,this,this._rowCallback,this._linkCallback,this,this._objectManager),this._filters={},this.kept_selection=null,this.kept_focus=null,this.kept_expansion=[],this.dataUnregisterUID=_egw.dataUnregisterUID,this._view=et2_nextmatch_controller.prototype.VIEW_ROW},destroy:function(){this._actionManager&&(this._objectManager.remove(),this._actionManager.remove()),this._super()},setFilters:function(_filters){this._filters=_filters},keepSelection:function(){this.kept_selection=this._selectionMgr?this._selectionMgr.getSelected():null,this.kept_focus=this._selectionMgr&&this._selectionMgr._focusedEntry?this._selectionMgr._focusedEntry.uid||null:null;var controller=(this._widget,this);$j(".arrow.opened",this._widget.getDOMNode(this._widget)).each(function(){var entry=controller.getRowByNode(this);entry&&entry.uid&&controller.kept_expansion.push(entry.uid)})},getObjectManager:function(){return this._objectManager},deleteRow:function(uid){var entry=this._selectionMgr._getRegisteredRowsEntry(uid);if(this._selectionMgr.setSelected(uid,!1),entry&&null!==entry.idx){this._grid.deleteRow(entry.idx),this.egw.dataStoreUID(uid,null),this.egw.dataDeleteUID(uid),delete this._indexMap[entry.idx];for(var mapIndex=entry.idx+1;"undefined"!=typeof this._indexMap[mapIndex];mapIndex++){var entry=this._indexMap[mapIndex];if(entry.idx=mapIndex-1,this._indexMap[mapIndex-1]=entry,entry.uid&&"undefined"!=typeof this._selectionMgr._registeredRows[entry.uid]){var reg=this._selectionMgr._getRegisteredRowsEntry(entry.uid);reg.idx=entry.idx,reg.ao&&reg.ao._index&&(reg.ao._index=entry.idx)}}delete this._indexMap[mapIndex-1]}},_createRow:function(ctx){switch(this._view){case et2_nextmatch_controller.prototype.VIEW_TILE:var row=new et2_dataview_tile(this._grid);return window.setTimeout(function(){row.tr&&(row.tr.css("float","none"),window.setTimeout(function(){row.tr&&row.tr.css("float","left")},50))},100),row;case et2_nextmatch_controller.prototype.VIEW_ROW:default:return new et2_dataview_row(this._grid)}},_initActions:function(_actions){var uid=this._widget.id||this.egw.uid();null==_actions&&(_actions=[]);var gam=egw_getActionManager(this.egw.appName,!0,1);null==this._actionManager&&(this._actionManager=gam.addAction("actionManager",uid)),this._actionManager.updateActions(_actions,this.egw.appName);var data=this._actionManager.data;"undefined"!=data&&data||(data={}),data.nextmatch=this._widget,this._actionManager.set_data(data);var self=this;this._actionManager.setDefaultExecute(function(_action,_senders,_target){var ids=self._selectionMgr.getSelected();"undefined"!=typeof _action.data&&_action.data||(_action.data={}),_action.data.nextmatch=self._widget,nm_action(_action,_senders,_target,ids)});var select_all=this._actionManager.getActionById("select_all");select_all&&select_all.set_onExecute(jQuery.proxy(function(action,selected){this._selectionMgr.selectAll()},this));var gom=egw_getObjectManager(this.egw.appName,!0,1);if(null==this._objectManager&&(this._objectManager=gom.addObject(new egwActionObjectManager(uid,this._actionManager)),this._objectManager.handleKeyPress=function(_keyCode,_shift,_ctrl,_alt){for(var i=0;i<self._actionManager.children.length;i++)if("object"==typeof self._actionManager.children[i].shortcut&&self._actionManager.children[i].shortcut&&_keyCode==self._actionManager.children[i].shortcut.keyCode)return this.executeActionImplementation({keyEvent:{keyCode:_keyCode,shift:_shift,ctrl:_ctrl,alt:_alt}},"popup",EGW_AO_EXEC_SELECTED);return egwActionObject.prototype.handleKeyPress.call(this,_keyCode,_shift,_ctrl,_alt)}),this._objectManager.flags=this._objectManager.flags|EGW_AO_FLAG_DEFAULT_FOCUS|EGW_AO_FLAG_IS_CONTAINER,this._init_links_dnd(this._actionManager),this._selectionMgr)for(var uid in this._selectionMgr._registeredRows){var entry=this._selectionMgr._getRegisteredRowsEntry(uid);entry.ao&&entry.ao.updateActionLinks(this._actionLinks)}},_init_links_dnd:function(){var mgr=this._actionManager,self=this,drop_action=mgr.getActionById("egw_link_drop"),drag_action=mgr.getActionById("egw_link_drag"),drop_cancel=mgr.getActionById("egw_cancel_drop");return this._actionLinks||(this._actionLinks=[]),drop_cancel||(drop_cancel=mgr.addAction("drop","egw_cancel_drop",this.egw.lang("Cancel"),egw.image("cancel"),function(){},!0),drop_cancel.set_group("99"),drop_cancel.acceptedTypes=drop_cancel.acceptedTypes.concat(Object.keys(egw.user("apps")).concat(["link","file"])),this._actionLinks.push(drop_cancel.id)),!egw.link_get_registry(this.dataStorePrefix||this.egw.appName,"query")||egw.link_get_registry(this.dataStorePrefix||this.egw.appName,"title")?(drop_action&&(drop_action.remove(),this._actionLinks.indexOf(drop_action.id)>=0&&this._actionLinks.splice(this._actionLinks.indexOf(drop_action.id),1)),void(drag_action&&(drag_action.remove(),this._actionLinks.indexOf(drag_action.id)>=0&&this._actionLinks.splice(this._actionLinks.indexOf(drag_action.id),1)))):(null==drop_action&&(drop_action=mgr.addAction("drop","egw_link_drop",this.egw.lang("Create link"),egw.image("link"),function(action,source,dropped){for(var links=[],id="",i=0;i<source.length;i++)source[i].id&&(id=source[i].id.split("::"),links.push({app:"filemanager"==id[0]?"link":id[0],id:id[1]}));links.length&&self.egw.json(self.egw.getAppName()+".etemplate_widget_link.ajax_link.etemplate",dropped.id.split("::").concat([links]),function(result){if(result){for(var i=0;i<this._objectManager.selectedChildren.length;i++)this._widget.refresh(this._objectManager.selectedChildren[i].id,"update");this._widget.egw().message("Linked"),this._widget.refresh(dropped.id,"update")}},self,!0,self).sendRequest()},!0)),this._actionLinks.indexOf(drop_action.id)<0&&this._actionLinks.push(drop_action.id),-1==drop_action.acceptedTypes.indexOf("link")&&drop_action.acceptedTypes.push("link"),null==drag_action&&(drag_action=mgr.addAction("drag","egw_link_drag",this.egw.lang("link"),"link",function(action,selected){for(var helper=$j(document.createElement("div")),i=0;i<selected.length&&10>i;i++){var id=selected[i].id.split("::"),span=$j(document.createElement("span")).appendTo(helper);self.egw.link_title(id[0],id[1],function(title){this.append(title),this.append("<br />")},span)}return null},!0)),this._actionLinks.indexOf(drag_action.id)<0&&this._actionLinks.push(drag_action.id),void drag_action.set_dragType("link"))},setPrefix:function(prefix){this._super.apply(this,arguments),this._init_links_dnd(this._actionManager)},_destroyCallback:function(_row){this.entry.widget&&(this.entry.widget.free(),this.entry.widget=null),this._super.apply(this,arguments)},_rowCallback:function(_data,_tr,_idx,_entry){_entry.widget=this._rowProvider.getDataRow({content:_data},_tr,_idx,this)},_linkCallback:function(_data,_idx,_uid){if(""!=_uid.trim())return this._actionLinks;var links=[];try{links="undefined"!=typeof this._widget.options.settings.placeholder_actions?this._widget.options.settings.placeholder_actions:this._widget.options.add?["add"]:[]}catch(e){}return links},_fetchCallback:function(_response){var nm=this.self._widget;if(nm){for(var i in _response.rows)if(!jQuery.isNumeric(i))if("sel_options"==i){var mgr=nm.getArrayMgr(i);for(var id in _response.rows.sel_options){mgr.data[id]=_response.rows.sel_options[id];var select=nm.getWidgetById(id);select&&select.set_select_options&&select.set_select_options(_response.rows.sel_options[id]),"cat_id"==id&&(this.self._rowProvider.categories=null)}}else{var mgr=nm.getArrayMgr("content");mgr.data[i]=_response.rows[i];var widget=nm.getWidgetById(i);widget&&widget.set_value&&widget.set_value(mgr.getEntry(i))}if(this.self&&null==this.self.kept_selection&&!this.refresh&&this.self._grid.getTotalCount()>_response.total&&this.self.keepSelection(),this._super.apply(this,arguments),this.self&&this.self.kept_selection&&this.self._selectionMgr){this.self.kept_selection.all&&this.self._selectionMgr.selectAll();for(var i=(this.self.kept_selection.ids.length||1)-1;i>=0;i--)_response.order.indexOf(this.self.kept_selection.ids[i])>=0?(this.self._selectionMgr.setSelected(this.self.kept_selection.ids[i],!0),this.self.kept_selection.ids.splice(i,1)):this.self.kept_selection.ids.splice(i,1);this.self.kept_focus&&_response.order.indexOf(this.self.kept_focus)>=0&&this.self._selectionMgr.setFocused(this.self.kept_focus,!0),null!=this.self.kept_selection&&"undefined"!=typeof this.self.kept_selection.ids&&0==this.self.kept_selection.ids.length&&(this.self.kept_selection=null),this.self.kept_focus=null}}},_selectCallback:function(action,senders){"undefined"==typeof senders&&(senders=[]),this._widget&&this._widget.onselect.call(this._widget,action,senders)},dataFetch:function(_queriedRange,_callback,_context){null!==this._parentId&&(_queriedRange.parent_id=this._parentId);for(var obj=this;("undefined"==typeof obj._filters||jQuery.isEmptyObject(obj._filters))&&obj._parentController;)obj=obj._parentController;this.egw.dataFetch(this._widget.getInstanceManager().etemplate_exec_id||this._execId,_queriedRange,obj._filters,this._widgetId,_callback,_context)},dataRegisterUID:function(_uid,_callback,_context){this.egw.dataRegisterUID(_uid,_callback,_context,this._widget.getInstanceManager().etemplate_exec_id||this._execId,this._widgetId)},dataUnregisterUID:function(){}})}.call(this),et2_nextmatch_rowProvider=function(){"use strict";return ClassWithAttributes.extend({init:function(_rowProvider,_subgridCallback,_context){this._rowProvider=_rowProvider,this._subgridCallback=_subgridCallback,this._context=_context,this._createEmptyPrototype()},setDataRowTemplate:function(_widgets,_rowData,_rootWidget){this._rootWidget=_rootWidget;var row=this._rowProvider.getPrototype("default"),rowTemplate={row:row[0],rowData:_rowData,widgets:_widgets,root:_rootWidget,seperated:null,mgrs:_rootWidget.getArrayMgrs()},rowWidget=new et2_nextmatch_rowWidget(rowTemplate.mgrs,row[0]);rowWidget._parent=_rootWidget,rowWidget.createWidgets(_widgets);var variableAttributes=this._getVariableAttributeSet(rowWidget);rowTemplate.seperated=this._seperateWidgets(variableAttributes);this._stripTemplateRow(rowTemplate),this._buildNodeAccessFuncs(rowTemplate);var tmpl=document.createDocumentFragment();row.children().each(function(){tmpl.appendChild(this)}),this._dataRow=tmpl,this._template=rowTemplate},getDataRow:function(_data,_row,_idx,_controller){var row=this._dataRow.cloneNode(!0),mgrs=et2_arrayMgrs_expand(rowWidget,this._template.mgrs,_data,_idx),rowWidget=null;if(this._template.seperated.remaining.length>0){for(var i=0;i<this._template.seperated.remaining.length;i++)for(var entry=this._template.seperated.remaining[i],j=0;j<entry.data.length;j++){var set=entry.data[j];entry.widget.options[set.attribute]=mgrs.content.expandName(set.expression)}var rowWidget=new et2_nextmatch_rowTemplateWidget(this._rootWidget,row);rowWidget.createWidgets(mgrs,this._template.placeholders)}for(var i=0;i<this._template.seperated.detachable.length;i++){for(var entry=this._template.seperated.detachable[i],data={},j=0;j<entry.data.length;j++){var set=entry.data[j];data[set.attribute]=mgrs.content.expandName(set.expression)}for(var nodes=new Array(entry.nodeFuncs.length),j=0;j<nodes.length;j++)nodes[j]=entry.nodeFuncs[j](row);entry.widget._mgrs=mgrs,"undefined"!=typeof data.id&&(entry.widget.id=data.id),entry.widget.transformAttributes.call(entry.widget,data),entry.widget.setDetachedAttributes(nodes,data)}var tr=_row.getDOMNode();if(tr.appendChild(row),"undefined"!=typeof _data.content.is_parent&&_data.content.is_parent){_row.makeExpandable(!0,function(){return this._subgridCallback.call(this._context,_row,_data,_controller)},this);for(var top_controller=_controller;null!=top_controller._parentController;)top_controller=top_controller._parentController;var expansion_index=top_controller.kept_expansion.indexOf(top_controller.dataStorePrefix+"::"+_data.content[this._context.settings.row_id]);top_controller.kept_expansion&&expansion_index>=0&&(top_controller.kept_expansion.splice(expansion_index,1),window.setTimeout(function(){_row.expansionButton.trigger("click")},ET2_GRID_INVALIDATE_TIMEOUT))}return this._setRowData(this._template.rowData,tr,mgrs),rowWidget},_createEmptyPrototype:function(){var label=this._context&&this._context.options&&this._context.options.settings.placeholder,placeholder=$j(document.createElement("td")).attr("colspan",this._rowProvider.getColumnCount()).css("height","19px").text("undefined"!=typeof label&&label?label:egw().lang("No matches found"));this._rowProvider._prototypes.empty=$j(document.createElement("tr")).addClass("egwGridView_empty").append(placeholder)},_getVariableAttributeSet:function(_widget){var variableAttributes=[];return _widget.iterateOver(function(_widget){var hasAttr=!1,widgetData={widget:_widget,data:[]};for(var key in _widget.attributes)if(!_widget.attributes[key].ignore&&"undefined"!=typeof _widget.options[key]){var val=_widget.options[key];"string"==typeof val&&val.indexOf("$")>=0&&(hasAttr=!0,widgetData.data.push({attribute:key,expression:val}))}hasAttr&&variableAttributes.push(widgetData)},this),variableAttributes},_seperateWidgets:function(_varAttrs){for(var detachable=[],remaining=[],i=0;i<_varAttrs.length;i++){var widget=_varAttrs[i].widget,insertWidget=!0,checkWidget=function(_widget){if(null!=_widget.parent){for(var i=0;i<remaining.length;i++)if(remaining[i].widget==_widget.parent)return void(insertWidget=!1);checkWidget(_widget.parent)}};if(checkWidget(widget),insertWidget){var isDetachable=!1;if(widget.implements(et2_IDetachedDOM)){var supportedAttrs=[];widget.getDetachedAttributes(supportedAttrs),supportedAttrs.push("id"),isDetachable=!0;for(var j=0;j<_varAttrs[i].data.length;j++){var data=_varAttrs[i].data[j],supportsAttr=-1!=supportedAttrs.indexOf(data.attribute);supportsAttr||egw.debug("warn","et2_IDetachedDOM widget "+widget._type+" does not support "+data.attribute),isDetachable&=supportsAttr}}isDetachable?detachable.push(_varAttrs[i]):remaining.push(_varAttrs[i])}}return{detachable:detachable,remaining:remaining}},_stripTemplateRow:function(_rowTemplate){_rowTemplate.placeholders=[];for(var i=0;i<_rowTemplate.seperated.remaining.length;i++){var entry=_rowTemplate.seperated.remaining[i];if(egw.debug("warn","Non-clonable widget '"+entry.widget._type+"' in dataview row - this might be slow",entry),
entry.placeholder=null,entry.widget.implements(et2_IDOMNode)){var node=entry.widget.getDOMNode(entry.widget);node&&node.parentNode&&(entry.placeholder=document.createElement("span"),node.parentNode.replaceChild(entry.placeholder,node),_rowTemplate.placeholders.push({widget:entry.widget,func:this._compileDOMAccessFunc(_rowTemplate.row,entry.placeholder)}))}}},_nodeIndex:function(_node){if(null==_node.parentNode)return 0;for(var i=0;i<_node.parentNode.childNodes.length;i++)if(_node.parentNode.childNodes[i]==_node)return i;return-1},_compileDOMAccessFunc:function(_root,_target){function recordPath(_root,_target,_path){if("undefined"==typeof _path&&(_path=[]),_root!=_target&&_target){var idx=this._nodeIndex(_target);if(idx>=0)return _path.unshift("childNodes["+idx+"]"),recordPath.call(this,_root,_target.parentNode,_path);throw"Internal error while compiling DOM access function."}return _path.unshift("_node"),"return "+_path.join(".")+";"}return new Function("_node",recordPath.call(this,_root,_target))},_buildNodeAccessFuncs:function(_rowTemplate){for(var i=0;i<_rowTemplate.seperated.detachable.length;i++)for(var entry=_rowTemplate.seperated.detachable[i],nodes=entry.widget.getDetachedNodes(),nodeFuncs=entry.nodeFuncs=new Array(nodes.length),j=0;j<nodes.length;j++)nodeFuncs[j]=this._compileDOMAccessFunc(_rowTemplate.row,nodes[j])},cat_regexp:/(^| |,|cat_)([0-9]+)/g,cat_cleanup:/[^0-9]/g,_setRowData:function(_data,_tr,_mgrs){if(_data.class){var classes=_mgrs.content.expandName(_data.class),cats=[];if(-1!==_data.class.indexOf("cat")||classes.match(/[0-9]+/)){var category_location=_data.class.match(/(cat(_id|egory)?)/);category_location&&(category_location=category_location[0]),cats=classes.match(this.cat_regexp)||[],classes=classes.replace(this.cat_regexp,"");for(var i=0;i<cats.length;i++){var cat_id=cats[i].replace(this.cat_cleanup,""),cat_class="cat_"+cat_id;classes+=" "+cat_class}classes+=" row_category"}classes+=" row",_tr.setAttribute("class",classes)}if(_data.valign){var align=_mgrs.content.expandName(_data.valign);_tr.setAttribute("valign",align)}}})}.call(this),et2_nextmatch_rowWidget=function(){"use strict";return et2_widget.extend(et2_IDOMNode,{init:function(_mgrs,_row){this._super(null,{id:"",type:"rowWidget"}),this._widgets=[],this._mgrs=_mgrs,this._row=_row},createWidgets:function(_widgets){this._widgets=new Array(_widgets.length);for(var i=0;i<_widgets.length;i++)_widgets[i]&&(this._widgets[i]=_widgets[i].clone(this),this._widgets[i].loadingFinished(),this._widgets[i].align&&(this._row.childNodes[i].align=this._widgets[i].align))},getDOMNode:function(_sender){for(var i=0;i<this._widgets.length;i++)if(this._widgets[i]==_sender)return this._row.childNodes[i].childNodes[0];return null}})}.call(this),et2_nextmatch_rowTemplateWidget=function(){"use strict";return et2_widget.extend(et2_IDOMNode,{init:function(_root,_row){this._super(null,{id:"",type:"rowTemplateWidget"}),this._root=_root,this._mgrs={},this._row=_row,this._parent=_root,this._widgets=[]},createWidgets:function(_mgrs,_widgets){this._mgrs=_mgrs,this._widgets=new Array(_widgets.length);for(var i=0;i<_widgets.length;i++)this._row.childNodes[0].childNodes[0],this._widgets[i]={widget:_widgets[i].widget.clone(this),node:_widgets[i].func(this._row)},this._widgets[i].widget.loadingFinished()},getDOMNode:function(_sender){for(var i=0;i<this._widgets.length;i++)if(this._widgets[i].widget==_sender)return this._widgets[i].node;return null}})}.call(this),et2_dynheight=function(){"use strict";return Class.extend({init:function(_outerNode,_innerNode,_minHeight){this.outerNode=$j(_outerNode),this.innerNode=$j(_innerNode),this.minHeight=_minHeight,this.bottomNodes=[],this.initialized=!1,this.innerMargin=0,this.outerMargin=0},update:function(_callback,_context){if(this.innerNode.is(":visible")){this._initialize();for(var oh=this.outerNode.height(),ot=this.outerNode.offset()?this.outerNode.offset().top:0,it=this.innerNode.offset().top,bminTop=this.bottomNodes.length?1/0:0,bmaxBot=0,i=0;i<this.bottomNodes.length;i++)if(this.bottomNodes[i].find(".action_popup").length)egw.debug("warn","Had to skip a hidden popup - it should be removed",this.bottomNodes[i].find(".action_popup"));else{var bh=this.bottomNodes[i].outerHeight(!0),bt=this.bottomNodes[i].offset().top,bb=bh+bt;(0==i||bminTop>bt)&&(bminTop=bt),(0==i||bb>bmaxBot)&&(bmaxBot=bb)}var bh=Math.max(0,bmaxBot-bminTop),h=Math.max(this.minHeight,oh+ot-it-bh-this.innerMargin-this.outerMargin);this.innerNode.height(h);var w=this.outerNode.width();w>$j(window).width()&&(w=$j(window).width()-50),w!=this.innerNode.outerWidth()&&this.innerNode.width(w),"undefined"!=typeof _callback&&_callback.call(_context,w,h)}},_collectBottomNodes:function(_node,_bottom){if("undefined"==typeof _bottom&&(_bottom=this.innerNode.offset().top+this.innerNode.height()),_node){var node=$j(_node),ooh=node.outerHeight(!0),oh=node.height();this.outerMargin+=(ooh-oh)/2;var self=this;$j(_node).children().each(function(){var $this=$j(this),top=$this.offset().top;this!=self.innerNode[0]&&top>=_bottom&&self.bottomNodes.push($this)}),_node!=this.outerNode[0]&&_node!=$j("body")[0]&&this._collectBottomNodes(_node.parentNode,_bottom)}},_initialize:function(){if(!this.initialized){this.bottomNodes=[],this.outerMargin=0,this._collectBottomNodes(this.innerNode[0].parentNode);var ioh=this.innerNode.outerHeight(!0),ih=this.innerNode.height();this.innerMargin=ioh-ih,this.initialized=!0}}})}.call(this),ET2_COL_TYPE_DEFAULT=0,ET2_COL_TYPE_NAME_ICON_FIXED=1,ET2_COL_VISIBILITY_ALWAYS=0,ET2_COL_VISIBILITY_VISIBLE=1,ET2_COL_VISIBILITY_INVISIBLE=2,ET2_COL_VISIBILITY_ALWAYS_NOSELECT=3,et2_dataview_column=function(){"use strict";return ClassWithAttributes.extend({attributes:{id:{name:"ID",type:"string",description:"Unique identifier for this column. It is used to store changed column widths or visibilities."},visibility:{name:"Visibility",type:"integer",default:ET2_COL_VISIBILITY_VISIBLE,description:"Defines the visibility state of this column."},caption:{name:"Caption",type:"string",description:"Caption of the column as it is displayed in the select columns popup."},type:{name:"Column type",type:"integer",default:ET2_COL_TYPE_DEFAULT,description:"Type of the column"},width:{name:"Width",type:"dimension",default:"80px",description:"Width of the column."},minWidth:{name:"Minimum width",type:"integer",default:20,description:"Minimum width of the column, in pixels. Values below this are rejected."},maxWidth:{name:"Maximum width",type:"integer",default:0,description:"Maximum width of the column"}},init:function(_attrs){this.fixedWidth=!1,this.relativeWidth=!1,this.generateAttributeSet(_attrs),this.initAttributes(_attrs)},set_width:function(_value){this.relativeWidth=!1,this.fixedWidth=!1;var w=_value;"number"==typeof w?this.relativeWidth=parseFloat(w.toFixed(3)):"%"!=w.charAt(w.length-1)||isNaN(w.substr(0,w.length-1))?"px"!=w.substr(w.length-2,2)||isNaN(w.substr(0,w.length-2))?"string"!=typeof w||isNaN(w)||(this.fixedWidth=parseInt(w)):this.fixedWidth=parseInt(w.substr(0,w.length-2)):(this.relativeWidth=parseInt(w.substr(0,w.length-1))/100,this.relativeWidth>1&&(this.relativeWidth=!1))},set_visibility:function(_value){this.visibility!=ET2_COL_VISIBILITY_ALWAYS&&this.visibility!=ET2_COL_VISIBILITY_ALWAYS_NOSELECT&&(_value===!0?this.visibility=ET2_COL_VISIBILITY_VISIBLE:_value===!1?this.visibility=ET2_COL_VISIBILITY_INVISIBLE:"number"==typeof _value?this.visibility=_value:this.egw().debug("warn","Invalid visibility option for column: ",_value))}})}.call(this),et2_dataview_columns=function(){"use strict";return Class.extend({init:function(_columnData){this.totalWidth=0,this.totalFixed=0,this.columnWidths=[],this.columns=new Array(_columnData.length);for(var i=0;i<_columnData.length;i++)this.columns[i]=new et2_dataview_column(_columnData[i]);this.updated=!0},destroy:function(){for(var i=0;i<this.columns.length;i++)this.columns[i].free()},setTotalWidth:function(_width){_width!=this.totalWidth&&_width>0&&(this.totalWidth=_width,this.updated=!0)},getColumnIndexById:function(_id){for(var i=0;i<this.columns.length;i++)if(this.columns[i].id==_id)return i;return-1},getColumnById:function(_id){var idx=this.getColumnIndexById(_id);return-1==idx?null:this.columns[idx]},getColumnWidth:function(_idx){return this.totalWidth>0&&_idx>=0&&_idx<this.columns.length?(this.updated&&(this._calculateWidths(),this.updated=!1),this.columnWidths[_idx]):0},getColumnData:function(){for(var result=[],i=0;i<this.columns.length;i++)result.push({id:this.columns[i].id,width:this.getColumnWidth(i),visible:this.columns[i].visibility!=ET2_COL_VISIBILITY_INVISIBLE});return result},getColumnVisibilitySet:function(){for(var result={},i=0;i<this.columns.length;i++)this.columns[i].visibility!=ET2_COL_VISIBILITY_ALWAYS_NOSELECT&&(result[this.columns[i].id]={caption:this.columns[i].caption,enabled:this.columns[i].visibility!=ET2_COL_VISIBILITY_ALWAYS&&this.columns[i].type!=ET2_COL_TYPE_NAME_ICON_FIXED,visible:this.columns[i].visibility!=ET2_COL_VISIBILITY_INVISIBLE});return result},setColumnVisibilitySet:function(_set){for(var k in _set){var col=this.getColumnById(k);col&&col.set_visibility(_set[k].visible?ET2_COL_VISIBILITY_VISIBLE:ET2_COL_VISIBILITY_INVISIBLE)}this.updated=!0},_calculateWidths:function(){for(var i=0;i<this.columns.length;i++)this.columns[i]._larger=!1,this.columns[i]._newWidth=!1;var tw=this.totalWidth,totalRelative=0;this.totalFixed=0;for(var i=0;i<this.columns.length;i++){var col=this.columns[i];col.visibility!=ET2_COL_VISIBILITY_INVISIBLE&&(col.fixedWidth>tw||col.fixedWidth<0?col.fixedWidth=!1:(col.relativeWidth>1||col.relativeWidth<0)&&(col.relativeWidth=!1),col.relativeWidth?totalRelative+=col.relativeWidth:col.fixedWidth&&(this.totalFixed+=col.fixedWidth))}var usedTotal=0;this.columnWidths=[];for(var i=0;i<this.columns.length;i++){var w=0,col=this.columns[i];col.visibility!=ET2_COL_VISIBILITY_INVISIBLE&&(col._larger?w=col.maxWidth:col.fixedWidth?w=col.fixedWidth:col.relativeWidth&&(col.relativeWidth=col.relativeWidth/totalRelative,w=Math.round((tw-this.totalFixed)*col.relativeWidth)),(w>tw||col.maxWidth&&w>col.maxWidth)&&(w=Math.min(tw-usedTotal,col.maxWidth)),(0>w||w<col.minWidth)&&(w=Math.max(0,col.minWidth))),this.columnWidths.push(w),usedTotal+=w}if(usedTotal!=tw){var column,columnIndex,remaining_width=usedTotal-tw;for(columnIndex=0;columnIndex<this.columns.length;columnIndex++)if(!(this.columns[columnIndex].visibility==ET2_COL_VISIBILITY_INVISIBLE||this.columnWidths[columnIndex]<=0)){var col=this.columns[columnIndex];if(col.relativeWidth||!col.fixedWidth){column=col;break}col.fixedWidth||(column=col)}if(column)this.columnWidths[columnIndex]=Math.max(column.minWidth,this.columnWidths[columnIndex]-remaining_width);else for(var i=0;i<this.columns.length;i++){var col=this.columns[i];col.fixedWidth-=Math.round(this.columnWidths[i]/tw*remaining_width),this.columnWidths[i]=Math.max(0,Math.min(col.fixedWidth,tw))}}}})}.call(this),et2_dataview_rowProvider=function(){"use strict";return Class.extend({init:function(_outerId,_columnIds){this._outerId=_outerId,this._columnIds=_columnIds,this._prototypes={},this._template=null,this._mgrs=null,this._rootWidget=null,this._createFullRowPrototype(),this._createDefaultPrototype(),this._createEmptyPrototype(),this._createLoadingPrototype()},getColumnCount:function(){return this._columnIds.length},getPrototype:function(_name,_generator,_context){if("undefined"==typeof this._prototypes[_name]){if("undefined"==typeof _generator)return null;this._prototypes[_name]=_generator.call(_context,this._outerId,this._columnIds)}return this._prototypes[_name].clone()},_createFullRowPrototype:function(){var tr=$j(document.createElement("tr")),td=$j(document.createElement("td")).addClass(this._outerId+"_td_fullRow").attr("colspan",this._columnIds.length).appendTo(tr);$j(document.createElement("div")).addClass(this._outerId+"_div_fullRow").appendTo(td);this._prototypes.fullRow=tr},_createDefaultPrototype:function(){for(var tr=$j(document.createElement("tr")),i=0;i<this._columnIds.length;i++){var td=$j(document.createElement("td")).addClass(this._outerId+"_td_"+this._columnIds[i]).appendTo(tr);$j(document.createElement("div")).addClass(this._outerId+"_div_"+this._columnIds[i]).addClass("innerContainer").appendTo(td)}this._prototypes.default=tr},_createEmptyPrototype:function(){this._prototypes.empty=$j(document.createElement("tr"))},_createLoadingPrototype:function(){var fullRow=this.getPrototype("fullRow");$j("div",fullRow).addClass("loading"),this._prototypes.loading=fullRow}})}.call(this),et2_dataview_spacer=function(){"use strict";return et2_dataview_container.extend({init:function(_parent,_rowProvider){this._super(_parent),this._count=0,this._rowHeight=19,this._avgSum=0,this._avgCount=0,this.spacerNode=_rowProvider.getPrototype("spacer",this._createSpacerPrototype,this),this._phDiv=$j("td",this.spacerNode),this.appendNode(this.spacerNode)},setCount:function(_count,_rowHeight){this._count=_count,"undefined"!=typeof _rowHeight&&(this._rowHeight=_rowHeight),this._phDiv.height(this._count*this._rowHeight),this.invalidate()},getCount:function(){return this._count},getHeight:function(){return this._height=this._count*this._rowHeight,this._height},getAvgHeightData:function(){return this._avgCount>0?{avgHeight:this._avgSum/this._avgCount,avgCount:this._avgCount}:null},addAvgHeight:function(_height){this._avgSum+=_height,this._avgCount++},_createSpacerPrototype:function(_outerId,_columnIds){var tr=$j(document.createElement("tr"));$j(document.createElement("td")).addClass("egwGridView_spacer").addClass(_outerId+"_spacer_fullRow").attr("colspan",_columnIds.length).appendTo(tr);return tr}})}.call(this),ET2_GRID_VIEW_EXT=50,ET2_GRID_SCROLL_TIMEOUT=50,ET2_GRID_INVALIDATE_TIMEOUT=25,ET2_GRID_HOLD_COUNT=50,et2_dataview_grid=function(){"use strict";return et2_dataview_container.extend(et2_dataview_IViewRange,{init:function(_parent,_parentGrid,_egw,_rowProvider,_avgHeight){this._super(_parent),null!=_parentGrid?(this.egw=_parent.egw,this._orgAvgHeight=!1,this._rowProvider=_parentGrid._rowProvider):(this.egw=_egw,this._orgAvgHeight=_avgHeight,this._rowProvider=_rowProvider,this._scrollHeight=0,this._scrollTimeout=null),this._parentGrid=_parentGrid,this._scrollTimeout=null,this._invalidateTimeout=null,this._invalidateCallback=null,this._invalidateContext=null,this.doInvalidate=!0,this._map=[],this._viewRange=et2_range(0,0),this._total=0,this._avgHeight=!1,this._avgCount=!1,this._createNodes()},destroy:function(){this.setTotalCount(0),this._scrollTimeout&&window.clearTimeout(this._scrollTimeout),this._invalidateTimeout&&window.clearTimeout(this._invalidateTimeout),this._super()},clear:function(){var oldTotalCount=this._total;this._orgAvgHeight=this.getAverageHeight(),this.setTotalCount(0),this.setTotalCount(oldTotalCount)},cleanup:function(){this._recalculateElementPosition();var mapVis=this._calculateVisibleMappingIndices();this._cleanupOutOfRangeElements(mapVis,0)},insertRow:function(_index,_container){var idx=this._calculateMapIndex(_index);if(idx!==!1){_container instanceof et2_dataview_container&&(_container=[_container]);for(var avg=this.getAverageHeight(),i=0;i<_container.length;i++)this._doInsertContainer(_index,idx,_container[i],avg);this.invalidate()}},deleteRow:function(_index){var idx=this._calculateMapIndex(_index);idx!==!1&&(this._doDeleteContainer(idx,!1),this.invalidate())},setInvalidateCallback:function(_callback,_context){this._invalidateCallback=_callback,this._invalidateContext=_context},setDataCallback:function(_callback,_context){this._callback=_callback,this._context=_context},setTotalCount:function(_count){if(_count!==this._total){var delta=Math.max(0,_count)-this._total;delta>0?this._appendEmptyRows(delta):this._decreaseTotal(-delta),this._total=Math.max(0,_count),this.invalidate()}},getTotalCount:function(){return this._total},setViewRange:function(_range){this._viewRange=_range,this._doInvalidate()},getVisibleIndexRange:function(_viewRange){function getElemIdx(_elem,_px){return _elem instanceof et2_dataview_spacer?_elem.getIndex()+Math.floor((_px-_elem.getTop())/this.getAverageHeight()):_elem.getIndex()}var vr,idxTop=0,idxBottom=0;vr=_viewRange?_viewRange:et2_bounds(this._viewRange.top+ET2_GRID_VIEW_EXT,this._viewRange.bottom-ET2_GRID_VIEW_EXT);for(var topElem=null,botElem=null,i=0;i<this._map.length;i++)if(!topElem&&this._map[i].getBottom()>vr.top&&(topElem=this._map[i]),this._map[i].getTop()>vr.bottom){botElem=this._map[i];break}return botElem||(botElem=this._map[this._map.length-1]),topElem&&(idxTop=getElemIdx.call(this,topElem,vr.top),idxBottom=getElemIdx.call(this,botElem,vr.bottom)),et2_bounds(idxTop,idxBottom)},getIndexRange:function(){for(var idxTop=!1,idxBottom=!1,i=0;i<this._map.length;i++)if(!(this._map[i]instanceof et2_dataview_spacer)){var idx=this._map[i].getIndex();idxTop===!1&&(idxTop=idx),idxBottom=idx}return et2_bounds(idxTop,idxBottom)},setScrollHeight:function(_height){this._scrollHeight=_height,this.scrollarea&&this.scrollarea.height(_height),this.setViewRange(et2_range(this._viewRange.top,this._scrollHeight))},getAvgHeightData:function(){if(this._avgHeight===!1){for(var avgCount=0,avgSum=0,i=0;i<this._map.length;i++){var data=this._map[i].getAvgHeightData();null!==data&&(avgSum+=data.avgHeight*data.avgCount,avgCount+=data.avgCount)}avgCount>0&&avgSum>0&&(this._avgHeight=avgSum/avgCount,this._avgCount=avgCount)}return this._avgHeight!==!1?{avgCount:this._avgCount,avgHeight:this._avgHeight}:this._parent?this._parent.getAvgHeightData():this._orgAvgHeight!==!1?{avgCount:1,avgHeight:this._orgAvgHeight}:null},getAverageHeight:function(){var data=this.getAvgHeightData();return data?data.avgHeight:19},getRowProvider:function(){return this._rowProvider},invalidate:function(){if(this._invalidateTimeout&&window.clearTimeout(this._invalidateTimeout),this.doInvalidate){var self=this,_super=this._super;this._invalidateTimeout=window.setTimeout(function(){egw.debug("log","Dataview grid timed invalidate"),self._avgHeight=!1,self._avgCount=!1,self._invalidateTimeout=null,self._doInvalidate(_super)},ET2_GRID_INVALIDATE_TIMEOUT)}},makeIndexVisible:function(_idx){var elemRange=this._getElementRange(_idx);if(!elemRange)return!1;var visibleRange=et2_bounds(this._viewRange.top+ET2_GRID_VIEW_EXT,this._viewRange.bottom-ET2_GRID_VIEW_EXT);if(visibleRange.top<elemRange.top&&visibleRange.bottom>elemRange.bottom)return!0;if(elemRange.top<visibleRange.top)this.scrollarea.scrollTop(elemRange.top);else{var h=elemRange.bottom-elemRange.top;this.scrollarea.scrollTop(elemRange.top-this._scrollHeight+h)}},_getElementRange:function(_idx){this._recalculateElementPosition();var mapIdx=this._calculateMapIndex(_idx);if(mapIdx===!1)return!1;var elem=this._map[mapIdx];if(elem instanceof et2_dataview_spacer){var avg=this.getAverageHeight();return et2_range(elem.getTop()+avg*(elem.getIndex()-_idx),avg)}return elem.getRange()},_recalculateElementPosition:function(){for(var i=0;i<this._map.length;i++)0==i?this._map[i].setTop(0):this._map[i].setTop(this._map[i-1].getBottom())},_calculateVisibleMappingIndices:function(){for(var mapVis={top:!1,bottom:!1},i=0;i<this._map.length;i++)if(mapVis.top===!1&&this._map[i].getBottom()>this._viewRange.top&&(mapVis.top=i),mapVis.bottom===!1&&this._map[i].getTop()>this._viewRange.bottom){mapVis.bottom=i;break}return mapVis},_cleanupOutOfRangeElements:function(_mapVis,_holdCount){function searchElements(_arr,_start,_stop,_dir){for(var dist=0,i=_start;_dir>0?_stop>=i:i>=_stop;i+=_dir)dist>_holdCount?_arr.push(i):dist+=this._map[i].getCount()}_holdCount="undefined"==typeof _holdCount?ET2_GRID_HOLD_COUNT:_holdCount;var deleteTop=[],deleteBottom=[];_mapVis.top!==!1&&searchElements.call(this,deleteTop,_mapVis.top,0,-1),_mapVis.bottom!==!1&&searchElements.call(this,deleteBottom,_mapVis.bottom,this._map.length-1,1);for(var offs=0,i=deleteTop.length-1;i>=0;i--){var mapLength=this._map.length;this._doDeleteContainer(deleteTop[i]-offs,!0),offs+=mapLength-this._map.length}for(var i=deleteBottom.length-1;i>=0;i--)this._doDeleteContainer(deleteBottom[i]-offs,!0);return deleteBottom.length+deleteTop.length>0},_updateContainers:function(){for(var i=0;i<this._map.length;i++){var container=this._map[i],isSpacer=container instanceof et2_dataview_spacer,hasIViewRange=!isSpacer&&container.implements(et2_dataview_IViewRange);if(isSpacer||hasIViewRange){var elemRange=container.getRange();if(!et2_rangeIntersect(this._viewRange,elemRange))continue;if(hasIViewRange)container.setViewRange(et2_bounds(this._viewRange.top-elemRange.top,this._viewRange.bottom-elemRange.top));else{var avg=container._rowHeight,vcr_top=Math.max(this._viewRange.top,elemRange.top),vcr_bot=Math.min(this._viewRange.bottom,elemRange.bottom),cidx=container.getIndex(),ccnt=container.getCount(),vtop=Math.max(0,vcr_top),idxStart=Math.floor(Math.min(cidx+ccnt-1,cidx+(vtop-elemRange.top)/avg,this._total)),vbot=Math.max(0,vcr_bot),idxEnd=Math.ceil(Math.min(cidx+ccnt-1,cidx+(vbot-elemRange.top)/avg,this._total));if(isNaN(idxStart)&&isSpacer&&(idxStart=cidx-1),isNaN(idxEnd)&&isSpacer&&this._scrollHeight>0&&0==elemRange.bottom&&(idxEnd=Math.min(ccnt,cidx+Math.ceil((this._viewRange.bottom-container._top)/this._orgAvgHeight))),this._callback){var self=this;egw.debug("log","Dataview grid flag for update: ",{start:idxStart,end:idxEnd}),window.setTimeout(function(){"undefined"!=typeof self._callback&&self._callback.call(self._context,idxStart,idxEnd)},0)}}}}},_doInvalidate:function(_super){if(this.doInvalidate){if(this._recalculateElementPosition(),this._invalidateCallback){var range=this.getVisibleIndexRange(et2_range(this.scrollarea.scrollTop(),this._scrollHeight));this._invalidateCallback.call(this._invalidateContext,range)}var mapVis=this._calculateVisibleMappingIndices();this._cleanupOutOfRangeElements(mapVis)&&this._recalculateElementPosition(),this._updateContainers(),this._parent&&_super&&_super.call(this)}},_calculateMapIndex:function(_index){for(var top=0,bot=this._map.length-1;bot>=top;){var idx=Math.floor((top+bot)/2),elem=this._map[idx],realIdx=elem.getIndex(),realCnt=elem.getCount();if(_index>=realIdx&&realIdx+realCnt>_index)return idx;realIdx>_index?bot=idx-1:top=idx+1}return!1},_insertContainerAtSpacer:function(_index,_mapIndex,_mapElem,_container,_avg){_container.setIndex(_index);var splitIdx=_index-_mapElem.getIndex(),cntTop=splitIdx,cntBottom=_mapElem.getCount()-splitIdx-1;if(cntTop>0&&cntBottom>0){_mapElem.setCount(cntTop),_container.insertIntoTree(_mapElem.getLastNode());var newSpacer=new et2_dataview_spacer(this,this._rowProvider);newSpacer.setCount(cntBottom,_avg),newSpacer.setIndex(_index+1),newSpacer.insertIntoTree(_container.getLastNode()),this._map.splice(_mapIndex+1,0,_container,newSpacer)}else 0===cntTop&&cntBottom>0?(_container.insertIntoTree(_mapElem.getFirstNode(),!0),_mapElem.setIndex(_index+1),_mapElem.setCount(cntBottom,_avg),this._map.splice(_mapIndex,0,_container)):cntTop>0&&0===cntBottom?(_container.insertIntoTree(_mapElem.getLastNode()),_mapElem.setCount(cntTop),this._map.splice(_mapIndex+1,0,_container)):(_container.insertIntoTree(_mapElem.getLastNode()),_mapElem.free(),this._map.splice(_mapIndex,1,_container))},_insertContainerAtElement:function(_index,_mapIndex,_mapElem,_container,_avg){_container.setIndex(_index),_container.insertIntoTree(_mapElem.getFirstNode(),!0),this._map.splice(_mapIndex,0,_container);for(var _newIndex=_index+1,i=_mapIndex+1;i<this._map.length;i++)if(this._map[i].setIndex(_newIndex++),this._map[i]instanceof et2_dataview_spacer)return void this._decrementSpacerCount(i,_avg);this._map.pop().free()},_doInsertContainer:function(_index,_mapIndex,_container,_avg){var mapElem=this._map[_mapIndex];mapElem instanceof et2_dataview_spacer?this._insertContainerAtSpacer(_index,_mapIndex,mapElem,_container,_avg):this._insertContainerAtElement(_index,_mapIndex,mapElem,_container,_avg)},_replaceContainerWithSpacer:function(_mapIndex,_mapElem){var spacerAbove=null,spacerBelow=null;if(_mapIndex>0&&this._map[_mapIndex-1]instanceof et2_dataview_spacer&&(spacerAbove=this._map[_mapIndex-1]),_mapIndex<this._map.length-1&&this._map[_mapIndex+1]instanceof et2_dataview_spacer&&(spacerBelow=this._map[_mapIndex+1]),spacerAbove||spacerBelow)if(spacerAbove&&spacerBelow){var totalHeight=spacerAbove.getHeight()+spacerBelow.getHeight()+_mapElem.getHeight(),totalCount=spacerAbove.getCount()+spacerBelow.getCount()+1,newAvg=totalHeight/totalCount;spacerAbove.addAvgHeight(_mapElem.getHeight()),spacerAbove.setCount(totalCount,newAvg),spacerBelow.free(),this._map.splice(_mapIndex+1,1)}else{var spacer=spacerAbove||spacerBelow,totalCount=spacer.getCount()+1,totalHeight=spacer.getHeight()+_mapElem.getHeight(),newAvg=totalHeight/totalCount;spacer.setIndex(Math.min(spacer.getIndex(),_mapElem.getIndex())),spacer.addAvgHeight(_mapElem.getHeight()),spacer.setCount(totalCount,newAvg)}else{var spacer=new et2_dataview_spacer(this,this._rowProvider);spacer.setIndex(_mapElem.getIndex()),spacer.addAvgHeight(_mapElem.getHeight()),spacer.setCount(1,_mapElem.getHeight()),spacer.insertIntoTree(_mapElem.getLastNode()),this._map.splice(_mapIndex+1,0,spacer)}},_consolidateSpacers:function(_mapIndex){if(_mapIndex<this._map.length-1&&this._map[_mapIndex]instanceof et2_dataview_spacer&&this._map[_mapIndex+1]instanceof et2_dataview_spacer){var spacerAbove=this._map[_mapIndex],spacerBelow=this._map[_mapIndex+1],totalHeight=spacerAbove.getHeight()+spacerBelow.getHeight(),totalCount=spacerAbove.getCount()+spacerBelow.getCount(),newAvg=totalCount/totalHeight;spacerAbove.setCount(totalCount,newAvg),spacerBelow.free(),this._map.splice(_mapIndex+1,1)}},_decrementSpacerCount:function(_mapIndex,_avg){var cnt=this._map[_mapIndex].getCount()-1;cnt>0?this._map[_mapIndex].setCount(cnt,_avg):(this._map[_mapIndex].free(),this._map.splice(_mapIndex,1))},_doDeleteContainer:function(_mapIndex,_replaceWithSpacer){_replaceWithSpacer=_replaceWithSpacer?_replaceWithSpacer:!1;var mapElem=this._map[_mapIndex],removedElement=!1;if(mapElem instanceof et2_dataview_spacer?_replaceWithSpacer||(this._decrementSpacerCount(_mapIndex),removedElement=!0):(_replaceWithSpacer?this._replaceContainerWithSpacer(_mapIndex,mapElem):removedElement=!0,this._map[_mapIndex].free(),this._map.splice(_mapIndex,1),_mapIndex--,this._consolidateSpacers(_mapIndex)),removedElement){for(var i=_mapIndex+1;i<this._map.length;i++)this._map[i].setIndex(this._map[i].getIndex()-1);this._appendEmptyRows(1)}},_appendEmptyRows:function(_count){var spacer=null,lastIndex=this._map.length-1;if(0!==this._map.length&&this._map[lastIndex]instanceof et2_dataview_spacer)spacer=this._map[lastIndex];else{if(spacer=new et2_dataview_spacer(this,this._rowProvider),0===this._map.length){var dummy=$j(document.createElement("tr"));this.innerTbody.append(dummy),spacer.setIndex(0),spacer.insertIntoTree(dummy,!1),dummy.remove()}else spacer.setIndex(this._map[lastIndex].getIndex()+1),spacer.insertIntoTree(this._map[lastIndex].getLastNode());this._map.push(spacer)}spacer.setCount(_count+spacer.getCount(),this.getAverageHeight())},_decreaseTotal:function(_delta){for(;_delta>0&&this._map.length>0;){var cont=this._map[this._map.length-1];if(cont instanceof et2_dataview_spacer){var diff=cont.getCount()-_delta;if(diff>0){_delta=0,cont.setCount(diff,this.getAverageHeight());break}_delta-=diff+_delta}else _delta-=1;cont.free(),this._map.pop()}_delta>0&&this.egw.debug("error","Error while decreasing the total count - requested to remove more rows than available.")},_createNodes:function(){this.tr=$j(document.createElement("tr")),this.outerCell=$j(document.createElement("td")).addClass("frame").attr("colspan",this._rowProvider.getColumnCount()+(this._parentGrid?0:1)).appendTo(this.tr),this.scrollarea=null,null==this._parentGrid&&(this.scrollarea=$j(document.createElement("div")).addClass("egwGridView_scrollarea").scroll(this,function(e){e.data._scrollTimeout&&window.clearTimeout(e.data._scrollTimeout),e.data._invalidateTimeout&&(window.clearTimeout(e.data._invalidateTimeout),e.data._invalidateTimeout=null),e.data._scrollTimeout=window.setTimeout(function(){var newRange=et2_range(e.data.scrollarea.scrollTop()-ET2_GRID_VIEW_EXT,e.data._scrollHeight+2*ET2_GRID_VIEW_EXT);et2_rangeEqual(newRange,e.data._viewRange)||e.data.setViewRange(newRange)},ET2_GRID_SCROLL_TIMEOUT)}).height(this._scrollHeight).appendTo(this.outerCell));var table=$j(document.createElement("table")).addClass("egwGridView_grid").appendTo(this.scrollarea?this.scrollarea:this.outerCell);this.innerTbody=$j(document.createElement("tbody")).appendTo(table),this.appendNode($j(this.tr[0]))}})}.call(this);(function(){"use strict";function inResizeRegion(_x,_elem){var ol=_x-_elem.offset().left;return ol>_elem.outerWidth(!0)-RESIZE_BORDER}function startResize(_outerElem,_elem,_callback,_column){if(null==overlay||null==helper){"undefined"!=typeof _elem[0].style.MozUserSelect?_elem[0].style.MozUserSelect="none":_elem[0].onselectstart=function(){return!1},$j(_outerElem).addClass("egwResizing"),didResize=!1;var left=_elem.offset().left;helper=$j(document.createElement("div")).addClass("egwResizeHelper").appendTo("body").css("top",_elem.offset().top+"px").css("left",left+"px").css("height",_outerElem.outerHeight(!0)+"px"),overlay=$j(document.createElement("div")).addClass("egwResizeOverlay").bind("mousemove",function(e){didResize=!0,resizeWidth=Math.max(e.pageX-left+RESIZE_ADD,_column&&_column.minWidth?_column.minWidth:RESIZE_MIN_WIDTH),helper.css("width",resizeWidth+"px")}).bind("mouseup",function(){stopResize(_outerElem),_elem[0].onselectstart=null,didResize&&_callback(resizeWidth)}).appendTo("body")}}function stopResize(_outerElem){$j(_outerElem).removeClass("egwResizing"),null!=helper&&(helper.remove(),helper=null),null!=overlay&&(overlay.remove(),overlay=null)}var RESIZE_BORDER=12,RESIZE_MIN_WIDTH=25,RESIZE_ADD=2,helper=null,overlay=null,didResize=!1,resizeWidth=0;this.et2_dataview_makeResizeable=function(_elem,_callback,_context){var outerTable=_elem.closest("table");_elem.bind("mousemove.resize",function(e){var stopResize=!1;e.target.clientHeight<e.target.scrollHeight&&e.target.offsetWidth-e.offsetX<=8&&(stopResize=!0),_elem.css("cursor",inResizeRegion(e.pageX,_elem)&&!stopResize?"ew-resize":"auto")}),_elem.bind("mousedown.resize",function(e){var stopResize=!1;e.target.clientHeight<e.target.scrollHeight&&e.target.offsetWidth-e.offsetX<=8&&(stopResize=!0),inResizeRegion(e.pageX,_elem)&&"SELECT"!=e.target.tagName&&!stopResize&&startResize(outerTable,_elem,function(_w){_callback.call(_context,_w)},_context)})},this.et2_dataview_resetResizeable=function(_elem){_elem.unbind(".resize")}}).call(window);var et2_dataview=function(){"use strict";return Class.extend({columnPadding:2,scrollbarWidth:!1,headerBorderWidth:!1,columnBorderWidth:!1,onUpdateColumns:!1,selectColumnsClick:!1,init:function(_parentNode,_egw){this.parentNode=$j(_parentNode),this.egw=_egw,this.columnNodes=[],this.columns=[],this.columnMgr=null,this.rowProvider=null,this.grid=null,this.width=0,this.height=0,this.uniqueId="gridCont_"+this.egw.uid(),this._createElements(),this._getDepVars()},destroy:function(){this._clearHeader(),this.grid&&this.grid.free(),this.rowProvider&&this.rowProvider.free(),this.table.remove()},clear:function(){this.grid&&this.grid.clear()},getHeaderContainerNode:function(_columnIdx){return"undefined"!=typeof this.columnNodes[_columnIdx]?this.columnNodes[_columnIdx].container[0]:null},setColumns:function(_columnData){this._clearHeader(),this.columnMgr=new et2_dataview_columns(_columnData),this.updateColumns(),this._buildHeader(),this._buildGrid()},resize:function(_w,_h){this.columnMgr&&(this.width!=_w&&(this.width=_w,this.columnMgr.setTotalWidth(_w-this.scrollbarWidth),this._updateColumns()),this.height!=_h&&(this.height=_h,this.grid&&this.grid.setScrollHeight(this.height-this.headTr.outerHeight(!0))))},getColumnMgr:function(){return this.columnMgr},updateColumns:function(setDefault){this.columnMgr&&this._updateColumns(),this.onUpdateColumns&&this.onUpdateColumns(setDefault);
},_createElements:function(){this.containerTr=$j(document.createElement("tr")),this.headTr=$j(document.createElement("tr")),this.thead=$j(document.createElement("thead")).append(this.headTr),this.tbody=$j(document.createElement("tbody")).append(this.containerTr),this.table=$j(document.createElement("table")).addClass("egwGridView_outer").append(this.thead,this.tbody).appendTo(this.parentNode)},_clearHeader:function(){this.columnMgr&&(this.columnMgr.free(),this.columnMgr=null);for(var i=0;i<this.columns.length;i++)this.columns[i].tdClass&&this.egw.css("."+this.columns[i].tdClass),this.columns[i].divClass&&(this.egw.css("."+this.columns[i].divClass),this.egw.css(".egwGridView_outer ."+this.columns[i].divClass),this.egw.css(".egwGridView_grid ."+this.columns[i].divClass));this.egw.css(".egwGridView_grid ."+this.uniqueId+"_div_fullRow"),this.egw.css(".egwGridView_outer ."+this.uniqueId+"_td_fullRow"),this.egw.css(".egwGridView_outer ."+this.uniqueId+"_spacer_fullRow"),this.columnNodes=[],this.columns=[],this.headTr.empty()},_updateColumns:function(){this.columns=this.columnMgr.getColumnData();for(var total_cnt=0,i=0;i<this.columns.length;i++)this.columns[i].visible&&total_cnt++;for(var first=!0,vis_col=this.visibleColumnCount=0,totalWidth=0,i=0;i<this.columns.length;i++){var col=this.columns[i];if(col.tdClass=this.uniqueId+"_td_"+col.id,col.divClass=this.uniqueId+"_div_"+col.id,col.visible){vis_col++,this.visibleColumnCount++,this.egw.css("."+col.tdClass,"display: table-cell; !important;");var subBorder=0,subHBorder=0;vis_col==total_cnt&&(subBorder+=1);var headerWidth=Math.max(0,col.width-this.headerBorderWidth-subHBorder);this.egw.css(".egwGridView_outer ."+col.divClass,"width: "+headerWidth+"px;");var columnWidth=Math.max(0,col.width-this.columnBorderWidth-subBorder);this.egw.css(".egwGridView_grid ."+col.divClass,"width: "+columnWidth+"px;"),totalWidth+=col.width,first=!1}else this.egw.css("."+col.tdClass,"display: none;")}this.egw.css(".egwGridView_grid ."+this.uniqueId+"_div_fullRow","width: "+(totalWidth-this.columnBorderWidth-2)+"px; border-right-width: 0 !important;"),this.egw.css(".egwGridView_outer ."+this.uniqueId+"_td_fullRow","border-right-width: 0 !important;"),this.egw.css(".egwGridView_outer ."+this.uniqueId+"_spacer_fullRow","width: "+(totalWidth-1)+"px; border-right-width: 0 !important;")},_buildHeader:function(){for(var self=this,i=0;i<this.columns.length;i++){var col=this.columns[i],cont=$j(document.createElement("div")).addClass("innerContainer").addClass(col.divClass),column=$j(document.createElement("th")).addClass(col.tdClass).attr("align","left").append(cont).appendTo(this.headTr);this.columnMgr&&this.columnMgr.columns[i]&&column.addClass(this.columnMgr.columns[i].fixedWidth?"fixedWidth":"relativeWidth");var enc_column=self.columnMgr.getColumnById(col.id);et2_dataview_makeResizeable(column,function(_w){if(this.relativeWidth){this.set_width(_w+"px"),self.columnMgr.updated=!0,self.columnMgr.getColumnWidth(0);var relative=self.columnMgr.totalWidth-self.columnMgr.totalFixed+_w;this.set_width(_w/relative);for(var i=0;i<self.columnMgr.columns.length;i++){var col=self.columnMgr.columns[i];col==this||col.fixedWidth||col.set_width(self.columnMgr.columnWidths[i]/relative)}self.updateColumns()}else this.set_width(this.relativeWidth?_w/self.columnMgr.totalWidth:_w+"px"),self.columnMgr.updated=!0,self.updateColumns()},enc_column),this.columnNodes.push({column:column,container:cont})}this._buildSelectCol()},_buildSelectCol:function(){this.selectColIcon=$j(document.createElement("span")).addClass("selectcols").css("display","inline-block"),this.selectCol=$j(document.createElement("th")).addClass("optcol").append(this.selectColIcon).click(this,function(e){e.data.selectColumnsClick&&e.data.selectColumnsClick(e)}).appendTo(this.headTr),this.selectCol.css("width",this.scrollbarWidth-this.selectCol.outerWidth()+this.selectCol.width()+1)},_buildGrid:function(){for(var colIds=new Array(this.columns.length),i=0;i<this.columns.length;i++)colIds[i]=this.columns[i].id;this.rowProvider&&this.rowProvider.free(),this.rowProvider=new et2_dataview_rowProvider(this.uniqueId,colIds),this.grid=new et2_dataview_grid(null,null,this.egw,this.rowProvider,19);var tr=$j(this.grid._nodes[0]);this.containerTr.replaceWith(tr),this.containerTr=tr},_getDepVars:function(){if(this.scrollbarWidth===!1){var clone=this.table.clone();$j(window.top.document.getElementsByTagName("body")[0]).append(clone),this.scrollbarWidth=this.constructor.prototype.scrollbarWidth=this._getScrollbarWidth(clone),this.headerBorderWidth=this.constructor.prototype.headerBorderWidth=this._getHeaderBorderWidth(clone),this.columnBorderWidth=this.constructor.prototype.columnBorderWidth=this._getColumnBorderWidth(clone),clone.remove()}},_getScrollbarWidth:function(_table){var div_inner=$j(document.createElement("div")).css("height","1000px"),div_outer=$j(document.createElement("div")).css("height","100px").css("width","100px").css("overflow","auto").append(div_inner),td=$j(document.createElement("td")).append(div_outer);$j("tbody tr",_table).append(td);var width=Math.max(10,div_outer.outerWidth()-div_inner.outerWidth());return div_outer.remove(),width},_getHeaderBorderWidth:function(_table){var cont=$j(document.createElement("div")).addClass("innerContainer"),th=$j(document.createElement("th")).append(cont);$j("thead tr",_table).append(th);var width=th.outerWidth(!0)-cont.width();return th.remove(),width},_getColumnBorderWidth:function(_table){var cont=$j(document.createElement("div")).addClass("innerContainer"),td=$j(document.createElement("td")).append(cont);$j("tbody tr",_table).append(td),_table.addClass("egwGridView_grid");var width=td.outerWidth(!0)-cont.width();return td.remove(),width}})}.call(this),et2_INextmatchHeader=new Interface({setNextmatch:function(_nextmatch){}}),et2_INextmatchSortable=new Interface({setSortmode:function(_mode){}}),et2_nextmatch=function(){"use strict";return et2_DOMWidget.extend([et2_IResizeable,et2_IInput,et2_IPrint],{attributes:{template:{name:"Template",type:"string",description:"The id of the template which contains the grid layout."},hide_header:{name:"Hide header",type:"boolean",description:"Hide the header",default:!1},header_left:{name:"Left custom template",type:"string",description:"Customise the nextmatch - left side. Provided template becomes a child of nextmatch, and any input widgets are automatically bound to refresh the nextmatch on change. Any inputs with an onChange attribute can trigger the nextmatch to refresh by returning true.",default:""},header_right:{name:"Right custom template",type:"string",description:"Customise the nextmatch - right side. Provided template becomes a child of nextmatch, and any input widgets are automatically bound to refresh the nextmatch on change. Any inputs with an onChange attribute can trigger the nextmatch to refresh by returning true.",default:""},header_row:{name:"Inline custom template",type:"string",description:"Customise the nextmatch - inline, after row count. Provided template becomes a child of nextmatch, and any input widgets are automatically bound to refresh the nextmatch on change. Any inputs with an onChange attribute can trigger the nextmatch to refresh by returning true.",default:""},no_filter:{name:"No filter",type:"boolean",description:"Hide the first filter",default:et2_no_init},no_filter2:{name:"No filter2",type:"boolean",description:"Hide the second filter",default:et2_no_init},view:{name:"View",type:"string",description:"Display entries as either 'row' or 'tile'. A matching template must also be set after changing this.",default:et2_no_init},onselect:{name:"onselect",type:"js",default:et2_no_init,description:"JS code which gets executed when rows are selected. Can also be a app.appname.func(selected) style method"},onfiledrop:{name:"onFileDrop",type:"js",default:et2_no_init,description:"JS code that gets executed when a _file_ is dropped on a row. Other drop interactions are handled by the action system. Return false to prevent the default link action."},settings:{name:"Settings",type:"any",description:"The nextmatch settings",default:{}}},legacyOptions:["template","hide_header","header_left","header_right"],createNamespace:!0,columns:[],view:"row",init:function(){this._super.apply(this,arguments),this.activeFilters={col_filter:{}},jQuery.extend(this.activeFilters.col_filter,this.options.settings.col_filter);for(var prefs=this._getPreferences(),cfs={},i=0;i<prefs.visible.length;i++)0==prefs.visible[i].indexOf(et2_nextmatch_customfields.prototype.prefix)&&(cfs[prefs.visible[i].substr(1)]=!prefs.negated);var global_data=this.getArrayMgr("modifications").getRoot().getEntry("~custom_fields~");"object"==typeof global_data&&null!=global_data&&(global_data.fields=cfs),this.div=$j(document.createElement("div")).addClass("et2_nextmatch"),this.header=et2_createWidget("nextmatch_header_bar",{},this),this.innerDiv=$j(document.createElement("div")).appendTo(this.div),this.dynheight=new et2_dynheight(this.getInstanceManager().DOMContainer,this.innerDiv,100),this.dataview=new et2_dataview(this.innerDiv,this.egw()),this.blank=$j(document.createElement("div")).appendTo(this.dataview.table),this.controller=null,this.rowProvider=null},destroy:function(){this._autorefresh_timer&&(window.clearInterval(this._autorefresh_timer),this._autorefresh_timer=null),$j(this.getInstanceManager().DOMContainer.parentNode).off("show.et2_nextmatch"),$j(this.getInstanceManager().DOMContainer.parentNode).off("hide.et2_nextmatch"),this.dataview.free(),this.rowProvider.free(),this.controller.free(),this.dynheight.free(),this._super.apply(this,arguments)},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),this.id){var entry=this.getArrayMgr("content").data;if(_attrs.settings={},entry){_attrs.settings=entry,_attrs.settings.actions&&!_attrs.settings.action_var&&(_attrs.settings.action_var="action");for(var attr in this.attributes)_attrs.settings[attr]&&(_attrs[attr]=_attrs.settings[attr],delete _attrs.settings[attr])}}},doLoadingFinished:function(){if(this._super.apply(this,arguments),this.options.settings.row_id){var split=this.options.template.split("."),appname=split[0];if(this.egw().link_get_registry(appname)){var self=this;$j(this.div).on("dragenter",".egwGridView_grid tr",function(e){var row=self.controller.getRowByNode(this);return row&&row.uid?(e.stopPropagation(),e.preventDefault(),row.controller&&row.controller._selectionMgr&&row.controller._selectionMgr.setFocused(row.uid,!0),!1):!1}).on("dragexit",".egwGridView_grid tr",function(e){self.controller._selectionMgr.setFocused()}).on("dragover",".egwGridView_grid tr",!1).attr("dropzone","copy").on("drop",".egwGridView_grid tr",function(e){return self.handle_drop(e,this),!1})}}return $j(this.getInstanceManager().DOMContainer.parentNode).on("hide.et2_nextmatch",jQuery.proxy(function(e){this.controller&&this.controller._grid&&(this.controller._grid.doInvalidate=!1)},this)),$j(this.getInstanceManager().DOMContainer.parentNode).on("show.et2_nextmatch",jQuery.proxy(function(e){this.controller&&this.controller._grid&&(this.controller._grid.doInvalidate=!0)},this)),!0},resize:function(){this.dynheight&&this.dynheight.update(function(_w,_h){this.dataview.resize(_w,_h)},this)},sortBy:function(_id,_asc,_update){"undefined"==typeof _update&&(_update=!0),"undefined"==typeof this.activeFilters.sort&&(this.activeFilters.sort={id:null,asc:!0}),"undefined"==typeof _asc&&(_asc=!0,this.activeFilters.sort.id==_id&&(_asc=!this.activeFilters.sort.asc)),this.iterateOver(function(_widget){_widget.setSortmode(_widget.id==_id?_asc?"asc":"desc":"none")},this,et2_INextmatchSortable),_update?this.applyFilters({sort:{id:_id,asc:_asc}}):this.activeFilters.sort={id:_id,asc:_asc}},resetSort:function(){"undefined"!=typeof this.activeFilters.sort&&(this.iterateOver(function(_widget){_widget.setSortmode("none")},this,et2_INextmatchSortable),this.applyFilters({sort:void 0}))},applyFilters:function(_set){var changed=!1,keep_selection=!1;if(!this.update_in_progress){if(this.update_in_progress=!0,"undefined"!=typeof _set&&jQuery.isEmptyObject(_set)&&(changed=!0,this.activeFilters={}),"undefined"==typeof this.activeFilters&&(this.activeFilters={col_filter:{}}),"undefined"==typeof this.activeFilters.col_filter&&(this.activeFilters.col_filter={}),"object"==typeof _set)for(var s in _set)if("col_filter"==s)if(void 0===_set.col_filter||null===_set.col_filter)this.activeFilters.col_filter={},changed=!0;else for(var c in _set.col_filter)this.activeFilters.col_filter[c]!==_set.col_filter[c]&&(_set.col_filter[c]?this.activeFilters.col_filter[c]=_set.col_filter[c]:delete this.activeFilters.col_filter[c],changed=!0);else if("selected"===s){changed=!0,keep_selection=!0,this.controller._selectionMgr.resetSelection();for(var i in _set.selected)this.controller._selectionMgr.setSelected(_set.selected[i].indexOf("::")>0?_set.selected[i]:this.controller.dataStorePrefix+"::"+_set.selected[i],!0);delete _set.selected}else this.activeFilters[s]!==_set[s]&&(this.activeFilters[s]=_set[s],changed=!0);if(this.egw().debug("info","Changing nextmatch filters to ",this.activeFilters),!changed||keep_selection?this.controller.keepSelection():this.controller._selectionMgr.resetSelection(),this.controller.setFilters(this.activeFilters),this.header.setFilters(this.activeFilters),this.iterateOver(function(column){"undefined"!=typeof column.id&&0==column.id.indexOf("favorite")||("undefined"!=typeof column.set_value&&column.id&&column.set_value("undefined"==typeof this[column.id]||null==this[column.id]?"":this[column.id]),column.id&&"function"==typeof column.get_value&&(this[column.id]=column.get_value()))},this.activeFilters.col_filter,et2_INextmatchHeader),this.controller.update(!0),changed&&this.getInstanceManager().app){var app=this.getInstanceManager().app;window.app[app]&&window.app[app].highlight_favorite&&window.app[app].highlight_favorite()}this.update_in_progress=!1}},refresh:function(_row_ids,_type){if(null!==this.controller&&this.div){if(!this.div.is(":visible"))return void $j(this.getInstanceManager().DOMContainer.parentNode).one("show.et2_nextmatch",jQuery.proxy(function(){this.refresh()},this));if("undefined"==typeof _type&&(_type="edit"),"string"!=typeof _row_ids&&"number"!=typeof _row_ids||(_row_ids=[_row_ids]),"undefined"==typeof _row_ids||null===_row_ids)return this.applyFilters(),void $j(this).triggerHandler("refresh",[this]);if("delete"==_type){var uid=0==_row_ids[0].toString().indexOf(this.controller.dataStorePrefix)?_row_ids[0]:this.controller.dataStorePrefix+"::"+_row_ids[0],entry=this.controller._selectionMgr._getRegisteredRowsEntry(uid),next=entry.ao?entry.ao.getNext(_row_ids.length):null;null!=next&&next.id&&next.id!=uid||(next=entry.ao?entry.ao.getPrevious(1):null),this.dataview.grid.doInvalidate=!1;for(var i=0;i<_row_ids.length;i++)uid=0==_row_ids[i].toString().indexOf(this.controller.dataStorePrefix)?_row_ids[i]:this.controller.dataStorePrefix+"::"+_row_ids[i],this.controller.deleteRow(uid);next&&next.id&&(this.controller._selectionMgr.setSelected(next.id,!0),this.controller._selectionMgr.setFocused(next.id,!0));var total=this.dataview.grid._total-_row_ids.length;this.dataview.grid.setTotalCount(total),this.dataview.grid.doInvalidate=!0,this.dataview.grid.invalidate()}id_loop:for(var i=0;i<_row_ids.length;i++){var uid=0==_row_ids[i].toString().indexOf(this.controller.dataStorePrefix)?_row_ids[i]:this.controller.dataStorePrefix+"::"+_row_ids[i];switch(_type){case"update":if(!this.egw().dataRefreshUID(uid)){this.applyFilters();break id_loop}break;case"delete":break;case"edit":case"add":default:this.applyFilters();break id_loop}}$j(this).triggerHandler("refresh",[this,_row_ids,_type])}},getSelection:function(){var selected=this.controller&&this.controller._selectionMgr?this.controller._selectionMgr.getSelected():null;return"object"==typeof selected&&null!=selected?selected:{ids:[],all:!1}},onselect:function(action,senders){return"function"==typeof this.options.onselect?this.options.onselect.call(this,this.getSelection().ids,this):void 0},_genColumnCaption:function(_widget){var result=null;return"function"==typeof _widget._genColumnCaption?_widget._genColumnCaption():(_widget.iterateOver(function(_widget){var label=_widget.options.label?_widget.options.label:_widget.options.empty_label;label&&(result?result+=", "+label:result=label)},this,et2_INextmatchHeader),result)},_getColumnName:function(_widget){if("function"==typeof _widget._getColumnName)return _widget._getColumnName();for(var name=_widget.id,child_names=[],children=_widget.getChildren(),i=0;i<children.length;i++)children[i].id&&child_names.push(children[i].id);var colName=name+(""!=name&&child_names.length>0?"_":"")+child_names.join("_");return""==colName&&this.egw().debug("info","Unable to generate nm column name for ",_widget),colName},_getPreferences:function(){var negated=!1,columnPreference="";this.options.settings.default_cols&&(negated="!"==this.options.settings.default_cols[0],columnPreference=negated?this.options.settings.default_cols.substring(1):this.options.settings.default_cols),this.options.settings.selectcols&&(columnPreference=this.options.settings.selectcols,negated=!1),this.options.settings.columnselection_pref||(this.options.settings.columnselection_pref=this.options.template);var app="";if(this.options.settings.columnselection_pref){var pref={},list=et2_csvSplit(this.options.settings.columnselection_pref,2,".");0==this.options.settings.columnselection_pref.indexOf("nextmatch")?(app=list[0].substring("nextmatch".length+1),pref=egw.preference(this.options.settings.columnselection_pref,app)):(app=list[0],pref=egw.preference("nextmatch-"+this.options.settings.columnselection_pref,app)),pref&&(negated="!"==pref[0],columnPreference=negated?pref.substring(1):pref)}"string"==typeof columnPreference&&0==columnPreference.length&&(columnDisplay={},negated=!0);var columnDisplay="string"==typeof columnPreference?et2_csvSplit(columnPreference,null,","):columnPreference,size={};if(this.options.settings.columnselection_pref&&app){var size_pref=this.options.settings.columnselection_pref+"-size";-1==size_pref.indexOf("nextmatch")&&(size_pref="nextmatch-"+size_pref),size=this.egw().preference(size_pref,app)}return size||(size={}),{visible:columnDisplay,visible_negated:negated,size:size}},_applyUserPreferences:function(_row,_colData){var prefs=this._getPreferences(),columnDisplay=prefs.visible,size=prefs.size,negated=prefs.visible_negated,colName="";if(columnDisplay&&columnDisplay.length>0)RowLoop:for(var i=0;i<_row.length;i++)if(colName="",_row[i].disabled)_colData[i].disabled=!0;else{if(_row[i].widget.instanceOf(et2_nextmatch_customfields)){for(var j=0;j<columnDisplay.length;j++)if(0==columnDisplay[j].indexOf(_row[i].widget.id)){_row[i].widget.options.fields={};for(var k=j;k<columnDisplay.length;k++)0==columnDisplay[k].indexOf(_row[i].widget.prefix)&&(_row[i].widget.options.fields[columnDisplay[k].substr(1)]=!0);_row[i].widget._getColumnName(),_colData[i].disabled=negated||jQuery.isEmptyObject(_row[i].widget.options.fields);break}if(jQuery.isEmptyObject(_row[i].widget.customfields)){_colData[i].disabled=!0;continue}colName=_row[i].widget.id}else colName=this._getColumnName(_row[i].widget);if(colName){size[colName]&&("%"==_colData[i].width.charAt(_colData[i].width.length-1)?_colData[i].width="string"==typeof size[colName]&&"%"==size[colName].charAt(size[colName].length-1)?size[colName]:_colData[i].width:_colData[i].width=parseInt(size[colName])+"px");for(var j=0;j<columnDisplay.length;j++)if(columnDisplay[j]==colName){_colData[i].disabled=negated;continue RowLoop}_colData[i].disabled=!negated}}},_updateUserPreferences:function(){var colMgr=this.dataview.getColumnMgr(),app="";this.options.settings.columnselection_pref||(this.options.settings.columnselection_pref=this.options.template);for(var visibility=colMgr.getColumnVisibilitySet(),colDisplay=[],colSize={},custom_fields=[],i=0;i<colMgr.columns.length;i++){var widget=this.columns[i].widget,colName=this._getColumnName(widget);if(colName){if(widget.instanceOf(et2_nextmatch_customfields)){colName=widget.id;for(var name in widget.options.fields)widget.options.fields[name]&&custom_fields.push(widget.prefix+name)}visibility[colMgr.columns[i].id].visible&&colDisplay.push(colName),colMgr.columns[i].relativeWidth?colSize[colName]=100*colMgr.columns[i].relativeWidth+"%":colMgr.columns[i].fixedWidth&&(colSize[colName]=colMgr.columns[i].fixedWidth)}else(colMgr.columns[i].fixedWidth||colMgr.columns[i].relativeWidth)&&this.egw().debug("info","Could not save column width - no name",colMgr.columns[i].id)}var list=et2_csvSplit(this.options.settings.columnselection_pref,2,"."),pref=this.options.settings.columnselection_pref;0==pref.indexOf("nextmatch")?app=list[0].substring("nextmatch".length+1):(app=list[0],pref="nextmatch-"+this.options.settings.columnselection_pref),jQuery.merge(colDisplay,custom_fields);var oldCols=this.activeFilters.selectcols?this.activeFilters.selectcols:[];this.activeFilters.selectcols=colDisplay;var changed=[];ColLoop:for(var i=0;i<colDisplay.length;i++){for(var j=0;j<oldCols.length;j++)if(colDisplay[i]==oldCols[j])continue ColLoop;changed.push(colDisplay[i])}var cf_added=$j(changed).filter($j(custom_fields)).length>0;this.egw().set_preference(app,pref,colDisplay.join(","),cf_added?jQuery.proxy(function(){this.controller&&this.controller.update(!0)},this):null),this.egw().set_preference(app,pref+"-size",colSize),!changed.length&&!custom_fields.length||cf_added||this.applyFilters()},_parseHeaderRow:function(_row,_colData){for(var x=0;x<_row.length;x++)_row[x].widget||(_row[x].widget=et2_createWidget("label"));this._applyUserPreferences(_row,_colData),this.columns=new Array(_row.length);for(var columnData=new Array(_row.length),remove_action_index=null,x=0;x<_row.length;x++){this.columns[x]=jQuery.extend({widget:_row[x].widget},_colData[x]),columnData[x]={id:"col_"+x,caption:this._genColumnCaption(_row[x].widget),visibility:!_colData[x]||_colData[x].disabled?ET2_COL_VISIBILITY_INVISIBLE:ET2_COL_VISIBILITY_VISIBLE,width:_colData[x]?_colData[x].width:0},_colData[x].minWidth&&(columnData[x].minWidth=_colData[x].minWidth),_colData[x].maxWidth&&(columnData[x].maxWidth=_colData[x].maxWidth);var colName=this._getColumnName(_row[x].widget);"actions"!=colName&&"legacy_actions"!=colName&&"legacy_actions_check_all"!=colName||(remove_action_index=x)}null!=remove_action_index&&(this.columns.splice(remove_action_index,remove_action_index),columnData.splice(remove_action_index,remove_action_index),_colData.splice(remove_action_index,remove_action_index)),this.dataview.setColumns(columnData);for(var x=0;x<_row.length;x++)this.addChild(_row[x].widget);this.rowProvider=new et2_nextmatch_rowProvider(this.dataview.rowProvider,this._getSubgrid,this);var self=this;this.dataview.onUpdateColumns=function(){self._updateUserPreferences.apply(self),self.iterateOver(function(widget){widget.resize()},self,et2_IResizeable)},this.selectPopup&&(this.selectPopup.remove(),this.selectPopup=null),this.options.settings.no_columnselection?(this.dataview.selectColumnsClick=function(){return!1},$j("span.selectcols",this.dataview.headTr).hide()):($j("span.selectcols",this.dataview.headTr).show(),this.dataview.selectColumnsClick=function(event){self._selectColumnsClick(event)})},_parseDataRow:function(_row,_rowData,_colData){for(var columnWidgets=new Array(this.columns.length),x=0;x<columnWidgets.length;x++)"undefined"!=typeof _row[x]&&_row[x].widget?(columnWidgets[x]=_row[x].widget,this.addChild(_row[x].widget)):columnWidgets[x]=_row[x].widget,_row[x].align&&(columnWidgets[x].align=_row[x].align);if(this.rowProvider.setDataRowTemplate(columnWidgets,_rowData,this),this.controller=new et2_nextmatch_controller(null,this.egw(),this.getInstanceManager().etemplate_exec_id,this,null,this.dataview.grid,this.rowProvider,this.options.settings.action_links,null,this.options.actions),0==total&&this.controller._emptyRow(),!this.options.settings.dataStorePrefix){var list=this.options.settings.get_rows.split(".",2);list.length<2&&(list=this.options.settings.get_rows.split("_")),this.options.settings.dataStorePrefix=list[0]}this.controller.setPrefix(this.options.settings.dataStorePrefix),this.controller._view=this.view;var total="undefined"!=typeof this.options.settings.total?this.options.settings.total:0;this.dataview.grid.setTotalCount(total),this.options.settings.rows&&this.options.settings.num_rows&&(this.controller.loadInitialData(this.options.settings.dataStorePrefix,this.options.settings.row_id,this.options.settings.rows),delete this.options.settings.rows)},_parseGrid:function(_grid){for(var y=0;y<_grid.rowData.length;y++)"th"==_grid.rowData[y].class||0==y?this._parseHeaderRow(_grid.cells[y],_grid.colData):this._parseDataRow(_grid.cells[y],_grid.rowData[y],_grid.colData);this.dataview.table.resize()},_getSubgrid:function(_row,_data,_controller){var rowId=_data.content[this.options.settings.row_id],grid=new et2_dataview_grid(_row,this.dataview.grid),controller=new et2_nextmatch_controller(_controller,this.egw(),this.getInstanceManager().etemplate_exec_id,this,rowId,grid,this.rowProvider,this.options.settings.action_links,_controller.getObjectManager());return controller.update(),grid.setDestroyCallback(function(){controller.free()}),grid},_getInitialOrder:function(_rows,_rowId){var _order=[],len=0;for(var key in _rows)!isNaN(key)&&parseInt(key)>len&&(len=parseInt(key));for(var i=0;len>i;i++){var uid=this.egw().appName+"::"+_rows[i][_rowId];this.egw().dataStoreUID(uid,_rows[i]),_order.push(uid)}return _order},_selectColumnsClick:function(e){for(var self=this,columnMgr=this.dataview.getColumnMgr(),LETTERS="~search_letter~",columns={},columns_selected=[],i=0;i<columnMgr.columns.length;i++){var col=columnMgr.columns[i],widget=this.columns[i].widget;if(col.caption&&col.visibility!=ET2_COL_VISIBILITY_ALWAYS_NOSELECT&&(columns[col.id]=col.caption,col.visibility==ET2_COL_VISIBILITY_VISIBLE&&columns_selected.push(col.id)),widget.instanceOf(et2_nextmatch_customfields)){if(jQuery.isEmptyObject(widget.customfields)){delete columns[col.id];continue}for(var field_name in widget.customfields)columns[widget.prefix+field_name]=" - "+widget.customfields[field_name].label,widget.options.fields[field_name]&&columns_selected.push(et2_customfields_list.prototype.prefix+field_name)}}if(this.options.settings.lettersearch&&(columns[LETTERS]=egw.lang("Search letter"),this.header.lettersearch.is(":visible")&&columns_selected.push(LETTERS)),this.selectPopup)this.selectPopup.toggle();else{var select=et2_createWidget("select",{multiple:!0,rows:8,empty_label:this.egw().lang("select columns"),selected_first:!1},this);select.set_select_options(columns),select.set_value(columns_selected);var autoRefresh=et2_createWidget("select",{empty_label:"Refresh"},this);autoRefresh.set_id("nm_autorefresh"),autoRefresh.set_select_options({300:"5 Minutes",900:"15 Minutes",1800:"30 Minutes"}),autoRefresh.set_value(this._get_autorefresh()),autoRefresh.set_statustext(egw.lang("Automatically refresh list"));var defaultCheck=et2_createWidget("select",{empty_label:"Preference"},this);defaultCheck.set_id("nm_col_preference"),defaultCheck.set_select_options({default:{label:"Default",title:"Set these columns as the default"},reset:{label:"Reset",title:"Reset all user's column preferences"},force:{label:"Force",title:"Force column preference so users cannot change it"}}),defaultCheck.set_value(this.options.settings.columns_forced?"force":"");var okButton=et2_createWidget("buttononly",{},this);okButton.set_label(this.egw().lang("ok")),okButton.onclick=function(){for(var visibility={},i=0;i<columnMgr.columns.length;i++){var col=columnMgr.columns[i];col.caption&&col.visibility!=ET2_COL_VISIBILITY_ALWAYS_NOSELECT&&(visibility[col.id]={visible:!1})}var value=select.getValue();if(self.header.lettersearch){var show_letters=!0;value.indexOf(LETTERS)>=0?value.splice(value.indexOf(LETTERS),1):show_letters=!1,self._set_lettersearch(show_letters)}for(var column=0,i=0;i<value.length;i++){for(;value[i]!="col_"+column&&column<columnMgr.columns.length;)column++;if(visibility[value[i]]&&(visibility[value[i]].visible=!0),self.columns[column]&&self.columns[column].widget.instanceOf(et2_nextmatch_customfields)){var cf=self.columns[column].widget.options.customfields,visible=self.columns[column].widget.options.fields;for(var field_name in cf)visible[field_name]=!1;for(var j=0;j<value.length;j++)0==value[j].indexOf(et2_customfields_list.prototype.prefix)&&(visible[value[j].substring(1)]=!0,i++);self.columns[column].widget.set_visible(visible)}}columnMgr.setColumnVisibilitySet(visibility),self.selectPopup.toggle(),self.dataview.updateColumns(),self._set_autorefresh(autoRefresh.get_value()),show_letters&&self.activeFilters.selectcols.push("lettersearch"),self.getInstanceManager().submit(),self.selectPopup=null};var cancelButton=et2_createWidget("buttononly",{},this);cancelButton.set_label(this.egw().lang("cancel")),cancelButton.onclick=function(){self.selectPopup.toggle(),self.selectPopup=null},this.selectPopup=jQuery(document.createElement("div")).addClass("colselection ui-dialog ui-widget-content").append(select.getDOMNode()).append(okButton.getDOMNode()).append(cancelButton.getDOMNode()).appendTo(this.innerDiv),this.selectPopup.append(autoRefresh.getSurroundings().getDOMNode(autoRefresh.getDOMNode()));var apps=this.egw().user("apps");apps.admin&&this.selectPopup.append(defaultCheck.getSurroundings().getDOMNode(defaultCheck.getDOMNode()))}var t_position=jQuery(e.target).position(),s_position=this.div.position();this.selectPopup.css("top",t_position.top).css("left",s_position.left+this.div.width()-this.selectPopup.width())},set_columns:function(column_list,trigger_update){for(var columnMgr=this.dataview.getColumnMgr(),visibility={},i=0;i<columnMgr.columns.length;i++){var col=columnMgr.columns[i];col.caption&&col.visibility!=ET2_COL_VISIBILITY_ALWAYS_NOSELECT&&(visibility[col.id]={visible:!1})}for(var i=0;i<this.columns.length;i++){var widget=this.columns[i].widget,colName=this._getColumnName(widget);if(-1!==column_list.indexOf(colName)&&(visibility[columnMgr.columns[i].id].visible=!0),widget&&widget.instanceOf(et2_nextmatch_customfields)){colName=widget.id,-1!==column_list.indexOf(colName)&&(visibility[columnMgr.columns[i].id].visible=!0);var cf=this.columns[i].widget.options.customfields,visible=this.columns[i].widget.options.fields;for(var field_name in cf)visible[field_name]=!1;for(var j=0;j<column_list.length;j++)0==column_list[j].indexOf(et2_customfields_list.prototype.prefix)&&(visible[column_list[j].substring(1)]=!0);widget.set_visible(visible)}}columnMgr.setColumnVisibilitySet(visibility),this.dataview._updateColumns(),this.iterateOver(function(widget){widget.resize()},this,et2_IResizeable)},_set_lettersearch:function(letters_on){letters_on?this.header.lettersearch.show():this.header.lettersearch.hide();var lettersearch_preference="nextmatch-"+this.options.settings.columnselection_pref+"-lettersearch";this.egw().set_preference(this.egw().getAppName(),lettersearch_preference,letters_on)},_set_autorefresh:function(time){var refresh_preference="nextmatch-"+this.options.settings.columnselection_pref+"-autorefresh",app=this.options.template.split(".");this._get_autorefresh()!=time&&this.egw().set_preference(app[0],refresh_preference,time),this._autorefresh_timer&&(window.clearInterval(this._autorefresh_timer),delete this._autorefresh_timer),time>0&&(this._autorefresh_timer=setInterval(jQuery.proxy(this.controller.update,this.controller),1e3*time),$j(this.getInstanceManager().DOMContainer.parentNode).on("hide.et2_nextmatch",jQuery.proxy(function(e){window.clearInterval(this._autorefresh_timer),$j(e.target).off(e),this._autorefresh_timer=setTimeout(jQuery.proxy(function(){this._autorefresh_timer&&this.getInstanceManager()&&$j(this.getInstanceManager().DOMContainer.parentNode).one("show.et2_nextmatch",jQuery.proxy(function(){this.refresh()},this));
},this),1e3*time)},this)),$j(this.getInstanceManager().DOMContainer.parentNode).on("show.et2_nextmatch",jQuery.proxy(function(e){this._set_autorefresh(this._get_autorefresh()),$j(e.target).off(e)},this)))},_get_autorefresh:function(){var refresh_preference="nextmatch-"+this.options.settings.columnselection_pref+"-autorefresh",app=this.options.template.split(".");return this.egw().preference(refresh_preference,app[0])},set_template:function(_value){if(this.template){if(this.template==_value)return;this.dataview.free(),this.rowProvider.free(),this.controller.free();for(var i=this._children.length-1;i>=0;i--){var _node=this._children[i];_node!=this.header&&(this.removeChild(_node),_node.destroy())}this.template==this.options.settings.columnselection_pref&&(this.options.settings.columnselection_pref=_value),this.dataview=new et2_dataview(this.innerDiv,this.egw())}var template=et2_createWidget("template",{id:_value},this);if(!template)return void this.egw().debug("error","Error while loading definition template for nextmatch widget.",_value);var parse=function(template){this.template=_value;var definitionGrid=template.getChildren()[0];return definitionGrid&&definitionGrid instanceof et2_grid?(this._parseGrid(definitionGrid),setTimeout(function(){template.free()},1),this.iterateOver(function(_node){_node.setNextmatch(this)},this,et2_INextmatchHeader),this.controller.setFilters(this.activeFilters),this.options.settings.num_rows||this.controller.update(),this.options.settings.order&&this.options.settings.sort&&this.sortBy(this.options.settings.order,"ASC"==this.options.settings.sort,!1),void this._set_autorefresh(this._get_autorefresh())):void this.egw().debug("error","Nextmatch widget expects a grid to be the first child of the defined template.")},promise=[];template.loadingFinished(promise),jQuery.when.apply(null,promise).done(jQuery.proxy(function(){parse.call(this,template),this.dynheight.initialized=!1,this.resize()},this))},set_hide_header:function(hide){hide?this.header.div.hide():this.header.div.show()},set_header_left:function(template){this.header._build_header("left",template)},set_header_right:function(template){this.header._build_header("right",template)},set_header_row:function(template){this.header._build_header("row",template)},set_no_filter:function(bool,filter_name){"undefined"==typeof filter_name&&(filter_name="filter"),this.options["no_"+filter_name]=bool;var filter=this.header[filter_name];filter?filter.set_disabled(bool):bool&&(filter=this.header._build_select(filter_name,"select",this.settings[filter_name],this.settings[filter_name+"_no_lang"]))},set_no_filter2:function(bool){this.set_no_filter(bool,"filter2")},set_disabled:function(_value){var previous=this.disabled;this._super.apply(this,arguments),previous&&!_value&&this.resize()},set_actions:function(actions){if(actions!=this.options.actions&&null!=this.controller&&this.controller._actionManager){for(var i=this.controller._actionManager.children.length-1;i>=0;i--)this.controller._actionManager.children[i].remove();this.options.actions=actions,this.options.settings.action_links=this.controller._actionLinks=this._get_action_links(actions),this.controller._initActions(actions)}},set_view:function(view){"tile"==view?this.view="tile":this.view="row"},set_onfiledrop:function(handler){this.options.onfiledrop=handler},handle_drop:function(event,target){var row=this.controller.getRowByNode(target),uid=row.uid||null,files=[];if(!(event.originalEvent&&event.originalEvent.dataTransfer&&event.originalEvent.dataTransfer.files&&event.originalEvent.dataTransfer.files.length>0))return!1;if(files=event.originalEvent.dataTransfer.files,this.options.onfiledrop&&!this.options.onfiledrop.call(this,uid,files))return!1;if(event.stopPropagation(),event.preventDefault(),!row||!row.uid)return!1;var split=uid.split("::"),link_value={to_app:split.shift(),to_id:split.join("::")},link=et2_createWidget("link-to",{value:link_value},this);if(link.loadingFinished(),link.file_upload.set_drop_target(!1),row.row.tr){var status=$j(document.createElement("div")).addClass("et2_link_to").width(row.row.tr.width()).position({my:"left top",at:"left top",of:row.row.tr}).append(link.status_span).append(link.file_upload.progress).appendTo(row.row.tr);link.div.on("link.et2_link_to",function(e,linked){linked?link._parent.refresh(uid,"edit"):$j("li.success",link.file_upload.progress).removeClass("success").addClass("validation_error"),status.delay(linked?1:2e3).fadeOut(500,function(){link.free(),status.remove()})})}link.file_upload.set_value(files)},getDOMNode:function(_sender){if(_sender==this)return this.div[0];if(_sender==this.header)return this.header.div[0];for(var i=0;i<this.columns.length;i++)if(this.columns[i]&&this.columns[i].widget&&_sender==this.columns[i].widget)return this.dataview.getHeaderContainerNode(i);return _sender&&_sender._parent&&_sender._parent==this?this.header.getDOMNode(_sender):null},getValue:function(){for(var _ids=this.getSelection(),idsArr=_ids.ids,i=0;i<idsArr.length;i++)idsArr[i]=idsArr[i].split("::").pop();var value={selected:idsArr};return jQuery.extend(value,this.activeFilters,this.value),value},resetDirty:function(){},isDirty:function(){return"undefined"!=typeof this.value},isValid:function(){return!0},set_value:function(_value){this.value=_value},beforePrint:function(){this.div.addClass("print"),this.dynheight.outerNode.css("max-width",this.div.css("max-width")),this.resize(),this.dynheight.innerNode.css("height","auto");var range=this.controller._grid.getIndexRange();this.old_height=this.controller._grid._scrollHeight;var loaded_count=range.bottom-range.top+1,total=this.controller._grid.getTotalCount();if(loaded_count!=total||this.controller._grid.getTotalCount()>100){var defer=jQuery.Deferred();return et2_dialog.show_prompt(jQuery.proxy(function(button,value){if("dialog[cancel]"==button)return void window.setTimeout(function(){defer.reject()},0);if(value=parseInt(value),value>total&&(value=total),"dialog[ok]"==button&&value==this.controller._grid.getTotalCount()&&(button="dialog[all]",this.div.addClass("print"),$j(".egwGridView_scrollarea",this.div).css("height","auto")),"dialog[all]"==button||value>loaded_count){var count=0,fetchedCount=0,cancel=!1,nm=this,dialog=et2_dialog.show_dialog(function(){count=total,cancel=!0,window.setTimeout(function(){defer.reject()},0)},egw.lang("Loading"),egw.lang("please wait..."),{},[{button_id:et2_dialog.CANCEL_BUTTON,text:"cancel",id:"dialog[cancel]",image:"cancel"}]);do{var ctx={self:this.controller,start:count,count:Math.min(value,200),lastModification:this.controller._lastModification};nm.controller.dataStorePrefix&&(ctx.prefix=nm.controller.dataStorePrefix),nm.controller.dataFetch({start:count,num_rows:Math.min(value,200)},function(data){if(data&&data.order&&(fetchedCount+=data.order.length),nm.controller._fetchCallback.apply(this,arguments),fetchedCount>=value){if(cancel)return dialog.destroy(),void defer.reject();nm.print_row_selector=".egwGridView_grid > tbody > tr:not(:nth-child(-n+"+value+"))",egw.css(nm.print_row_selector,"display: none"),$j(".egwGridView_scrollarea",this.div).css("overflow-y","hidden"),$j(".egwGridView_scrollarea",this.div).css("height","auto"),window.setTimeout(jQuery.proxy(function(){dialog.destroy(),defer.resolve()},nm),ET2_GRID_INVALIDATE_TIMEOUT)}},ctx),count+=200}while(value>count);nm.controller._grid.setScrollHeight(nm.controller._grid.getAverageHeight()*(value+1))}else $j(".egwGridView_scrollarea",this.div).css("height","auto"),this.print_row_selector=".egwGridView_grid > tbody > tr:not(:nth-child(-n+"+value+"))",egw.css(this.print_row_selector,"display: none"),$j(".egwGridView_scrollarea",this.div).css("overflow-y","hidden"),window.setTimeout(function(){defer.resolve()},0)},this),egw.lang("How many rows to print"),egw.lang("Print"),Math.min(100,total),[{button_id:1,text:egw.lang("Ok"),id:"dialog[ok]",image:"check",default:!0},{button_id:0,text:egw.lang("Cancel"),id:"dialog[cancel]",image:"cancel"}]),defer}this.dynheight.innerNode.css("height","auto"),$j(".egwGridView_scrollarea",this.div).css("height","auto")},afterPrint:function(){this.div.removeClass("print"),$j(".egwGridView_scrollarea",this.div).css("overflow-y",""),this.controller._grid.setScrollHeight(this.old_height),delete this.old_height,this.print_row_selector&&(egw.css(this.print_row_selector,!1),delete this.print_row_selector),this.dynheight.outerNode.css("max-width","inherit"),this.resize()}})}.call(this);et2_register_widget(et2_nextmatch,["nextmatch"]);var et2_nextmatch_header_bar=function(){"use strict";return et2_DOMWidget.extend(et2_INextmatchHeader,{attributes:{filter_label:{name:"Filter label",type:"string",description:"Label for filter",default:"",translate:!0},filter_help:{name:"Filter help",type:"string",description:"Help message for filter",default:"",translate:!0},filter:{name:"Filter value",type:"any",description:"Current value for filter",default:""},no_filter:{name:"No filter",type:"boolean",description:"Remove filter",default:!1}},headers:[],header_div:[],init:function(nextmatch,nm_div){this._super.apply(this,[nextmatch,nextmatch.options.settings]),this.nextmatch=nextmatch,this.div=jQuery(document.createElement("div")).addClass("nextmatch_header"),this._createHeader(),this.update_in_progress=!1},destroy:function(){this.nextmatch=null,this._super.apply(this,arguments),this.div=null},setNextmatch:function(nextmatch){var create_once=null==this.nextmatch;this.nextmatch=nextmatch,create_once&&this._createHeader(),this.nextmatch.dataview.grid.setInvalidateCallback(function(){this.count_total.text(this.nextmatch.dataview.grid.getTotalCount()+"")},this)},set_actions:function(actions){},_createHeader:function(){var self=this,nm_div=this.nextmatch.div,settings=this.nextmatch.options.settings;this.div.prependTo(nm_div),this.headers=[{id:this.nextmatch.options.header_left},{id:this.nextmatch.options.header_right},{id:this.nextmatch.options.header_row}],this.header_div=this.row_div=jQuery(document.createElement("div")).addClass("nextmatch_header_row").appendTo(this.div),this.filter_div=jQuery(document.createElement("div")).addClass("filtersContainer").appendTo(this.row_div),this.search_box=jQuery(document.createElement("div")).addClass("search").prependTo(egwIsMobile()?this.nextmatch.div:this.row_div);var searchbox_options={id:"search",overlay:"undefined"!=typeof settings.searchbox&&"undefined"!=typeof settings.searchbox.overlay?settings.searchbox.overlay:Boolean(egwIsMobile()),onchange:function(){self.nextmatch.applyFilters({search:this.get_value()})},value:settings.search,fix:!egwIsMobile()};if(this.et2_searchbox=et2_createWidget("searchbox",searchbox_options,this),this.nextmatch.activeFilters.search=settings.search,this.et2_searchbox.set_value(settings.search),egwIsMobile()&&(this.search_box.addClass("nm-mob-header"),jQuery(this.div).css({display:"inline-block"}).addClass("nm_header_hide"),jQuery(document.createElement("div")).addClass("nm_appname_header").text(egw.lang(egw.app_name())).appendTo(this.search_box),this.fav_span=jQuery(document.createElement("div")).addClass("nm_favorites_div").prependTo(this.search_box),this.toggle_header=jQuery(document.createElement("button")).addClass("nm_toggle_header").click(function(){jQuery(self.div).slideToggle("fast"),jQuery(self.div).removeClass("nm_header_hide"),jQuery(this).toggleClass("nm_toggle_header_on"),window.setTimeout(function(){self.nextmatch.resize()},800)}).prependTo(this.search_box),this.action_header=jQuery(document.createElement("button")).addClass("nm_action_header").click(function(e){jQuery("tr.selected",self.nextmatch.div).trigger({type:"contextmenu",which:3,originalEvent:e})}).prependTo(this.search_box)),settings.no_cat||("undefined"==typeof settings.cat_id_label&&(settings.cat_id_label=""),this.category=this._build_select("cat_id","select-cat",settings.cat_id,settings.cat_is_select!==!0)),settings.no_filter||(this.filter=this._build_select("filter","select",settings.filter,settings.filter_no_lang)),settings.no_filter2||(this.filter2=this._build_select("filter2","select",settings.filter2,settings.filter2_no_lang)),this.right_div=jQuery(document.createElement("div")).addClass("header_row_right").appendTo(this.row_div),this.count=jQuery(document.createElement("span")).addClass("header_count ui-corner-all"),this.count_total=jQuery(document.createElement("span")).appendTo(this.count).text(settings.total+""),this.count.prependTo(this.right_div),this._setup_favorites(settings.favorites),"undefined"!=typeof settings.csv_fields&&0!=settings.csv_fields){var definition=settings.csv_fields;settings.csv_fields===!0&&(definition=egw.preference("nextmatch-export-definition",this.nextmatch.egw().getAppName()));var button=et2_createWidget("buttononly",{id:"export",label:"Export",image:"phpgwapi/filesave"},this);jQuery(button.getDOMNode()).click(this.nextmatch,function(event){egw_openWindowCentered2(egw.link("/index.php",{menuaction:"importexport.importexport_export_ui.export_dialog",appname:event.data.egw().getAppName(),definition:definition}),"_blank",850,440,"yes")})}this.header_row=jQuery(document.createElement("div")).addClass("header_row").appendTo(this.right_div);var current_letter=this.nextmatch.options.settings.searchletter?this.nextmatch.options.settings.searchletter:this.nextmatch.activeFilters?this.nextmatch.activeFilters.searchletter:!1;if(this.nextmatch.options.settings.lettersearch||current_letter){this.lettersearch=jQuery(document.createElement("table")).css("width","100%").appendTo(this.div);for(var tbody=jQuery(document.createElement("tbody")).appendTo(this.lettersearch),row=jQuery(document.createElement("tr")).appendTo(tbody),i=65;90>=i;i++){var button=jQuery(document.createElement("td")).addClass("lettersearch").appendTo(row).attr("id",String.fromCharCode(i)).text(String.fromCharCode(i));String.fromCharCode(i)==current_letter&&button.addClass("lettersearch_active")}button=jQuery(document.createElement("td")).addClass("lettersearch").appendTo(row).attr("id","").text(egw.lang("all")),current_letter||button.addClass("lettersearch_active"),this.lettersearch.click(this.nextmatch,function(event){jQuery("td",this).removeClass("lettersearch_active"),jQuery(event.target).addClass("lettersearch_active"),event.data.applyFilters({searchletter:event.target.id||!1})}),this.nextmatch.activeFilters.searchletter=current_letter}var lettersearch_preference="nextmatch-"+this.nextmatch.options.settings.columnselection_pref+"-lettersearch";this.lettersearch&&!egw.preference(lettersearch_preference,this.nextmatch.egw().getAppName())&&this.lettersearch.hide()},_build_header:function(location,template_name){var id="left"==location?0:"right"==location?1:2,existing=this.headers[id];if(existing&&existing._type){if(existing.id==template_name)return;existing.free(),this.headers[id]=""}var self=this,header=et2_createWidget("template",{id:template_name},this);this.headers[id]=header;var deferred=[];header.loadingFinished(deferred),jQuery.when.apply(jQuery,deferred).then(function(){switch(id){case 0:jQuery(header.getDOMNode()).prependTo(self.header_div);break;case 1:jQuery(header.getDOMNode()).prependTo(self.header_div.find("div.header_row_right"));break;case 2:window.setTimeout(function(){jQuery(header.getDOMNode()).insertAfter(self.header_div.find("div.search"))},1)}self._bindHeaderInput(header)})},_build_select:function(name,type,value,lang){var widget_options={id:name,label:this.nextmatch.options.settings[name+"_label"],no_lang:lang,disabled:this.nextmatch.options["no_"+name]},mgr=this.nextmatch.getArrayMgr("content"),options=mgr.getEntry("options-"+name);options||(options=this.nextmatch.getArrayMgr("sel_options").getEntry(name)),options||(options=this.nextmatch.getArrayMgr("sel_options").parentMgr.getEntry(name)),options||(options=mgr.getEntry("rows[sel_options]["+name+"]"));for(var row_stuck=["${row}","{$row}"],i=0;!options&&i<row_stuck.length;i++){var row_id="";if((!options||0==options.length)&&(this.nextmatch.getArrayMgr("sel_options").perspectiveData.row||this.nextmatch.getArrayMgr("sel_options").data[row_stuck[i]])){var row_id=name.replace(/[0-9]+/,row_stuck[i]);options=this.nextmatch.getArrayMgr("sel_options").getEntry(row_id),options||(row_id=row_stuck[i]+"["+name+"]",options=this.nextmatch.getArrayMgr("sel_options").getEntry(row_id))}options&&this.egw().debug("warn",'Nextmatch filter options in a weird place - "%s". Should be in sel_options[%s].',row_id,name)}"cat_id"==name&&null!=options&&"undefined"==typeof options[""]&&"undefined"!=typeof options[0]&&""!=options[0].value&&(widget_options.empty_label=this.egw().lang("All categories"));var select=et2_createWidget(type,widget_options,this);options&&select.set_select_options(options),select.set_value(value),this.nextmatch.activeFilters[select.id]=select.get_value();var input=select.input;if(select.attributes.select_options.ignore=!0,this.nextmatch.options.settings[name+"_onchange"]){input.change(this.nextmatch,function(event){var set={};set[name]=select.getValue(),event.data.applyFilters(set)});var onchange=this.nextmatch.options.settings[name+"_onchange"];onchange.match(/this\.form\.submit/)&&(this.egw().debug("warn","%s tries to submit form, which is not allowed. Filter changes automatically refresh data with no reload.",name),onchange=onchange.replace(/this\.form\.submit\([^)]*\);?/,"return true;")),input.change(this.nextmatch,et2_compileLegacyJS(onchange,this.nextmatch,select.getInputNode()))}else input.change(this.nextmatch,function(event){var set={};set[name]=select.getValue(),event.data.applyFilters(set)});return select},_setup_favorites:function(filters){if("undefined"!=typeof filters&&filters!==!1){var list=et2_csvSplit(this.options.get_rows,2,"."),widget_options={default_pref:"nextmatch-"+this.nextmatch.options.settings.columnselection_pref+"-favorite",app:list[0],filters:filters,sidebox_target:"favorite_sidebox_"+list[0]};this.favorites=et2_createWidget("favorites",widget_options,this),$j(this.favorites.getDOMNode(this.favorites)).prependTo(egwIsMobile()?this.search_box.find(".nm_favorites_div"):this.right_div)}},setFilters:function(filters){if(!this.update_in_progress){this.update_in_progress=!0;var mgr=new et2_arrayMgr(filters);this.iterateOver(function(child){if("undefined"==typeof child.id||0!=child.id.indexOf("favorite")){var value="";if("undefined"!=typeof child.set_value&&child.id){if(value=mgr.getEntry(child.id),null==value&&(value=""),value&&"object"!=typeof value&&child.instanceOf(et2_selectbox)){var found="undefined"!=typeof child.options.select_options[value];if(jQuery.isArray(child.options.select_options))for(var o=0;o<child.options.select_options.length;++o)if(child.options.select_options[o].value==value){found=!0;break}if(!found){var old_options=child.options.select_options;old_options[value]=child.egw().lang("Loading"),child.set_select_options(old_options)}}child.set_value(value)}if("function"==typeof child.get_value&&child.id)for(var target=this,value=child.get_value(),indexes=child.id.replace(/&#x5B;/g,"[").split("["),i=0;i<indexes.length;i++)indexes[i]=indexes[i].replace(/&#x5D;/g,"").replace("]",""),i<indexes.length-1?("undefined"==typeof target[indexes[i]]&&(target[indexes[i]]={}),target=target[indexes[i]]):target[indexes[i]]=value}},filters),this.nextmatch.options.settings.lettersearch&&(jQuery("td",this.lettersearch).removeClass("lettersearch_active"),$j(filters.searchletter?"td#"+filters.searchletter:"td.lettersearch[id='']").addClass("lettersearch_active"),filters.searchletter=$j("td.lettersearch_active").attr("id")),this.update_in_progress=!1}},getDOMNode:function(_sender){for(var filters=[this.category,this.filter,this.filter2],i=0;i<filters.length;i++)if(_sender==filters[i])return this.filter_div[0];if(_sender==this.et2_searchbox)return this.search_box[0];if("export"==_sender.id)return this.right_div[0];if(_sender&&"template"==_sender._type)for(var i=0;i<this.headers.length;i++)if(_sender.id==this.headers[i].id&&_sender._parent==this)return 2==i?this.header_row[0]:this.header_div[0];return null},_bindHeaderInput:function(sub_header){var header=this;sub_header.iterateOver(function(_widget){var widget_change=_widget.change,change=function(_node){var result=widget_change.call(_widget,_node);if(result&&_widget.isDirty()&&!header.update_in_progress)if(_widget._oldValue=_widget.getValue(),null==_widget._oldValue){var path=_widget.getArrayMgr("content").explodeKey(_widget.id);if(path.length>0){for(var entry=header.nextmatch.activeFilters,i=0;i<path.length-1;i++)entry=entry[path[i]];delete entry[path[i]]}header.nextmatch.applyFilters(header.nextmatch.activeFilters)}else{var value=this.getInstanceManager().getValues(sub_header);header.nextmatch.applyFilters(value[header.nextmatch.id])}return!0};_widget.change=change;var value={};value[_widget.id]=_widget._oldValue=_widget.getValue();var mgr=new et2_arrayMgr(value);jQuery.extend(!0,this.nextmatch.activeFilters,mgr.data)},this,et2_inputWidget)}})}.call(this);et2_register_widget(et2_nextmatch_header_bar,["nextmatch_header_bar"]);var et2_nextmatch_header=function(){"use strict";return et2_baseWidget.extend(et2_INextmatchHeader,{attributes:{label:{name:"Caption",type:"string",description:"Caption for the nextmatch header",translate:!0}},init:function(){this._super.apply(this,arguments),this.labelNode=$j(document.createElement("span")),this.nextmatch=null,this.setDOMNode(this.labelNode[0])},destroy:function(){this._super.apply(this,arguments)},setNextmatch:function(_nextmatch){this.nextmatch=_nextmatch},set_label:function(_value){this.label=_value,this.labelNode.text(_value)}})}.call(this);et2_register_widget(et2_nextmatch_header,["nextmatch-header"]);var et2_nextmatch_customfields=function(){"use strict";return et2_customfields_list.extend(et2_INextmatchHeader,{attributes:{customfields:{name:"Custom fields",description:"Auto filled"},fields:{name:"Visible fields",description:"Auto filled"}},init:function(){this.nextmatch=null,this._super.apply(this,arguments),this.table.css("width","100%")},destroy:function(){this.nextmatch=null,this._super.apply(this,arguments)},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),!_attrs.customfields){var data=this.getArrayMgr("modifications").getEntry(this.id);data||(data=this.getArrayMgr("modifications").getRoot().getEntry("~custom_fields~",!0));for(var key in data)"object"!=typeof data[key]||_attrs[key]||(_attrs[key]=data[key])}},setNextmatch:function(_nextmatch){this.nextmatch=_nextmatch,this.loadFields()},loadFields:function(){if(null!=this.nextmatch){for(var columnMgr=this.nextmatch.dataview.getColumnMgr(),nm_column=null,set_fields={},i=0;i<this.nextmatch.columns.length;i++)if(this.nextmatch.columns[i].widget==this){nm_column=columnMgr.columns[i];break}if(nm_column){var global_data=this.getArrayMgr("modifications").getRoot().getEntry("~custom_fields~");null!=global_data&&global_data.fields&&(this.options.fields=global_data.fields);var apps=egw.link_app_list();for(var field_name in this.options.customfields){var field=this.options.customfields[field_name],cf_id=et2_customfields_list.prototype.prefix+field_name;if(!this.rows[field_name]){var row=jQuery(document.createElement("tr")).appendTo(this.tbody),cf=jQuery(document.createElement("td")).appendTo(row);this.rows[cf_id]=cf[0];var widget=null;"select"==field.type||"select-account"==field.type?(field.values&&"undefined"!=typeof field.values[""]&&delete field.values[""],widget=et2_createWidget("select-account"==field.type?"nextmatch-accountfilter":"nextmatch-filterheader",{id:cf_id,empty_label:field.label,select_options:field.values},this)):widget=apps[field.type]?et2_createWidget("nextmatch-entryheader",{id:cf_id,only_app:field.type,blur:field.label},this):et2_createWidget("nextmatch-sortheader",{id:cf_id,label:field.label},this),jQuery.isEmptyObject(this.options.fields)||0!=this.options.fields[field_name]&&"undefined"!=typeof this.options.fields[field_name]?jQuery.isEmptyObject(this.options.fields)&&(set_fields[field_name]=!0):cf.hide()}}jQuery.extend(this.options.fields,set_fields)}}},set_visible:function(_fields){this._super.apply(this,arguments);var self=this;this.nextmatch&&this.nextmatch.iterateOver(function(widget){widget!=self&&widget.set_visible(_fields)},this,et2_customfields_list)},_genColumnCaption:function(){return egw.lang("Custom fields")},_getColumnName:function(){var name=this.id,visible=[];for(var field_name in this.options.customfields)jQuery.isEmptyObject(this.options.fields)||1==this.options.fields[field_name]?(visible.push(et2_customfields_list.prototype.prefix+field_name),jQuery(this.rows[field_name]).show()):"undefined"!=typeof this.rows[field_name]&&jQuery(this.rows[field_name]).hide();visible.length?name+="_"+visible.join("_"):jQuery(this.rows[field_name]).parent().parent().children().show();var data=this.getArrayMgr("modifications").getEntry(this.id);data||(data=this.getArrayMgr("modifications").getRoot().getEntry("~custom_fields~",!0)||{}),data.fields||(data.fields={});for(var field in this.options.customfields)data.fields[field]=null==this.options.fields||"undefined"==typeof this.options.fields[field]?!1:this.options.fields[field];return name}})}.call(this);et2_register_widget(et2_nextmatch_customfields,["nextmatch-customfields"]);var et2_nextmatch_sortheader=function(){"use strict";return et2_nextmatch_header.extend(et2_INextmatchSortable,{attributes:{sortmode:{name:"Sort order",type:"string",description:"Default sort order",translate:!1}},legacyOptions:["sortmode"],init:function(){this._super.apply(this,arguments),this.sortmode="none",this.labelNode.addClass("nextmatch_sortheader none")},click:function(){return this.nextmatch&&this._super.apply(this,arguments)?(this.nextmatch.sortBy(this.id,"none"==this.sortmode?!("DESC"==this.options.sortmode.toUpperCase()):void 0),!0):!1},set_sortmode:function(_mode){this.nextmatch||this.setSortmode(_mode)},setSortmode:function(_mode){this.labelNode.removeClass(this.sortmode).addClass(_mode),this.sortmode=_mode}})}.call(this);et2_register_widget(et2_nextmatch_sortheader,["nextmatch-sortheader"]);var et2_nextmatch_filterheader=function(){"use strict";return et2_selectbox.extend([et2_INextmatchHeader,et2_IResizeable],{createInputWidget:function(){this.options.empty_label||this.options.select_options&&this.options.select_options[""]||(this.options.empty_label=this.options.label?this.options.label:egw.lang("All")),this._super.apply(this,arguments),this.input.change(this,function(event){if("undefined"!=typeof event.data.nextmatch){var col_filter={};col_filter[event.data.id]=event.data.input.val(),event.data.set_value(event.data.input.val()),event.data.nextmatch.applyFilters({col_filter:col_filter})}})},setNextmatch:function(_nextmatch){this.nextmatch=_nextmatch,this.nextmatch.activeFilters.col_filter&&"undefined"!=typeof this.nextmatch.activeFilters.col_filter[this.id]&&(this.set_value(this.nextmatch.activeFilters.col_filter[this.id]),_nextmatch.activeFilters.col_filter[this.id]=this.getValue())},resize:function(){this.input.css("max-width",jQuery(this.parentNode).innerWidth()+"px")}})}.call(this);et2_register_widget(et2_nextmatch_filterheader,["nextmatch-filterheader"]);var et2_nextmatch_accountfilterheader=function(){"use strict";return et2_selectAccount.extend([et2_INextmatchHeader,et2_IResizeable],{createInputWidget:function(){this.options.empty_label||this.options.select_options[""]||(this.options.empty_label=this.options.label?this.options.label:egw.lang("All")),this._super.apply(this,arguments),this.input.change(this,function(event){if("undefined"!=typeof event.data.nextmatch){var col_filter={};col_filter[event.data.id]=event.data.getValue(),event.data.nextmatch.applyFilters({col_filter:col_filter})}})},setNextmatch:function(_nextmatch){this.nextmatch=_nextmatch,this.nextmatch.activeFilters.col_filter&&this.nextmatch.activeFilters.col_filter[this.id]&&this.set_value(this.nextmatch.activeFilters.col_filter[this.id])},resize:function(){for(var max=jQuery(this.parentNode).innerWidth()-4,surroundings=this.getSurroundings()._widgetSurroundings,i=0;i<surroundings.length;i++)max-=jQuery(surroundings[i]).outerWidth();this.input.css("max-width",max+"px")}})}.call(this);et2_register_widget(et2_nextmatch_accountfilterheader,["nextmatch-accountfilter"]);var et2_nextmatch_entryheader=function(){"use strict";return et2_link_entry.extend(et2_INextmatchHeader,{select:function(event,selected){this._super.apply(this,arguments);var col_filter={};selected&&selected.item.value?event.data.options.only_app?col_filter[this.id]=selected.item.value:col_filter[this.id]=event.data.app_select.val()+":"+selected.item.value:col_filter[this.id]="",this.nextmatch.applyFilters.call(this.nextmatch,{col_filter:col_filter})},getValue:function(){var value=this._super.apply(this,arguments);if("object"==typeof value&&null!=value){if(!value.app||!value.id)return null;"object"==typeof value.id&&value.id.shift&&1==value.id.length&&(value.id=value.id.shift()),"string"==typeof value.id&&(value=value.app+":"+value.id)}return value},setNextmatch:function(_nextmatch){this.nextmatch=_nextmatch,this.nextmatch.options.settings.col_filter&&this.nextmatch.options.settings.col_filter[this.id]&&(this.set_value(this.nextmatch.options.settings.col_filter[this.id]),this.getValue()!=this.nextmatch.activeFilters.col_filter[this.id]&&(this.nextmatch.activeFilters.col_filter[this.id]=this.getValue()),this.attributes.value.ignore=!0)}})}.call(this);et2_register_widget(et2_nextmatch_entryheader,["nextmatch-entryheader"]);var et2_nextmatch_customfilter=function(){"use strict";return et2_nextmatch_filterheader.extend({attributes:{widget_type:{name:"Actual type",type:"string",description:"The actual type of widget you should use",no_lang:1},widget_options:{name:"Actual options",type:"any",description:"The options for the actual widget",no_lang:1,default:{}}},legacyOptions:["widget_type","widget_options"],real_node:null,init:function(_parent,_attrs){switch(_attrs.widget_type){case"link-entry":_attrs.type="nextmatch-entryheader";break;default:0===_attrs.widget_type.indexOf("select")?_attrs.type="nextmatch-filterheader":_attrs.type=_attrs.widget_type}jQuery.extend(_attrs.widget_options,{id:this.id}),_attrs.id="",this._super.apply(this,arguments),this.real_node=et2_createWidget(_attrs.type,_attrs.widget_options,this._parent);var select_options=[],correct_type=_attrs.type;this.real_node._type=_attrs.widget_type,et2_selectbox.find_select_options(this.real_node,select_options,_attrs),this.real_node._type=correct_type,"function"==typeof this.real_node.set_select_options&&this.real_node.set_select_options(select_options)},getDOMNode:function(_sender){return this.real_node?this.real_node.getDOMNode(_sender):null},getChildren:function(){return this.real_node.getChildren()||[]},setNextmatch:function(_nextmatch){return this.real_node&&this.real_node.setNextmatch?this.real_node.setNextmatch(_nextmatch):void 0}})}.call(this);et2_register_widget(et2_nextmatch_customfilter,["nextmatch-customfilter"]);var et2_favorites=function(){"use strict";return et2_dropdown_button.extend([et2_INextmatchHeader],{attributes:{default_pref:{name:"Default preference key",type:"string",description:"The preference key where default favorite is stored (not the value)"},sidebox_target:{name:"Sidebox target",type:"string",description:"ID of element to insert favorite list into",default:"favorite_sidebox"},app:{name:"Application",type:"string",description:"Application to show favorites for"},filters:{name:"Extra filters",type:"any",description:"Array of extra filters to include in the saved favorite"},id:{default:"favorite"},label:{default:""},label_updates:{default:!1},image:{default:"etemplate/fav_filter"},statustext:{default:"Favorite queries",type:"string"}},header:null,nextmatch:null,favorite_prefix:"favorite_",stored_filters:{},nm_filter:!1,init:function(){if(this._super.apply(this,arguments),this.sidebox_target=$j("#"+this.options.sidebox_target),0==this.sidebox_target.length&&null!=egw_getFramework()){var egw_fw=egw_getFramework();this.sidebox_target=$j("#"+this.options.sidebox_target,egw_fw.sidemenuDiv);
}this.favSortedList=["blank"];var apps=egw().user("apps");this.is_admin="undefined"!=typeof apps.admin,this.stored_filters=this.load_favorites(this.options.app),this.preferred=egw.preference(this.options.default_pref,this.options.app),this.preferred&&"undefined"!=typeof this.stored_filters[this.preferred]||(this.preferred="blank"),this.set_id(this.id),this.init_filters(this),this.menu.addClass("favorites"),this.set_value(this.preferred,!0);var self=this;$j(this.menu).on("click","input:radio",function(event){event.stopImmediatePropagation(),self.egw().set_preference(self.options.app,self.options.default_pref,$j(this).val()),self.preferred=$j(this).val(),self.sidebox_target.length&&(self.sidebox_target.find("div.ui-icon-heart").replaceWith("<div class='sideboxstar'/>"),$j("li[data-id='"+self.preferred+"'] div.sideboxstar",self.sidebox_target).replaceWith("<div class='ui-icon ui-icon-heart'/>")),self.menu.hide(),self.button.addClass("ui-state-active",500,"swing",function(){self.button.removeClass("ui-state-active",2e3)})});var sideBoxDOMNodeSort=function(_favSList){for(var favS=jQuery.isArray(_favSList)?_favSList.slice(0).reverse():[],i=0;i<favS.length;i++)self.sidebox_target.children().find('[data-id$="'+favS[i]+'"]').prependTo(self.sidebox_target.children())};$j(this.menu).sortable({items:'li:not([data-id$="add"])',placeholder:"ui-fav-sortable-placeholder",delay:250,update:function(event,ui){self.favSortedList=jQuery(this).sortable("toArray",{attribute:"data-id"}),self.egw().set_preference(self.options.app,"fav_sort_pref",self.favSortedList),sideBoxDOMNodeSort(self.favSortedList)}}),this.menu.on("click","div.ui-icon-trash",app[self.options.app],function(){app[self.options.app].delete_favorite.apply(this,arguments)}).on("mouseenter","div.ui-icon-trash",function(){$j(this).wrap("<span class='ui-state-active'/>")}).on("mouseleave","div.ui-icon-trash",function(){$j(this).unwrap()}),this.sidebox_target.length>0&&this.init_filters(this)},load_favorites:function(app){var stored_filters={blank:{name:this.egw().lang("No filters"),state:{}}},preferences=egw.preference("*",app);for(var pref_name in preferences){if(0==pref_name.indexOf(this.favorite_prefix)&&"object"==typeof preferences[pref_name]){var name=pref_name.substr(this.favorite_prefix.length);stored_filters[name]=preferences[pref_name],preferences[pref_name].filters&&(stored_filters[pref_name].state=preferences[pref_name].filters)}"fav_sort_pref"==pref_name&&(this.favSortedList=preferences[pref_name],jQuery.isArray(this.favSortedList)||(this.favSortedList=this.favSortedList.split(",")))}if("undefined"!=typeof stored_filters&&stored_filters){for(var name in stored_filters)this.favSortedList.indexOf(name)<0&&this.favSortedList.push(name);if(this.egw().set_preference(this.options.app,"fav_sort_pref",this.favSortedList),this.favSortedList.length>0){for(var sortedListObj={},i=0;i<this.favSortedList.length;i++)"undefined"!=typeof stored_filters[this.favSortedList[i]]?sortedListObj[this.favSortedList[i]]=stored_filters[this.favSortedList[i]]:(this.favSortedList.splice(i,1),this.egw().set_preference(this.options.app,"fav_sort_pref",this.favSortedList));stored_filters=jQuery.extend(sortedListObj,stored_filters)}}else stored_filters={};return stored_filters},init_filters:function(widget,filters){"undefined"==typeof filters&&(filters=this.stored_filters);var options={};for(var name in filters)options[name]="<input type='radio' name='"+this.internal_ids.menu+"[button][favorite]' value='"+name+"' title='"+this.egw().lang("Set as default")+"'/>"+(void 0!=filters[name].name?filters[name].name:name)+(0!=filters[name].group&&!this.is_admin||"blank"==name?"":"<div class='ui-icon ui-icon-trash' title='"+this.egw().lang("Delete")+"'/>");this.nextmatch&&(options.add="<img src='"+this.egw().image("new")+"'/>"+this.egw().lang("Add current")),widget.set_select_options.call(widget,options),$j("input[value='"+this.preferred+"']:radio",this.menu).attr("checked",!0)},set_nm_filters:function(filters){this.nextmatch?this.nextmatch.applyFilters(filters):console.log(filters)},onclick:function(node){this.preferred&&this.stored_filters[this.preferred]?"undefined"!=typeof app[this.options.app]?app[this.options.app].setState(this.stored_filters[this.preferred]):this.set_nm_filters(jQuery.extend({},this.stored_filters[this.preferred].state)):alert(this.egw().lang("No default set"))},change:function(selected_node){if(this.value=$j(selected_node).attr("data-id"),"add"==this.value&&this.nextmatch){var current_filters=$j.extend({},this.nextmatch.activeFilters);for(var extra in this.options.filters)"undefined"==typeof current_filters&&(current_filters[extra]=this.nextmatch.options.settings[extra]);if(delete current_filters.selcolumns,1!=this.filters)for(var i=0;i<this.filters.length;i++)current_filters[this.options.filters[i]]=this.nextmatch.options.settings[this.options.filters[i]];app[this.options.app].add_favorite(current_filters),this.set_value(this.preferred,!0)}},set_value:function(filter_name,parent){return parent?this._super.call(this,filter_name):"add"==filter_name?!1:(app[this.options.app].setState(this.stored_filters[filter_name]),!1)},getValue:function(){return null},setNextmatch:function(nextmatch){this.nextmatch=nextmatch,this.nm_filter&&(this.set_value(this.nm_filter),this.nm_filter=!1),this.init_filters(this)}})}.call(this);et2_register_widget(et2_favorites,["favorites"]),window.dhtmlx||(dhtmlx=function(t){for(var e in t)dhtmlx[e]=t[e];return dhtmlx}),dhtmlx.extend_api=function(t,e,n){var i=window[t];i&&(window[t]=function(t){var n;if(t&&"object"==typeof t&&!t.tagName){n=i.apply(this,e._init?e._init(t):arguments);for(var a in dhtmlx)e[a]&&this[e[a]](dhtmlx[a]);for(var a in t)e[a]?this[e[a]](t[a]):0===a.indexOf("on")&&this.attachEvent(a,t[a])}else n=i.apply(this,arguments);return e._patch&&e._patch(this),n||this},window[t].prototype=i.prototype,n&&dhtmlXHeir(window[t].prototype,n))},dhtmlxAjax={get:function(t,e){var n=new dtmlXMLLoaderObject(!0);return n.async=arguments.length<3,n.waitCall=e,n.loadXML(t),n},post:function(t,e,n){var i=new dtmlXMLLoaderObject(!0);return i.async=arguments.length<4,i.waitCall=n,i.loadXML(t,!0,e),i},getSync:function(t){return this.get(t,null,!0)},postSync:function(t,e){return this.post(t,e,null,!0)}},dtmlXMLLoaderObject.count=0,dtmlXMLLoaderObject.prototype.waitLoadFunction=function(t){var e=!0;return this.check=function(){if(t&&t.onloadAction&&(!t.xmlDoc.readyState||4==t.xmlDoc.readyState)){if(!e)return;e=!1,dtmlXMLLoaderObject.count++,"function"==typeof t.onloadAction&&t.onloadAction(t.mainObject,null,null,null,t),t.waitCall&&(t.waitCall.call(this,t),t.waitCall=null)}},this.check},dtmlXMLLoaderObject.prototype.getXMLTopNode=function(t,e){var n;if(this.xmlDoc.responseXML){var i=this.xmlDoc.responseXML.getElementsByTagName(t);if(0===i.length&&-1!=t.indexOf(":"))var i=this.xmlDoc.responseXML.getElementsByTagName(t.split(":")[1]);n=i[0]}else n=this.xmlDoc.documentElement;if(n)return this._retry=!1,n;if(!this._retry&&_isIE){this._retry=!0;var e=this.xmlDoc;return this.loadXMLString(this.xmlDoc.responseText.replace(/^[\s]+/,""),!0),this.getXMLTopNode(t,e)}return dhtmlxError.throwError("LoadXML","Incorrect XML",[e||this.xmlDoc,this.mainObject]),document.createElement("DIV")},dtmlXMLLoaderObject.prototype.loadXMLString=function(t,e){if(_isIE)this.xmlDoc=new ActiveXObject("Microsoft.XMLDOM"),this.xmlDoc.async=this.async,this.xmlDoc.onreadystatechange=function(){},this.xmlDoc.loadXML(t);else{var n=new DOMParser;this.xmlDoc=n.parseFromString(t,"text/xml")}e||(this.onloadAction&&this.onloadAction(this.mainObject,null,null,null,this),this.waitCall&&(this.waitCall(),this.waitCall=null))},dtmlXMLLoaderObject.prototype.loadXML=function(t,e,n,i){this.rSeed&&(t+=(-1!=t.indexOf("?")?"&":"?")+"a_dhx_rSeed="+(new Date).valueOf()),this.filePath=t,this.xmlDoc=!_isIE&&window.XMLHttpRequest?new XMLHttpRequest:new ActiveXObject("Microsoft.XMLHTTP"),this.async&&(this.xmlDoc.onreadystatechange=new this.waitLoadFunction(this)),this.xmlDoc.open(e?"POST":"GET",t,this.async),i?(this.xmlDoc.setRequestHeader("User-Agent","dhtmlxRPC v0.1 ("+navigator.userAgent+")"),this.xmlDoc.setRequestHeader("Content-type","text/xml")):e&&this.xmlDoc.setRequestHeader("Content-type","application/x-www-form-urlencoded"),this.xmlDoc.setRequestHeader("X-Requested-With","XMLHttpRequest"),this.xmlDoc.send(n),this.async||new this.waitLoadFunction(this)()},dtmlXMLLoaderObject.prototype.destructor=function(){return this._filterXPath=null,this._getAllNamedChilds=null,this._retry=null,this.async=null,this.rSeed=null,this.filePath=null,this.onloadAction=null,this.mainObject=null,this.xmlDoc=null,this.doXPath=null,this.doXPathOpera=null,this.doXSLTransToObject=null,this.doXSLTransToString=null,this.loadXML=null,this.loadXMLString=null,this.doSerialization=null,this.xmlNodeToJSON=null,this.getXMLTopNode=null,this.setXSLParamValue=null,null},dtmlXMLLoaderObject.prototype.xmlNodeToJSON=function(t){for(var e={},n=0;n<t.attributes.length;n++)e[t.attributes[n].name]=t.attributes[n].value;e._tagvalue=t.firstChild?t.firstChild.nodeValue:"";for(var n=0;n<t.childNodes.length;n++){var i=t.childNodes[n].tagName;i&&(e[i]||(e[i]=[]),e[i].push(this.xmlNodeToJSON(t.childNodes[n])))}return e},dhtmlDragAndDropObject.prototype.removeDraggableItem=function(t){t.onmousedown=null,t.dragStarter=null,t.dragLanding=null},dhtmlDragAndDropObject.prototype.addDraggableItem=function(t,e){t.onmousedown=this.preCreateDragCopy,t.dragStarter=e,this.addDragLanding(t,e)},dhtmlDragAndDropObject.prototype.addDragLanding=function(t,e){t.dragLanding=e},dhtmlDragAndDropObject.prototype.preCreateDragCopy=function(t){return!t&&!window.event||2!=(t||event).button?window.dhtmlDragAndDrop.waitDrag?(window.dhtmlDragAndDrop.waitDrag=0,document.body.onmouseup=window.dhtmlDragAndDrop.tempDOMU,document.body.onmousemove=window.dhtmlDragAndDrop.tempDOMM,!1):(window.dhtmlDragAndDrop.dragNode&&window.dhtmlDragAndDrop.stopDrag(t),window.dhtmlDragAndDrop.waitDrag=1,window.dhtmlDragAndDrop.tempDOMU=document.body.onmouseup,window.dhtmlDragAndDrop.tempDOMM=document.body.onmousemove,window.dhtmlDragAndDrop.dragStartNode=this,window.dhtmlDragAndDrop.dragStartObject=this.dragStarter,document.body.onmouseup=window.dhtmlDragAndDrop.preCreateDragCopy,document.body.onmousemove=window.dhtmlDragAndDrop.callDrag,window.dhtmlDragAndDrop.downtime=(new Date).valueOf(),t&&t.preventDefault?(t.preventDefault(),!1):!1):void 0},dhtmlDragAndDropObject.prototype.callDrag=function(t){t||(t=window.event);var e=window.dhtmlDragAndDrop;if(!((new Date).valueOf()-e.downtime<100)){if(!e.dragNode){if(!e.waitDrag)return e.stopDrag(t,!0);if(e.dragNode=e.dragStartObject._createDragNode(e.dragStartNode,t),!e.dragNode)return e.stopDrag();e.dragNode.onselectstart=function(){return!1},e.gldragNode=e.dragNode,document.body.appendChild(e.dragNode),document.body.onmouseup=e.stopDrag,e.waitDrag=0,e.dragNode.pWindow=window,e.initFrameRoute()}if(e.dragNode.parentNode!=window.document.body&&e.gldragNode){var n=e.gldragNode;e.gldragNode.old&&(n=e.gldragNode.old),n.parentNode.removeChild(n);var i=e.dragNode.pWindow;if(n.pWindow&&n.pWindow.dhtmlDragAndDrop.lastLanding&&n.pWindow.dhtmlDragAndDrop.lastLanding.dragLanding._dragOut(n.pWindow.dhtmlDragAndDrop.lastLanding),_isIE){var a=document.createElement("Div");a.innerHTML=e.dragNode.outerHTML,e.dragNode=a.childNodes[0]}else e.dragNode=e.dragNode.cloneNode(!0);e.dragNode.pWindow=window,e.gldragNode.old=e.dragNode,document.body.appendChild(e.dragNode),i.dhtmlDragAndDrop.dragNode=e.dragNode}e.dragNode.style.left=t.clientX+15+(e.fx?-1*e.fx:0)+(document.body.scrollLeft||document.documentElement.scrollLeft)+"px",e.dragNode.style.top=t.clientY+3+(e.fy?-1*e.fy:0)+(document.body.scrollTop||document.documentElement.scrollTop)+"px";var s;s=t.srcElement?t.srcElement:t.target,e.checkLanding(s,t)}},dhtmlDragAndDropObject.prototype.calculateFramePosition=function(t){if(window.name){for(var e=parent.frames[window.name].frameElement.offsetParent,n=0,i=0;e;)n+=e.offsetLeft,i+=e.offsetTop,e=e.offsetParent;if(parent.dhtmlDragAndDrop){var a=parent.dhtmlDragAndDrop.calculateFramePosition(1);n+=1*a.split("_")[0],i+=1*a.split("_")[1]}if(t)return n+"_"+i;this.fx=n,this.fy=i}return"0_0"},dhtmlDragAndDropObject.prototype.checkLanding=function(t,e){t&&t.dragLanding?(this.lastLanding&&this.lastLanding.dragLanding._dragOut(this.lastLanding),this.lastLanding=t,this.lastLanding=this.lastLanding.dragLanding._dragIn(this.lastLanding,this.dragStartNode,e.clientX,e.clientY,e),this.lastLanding_scr=_isIE?e.srcElement:e.target):t&&"BODY"!=t.tagName?this.checkLanding(t.parentNode,e):(this.lastLanding&&this.lastLanding.dragLanding._dragOut(this.lastLanding,e.clientX,e.clientY,e),this.lastLanding=0,this._onNotFound&&this._onNotFound())},dhtmlDragAndDropObject.prototype.stopDrag=function(t,e){var n=window.dhtmlDragAndDrop;if(!e){n.stopFrameRoute();var i=n.lastLanding;n.lastLanding=null,i&&i.dragLanding._drag(n.dragStartNode,n.dragStartObject,i,_isIE?event.srcElement:t.target)}n.lastLanding=null,n.dragNode&&n.dragNode.parentNode==document.body&&n.dragNode.parentNode.removeChild(n.dragNode),n.dragNode=0,n.gldragNode=0,n.fx=0,n.fy=0,n.dragStartNode=0,n.dragStartObject=0,document.body.onmouseup=n.tempDOMU,document.body.onmousemove=n.tempDOMM,n.tempDOMU=null,n.tempDOMM=null,n.waitDrag=0},dhtmlDragAndDropObject.prototype.stopFrameRoute=function(t){t&&window.dhtmlDragAndDrop.stopDrag(1,1);for(var e=0;e<window.frames.length;e++)try{window.frames[e]!=t&&window.frames[e].dhtmlDragAndDrop&&window.frames[e].dhtmlDragAndDrop.stopFrameRoute(window)}catch(n){}try{parent.dhtmlDragAndDrop&&parent!=window&&parent!=t&&parent.dhtmlDragAndDrop.stopFrameRoute(window)}catch(n){}},dhtmlDragAndDropObject.prototype.initFrameRoute=function(t,e){t&&(window.dhtmlDragAndDrop.preCreateDragCopy(),window.dhtmlDragAndDrop.dragStartNode=t.dhtmlDragAndDrop.dragStartNode,window.dhtmlDragAndDrop.dragStartObject=t.dhtmlDragAndDrop.dragStartObject,window.dhtmlDragAndDrop.dragNode=t.dhtmlDragAndDrop.dragNode,window.dhtmlDragAndDrop.gldragNode=t.dhtmlDragAndDrop.dragNode,window.document.body.onmouseup=window.dhtmlDragAndDrop.stopDrag,window.waitDrag=0,!_isIE&&e&&(!_isFF||1.8>_FFrv)&&window.dhtmlDragAndDrop.calculateFramePosition());try{parent.dhtmlDragAndDrop&&parent!=window&&parent!=t&&parent.dhtmlDragAndDrop.initFrameRoute(window)}catch(n){}for(var i=0;i<window.frames.length;i++)try{window.frames[i]!=t&&window.frames[i].dhtmlDragAndDrop&&window.frames[i].dhtmlDragAndDrop.initFrameRoute(window,!t||e?1:0)}catch(n){}},_isFF=!1,_isIE=!1,_isOpera=!1,_isKHTML=!1,_isMacOS=!1,_isChrome=!1,_FFrv=!1,_KHTMLrv=!1,_OperaRv=!1,-1!=navigator.userAgent.indexOf("Macintosh")&&(_isMacOS=!0),navigator.userAgent.toLowerCase().indexOf("chrome")>-1&&(_isChrome=!0),-1!=navigator.userAgent.indexOf("Safari")||-1!=navigator.userAgent.indexOf("Konqueror")?(_KHTMLrv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf("Safari")+7,5)),_KHTMLrv>525?(_isFF=!0,_FFrv=1.9):_isKHTML=!0):-1!=navigator.userAgent.indexOf("Opera")?(_isOpera=!0,_OperaRv=parseFloat(navigator.userAgent.substr(navigator.userAgent.indexOf("Opera")+6,3))):-1!=navigator.appName.indexOf("Microsoft")?(_isIE=!0,-1==navigator.appVersion.indexOf("MSIE 8.0")&&-1==navigator.appVersion.indexOf("MSIE 9.0")&&-1==navigator.appVersion.indexOf("MSIE 10.0")||"BackCompat"==document.compatMode||(_isIE=8)):"Netscape"==navigator.appName&&-1!=navigator.userAgent.indexOf("Trident")?_isIE=8:(_isFF=!0,_FFrv=parseFloat(navigator.userAgent.split("rv:")[1])),dtmlXMLLoaderObject.prototype.doXPath=function(t,e,n,i){if(_isKHTML||!_isIE&&!window.XPathResult)return this.doXPathOpera(t,e);if(_isIE)return e||(e=this.xmlDoc.nodeName?this.xmlDoc:this.xmlDoc.responseXML),e||dhtmlxError.throwError("LoadXML","Incorrect XML",[e||this.xmlDoc,this.mainObject]),n&&e.setProperty("SelectionNamespaces","xmlns:xsl='"+n+"'"),"single"==i?e.selectSingleNode(t):e.selectNodes(t)||new Array(0);var a=e;e||(e=this.xmlDoc.nodeName?this.xmlDoc:this.xmlDoc.responseXML),e||dhtmlxError.throwError("LoadXML","Incorrect XML",[e||this.xmlDoc,this.mainObject]),-1!=e.nodeName.indexOf("document")?a=e:(a=e,e=e.ownerDocument);var s=XPathResult.ANY_TYPE;"single"==i&&(s=XPathResult.FIRST_ORDERED_NODE_TYPE);var r=[],o=e.evaluate(t,a,function(){return n},s,null);if(s==XPathResult.FIRST_ORDERED_NODE_TYPE)return o.singleNodeValue;for(var d=o.iterateNext();d;)r[r.length]=d,d=o.iterateNext();return r},_dhtmlxError.prototype.catchError=function(t,e){this.catches[t]=e},_dhtmlxError.prototype.throwError=function(t,e,n){return this.catches[t]?this.catches[t](t,e,n):this.catches.ALL?this.catches.ALL(t,e,n):(window.alert("Error type: "+arguments[0]+"\nDescription: "+arguments[1]),null)},window.dhtmlxError=new _dhtmlxError,dtmlXMLLoaderObject.prototype.doXPathOpera=function(t,e){var n=t.replace(/[\/]+/gi,"/").split("/"),i=null,a=1;if(!n.length)return[];if("."==n[0])i=[e];else{if(""!==n[0])return[];i=(this.xmlDoc.responseXML||this.xmlDoc).getElementsByTagName(n[a].replace(/\[[^\]]*\]/g,"")),a++}for(a;a<n.length;a++)i=this._getAllNamedChilds(i,n[a]);return-1!=n[a-1].indexOf("[")&&(i=this._filterXPath(i,n[a-1])),i},dtmlXMLLoaderObject.prototype._filterXPath=function(t,e){for(var n=[],e=e.replace(/[^\[]*\[\@/g,"").replace(/[\[\]\@]*/g,""),i=0;i<t.length;i++)t[i].getAttribute(e)&&(n[n.length]=t[i]);return n},dtmlXMLLoaderObject.prototype._getAllNamedChilds=function(t,e){var n=[];_isKHTML&&(e=e.toUpperCase());for(var i=0;i<t.length;i++)for(var a=0;a<t[i].childNodes.length;a++)_isKHTML?t[i].childNodes[a].tagName&&t[i].childNodes[a].tagName.toUpperCase()==e&&(n[n.length]=t[i].childNodes[a]):t[i].childNodes[a].tagName==e&&(n[n.length]=t[i].childNodes[a]);return n},dtmlXMLLoaderObject.prototype.xslDoc=null,dtmlXMLLoaderObject.prototype.setXSLParamValue=function(t,e,n){n||(n=this.xslDoc),n.responseXML&&(n=n.responseXML);var i=this.doXPath("/xsl:stylesheet/xsl:variable[@name='"+t+"']",n,"http://www.w3.org/1999/XSL/Transform","single");i&&(i.firstChild.nodeValue=e)},dtmlXMLLoaderObject.prototype.doXSLTransToObject=function(t,e){t||(t=this.xslDoc),t.responseXML&&(t=t.responseXML),e||(e=this.xmlDoc),e.responseXML&&(e=e.responseXML);var n;if(_isIE){n=new ActiveXObject("Msxml2.DOMDocument.3.0");try{e.transformNodeToObject(t,n)}catch(i){n=e.transformNode(t)}}else this.XSLProcessor||(this.XSLProcessor=new XSLTProcessor,this.XSLProcessor.importStylesheet(t)),n=this.XSLProcessor.transformToDocument(e);return n},dtmlXMLLoaderObject.prototype.doXSLTransToString=function(t,e){var n=this.doXSLTransToObject(t,e);return"string"==typeof n?n:this.doSerialization(n)},dtmlXMLLoaderObject.prototype.doSerialization=function(t){if(t||(t=this.xmlDoc),t.responseXML&&(t=t.responseXML),_isIE)return t.xml;var e=new XMLSerializer;return e.serializeToString(t)},dhtmlxEventable=function(obj){obj.attachEvent=function(t,e,n){return t="ev_"+t.toLowerCase(),this[t]||(this[t]=new this.eventCatcher(n||this)),t+":"+this[t].addEvent(e)},obj.callEvent=function(t,e){return t="ev_"+t.toLowerCase(),this[t]?this[t].apply(this,e):!0},obj.checkEvent=function(t){return!!this["ev_"+t.toLowerCase()]},obj.eventCatcher=function(obj){var dhx_catch=[],z=function(){for(var t=!0,e=0;e<dhx_catch.length;e++)if(dhx_catch[e]){var n=dhx_catch[e].apply(obj,arguments);t=t&&n}return t};return z.addEvent=function(ev){return"function"!=typeof ev&&(ev=eval(ev)),ev?dhx_catch.push(ev)-1:!1},z.removeEvent=function(t){dhx_catch[t]=null},z},obj.detachEvent=function(t){if(t){var e=t.split(":");this[e[0]].removeEvent(e[1])}},obj.detachAllEvents=function(){for(var t in this)0===t.indexOf("ev_")&&(this.detachEvent(t),this[t]=null)},obj=null},window.dhtmlx||(window.dhtmlx={}),function(){function t(t,e){var i=t.callback;n(!1),t.box.parentNode.removeChild(t.box),c=t.box=null,i&&i(e)}function e(e){if(c){e=e||event;var n=e.which||event.keyCode;return dhtmlx.message.keyboard&&((13==n||32==n)&&t(c,!0),27==n&&t(c,!1)),e.preventDefault&&e.preventDefault(),!(e.cancelBubble=!0)}}function n(t){n.cover||(n.cover=document.createElement("DIV"),n.cover.onkeydown=e,n.cover.className="dhx_modal_cover",document.body.appendChild(n.cover)),document.body.scrollHeight,n.cover.style.display=t?"inline-block":"none"}function i(t,e){var n="dhtmlx_"+t.toLowerCase().replace(/ /g,"_")+"_button";return"<div class='dhtmlx_popup_button "+n+"' result='"+e+"' ><div>"+t+"</div></div>"}function a(t){g.area||(g.area=document.createElement("DIV"),g.area.className="dhtmlx_message_area",g.area.style[g.position]="5px",document.body.appendChild(g.area)),g.hide(t.id);var e=document.createElement("DIV");return e.innerHTML="<div>"+t.text+"</div>",e.className="dhtmlx-info dhtmlx-"+t.type,e.onclick=function(){g.hide(t.id),t=null},"bottom"==g.position&&g.area.firstChild?g.area.insertBefore(e,g.area.firstChild):g.area.appendChild(e),t.expire>0&&(g.timers[t.id]=window.setTimeout(function(){g.hide(t.id)},t.expire)),g.pull[t.id]=e,e=null,t.id}function s(e,n,a){var s=document.createElement("DIV");s.className=" dhtmlx_modal_box dhtmlx-"+e.type,s.setAttribute("dhxbox",1);var r="";if(e.width&&(s.style.width=e.width),e.height&&(s.style.height=e.height),e.title&&(r+='<div class="dhtmlx_popup_title">'+e.title+"</div>"),r+='<div class="dhtmlx_popup_text"><span>'+(e.content?"":e.text)+'</span></div><div class="dhtmlx_popup_controls">',n&&(r+=i(e.ok||"OK",!0)),a&&(r+=i(e.cancel||"Cancel",!1)),e.buttons)for(var o=0;o<e.buttons.length;o++)r+=i(e.buttons[o],o);if(r+="</div>",s.innerHTML=r,e.content){var d=e.content;"string"==typeof d&&(d=document.getElementById(d)),"none"==d.style.display&&(d.style.display=""),s.childNodes[e.title?1:0].appendChild(d)}return s.onclick=function(n){n=n||event;var i=n.target||n.srcElement;if(i.className||(i=i.parentNode),"dhtmlx_popup_button"==i.className.split(" ")[0]){var a=i.getAttribute("result");a="true"==a||("false"==a?!1:a),t(e,a)}},e.box=s,(n||a)&&(c=e),s}function r(t,i,a){var r=t.tagName?t:s(t,i,a);t.hidden||n(!0),document.body.appendChild(r);var o=Math.abs(Math.floor(((window.innerWidth||document.documentElement.offsetWidth)-r.offsetWidth)/2)),d=Math.abs(Math.floor(((window.innerHeight||document.documentElement.offsetHeight)-r.offsetHeight)/2));return r.style.top="top"==t.position?"-3px":d+"px",r.style.left=o+"px",r.onkeydown=e,r.focus(),t.hidden&&dhtmlx.modalbox.hide(r),r}function o(t){return r(t,!0,!1)}function d(t){return r(t,!0,!0)}function l(t){return r(t)}function _(t,e,n){return"object"!=typeof t&&("function"==typeof e&&(n=e,e=""),t={text:t,type:e,callback:n}),t}function h(t,e,n,i){return"object"!=typeof t&&(t={text:t,type:e,expire:n,id:i}),t.id=t.id||g.uid(),t.expire=t.expire||g.expire,t}var c=null;document.attachEvent?document.attachEvent("onkeydown",e):document.addEventListener("keydown",e,!0),dhtmlx.alert=function(){var t=_.apply(this,arguments);return t.type=t.type||"confirm",o(t)},dhtmlx.confirm=function(){var t=_.apply(this,arguments);return t.type=t.type||"alert",d(t)},dhtmlx.modalbox=function(){var t=_.apply(this,arguments);return t.type=t.type||"alert",l(t)},dhtmlx.modalbox.hide=function(t){for(;t&&t.getAttribute&&!t.getAttribute("dhxbox");)t=t.parentNode;t&&(t.parentNode.removeChild(t),n(!1))};var g=dhtmlx.message=function(t){t=h.apply(this,arguments),t.type=t.type||"info";var e=t.type.split("-")[0];switch(e){case"alert":return o(t);case"confirm":return d(t);case"modalbox":return l(t);default:return a(t)}};g.seed=(new Date).valueOf(),g.uid=function(){return g.seed++},g.expire=4e3,g.keyboard=!0,g.position="top",g.pull={},g.timers={},g.hideAll=function(){for(var t in g.pull)g.hide(t)},g.hide=function(t){var e=g.pull[t];e&&e.parentNode&&(window.setTimeout(function(){e.parentNode.removeChild(e),e=null},2e3),e.className+=" hidden",g.timers[t]&&window.clearTimeout(g.timers[t]),delete g.pull[t])}}(),gantt={version:"2.1.1"},dhtmlxEventable=function(obj){obj._silent_mode=!1,obj._silentStart=function(){this._silent_mode=!0},obj._silentEnd=function(){this._silent_mode=!1},obj.attachEvent=function(t,e,n){return t="ev_"+t.toLowerCase(),this[t]||(this[t]=new this._eventCatcher(n||this)),t+":"+this[t].addEvent(e)},obj.callEvent=function(t,e){return this._silent_mode?!0:(t="ev_"+t.toLowerCase(),this[t]?this[t].apply(this,e):!0)},obj.checkEvent=function(t){return!!this["ev_"+t.toLowerCase()]},obj._eventCatcher=function(obj){var dhx_catch=[],z=function(){for(var t=!0,e=0;e<dhx_catch.length;e++)if(dhx_catch[e]){var n=dhx_catch[e].apply(obj,arguments);t=t&&n}return t};return z.addEvent=function(ev){return"function"!=typeof ev&&(ev=eval(ev)),ev?dhx_catch.push(ev)-1:!1},z.removeEvent=function(t){dhx_catch[t]=null},z},obj.detachEvent=function(t){if(t){var e=t.split(":");this[e[0]].removeEvent(e[1])}},obj.detachAllEvents=function(){for(var t in this)0===t.indexOf("ev_")&&delete this[t]},obj=null},dhtmlx.copy=function(t){var e,n,i;if(t&&"object"==typeof t){for(i={},n=[Array,Date,Number,String,Boolean],e=0;e<n.length;e++)t instanceof n[e]&&(i=e?new n[e](t):new n[e]);for(e in t)Object.prototype.hasOwnProperty.apply(t,[e])&&(i[e]=dhtmlx.copy(t[e]))}return i||t},dhtmlx.mixin=function(t,e,n){for(var i in e)(!t[i]||n)&&(t[i]=e[i]);return t},dhtmlx.defined=function(t){return"undefined"!=typeof t},dhtmlx.uid=function(){return this._seed||(this._seed=(new Date).valueOf()),this._seed++,this._seed},dhtmlx.bind=function(t,e){return function(){return t.apply(e,arguments)}},gantt._get_position=function(t){var e=0,n=0;if(t.getBoundingClientRect){var i=t.getBoundingClientRect(),a=document.body,s=document.documentElement,r=window.pageYOffset||s.scrollTop||a.scrollTop,o=window.pageXOffset||s.scrollLeft||a.scrollLeft,d=s.clientTop||a.clientTop||0,l=s.clientLeft||a.clientLeft||0;return e=i.top+r-d,n=i.left+o-l,{y:Math.round(e),x:Math.round(n),width:t.offsetWidth,height:t.offsetHeight}}for(;t;)e+=parseInt(t.offsetTop,10),n+=parseInt(t.offsetLeft,10),t=t.offsetParent;return{y:e,x:n,width:t.offsetWidth,height:t.offsetHeight}},gantt._detectScrollSize=function(){var t=document.createElement("div");t.style.cssText="visibility:hidden;position:absolute;left:-1000px;width:100px;padding:0px;margin:0px;height:110px;min-height:100px;overflow-y:scroll;",document.body.appendChild(t);var e=t.offsetWidth-t.clientWidth;return document.body.removeChild(t),e},dhtmlxEventable(gantt),gantt._click={},gantt._dbl_click={},gantt._context_menu={},gantt._on_click=function(t){t=t||window.event;var e=t.target||t.srcElement,n=gantt.locate(t);if(null!==n){var i=!gantt.checkEvent("onTaskClick")||gantt.callEvent("onTaskClick",[n,t]);i&&gantt.config.select_task&&gantt.selectTask(n)}else gantt.callEvent("onEmptyClick",[t]);gantt._find_ev_handler(t,e,gantt._click,n)},gantt._on_contextmenu=function(t){t=t||window.event;var e=t.target||t.srcElement,n=gantt.locate(e),i=gantt.locate(e,gantt.config.link_attribute),a=!gantt.checkEvent("onContextMenu")||gantt.callEvent("onContextMenu",[n,i,t]);return a||t.preventDefault(),a},gantt._find_ev_handler=function(t,e,n,i){for(var a=!0;e&&e.parentNode;){var s=e.className;if(s){s=s.split(" ");for(var r=0;r<s.length;r++)s[r]&&n[s[r]]&&(a=n[s[r]].call(gantt,t,i,e),a=!("undefined"!=typeof a&&a!==!0))}e=e.parentNode}return a},gantt._on_dblclick=function(t){t=t||window.event;var e=t.target||t.srcElement,n=gantt.locate(t),i=gantt._find_ev_handler(t,e,gantt._dbl_click,n);if(i&&null!==n){var a=!gantt.checkEvent("onTaskDblClick")||gantt.callEvent("onTaskDblClick",[n,t]);a&&gantt.config.details_on_dblclick&&gantt.showLightbox(n)}},gantt._on_mousemove=function(t){if(gantt.checkEvent("onMouseMove")){var e=gantt.locate(t);gantt._last_move_event=t,gantt.callEvent("onMouseMove",[e,t])}},dhtmlxDnD.prototype={dragStart:function(t,e){this.config={obj:t,marker:null,started:!1,pos:this.getPosition(e),sensitivity:4},this._settings&&dhtmlx.mixin(this.config,this._settings,!0);var n=dhtmlx.bind(function(e){return this.dragMove(t,e)},this),i=(dhtmlx.bind(function(e){return this.dragScroll(t,e)},this),dhtmlx.bind(function(t){return dhtmlx.defined(this.config.updates_per_second)&&!gantt._checkTimeout(this,this.config.updates_per_second)?!0:n(t)},this)),a=dhtmlx.bind(function(){return dhtmlxDetachEvent(document.body,"mousemove",i),dhtmlxDetachEvent(document.body,"mouseup",a),this.dragEnd(t)},this);dhtmlxEvent(document.body,"mousemove",i),dhtmlxEvent(document.body,"mouseup",a),document.body.className+=" gantt_noselect"},dragMove:function(t,e){if(!this.config.marker&&!this.config.started){var n=this.getPosition(e),i=n.x-this.config.pos.x,a=n.y-this.config.pos.y,s=Math.sqrt(Math.pow(Math.abs(i),2)+Math.pow(Math.abs(a),2));if(s>this.config.sensitivity){if(this.config.started=!0,this.config.ignore=!1,this.callEvent("onBeforeDragStart",[t,e])===!1)return this.config.ignore=!0,!0;var r=this.config.marker=document.createElement("div");r.className="gantt_drag_marker",r.innerHTML="Dragging object",document.body.appendChild(r),this.callEvent("onAfterDragStart",[t,e])}else this.config.ignore=!0}this.config.ignore||(e.pos=this.getPosition(e),this.config.marker.style.left=e.pos.x+"px",this.config.marker.style.top=e.pos.y+"px",this.callEvent("onDragMove",[t,e]))},dragEnd:function(){this.config.marker&&(this.config.marker.parentNode.removeChild(this.config.marker),this.config.marker=null,this.callEvent("onDragEnd",[])),document.body.className=document.body.className.replace(" gantt_noselect","")},getPosition:function(t){var e=0,n=0;return t=t||window.event,t.pageX||t.pageY?(e=t.pageX,n=t.pageY):(t.clientX||t.clientY)&&(e=t.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,n=t.clientY+document.body.scrollTop+document.documentElement.scrollTop),{x:e,y:n}}},gantt._init_grid=function(){this._click.gantt_close=dhtmlx.bind(function(t,e){this.close(e)},this),this._click.gantt_open=dhtmlx.bind(function(t,e){this.open(e)},this),this._click.gantt_row=dhtmlx.bind(function(t,e,n){if(null!==e){var i=this.getTaskNode(e),a=Math.max(i.offsetLeft-this.config.task_scroll_offset,0);this.scrollTo(a),this.callEvent("onTaskRowClick",[e,n])}},this),this._click.gantt_grid_head_cell=dhtmlx.bind(function(t,e,n){var i=n.getAttribute("column_id");if(this.callEvent("onGridHeaderClick",[i,t]))if("add"==i)this._click.gantt_add(t,this.config.root_id);else if(this.config.sort){var a=this._sort&&this._sort.direction&&this._sort.name==i?this._sort.direction:"desc";a="desc"==a?"asc":"desc",this._sort={name:i,direction:a},this._render_grid_header(),this.sort(i,"desc"==a)}},this),!this.config.sort&&this.config.order_branch&&this._init_dnd(),this._click.gantt_add=dhtmlx.bind(function(t,e){if(!this.config.readonly){var n=e?this.getTask(e):!1,i="";if(n)i=n.start_date;else{var a=this._order[0];i=a?this.getTask(a).start_date:this.getState().min_date}n&&(n.$open=!0);var s={text:gantt.locale.labels.new_task,start_date:this.templates.xml_format(i),duration:1,progress:0,parent:e};s.id=dhtmlx.uid(),this.callEvent("onTaskCreated",[s]),this.config.details_on_create?(s.$new=!0,this._pull[s.id]=this._init_task(s),this._add_branch(s),s.$level=this._item_level(s),this.selectTask(s.id),this.refreshData(),this.showLightbox(s.id)):(this.addTask(s),this.showTask(s.id),this.selectTask(s.id))}},this)},gantt._render_grid=function(){this._is_grid_visible()&&(this._calc_grid_width(),this._render_grid_header())},gantt._calc_grid_width=function(){if(this.config.autofit){for(var t=this.config.columns,e=0,n=[],i=[],a=0;a<t.length;a++){var s=parseInt(t[a].width,10);window.isNaN(s)&&(s=50,n.push(a)),i[a]=s,e+=s}var r=this._get_grid_width()-e;if(r/(n.length>0?n.length:i.length>0?i.length:1),n.length>0)for(var o=r/(n.length?n.length:1),a=0;a<n.length;a++){var d=n[a];i[d]+=o}else for(var o=r/(i.length?i.length:1),a=0;a<i.length;a++)i[a]+=o;for(var a=0;a<i.length;a++)t[a].width=i[a]}},gantt._render_grid_header=function(){for(var t=this.config.columns,e=[],n=0,i=this.locale.labels,a=this.config.scale_height-2,s=0;s<t.length;s++){var r=s==t.length-1,o=t[s];r&&this._get_grid_width()>n+o.width&&(o.width=this._get_grid_width()-n),n+=o.width;var d=this._sort&&o.name==this._sort.name?"<div class='gantt_sort gantt_"+this._sort.direction+"'></div>":"",l=["gantt_grid_head_cell","gantt_grid_head_"+o.name,r?"gantt_last_cell":"",this.templates.grid_header_class(o.name,o)].join(" "),_="width:"+(o.width-(r?1:0))+"px;",h=o.label||i["column_"+o.name];
h=h||"";var c="<div class='"+l+"' style='"+_+"' column_id='"+o.name+"'>"+h+d+"</div>";e.push(c)}this.$grid_scale.style.height=this.config.scale_height-1+"px",this.$grid_scale.style.lineHeight=a+"px",this.$grid_scale.style.width=n-1+"px",this.$grid_scale.innerHTML=e.join("")},gantt._render_grid_item=function(t){if(!gantt._is_grid_visible())return null;for(var e=this.config.columns,n=[],i=0;i<e.length;i++){var a,s,r=i==e.length-1,o=e[i];"add"==o.name&&i==e.length-1?s="<div class='gantt_add'></div>":(s=o.template?o.template(t):t[o.name],s instanceof Date&&(s=this.templates.date_grid(s)),s="<div class='gantt_tree_content'>"+s+"</div>");var d="gantt_cell"+(r?" gantt_last_cell":""),l="";if(o.tree){for(var _=0;_<t.$level;_++)l+=this.templates.grid_indent(t);var h=this._branches[t.id]&&this._branches[t.id].length>0;h?(l+=this.templates.grid_open(t),l+=this.templates.grid_folder(t)):(l+=this.templates.grid_blank(t),l+=this.templates.grid_file(t))}var c="width:"+(o.width-(r?1:0))+"px;";dhtmlx.defined(o.align)&&(c+="text-align:"+o.align+";"),a="<div class='"+d+"' style='"+c+"'>"+l+s+"</div>",n.push(a)}var d=t.$index%2===0?"":" odd";if(d+=t.$transparent?" gantt_transparent":"",this.templates.grid_row_class){var g=this.templates.grid_row_class.call(this,t.start_date,t.end_date,t);g&&(d+=" "+g)}this.getState().selected_task==t.id&&(d+=" gantt_selected");var u=document.createElement("div");return u.className="gantt_row"+d,u.style.height=this.config.row_height+"px",u.style.lineHeight=gantt.config.row_height+"px",u.setAttribute(this.config.task_attribute,t.id),u.innerHTML=n.join(""),u},gantt.open=function(t){gantt._set_item_state(t,!0),this.callEvent("onTaskOpened",[t])},gantt.close=function(t){gantt._set_item_state(t,!1),this.callEvent("onTaskClosed",[t])},gantt._set_item_state=function(t,e){t&&this._pull[t]&&(this._pull[t].$open=e,this.refreshData())},gantt._is_grid_visible=function(){return this.config.grid_width&&this.config.show_grid},gantt._get_grid_width=function(){return this._is_grid_visible()?this._is_chart_visible()?this.config.grid_width:this._x:0},gantt.getTaskIndex=function(t){for(var e=this._branches[this.getTask(t).parent],n=0;n<e.length;n++)if(e[n]==t)return n;return-1},gantt.getGlobalTaskIndex=function(t){for(var e=this._order,n=0;n<e.length;n++)if(e[n]==t)return n;return-1},gantt.moveTask=function(t,e,n){var i=arguments[3];if(i){if(i===t)return;n=this.getTask(i).parent,e=this.getTaskIndex(i)}n=n||this.config.root_id;var a=this.getTask(t),s=(this._branches[a.parent],this._branches[n]);if(-1==e&&(e=s.length+1),a.parent==n){var r=this.getTaskIndex(t);if(r==e)return;e>r&&e--}this._replace_branch_child(a.parent,t),s=this._branches[n];var o=s[e];o?s=s.slice(0,e).concat([t]).concat(s.slice(e)):s.push(t),a.parent=n,this._branches[n]=s,this.refreshData()},gantt._init_dnd=function(){var t=new dhtmlxDnD(this.$grid_data,{updates_per_second:60});dhtmlx.defined(this.config.dnd_sensitivity)&&(t.config.sensitivity=this.config.dnd_sensitivity),t.attachEvent("onBeforeDragStart",dhtmlx.bind(function(t,e){var n=this._locateHTML(e);if(!n)return!1;this.hideQuickInfo&&this._hideQuickInfo();var i=this.locate(e);return this.callEvent("onRowDragStart",[i,e.target||e.srcElement,e])?void 0:!1},this)),t.attachEvent("onAfterDragStart",dhtmlx.bind(function(e,n){var i=this._locateHTML(n);t.config.marker.innerHTML=i.outerHTML,t.config.id=this.locate(n);var a=this.getTask(t.config.id);a.$open=!1,a.$transparent=!0,this.refreshData()},this)),t.lastTaskOfLevel=function(t){for(var e=gantt._order,n=gantt._pull,i=null,a=0,s=e.length;s>a;a++)n[e[a]].$level==t&&(i=n[e[a]]);return i?i.id:null},t.attachEvent("onDragMove",dhtmlx.bind(function(e,n){var i=t.config,a=this._get_position(this.$grid_data),s=a.x+10,r=n.pos.y-10;r<a.y&&(r=a.y),r>a.y+this.$grid_data.offsetHeight-this.config.row_height&&(r=a.y+this.$grid_data.offsetHeight-this.config.row_height),i.marker.style.left=s+"px",i.marker.style.top=r+"px";var o=document.elementFromPoint(a.x-document.body.scrollLeft+1,r-document.body.scrollTop),d=this.locate(o),l=this.getTask(t.config.id);if(this.isTaskExists(d)||(d=t.lastTaskOfLevel(l.$level),d==t.config.id&&(d=null)),this.isTaskExists(d)){var _=gantt._get_position(o),h=this.getTask(d);if(_.y+o.offsetHeight/2<r){var c=this.getGlobalTaskIndex(h.id),g=this._pull[this._order[c+1+(h.id==l.id?1:0)]];if(g){if(g.id==l.id)return;h=g}else if(g=this._pull[this._order[c]],g.$level==l.$level)return this.moveTask(l.id,-1,g.parent),void(i.target="next:"+g.id)}if(h.$level==l.$level&&l.id!=h.id)this.moveTask(l.id,0,0,h.id),i.target=h.id;else{if(l.id==h.id)return;var c=this.getGlobalTaskIndex(h.id),u=this._pull[this._order[c-1]];u&&u.$level==l.$level&&l.id!=u.id&&(this.moveTask(l.id,-1,u.parent),i.target="next:"+u.id)}}return!0},this)),t.attachEvent("onDragEnd",dhtmlx.bind(function(){this.getTask(t.config.id).$transparent=!1,this.refreshData(),this.callEvent("onRowDragEnd",[t.config.id,t.config.target])},this))},gantt._scale_helpers={getSum:function(t,e,n){void 0===n&&(n=t.length-1),void 0===e&&(e=0);for(var i=0,a=e;n>=a;a++)i+=t[a];return i},setSumWidth:function(t,e,n,i){var a=e.width;void 0===i&&(i=a.length-1),void 0===n&&(n=0);var s=i-n+1;if(!(n>a.length-1||0>=s||i>a.length-1)){var r=this.getSum(a,n,i),o=t-r;this.adjustSize(o,a,n,i),this.adjustSize(-o,a,i+1),e.full_width=this.getSum(a)}},splitSize:function(t,e){for(var n=[],i=0;e>i;i++)n[i]=0;return this.adjustSize(t,n),n},adjustSize:function(t,e,n,i){n||(n=0),void 0===i&&(i=e.length-1);for(var a=i-n+1,s=this.getSum(e,n,i),r=0,o=n;i>=o;o++){var d=Math.floor(t*(s?e[o]/s:1/a));s-=e[o],t-=d,a--,e[o]+=d,r+=d}e[e.length-1]+=t},sortScales:function(t){function e(t,e){var n=new Date(1970,0,1);return gantt.date.add(n,e,t)-n}t.sort(function(t,n){return e(t.unit,t.step)<e(n.unit,n.step)?1:-1})},primaryScale:function(){return gantt._init_template("date_scale"),{unit:gantt.config.scale_unit,step:gantt.config.step,template:gantt.templates.date_scale,date:gantt.config.date_scale,css:gantt.templates.scale_cell_class}},prepareConfigs:function(t,e,n,i){for(var a=this.splitSize(i,t.length),s=n,r=[],o=t.length-1;o>=0;o--){var d=o==t.length-1,l=this.initScaleConfig(t[o]);d&&this.processIgnores(l),this.initColSizes(l,e,s,a[o]),this.limitVisibleRange(l),d&&(s=l.full_width),r.unshift(l)}for(var o=0;o<r.length-1;o++)this.alineScaleColumns(r[r.length-1],r[o]);return r},_ignore_time_config:function(t){return this.config.skip_off_time?!this.isWorkTime(t):!1},processIgnores:function(t){var e=t.count;if(t.ignore_x={},gantt.ignore_time||gantt.config.skip_off_time){var n=gantt.ignore_time||function(){return!1};e=0;for(var i=0;i<t.trace_x.length;i++)n.call(gantt,t.trace_x[i])||this._ignore_time_config.call(gantt,t.trace_x[i])?(t.ignore_x[t.trace_x[i].valueOf()]=!0,t.ignored_colls=!0):e++}t.display_count=e},initColSizes:function(t,e,n,i){var a=n;t.height=i;var s=void 0===t.display_count?t.count:t.display_count;s||(s=1),t.col_width=Math.floor(a/s),e&&t.col_width<e&&(t.col_width=e,a=t.col_width*s),t.width=[];for(var r=t.ignore_x||{},o=0;o<t.trace_x.length;o++)t.width[o]=r[t.trace_x[o].valueOf()]||t.display_count==t.count?0:1;this.adjustSize(a-this.getSum(t.width),t.width),t.full_width=this.getSum(t.width)},initScaleConfig:function(t){var e=dhtmlx.mixin({count:0,col_width:0,full_width:0,height:0,width:[],trace_x:[]},t);return this.eachColumn(t.unit,t.step,function(t){e.count++,e.trace_x.push(new Date(t))}),e},iterateScales:function(t,e,n,i,a){for(var s=e.trace_x,r=t.trace_x,o=n||0,d=i||r.length-1,l=0,_=1;_<s.length;_++)for(var h=o;d>=h;h++)+r[h]!=+s[_]||(a&&a.apply(this,[l,_,o,h]),o=h,l=_)},alineScaleColumns:function(t,e,n,i){this.iterateScales(t,e,n,i,function(n,i,a,s){var r=this.getSum(t.width,a,s-1),o=this.getSum(e.width,n,i-1);o!=r&&this.setSumWidth(r,e,n,i-1)})},eachColumn:function(t,e,n){var i=new Date(gantt._min_date),a=new Date(gantt._max_date);gantt.date[t+"_start"]&&(i=gantt.date[t+"_start"](i));for(var s=new Date(i);+a>+s;)n.call(this,new Date(s)),s=gantt.date.add(s,e,t)},limitVisibleRange:function(t){var e=t.trace_x,n=0,i=t.width.length-1,a=0;if(+e[0]<+gantt._min_date&&n!=i){var s=Math.floor(t.width[0]*((e[1]-gantt._min_date)/(e[1]-e[0])));a+=t.width[0]-s,t.width[0]=s,e[0]=new Date(gantt._min_date)}var r=e.length-1,o=e[r],d=gantt.date.add(o,t.step,t.unit);if(+d>+gantt._max_date&&r>0){var s=t.width[r]-Math.floor(t.width[r]*((d-gantt._max_date)/(d-o)));a+=t.width[r]-s,t.width[r]=s}if(a){for(var l=this.getSum(t.width),_=0,h=0;h<t.width.length;h++){var c=Math.floor(a*(t.width[h]/l));t.width[h]+=c,_+=c}this.adjustSize(a-_,t.width)}}},gantt._tasks_dnd={drag:null,_events:{before_start:{},before_finish:{},after_finish:{}},_handlers:{},init:function(){this.clear_drag_state();var t=gantt.config.drag_mode;this.set_actions();var e={before_start:"onBeforeTaskDrag",before_finish:"onBeforeTaskChanged",after_finish:"onAfterTaskDrag"};for(var n in this._events)for(var i in t)this._events[n][i]=e[n];this._handlers[t.move]=this._move,this._handlers[t.resize]=this._resize,this._handlers[t.progress]=this._resize_progress},set_actions:function(){var t=gantt.$task_data;dhtmlxEvent(t,"mousemove",dhtmlx.bind(function(t){this.on_mouse_move(t||event)},this)),dhtmlxEvent(t,"mousedown",dhtmlx.bind(function(t){this.on_mouse_down(t||event)},this)),dhtmlxEvent(t,"mouseup",dhtmlx.bind(function(t){this.on_mouse_up(t||event)},this))},clear_drag_state:function(){this.drag={id:null,mode:null,pos:null,start_x:null,start_y:null,obj:null,left:null}},_resize:function(t,e,n){var i=gantt.config,a=this._drag_task_coords(t,n);n.left?(t.start_date=gantt._date_from_pos(a.start+e),t.start_date||(t.start_date=new Date(gantt.getState().min_date))):(t.end_date=gantt._date_from_pos(a.end+e),t.end_date||(t.end_date=new Date(gantt.getState().max_date))),t.end_date-t.start_date<i.min_duration&&(n.left?t.start_date=gantt.calculateEndDate(t.end_date,-1):t.end_date=gantt.calculateEndDate(t.start_date,1)),gantt._init_task_timing(t)},_resize_progress:function(t,e,n){var i=this._drag_task_coords(t,n),a=Math.max(0,n.pos.x-i.start);t.progress=Math.min(1,a/(i.end-i.start))},_move:function(t,e,n){var i=this._drag_task_coords(t,n),a=gantt._date_from_pos(i.start+e),s=gantt._date_from_pos(i.end+e);a?s?(t.start_date=a,t.end_date=s):(t.end_date=new Date(gantt.getState().max_date),t.start_date=gantt._date_from_pos(gantt.posFromDate(t.end_date)-(i.end-i.start))):(t.start_date=new Date(gantt.getState().min_date),t.end_date=gantt._date_from_pos(gantt.posFromDate(t.start_date)+(i.end-i.start)))},_drag_task_coords:function(t,e){var n=e.obj_s_x=e.obj_s_x||gantt.posFromDate(t.start_date),i=e.obj_e_x=e.obj_e_x||gantt.posFromDate(t.end_date);return{start:n,end:i}},on_mouse_move:function(t){this.drag.start_drag&&this._start_dnd(t);var e=this.drag;if(e.mode){if(!gantt._checkTimeout(this,40))return;this._update_on_move(t)}},_update_on_move:function(t){var e=this.drag;if(e.mode){var n=gantt._get_mouse_pos(t);if(e.pos&&e.pos.x==n.x)return;e.pos=n;var i=gantt._date_from_pos(n.x);if(!i||isNaN(i.getTime()))return;var a=n.x-e.start_x,s=gantt.getTask(e.id);if(this._handlers[e.mode]){var r=dhtmlx.mixin({},s),o=dhtmlx.mixin({},s);this._handlers[e.mode].apply(this,[o,a,e]),dhtmlx.mixin(s,o,!0),gantt._update_parents(e.id,!0),gantt.callEvent("onTaskDrag",[s.id,e.mode,o,r,t]),dhtmlx.mixin(s,o,!0),gantt._update_parents(e.id),gantt.refreshTask(e.id)}}},on_mouse_down:function(t,e){if(2!=t.button&&!gantt.config.readonly&&!this.drag.mode){this.clear_drag_state(),e=e||t.target||t.srcElement;var n=gantt._trim(e.className||"");if(!n||!this._get_drag_mode(n))return e.parentNode?this.on_mouse_down(t,e.parentNode):void 0;var i=this._get_drag_mode(n);if(i)if(i.mode&&i.mode!=gantt.config.drag_mode.ignore&&gantt.config["drag_"+i.mode]){var a=gantt.locate(e),s=dhtmlx.copy(gantt.getTask(a)||{});if(gantt._is_flex_task(s)&&i.mode!=gantt.config.drag_mode.progress)return void this.clear_drag_state();i.id=a;var r=gantt._get_mouse_pos(t);i.start_x=r.x,i.start_y=r.y,i.obj=s,this.drag.start_drag=i}else this.clear_drag_state();else if(gantt.checkEvent("onMouseDown")&&gantt.callEvent("onMouseDown",[n.split(" ")[0]])&&e.parentNode)return this.on_mouse_down(t,e.parentNode)}},_fix_dnd_scale_time:function(t,e){var n=gantt._tasks.unit,i=gantt._tasks.step;gantt.config.round_dnd_dates||(n="minute",i=gantt.config.time_step),e.mode==gantt.config.drag_mode.resize?e.left?t.start_date=gantt._get_closest_date({date:t.start_date,unit:n,step:i}):t.end_date=gantt._get_closest_date({date:t.end_date,unit:n,step:i}):e.mode==gantt.config.drag_mode.move&&(t.start_date=gantt._get_closest_date({date:t.start_date,unit:n,step:i}),t.end_date=gantt.calculateEndDate(t.start_date,t.duration,gantt.config.duration_unit))},_fix_working_times:function(t,e){gantt.config.work_time&&gantt.config.correct_work_time&&(e.mode==gantt.config.drag_mode.resize?e.left?t.start_date=gantt.getClosestWorkTime({date:t.start_date,dir:"future"}):t.end_date=gantt.getClosestWorkTime({date:t.end_date,dir:"past"}):e.mode==gantt.config.drag_mode.move&&(gantt.isWorkTime(t.start_date)?gantt.isWorkTime(new Date(+t.end_date-1))||(t.end_date=gantt.getClosestWorkTime({date:t.end_date,dir:"past"}),t.start_date=gantt.calculateEndDate(t.end_date,-1*t.duration)):(t.start_date=gantt.getClosestWorkTime({date:t.start_date,dir:"future"}),t.end_date=gantt.calculateEndDate(t.start_date,t.duration))))},on_mouse_up:function(t){var e=this.drag;if(e.mode&&e.id){var n=gantt.getTask(e.id);if(gantt.config.work_time&&gantt.config.correct_work_time&&this._fix_working_times(n,e),this._fix_dnd_scale_time(n,e),gantt._init_task_timing(n),this._fireEvent("before_finish",e.mode,[e.id,e.mode,dhtmlx.copy(e.obj),t])){var i=e.id;gantt._init_task_timing(n),gantt.updateTask(n.id),this._fireEvent("after_finish",e.mode,[i,e.mode,t]),this.clear_drag_state()}else e.obj._dhx_changed=!1,dhtmlx.mixin(n,e.obj,!0),gantt.updateTask(n.id)}this.clear_drag_state()},_get_drag_mode:function(t){var e=gantt.config.drag_mode,n=(t||"").split(" "),i=n[0],a={mode:null,left:null};switch(i){case"gantt_task_line":case"gantt_task_content":a.mode=e.move;break;case"gantt_task_drag":a.mode=e.resize,a.left=!(!n[1]||-1===n[1].indexOf("left",n[1].length-"left".length));break;case"gantt_task_progress_drag":a.mode=e.progress;break;case"gantt_link_control":case"gantt_link_point":a.mode=e.ignore;break;default:a=null}return a},_start_dnd:function(t){var e=this.drag=this.drag.start_drag;delete e.start_drag;var n=gantt.config,i=e.id;n["drag_"+e.mode]&&gantt.callEvent("onBeforeDrag",[i,e.mode,t])&&this._fireEvent("before_start",e.mode,[i,e.mode,t])?delete e.start_drag:this.clear_drag_state()},_fireEvent:function(t,e,n){dhtmlx.assert(this._events[t],"Invalid stage:{"+t+"}");var i=this._events[t][e];return dhtmlx.assert(i,"Unknown after drop mode:{"+e+"}"),dhtmlx.assert(n,"Invalid event arguments"),gantt.checkEvent(i)?gantt.callEvent(i,n):!0}},gantt._render_link=function(t){var e=this.getLink(t);gantt._linkRenderer.render_item(e,this.$task_links)},gantt._get_link_type=function(t,e){var n=null;return t&&e?n=gantt.config.links.start_to_start:!t&&e?n=gantt.config.links.finish_to_start:t||e?t&&!e&&(n=gantt.config.links.start_to_finish):n=gantt.config.links.finish_to_finish,n},gantt.isLinkAllowed=function(t,e,n,i){var a=null;if(a="object"==typeof t?t:{source:t,target:e,type:this._get_link_type(n,i)},!a)return!1;if(!(a.source&&a.target&&a.type))return!1;if(a.source==a.target)return!1;var s=!0;return this.checkEvent("onLinkValidation")&&(s=this.callEvent("onLinkValidation",[a])),s},gantt._render_link_element=function(t){var e=this._path_builder.get_points(t),n=gantt._drawer,i=n.get_lines(e),a=document.createElement("div"),s="gantt_task_link",r=this.templates.link_class?this.templates.link_class(t):"";r&&(s+=" "+r),a.className=s,a.setAttribute(gantt.config.link_attribute,t.id);for(var o=0;o<i.length;o++)o==i.length-1&&(i[o].size-=gantt.config.link_arrow_size),a.appendChild(n.render_line(i[o],i[o+1]));var d=i[i.length-1].direction,l=gantt._render_link_arrow(e[e.length-1],d);return a.appendChild(l),a},gantt._render_link_arrow=function(t,e){var n=document.createElement("div"),i=gantt._drawer,a=t.y,s=t.x,r=gantt.config.link_arrow_size,o=gantt.config.row_height,d="gantt_link_arrow gantt_link_arrow_"+e;switch(e){case i.dirs.right:a-=(r-o)/2,s-=r;break;case i.dirs.left:a-=(r-o)/2;break;case i.dirs.up:s-=(r-o)/2;break;case i.dirs.down:a-=r,s-=(r-o)/2}return n.style.cssText=["top:"+a+"px","left:"+s+"px"].join(";"),n.className=d,n},gantt._drawer={current_pos:null,dirs:{left:"left",right:"right",up:"up",down:"down"},path:[],clear:function(){this.current_pos=null,this.path=[]},point:function(t){this.current_pos=dhtmlx.copy(t)},get_lines:function(t){this.clear(),this.point(t[0]);for(var e=1;e<t.length;e++)this.line_to(t[e]);return this.get_path()},line_to:function(t){var e=dhtmlx.copy(t),n=this.current_pos,i=this._get_line(n,e);this.path.push(i),this.current_pos=e},get_path:function(){return this.path},get_wrapper_sizes:function(t){var e,n=gantt.config.link_wrapper_width,i=(gantt.config.link_line_width,t.y+(gantt.config.row_height-n)/2);switch(t.direction){case this.dirs.left:e={top:i,height:n,lineHeight:n,left:t.x-t.size-n/2,width:t.size+n};break;case this.dirs.right:e={top:i,lineHeight:n,height:n,left:t.x-n/2,width:t.size+n};break;case this.dirs.up:e={top:i-t.size,lineHeight:t.size+n,height:t.size+n,left:t.x-n/2,width:n};break;case this.dirs.down:e={top:i,lineHeight:t.size+n,height:t.size+n,left:t.x-n/2,width:n}}return e},get_line_sizes:function(t){var e,n=gantt.config.link_line_width,i=gantt.config.link_wrapper_width,a=t.size+n;switch(t.direction){case this.dirs.left:case this.dirs.right:e={height:n,width:a,marginTop:(i-n)/2,marginLeft:(i-n)/2};break;case this.dirs.up:case this.dirs.down:e={height:a,width:n,marginTop:(i-n)/2,marginLeft:(i-n)/2}}return e},render_line:function(t){var e=this.get_wrapper_sizes(t),n=document.createElement("div");n.style.cssText=["top:"+e.top+"px","left:"+e.left+"px","height:"+e.height+"px","width:"+e.width+"px"].join(";"),n.className="gantt_line_wrapper";var i=this.get_line_sizes(t),a=document.createElement("div");return a.style.cssText=["height:"+i.height+"px","width:"+i.width+"px","margin-top:"+i.marginTop+"px","margin-left:"+i.marginLeft+"px"].join(";"),a.className="gantt_link_line_"+t.direction,n.appendChild(a),n},_get_line:function(t,e){var n=this.get_direction(t,e),i={x:t.x,y:t.y,direction:this.get_direction(t,e)};return i.size=Math.abs(n==this.dirs.left||n==this.dirs.right?t.x-e.x:t.y-e.y),i},get_direction:function(t,e){var n=0;return n=e.x<t.x?this.dirs.left:e.x>t.x?this.dirs.right:e.y>t.y?this.dirs.down:this.dirs.up}},gantt._y_from_ind=function(t){return t*gantt.config.row_height},gantt._path_builder={path:[],clear:function(){this.path=[]},current:function(){return this.path[this.path.length-1]},point:function(t){return t?(this.path.push(dhtmlx.copy(t)),t):this.current()},point_to:function(t,e,n){n=n?{x:n.x,y:n.y}:dhtmlx.copy(this.point());var i=gantt._drawer.dirs;switch(t){case i.left:n.x-=e;break;case i.right:n.x+=e;break;case i.up:n.y-=e;break;case i.down:n.y+=e}return this.point(n)},get_points:function(t){var e=this.get_endpoint(t),n=gantt.config,i=e.e_y-e.y,a=e.e_x-e.x,s=gantt._drawer.dirs;this.clear(),this.point({x:e.x,y:e.y});var r=2*n.link_arrow_size,o=e.e_x>e.x;if(t.type==gantt.config.links.start_to_start)this.point_to(s.left,r),o?(this.point_to(s.down,i),this.point_to(s.right,a)):(this.point_to(s.right,a),this.point_to(s.down,i)),this.point_to(s.right,r);else if(t.type==gantt.config.links.finish_to_start)if(o=e.e_x>e.x+2*r,this.point_to(s.right,r),o)a-=r,this.point_to(s.down,i),this.point_to(s.right,a);else{a-=2*r;var d=i>0?1:-1;this.point_to(s.down,d*(n.row_height/2)),this.point_to(s.right,a),this.point_to(s.down,d*(Math.abs(i)-n.row_height/2)),this.point_to(s.right,r)}else if(t.type==gantt.config.links.finish_to_finish)this.point_to(s.right,r),o?(this.point_to(s.right,a),this.point_to(s.down,i)):(this.point_to(s.down,i),this.point_to(s.right,a)),this.point_to(s.left,r);else if(t.type==gantt.config.links.start_to_finish)if(o=e.e_x>e.x-2*r,this.point_to(s.left,r),o){a+=2*r;var d=i>0?1:-1;this.point_to(s.down,d*(n.row_height/2)),this.point_to(s.right,a),this.point_to(s.down,d*(Math.abs(i)-n.row_height/2)),this.point_to(s.left,r)}else a+=r,this.point_to(s.down,i),this.point_to(s.right,a);return this.path},get_endpoint:function(t){var e=gantt.config.links,n=!1,i=!1;t.type==e.start_to_start?n=i=!0:t.type==e.finish_to_finish?n=i=!1:t.type==e.finish_to_start?(n=!1,i=!0):t.type==e.start_to_finish?(n=!0,i=!1):dhtmlx.assert(!1,"Invalid link type");var a=gantt._get_task_visible_pos(gantt._pull[t.source],n),s=gantt._get_task_visible_pos(gantt._pull[t.target],i);return{x:a.x,e_x:s.x,y:a.y,e_y:s.y}}},gantt._init_links_dnd=function(){function t(t,e,n){var i=gantt._get_task_pos(t,!!e);return i.y+=gantt._get_task_height()/2,n=n||0,i.x+=(e?-1:1)*n,i}function e(t){var e=i(),n=["gantt_link_tooltip"];e.from&&e.to&&n.push(gantt.isLinkAllowed(e.from,e.to,e.from_start,e.to_start)?"gantt_allowed_link":"gantt_invalid_link");var a=gantt.templates.drag_link_class(e.from,e.from_start,e.to,e.to_start);a&&n.push(a);var s="<div class='"+a+"'>"+gantt.templates.drag_link(e.from,e.from_start,e.to,e.to_start)+"</div>";t.innerHTML=s}function n(t,e){t.style.left=e.x+5+"px",t.style.top=e.y+5+"px"}function i(){return{from:gantt._link_source_task,to:gantt._link_target_task,from_start:gantt._link_source_task_start,to_start:gantt._link_target_task_start}}function a(){gantt._link_source_task=gantt._link_source_task_start=gantt._link_target_task=null,gantt._link_target_task_start=!0}function s(t,e,n,a){var s=d(),l=i(),_=["gantt_link_direction"];gantt.templates.link_direction_class&&_.push(gantt.templates.link_direction_class(l.from,l.from_start,l.to,l.to_start));var h=Math.sqrt(Math.pow(n-t,2)+Math.pow(a-e,2));if(h=Math.max(0,h-3)){s.className=_.join(" ");var c=(a-e)/(n-t),g=Math.atan(c);2==o(t,n,e,a)?g+=Math.PI:3==o(t,n,e,a)&&(g-=Math.PI);var u=Math.sin(g),f=Math.cos(g),p=Math.round(e),m=Math.round(t),v=["-webkit-transform: rotate("+g+"rad)","-moz-transform: rotate("+g+"rad)","-ms-transform: rotate("+g+"rad)","-o-transform: rotate("+g+"rad)","transform: rotate("+g+"rad)","width:"+Math.round(h)+"px"];if(-1!=window.navigator.userAgent.indexOf("MSIE 8.0")){v.push('-ms-filter: "'+r(u,f)+'"');var k=Math.abs(Math.round(t-n)),x=Math.abs(Math.round(a-e));switch(o(t,n,e,a)){case 1:p-=x;break;case 2:m-=k,p-=x;break;case 3:m-=k}}v.push("top:"+p+"px"),v.push("left:"+m+"px"),s.style.cssText=v.join(";")}}function r(t,e){return"progid:DXImageTransform.Microsoft.Matrix(M11 = "+e+",M12 = -"+t+",M21 = "+t+",M22 = "+e+",SizingMethod = 'auto expand')"}function o(t,e,n,i){return e>=t?n>=i?1:4:n>=i?2:3}function d(){return _._direction||(_._direction=document.createElement("div"),gantt.$task_links.appendChild(_._direction)),_._direction}function l(){_._direction&&(_._direction.parentNode&&_._direction.parentNode.removeChild(_._direction),_._direction=null)}var _=new dhtmlxDnD(this.$task_bars,{sensitivity:0,updates_per_second:60}),h="task_left",c="task_right",g="gantt_link_point",u="gantt_link_control";_.attachEvent("onBeforeDragStart",dhtmlx.bind(function(e,n){if(gantt.config.readonly)return!1;var i=n.target||n.srcElement;if(a(),gantt.getState().drag_id)return!1;if(gantt._locate_css(i,g)){gantt._locate_css(i,h)&&(gantt._link_source_task_start=!0);var s=gantt._link_source_task=this.locate(n),r=gantt.getTask(s),o=0;return r.type==gantt.config.types.milestone&&(o=(gantt._get_visible_milestone_width()-gantt._get_milestone_width())/2),this._dir_start=t(r,!!gantt._link_source_task_start,o),!0}return!1},this)),_.attachEvent("onAfterDragStart",dhtmlx.bind(function(){e(_.config.marker)},this)),_.attachEvent("onDragMove",dhtmlx.bind(function(i,a){var r=_.config,o=_.getPosition(a);n(r.marker,o);var d=gantt._is_link_drop_area(a),l=gantt._link_target_task,h=gantt._link_landing,g=gantt._link_target_task_start,f=gantt.locate(a),p=!0;if(d&&(p=!gantt._locate_css(a,c),d=!!f),gantt._link_target_task=f,gantt._link_landing=d,gantt._link_target_task_start=p,d){var m=gantt.getTask(f),v=gantt._locate_css(a,u),k=0;v&&(k=Math.floor(v.offsetWidth/2)),this._dir_end=t(m,!!gantt._link_target_task_start,k)}else this._dir_end=gantt._get_mouse_pos(a);var x=!(h==d&&l==f&&g==p);return x&&(l&&gantt.refreshTask(l,!1),f&&gantt.refreshTask(f,!1)),x&&e(r.marker),s(this._dir_start.x,this._dir_start.y,this._dir_end.x,this._dir_end.y),!0},this)),_.attachEvent("onDragEnd",dhtmlx.bind(function(){var t=i();if(t.from&&t.to&&t.from!=t.to){var e=gantt._get_link_type(t.from_start,t.to_start);e&&gantt.addLink({source:t.from,target:t.to,type:e})}a(),t.from&&gantt.refreshTask(t.from,!1),t.to&&gantt.refreshTask(t.to,!1),l()},this)),gantt._is_link_drop_area=function(t){return!!gantt._locate_css(t,u)}},gantt._get_link_state=function(){return{link_landing_area:this._link_landing,link_target_id:this._link_target_task,link_target_start:this._link_target_task_start,link_source_id:this._link_source_task,link_source_start:this._link_source_task_start}},gantt._init_tasks=function(){function t(t,e,n,i){for(var a=0;a<t.length;a++)t[a].change_id(e,n),t[a].render_item(i)}this._tasks={col_width:this.config.columnWidth,width:[],full_width:0,trace_x:[],rendered:{}},this._click.gantt_task_link=dhtmlx.bind(function(t){var e=this.locate(t,gantt.config.link_attribute);e&&this.callEvent("onLinkClick",[e,t])},this),this._dbl_click.gantt_task_link=dhtmlx.bind(function(t,e){var e=this.locate(t,gantt.config.link_attribute);this._delete_link_handler(e,t)},this),this._dbl_click.gantt_link_point=dhtmlx.bind(function(t,e,n){var e=this.locate(t),i=this.getTask(e),a=null;return n.parentNode&&n.parentNode.className&&(a=n.parentNode.className.indexOf("_left")>-1?i.$target[0]:i.$source[0]),a&&this._delete_link_handler(a,t),!1},this),this._tasks_dnd.init(),this._init_links_dnd();var e=this._create_filter("_filter_task","_is_grid_visible"),n=this._create_filter("_filter_task","_is_chart_visible"),i=this._create_filter("_filter_link","_is_chart_visible");this._taskRenderer=gantt._task_renderer("line",this._render_task_element,this.$task_bars,n),this._linkRenderer=gantt._task_renderer("links",this._render_link_element,this.$task_links,i),this._gridRenderer=gantt._task_renderer("grid_items",this._render_grid_item,this.$grid_data,e),this._bgRenderer=gantt._task_renderer("bg_lines",this._render_bg_line,this.$task_bg,n),this.attachEvent("onTaskIdChange",function(e,n){var i=this._get_task_renderers();t(i,e,n,this.getTask(n))}),this.attachEvent("onLinkIdChange",function(e,n){var i=this._get_link_renderers();t(i,e,n,this.getLink(n))})},gantt._create_filter=function(t){return t instanceof Array||(t=Array.prototype.slice.call(arguments,0)),function(e){for(var n=!0,i=0,a=t.length;a>i;i++){var s=t[i];gantt[s]&&(n=n&&gantt[s].apply(gantt,[e.id,e])!==!1)}return n}},gantt._is_chart_visible=function(){return!!this.config.show_chart},gantt._filter_task=function(t,e){var n=null,i=null;return!(this.config.start_date&&this.config.end_date&&(n=this.config.start_date.valueOf(),i=this.config.end_date.valueOf(),+e.start_date>i||+e.end_date<+n))},gantt._filter_link=function(t,e){return this.config.show_links&&gantt.isTaskVisible(e.source)&&gantt.isTaskVisible(e.target)?this.callEvent("onBeforeLinkDisplay",[t,e]):!1},gantt._get_task_renderers=function(){return[this._taskRenderer,this._gridRenderer,this._bgRenderer]},gantt._get_link_renderers=function(){return[this._linkRenderer]},gantt._delete_link_handler=function(t,e){if(t&&this.callEvent("onLinkDblClick",[t,e])){if(this.config.readonly)return;var n="",i=gantt.locale.labels.link+" "+this.templates.link_description(this.getLink(t))+" "+gantt.locale.labels.confirm_link_deleting;window.setTimeout(function(){gantt._dhtmlx_confirm(i,n,function(){gantt.deleteLink(t)})},gantt.config.touch?300:1)}},gantt.getTaskNode=function(t){return this._taskRenderer.rendered[t]},gantt.getLinkNode=function(t){return this._linkRenderer.rendered[t]},gantt._get_tasks_data=function(){for(var t=[],e=0;e<this._order.length;e++){var n=this._pull[this._order[e]];n.$index=e,this._update_parents(n.id,!0),t.push(n)}return t},gantt._get_links_data=function(){var t=[];for(var e in this._lpull)t.push(this._lpull[e]);return t},gantt._render_data=function(){this._update_layout_sizes();for(var t=this._get_tasks_data(),e=this._get_task_renderers(),n=0;n<e.length;n++)e[n].render_items(t);var i=gantt._get_links_data();e=this._get_link_renderers();for(var n=0;n<e.length;n++)e[n].render_items(i)},gantt._update_layout_sizes=function(){var t=this._tasks;if(t.bar_height=this._get_task_height(),this.$task_data.style.height=Math.max(this.$task.offsetHeight-this.config.scale_height,0)+"px",this.$task_bg.style.width=t.full_width+"px",this._is_grid_visible()){for(var e=this.config.columns,n=0,i=0;i<e.length;i++)n+=e[i].width;this.$grid_data.style.width=Math.max(n-1,0)+"px"}},gantt._init_tasks_range=function(){var t=this.config.scale_unit;if(this.config.start_date&&this.config.end_date)return this._min_date=this.date[t+"_start"](new Date(this.config.start_date)),void(this._max_date=this.date[t+"_start"](new Date(this.config.end_date)));var e=this._get_tasks_data(),n=this._init_task({id:this.config.root_id});e.push(n);var i=-1/0,a=1/0;this.eachTask(function(t){t.end_date&&+t.end_date>+i&&(i=new Date(t.end_date))},this.config.root_id),this.eachTask(function(t){t.start_date&&+t.start_date<+a&&(a=new Date(t.start_date))},this.config.root_id),this._min_date=a,this._max_date=i,i&&i!=-1/0||(this._min_date=new Date,this._max_date=new Date(this._min_date)),this._min_date=this.date[t+"_start"](this._min_date),+this._min_date==+a&&(this._min_date=this.date.add(this.date[t+"_start"](this._min_date),-1,t)),this._max_date=this.date[t+"_start"](this._max_date),this._max_date=this.date.add(this._max_date,1,t)},gantt._prepare_scale_html=function(t){var e=[],n=null,i=null,a=null;(t.template||t.date)&&(i=t.template||this.date.date_to_str(t.date)),a=t.css||gantt.templates.scale_cell_class;for(var s=0;s<t.count;s++){n=new Date(t.trace_x[s]);var r=i.call(this,n),o=t.width[s],d="",l="",_="";if(o){d="width:"+o+"px;",_="gantt_scale_cell"+(s==t.count-1?" gantt_last_cell":""),l=a.call(this,n),l&&(_+=" "+l);var h="<div class='"+_+"' style='"+d+"'>"+r+"</div>";e.push(h)}}return e.join("")},gantt._render_tasks_scales=function(){this._init_tasks_range(),this._scroll_resize(),this._set_sizes();var t="",e=0,n=0,i=0;if(this._is_chart_visible()){var a=this._scale_helpers,s=[a.primaryScale()].concat(this.config.subscales);i=this.config.scale_height-1,a.sortScales(s);for(var r=this._get_resize_options(),o=r.x?0:this.$task.offsetWidth,d=a.prepareConfigs(s,this.config.min_column_width,o,i),l=this._tasks=d[d.length-1],_=[],h=this.templates.scale_row_class,c=0;c<d.length;c++){var g="gantt_scale_line",u=h(d[c]);u&&(g+=" "+u),_.push('<div class="'+g+'" style="height:'+d[c].height+"px;line-height:"+d[c].height+'px">'+this._prepare_scale_html(d[c])+"</div>")}t=_.join(""),e=l.full_width+this.$scroll_ver.offsetWidth+"px",n=l.full_width+"px",i+="px"}this.$task.style.display=this._is_chart_visible()?"":"none",this.$task_scale.style.height=i,this.$task_data.style.width=this.$task_scale.style.width=e,this.$task_links.style.width=this.$task_bars.style.width=n,this.$task_scale.innerHTML=t},gantt._render_bg_line=function(t){var e=gantt._tasks,n=e.count,i=[];if(gantt.config.show_task_cells)for(var a=0;n>a;a++){var s=e.width[a],r="",o="";if(s>0){r="width:"+s+"px;",o="gantt_task_cell"+(a==n-1?" gantt_last_cell":""),_=this.templates.task_cell_class(t,e.trace_x[a]),_&&(o+=" "+_);var d="<div class='"+o+"' style='"+r+"'></div>";i.push(d)}}var l=t.$index%2!==0,_=gantt.templates.task_row_class(t.start_date,t.end_date,t),h="gantt_task_row"+(l?" odd":"")+(_?" "+_:"");this.getState().selected_task==t.id&&(h+=" gantt_selected");var c=document.createElement("div");return c.className=h,c.style.height=gantt.config.row_height+"px",c.setAttribute(this.config.task_attribute,t.id),c.innerHTML=i.join(""),
c},gantt._adjust_scales=function(){if(this.config.fit_tasks){var t=+this._min_date,e=+this._max_date;if(this._init_tasks_range(),+this._min_date!=t||+this._max_date!=e)return this.render(),this.callEvent("onScaleAdjusted",[]),!0}return!1},gantt.refreshTask=function(t,e){var n=this._get_task_renderers(),i=this.getTask(t);if(i&&this.isTaskVisible(t))for(var a=0;a<n.length;a++)n[a].render_item(i);else for(var a=0;a<n.length;a++)n[a].remove_item(t);if(void 0===e||e){for(var i=this.getTask(t),a=0;a<i.$source.length;a++)gantt.refreshLink(i.$source[a]);for(var a=0;a<i.$target.length;a++)gantt.refreshLink(i.$target[a])}},gantt.refreshLink=function(t){this.isLinkExists(t)?gantt._render_link(t):gantt._linkRenderer.remove_item(t)},gantt._combine_item_class=function(t,e,n){var i=[t];e&&i.push(e);var a=gantt.getState(),s=this.getTask(n);this._get_safe_type(s.type)==this.config.types.milestone&&i.push("gantt_milestone"),this._get_safe_type(s.type)==this.config.types.project&&i.push("gantt_project"),this._is_flex_task(s)&&i.push("gantt_dependent_task"),this.config.select_task&&n==a.selected_task&&i.push("gantt_selected"),n==a.drag_id&&i.push("gantt_drag_"+a.drag_mode);var r=gantt._get_link_state();if(r.link_source_id==n&&i.push("gantt_link_source"),r.link_target_id==n&&i.push("gantt_link_target"),r.link_landing_area&&r.link_target_id&&r.link_source_id&&r.link_target_id!=r.link_source_id){var o=r.link_source_id,d=r.link_source_start,l=r.link_target_start,_=gantt.isLinkAllowed(o,n,d,l),h="";h=_?l?"link_start_allow":"link_finish_allow":l?"link_start_deny":"link_finish_deny",i.push(h)}return i.join(" ")},gantt._render_pair=function(t,e,n,i){var a=gantt.getState();+n.end_date<=+a.max_date&&t.appendChild(i(e+" task_right")),+n.start_date>=+a.min_date&&t.appendChild(i(e+" task_left"))},gantt._get_task_height=function(){var t=this.config.task_height;return"full"==t&&(t=this.config.row_height-5),t=Math.min(t,this.config.row_height),Math.max(t,0)},gantt._get_milestone_width=function(){return this._get_task_height()},gantt._get_visible_milestone_width=function(){var t=gantt._get_task_height();return Math.sqrt(2*t*t)},gantt._get_task_width=function(t){return Math.round(this._get_task_pos(t,!1).x-this._get_task_pos(t,!0).x)},gantt._render_task_element=function(t){var e=this._get_task_pos(t),n=this.config,i=this._get_task_height(),a=Math.floor((this.config.row_height-i)/2);t.type==n.types.milestone&&n.link_line_width>1&&(a+=1);var s=document.createElement("div"),r=gantt._get_task_width(t),o=this._get_safe_type(t.type);s.setAttribute(this.config.task_attribute,t.id),s.appendChild(gantt._render_task_content(t,r)),s.className=this._combine_item_class("gantt_task_line",this.templates.task_class(t.start_date,t.end_date,t),t.id),s.style.cssText=["left:"+e.x+"px","top:"+(a+e.y)+"px","height:"+i+"px","line-height:"+i+"px","width:"+r+"px"].join(";");var d=this._render_leftside_content(t);return d&&s.appendChild(d),d=this._render_rightside_content(t),d&&s.appendChild(d),n.show_progress&&o!=this.config.types.milestone&&this._render_task_progress(t,s,r),this.config.readonly||(n.drag_resize&&!this._is_flex_task(t)&&o!=this.config.types.milestone&&gantt._render_pair(s,"gantt_task_drag",t,function(t){var e=document.createElement("div");return e.className=t,e}),n.drag_links&&gantt._render_pair(s,"gantt_link_control",t,function(t){var e=document.createElement("div");e.className=t,e.style.cssText=["height:"+i+"px","line-height:"+i+"px"].join(";");var n=document.createElement("div");return n.className="gantt_link_point",e.appendChild(n),e})),s},gantt._render_side_content=function(t,e,n){if(!e)return null;var i=e(t.start_date,t.end_date,t);if(!i)return null;var a=document.createElement("div");return a.className="gantt_side_content "+n,a.innerHTML=i,a},gantt._render_leftside_content=function(t){var e="gantt_left "+gantt._get_link_crossing_css(!0,t);return gantt._render_side_content(t,this.templates.leftside_text,e)},gantt._render_rightside_content=function(t){var e="gantt_right "+gantt._get_link_crossing_css(!1,t);return gantt._render_side_content(t,this.templates.rightside_text,e)},gantt._get_conditions=function(t){return t?{$source:[gantt.config.links.start_to_start],$target:[gantt.config.links.start_to_start,gantt.config.links.finish_to_start]}:{$source:[gantt.config.links.finish_to_start,gantt.config.links.finish_to_finish],$target:[gantt.config.links.finish_to_finish]}},gantt._get_link_crossing_css=function(t,e){var n=gantt._get_conditions(t);for(var i in n)for(var a=e[i],s=0;s<a.length;s++)for(var r=gantt.getLink(a[s]),o=0;o<n[i].length;o++)if(r.type==n[i][o])return"gantt_link_crossing";return""},gantt._render_task_content=function(t){var e=document.createElement("div");return this._get_safe_type(t.type)!=this.config.types.milestone&&(e.innerHTML=this.templates.task_text(t.start_date,t.end_date,t)),e.className="gantt_task_content",e},gantt._render_task_progress=function(t,e,n){var i=1*t.progress||0;n=Math.max(n-2,0);var a=document.createElement("div"),s=Math.round(n*i);if(s=Math.min(n,s),a.style.width=s+"px",a.className="gantt_task_progress",a.innerHTML=this.templates.progress_text(t.start_date,t.end_date,t),e.appendChild(a),this.config.drag_progress&&!gantt.config.readonly){var r=document.createElement("div");r.style.left=s+"px",r.className="gantt_task_progress_drag",a.appendChild(r),e.appendChild(r)}},gantt._get_line=function(t){var e={second:1,minute:60,hour:3600,day:86400,week:604800,month:2592e3,year:31536e3};return e[t]||0},gantt._date_from_pos=function(t){var e=this._tasks;if(0>t||t>e.full_width)return null;for(var n=0,i=0;i+e.width[n]<t;)i+=e.width[n],n++;var a=(t-i)/e.width[n],s=gantt._get_coll_duration(e,e.trace_x[n]),r=new Date(e.trace_x[n].valueOf()+Math.round(a*s));return r},gantt.posFromDate=function(t){var e=gantt._day_index_by_date(t);dhtmlx.assert(e>=0,"Invalid day index");for(var n=Math.floor(e),i=e%1,a=0,s=1;n>=s;s++)a+=gantt._tasks.width[s-1];return i&&(a+=n<gantt._tasks.width.length?gantt._tasks.width[n]*(i%1):1),a},gantt._day_index_by_date=function(t){var e=new Date(t),n=gantt._tasks.trace_x,i=gantt._tasks.ignore_x;if(+e<=this._min_date)return 0;if(+e>=this._max_date)return n.length;for(var a=0;a<n.length-1&&(!(+e<n[a+1])||i[+n[a+1]]);a++);return a+(t-n[a])/gantt._get_coll_duration(gantt._tasks,n[a])},gantt._get_coll_duration=function(t,e){return gantt.date.add(e,t.step,t.unit)-e},gantt._get_x_pos=function(t,e){e=e!==!1,gantt.posFromDate(e?t.start_date:t.end_date)},gantt._get_task_coord=function(t,e,n){e=e!==!1,n=n||0;var i=t.type==this.config.types.milestone,a=this.posFromDate(e||i?t.start_date:t.end_date),s=this._y_from_ind(this._get_visible_order(t.id));return i&&(e?a-=n:a+=n),{x:a,y:s}},gantt._get_task_pos=function(t,e){e=e!==!1;var n=gantt._get_milestone_width()/2;return this._get_task_coord(t,e,n)},gantt._get_task_visible_pos=function(t,e){e=e!==!1;var n=gantt._get_visible_milestone_width()/2;return this._get_task_coord(t,e,n)},gantt._correct_shift=function(t,e){return t-=6e4*(new Date(gantt._min_date).getTimezoneOffset()-new Date(t).getTimezoneOffset())*(e?-1:1)},gantt._get_mouse_pos=function(t){if(t.pageX||t.pageY)var e={x:t.pageX,y:t.pageY};var n=_isIE?document.documentElement:document.body,e={x:t.clientX+n.scrollLeft-n.clientLeft,y:t.clientY+n.scrollTop-n.clientTop},i=gantt._get_position(gantt.$task_data);return e.x=e.x-i.x+gantt.$task_data.scrollLeft,e.y=e.y-i.y+gantt.$task_data.scrollTop,e},gantt._task_renderer=function(t,e,n,i){return this._task_area_pulls||(this._task_area_pulls={}),this._task_area_renderers||(this._task_area_renderers={}),this._task_area_renderers[t]?this._task_area_renderers[t]:(e||dhtmlx.assert(!1,"Invalid renderer call"),this._task_area_renderers[t]={render_item:function(a,s){var r=gantt._task_area_pulls[t];if(s=s||n,i&&!i(a))return void this.remove_item(a.id);var o=e.call(gantt,a);o&&(r[a.id]?this.replace_item(a.id,o):(r[a.id]=o,s.appendChild(o)))},render_items:function(e,i){this.rendered=gantt._task_area_pulls[t]={},i=i||n,i.innerHTML="";for(var a=document.createDocumentFragment(),s=0,r=e.length;r>s;s++)this.render_item(e[s],a);i.appendChild(a)},replace_item:function(t,e){var n=this.rendered[t];n&&n.parentNode&&n.parentNode.replaceChild(e,n),this.rendered[t]=e},remove_item:function(t){var e=this.rendered[t];e&&e.parentNode&&e.parentNode.removeChild(e),delete this.rendered[t]},change_id:function(t,e){this.rendered[e]=this.rendered[t],delete this.rendered[t]},rendered:this._task_area_pulls[t],node:n},this._task_area_renderers[t])},gantt._pull={},gantt._branches={},gantt._order=[],gantt._lpull={},gantt.load=function(t,e,n){dhtmlx.assert(arguments.length,"Invalid load arguments"),this.callEvent("onLoadStart",[]);var i="json",a=null;arguments.length>=3?(i=e,a=n):"string"==typeof arguments[1]?i=arguments[1]:"function"==typeof arguments[1]&&(a=arguments[1]),dhtmlxAjax.get(t,dhtmlx.bind(function(t){this.on_load(t,i),"function"==typeof a&&a.call(this)},this))},gantt.parse=function(t,e){this.on_load({xmlDoc:{responseText:t}},e)},gantt.serialize=function(t){return t=t||"json",this[t].serialize()},gantt.on_load=function(t,e){e||(e="json"),dhtmlx.assert(this[e],"Invalid data type:'"+e+"'");var n=t.xmlDoc.responseText,i=this[e].parse(n,t);this._process_loading(i),this.callEvent("onLoadEnd",[])},gantt._process_loading=function(t){t.collections&&this._load_collections(t.collections);for(var e=t.data,n=0;n<e.length;n++){var i=e[n];this._init_task(i),this.callEvent("onTaskLoading",[i])&&(this._pull[i.id]=i,this._add_branch(i))}this._sync_order();for(var n in this._pull)this._pull[n].$level=this._item_level(this._pull[n]);this._init_links(t.links||(t.collections?t.collections.links:[]))},gantt._init_links=function(t){if(t)for(var e=0;e<t.length;e++)if(t[e]){var n=this._init_link(t[e]);this._lpull[n.id]=n}this._sync_links()},gantt._load_collections=function(t){var e=!1;for(var n in t)if(t.hasOwnProperty(n)){e=!0;var i=t[n],a=this.serverList[n];if(!a)continue;a.splice(0,a.length);for(var s=0;s<i.length;s++){var r=i[s],o=dhtmlx.copy(r);o.key=o.value;for(var d in r)if(r.hasOwnProperty(d)){if("value"==d||"label"==d)continue;o[d]=r[d]}a.push(o)}}e&&this.callEvent("onOptionsLoad",[])},gantt._sync_order=function(){this._order=[],this._sync_order_item({parent:this.config.root_id,$open:!0,$ignore:!0,id:this.config.root_id}),this._scroll_resize(),this._set_sizes()},gantt.attachEvent("onBeforeTaskDisplay",function(t,e){return!e.$ignore}),gantt._sync_order_item=function(t){if(t.id&&this._filter_task(t.id,t)&&this.callEvent("onBeforeTaskDisplay",[t.id,t])&&this._order.push(t.id),t.$open){var e=this._branches[t.id];if(e)for(var n=0;n<e.length;n++)this._sync_order_item(this._pull[e[n]])}},gantt._get_visible_order=function(t){dhtmlx.assert(t,"Invalid argument");for(var e=this._order,n=0,i=e.length;i>n;n++)if(e[n]==t)return n;return-1},gantt.eachTask=function(t,e,n){e=e||this.config.root_id,n=n||this;var i=this._branches[e];if(i)for(var a=0;a<i.length;a++){var s=this._pull[i[a]];t.call(n,s),this._branches[s.id]&&this.eachTask(t,s.id,n)}},gantt.json={parse:function(data){return dhtmlx.assert(data,"Invalid data"),"string"==typeof data&&(window.JSON?data=JSON.parse(data):(gantt._temp=eval("("+data+")"),data=gantt._temp||{},gantt._temp=null)),data.dhx_security&&(dhtmlx.security_key=data.dhx_security),data},_copyLink:function(t){var e={};for(var n in t)e[n]=t[n];return e},_copyObject:function(t){var e={};for(var n in t)"$"!=n.charAt(0)&&(e[n]=t[n]);return e.start_date=gantt.templates.xml_format(e.start_date),e.end_date&&(e.end_date=gantt.templates.xml_format(e.end_date)),e},serialize:function(){var t=[],e=[];gantt.eachTask(function(e){t.push(this._copyObject(e))},gantt.config.root_id,this);for(var n in gantt._lpull)e.push(this._copyLink(gantt._lpull[n]));return{data:t,links:e}}},gantt.xml={_xmlNodeToJSON:function(t,e){for(var n={},i=0;i<t.attributes.length;i++)n[t.attributes[i].name]=t.attributes[i].value;if(!e){for(var i=0;i<t.childNodes.length;i++){var a=t.childNodes[i];1==a.nodeType&&(n[a.tagName]=a.firstChild?a.firstChild.nodeValue:"")}n.text||(n.text=t.firstChild?t.firstChild.nodeValue:"")}return n},_getCollections:function(t){for(var e={},n=t.doXPath("//coll_options"),i=0;i<n.length;i++)for(var a=n[i].getAttribute("for"),s=e[a]=[],r=t.doXPath(".//item",n[i]),o=0;o<r.length;o++){for(var d=r[o],l=d.attributes,_={key:r[o].getAttribute("value"),label:r[o].getAttribute("label")},h=0;h<l.length;h++){var c=l[h];"value"!=c.nodeName&&"label"!=c.nodeName&&(_[c.nodeName]=c.nodeValue)}s.push(_)}return e},_getXML:function(t,e,n){n=n||"data",e.getXMLTopNode||(e=new dtmlXMLLoaderObject(function(){}),e.loadXMLString(t));var i=e.getXMLTopNode(n);if(i.tagName!=n)throw"Invalid XML data";var a=i.getAttribute("dhx_security");return a&&(dhtmlx.security_key=a),e},parse:function(t,e){e=this._getXML(t,e);for(var n={},i=n.data=[],a=e.doXPath("//task"),s=0;s<a.length;s++)i[s]=this._xmlNodeToJSON(a[s]);return n.collections=this._getCollections(e),n},_copyLink:function(t){return"<item id='"+t.id+"' source='"+t.source+"' target='"+t.target+"' type='"+t.type+"' />"},_copyObject:function(t){var e=gantt.templates.xml_format(t.start_date),n=gantt.templates.xml_format(t.end_date);return"<task id='"+t.id+"' parent='"+(t.parent||"")+"' start_date='"+e+"' duration='"+t.duration+"' open='"+!!t.open+"' progress='"+t.progress+"' end_date='"+n+"'><![CDATA["+t.text+"]]></task>"},serialize:function(){var t=[],e=[];gantt.eachTask(function(e){t.push(this._copyObject(e))},this.config.root_id,this);for(var n in gantt._lpull)e.push(this._copyLink(gantt._lpull[n]));return"<data>"+t.join("")+"<coll_options for='links'>"+e.join("")+"</coll_options></data>"}},gantt.oldxml={parse:function(t,e){e=gantt.xml._getXML(t,e,"projects");for(var n={collections:{links:[]}},i=n.data=[],a=e.doXPath("//task"),s=0;s<a.length;s++){i[s]=gantt.xml._xmlNodeToJSON(a[s]);var r=a[s].parentNode;i[s].parent="project"==r.tagName?"project-"+r.getAttribute("id"):r.parentNode.getAttribute("id")}a=e.doXPath("//project");for(var s=0;s<a.length;s++){var o=gantt.xml._xmlNodeToJSON(a[s],!0);o.id="project-"+o.id,i.push(o)}for(var s=0;s<i.length;s++){var o=i[s];o.start_date=o.startdate||o.est,o.end_date=o.enddate,o.text=o.name,o.duration=o.duration/8,o.open=1,o.duration||o.end_date||(o.duration=1),o.predecessortasks&&n.collections.links.push({target:o.id,source:o.predecessortasks,type:gantt.config.links.finish_to_start})}return n},serialize:function(){dhtmlx.message("Serialization to 'old XML' is not implemented")}},gantt.serverList=function(t,e){return e?this.serverList[t]=e.slice(0):this.serverList[t]||(this.serverList[t]=[]),this.serverList[t]},gantt._working_time_helper={units:["year","month","week","day","hour","minute"],hours:[8,17],dates:{0:!1,6:!1},_get_unit_order:function(t){for(var e=0,n=this.units.length;n>e;e++)if(this.units[e]==t)return e;dhtmlx.assert(!1,"Incorrect duration unit")},_timestamp:function(t){var e=null;return t.day||0===t.day?e=t.day:t.date&&(e=gantt.date.date_part(new Date(t.date)).valueOf()),e},set_time:function(t){var e=void 0!==t.hours?t.hours:!0,n=this._timestamp(t);null!==n?this.dates[n]=e:this.hours=e},unset_time:function(t){if(t){var e=this._timestamp(t);null!==e&&delete this.dates[e]}else this.hours=[]},is_working_unit:function(t,e,n){return gantt.config.work_time?(void 0===n&&(n=this._get_unit_order(e)),void 0===n?!1:n&&!this.is_working_unit(t,this.units[n-1],n-1)?!1:this["is_work_"+e]?this["is_work_"+e](t):!0):!0},is_work_day:function(t){var e=this.get_working_hours(t);return e instanceof Array?e.length>0:!1},is_work_hour:function(t){for(var e=this.get_working_hours(t),n=t.getHours(),i=0;i<e.length;i+=2){if(void 0===e[i+1])return e[i]==n;if(n>=e[i]&&n<e[i+1])return!0}return!1},get_working_hours:function(t){var e=this._timestamp({date:t}),n=!0;return void 0!==this.dates[e]?n=this.dates[e]:void 0!==this.dates[t.getDay()]&&(n=this.dates[t.getDay()]),n===!0?this.hours:n?n:[]},get_work_units_between:function(t,e,n,i){if(!n)return!1;for(var a=new Date(t),s=new Date(e),i=i||1,r=0;a.valueOf()<s.valueOf();)this.is_working_unit(a,n)&&r++,a=gantt.date.add(a,i,n);return r},add_worktime:function(t,e,n,i){if(!n)return!1;for(var a=new Date(t),s=0,i=i||1,e=1*e;e>s;){var r=gantt.date.add(a,i,n);this.is_working_unit(i>0?a:r,n)&&s++,a=r}return a},get_closest_worktime:function(t){if(this.is_working_unit(t.date,t.unit))return t.date;var e=t.unit,n=gantt.date[e+"_start"](t.date),i=new Date(n),a=new Date(n),s=!0,r=3e3,o=0,d="any"==t.dir||!t.dir,l=1;for("past"==t.dir&&(l=-1);!this.is_working_unit(n,e);)if(d&&(n=s?i:a,l=-1*l),n=gantt.date.add(n,l,e),d&&(s?i=n:a=n),s=!s,o++,o>r)return dhtmlx.assert(!1,"Invalid working time check"),!1;return(n==a||"past"==t.dir)&&(n=gantt.date.add(n,1,e)),n}},gantt.getTask=function(t){return dhtmlx.assert(this._pull[t]),this._pull[t]},gantt.getTaskByTime=function(t,e){var n=this._pull,i=[];if(t||e){t=+t||-1/0,e=+e||1/0;for(var a in n){var s=n[a];+s.start_date<e&&+s.end_date>t&&i.push(s)}}else for(var a in n)i.push(n[a]);return i},gantt.isTaskExists=function(t){return dhtmlx.defined(this._pull[t])},gantt.isTaskVisible=function(t){if(!this._pull[t])return!1;if(!(+this._pull[t].start_date<+this._max_date&&+this._pull[t].end_date>+this._min_date))return!1;for(var e=0,n=this._order.length;n>e;e++)if(this._order[e]==t)return!0;return!1},gantt.updateTask=function(t,e){return dhtmlx.defined(e)||(e=this.getTask(t)),this.callEvent("onBeforeTaskUpdate",[t,e])===!1?!1:(this._pull[e.id]=e,this._is_parent_sync(e)||this._resync_parent(e),this._update_parents(e.id),this.refreshTask(e.id),this.callEvent("onAfterTaskUpdate",[t,e]),this._sync_order(),void this._adjust_scales())},gantt._add_branch=function(t){this._branches[t.parent]||(this._branches[t.parent]=[]);for(var e=this._branches[t.parent],n=!1,i=0,a=e.length;a>i;i++)if(e[i]==t.id){n=!0;break}n||e.push(t.id),this._sync_parent(t),this._sync_order()},gantt._move_branch=function(t,e,n){t.parent=n,this._sync_parent(t),this._replace_branch_child(e,t.id),n?this._add_branch(t):delete this._branches[t.id],t.$level=this._item_level(t),this._sync_order()},gantt._resync_parent=function(t){this._move_branch(t,t.$rendered_parent,t.parent)},gantt._sync_parent=function(t){t.$rendered_parent=t.parent},gantt._is_parent_sync=function(t){return t.$rendered_parent==t.parent},gantt._replace_branch_child=function(t,e,n){var i=this._branches[t];if(i){for(var a=[],s=0;s<i.length;s++)i[s]!=e?a.push(i[s]):n&&a.push(n);this._branches[t]=a}this._sync_order()},gantt.addTask=function(t,e){return dhtmlx.defined(e)||(e=t.parent||0),dhtmlx.defined(this._pull[e])||(e=0),t.parent=e,t=this._init_task(t),this.callEvent("onBeforeTaskAdd",[t.id,t])===!1?!1:(this._pull[t.id]=t,this._add_branch(t),this.refreshData(),this.callEvent("onAfterTaskAdd",[t.id,t]),this._adjust_scales(),t.id)},gantt.deleteTask=function(t){return this._deleteTask(t)},gantt._deleteTask=function(t,e){var n=this.getTask(t);if(!e&&this.callEvent("onBeforeTaskDelete",[t,n])===!1)return!1;!e&&this._dp&&this._dp.setUpdateMode("off");var i=this._branches[n.id]||[];this._update_flags(t,!1);for(var a=0;a<i.length;a++)this._silentStart(),this._deleteTask(i[a],!0),this._dp&&(this._dp._ganttMode="tasks",this._dp.setUpdated(i[a],!0,"deleted")),this._silentEnd();for(!e&&this._dp&&this._dp.setUpdateMode("cell");n.$source.length>0;)this.deleteLink(n.$source[0]);for(;n.$target.length>0;)this.deleteLink(n.$target[0]);return delete this._pull[t],this._move_branch(n,n.parent,null),e||(this.callEvent("onAfterTaskDelete",[t,n]),this.refreshData()),!0},gantt.clearAll=function(){this._pull={},this._branches={},this._order=[],this._order_full=[],this._lpull={},this.refreshData(),this.callEvent("onClear",[])},gantt._update_flags=function(t,e){this._lightbox_id==t&&(this._lightbox_id=e),this._selected_task==t&&(this._selected_task=e),this._tasks_dnd.drag&&this._tasks_dnd.drag.id==t&&(this._tasks_dnd.drag.id=e)},gantt.changeTaskId=function(t,e){var n=this._pull[e]=this._pull[t];this._pull[e].id=e,delete this._pull[t];for(var i in this._pull)this._pull[i].parent==t&&(this._pull[i].parent=e);this._update_flags(t,e),this._replace_branch_child(n.parent,t,e),this.callEvent("onTaskIdChange",[t,e])},gantt._get_duration_unit=function(){return 1e3*gantt._get_line(this.config.duration_unit)||this.config.duration_unit},gantt._get_safe_type=function(t){for(var e in this.config.types)if(this.config.types[e]==t)return t;return gantt.config.types.task},gantt._get_type_name=function(t){for(var e in this.config.types)if(this.config.types[e]==t)return e;return"task"},gantt.getWorkHours=function(t){return this._working_time_helper.get_working_hours(t)},gantt.setWorkTime=function(t){this._working_time_helper.set_time(t)},gantt.isWorkTime=function(t,e){var n=this._working_time_helper;return n.is_working_unit(t,e||this.config.duration_unit)},gantt.getClosestWorkTime=function(t){var e=this._working_time_helper;return t instanceof Date&&(t={date:t}),t.dir=t.dir||"any",t.unit=t.unit||this.config.duration_unit,e.get_closest_worktime(t)},gantt.calculateDuration=function(t,e){var n=this._working_time_helper;return n.get_work_units_between(t,e,this.config.duration_unit,this.config.duration_step)},gantt.calculateEndDate=function(t,e){var n=this._working_time_helper,i=e>=0?1:-1;return n.add_worktime(t,Math.abs(e),this.config.duration_unit,i*this.config.duration_step)},gantt._init_task=function(t){return dhtmlx.defined(t.id)||(t.id=dhtmlx.uid()),t.start_date&&(t.start_date=gantt.date.parseDate(t.start_date,"xml_date")),t.end_date&&(t.end_date=gantt.date.parseDate(t.end_date,"xml_date")),t.start_date&&!t.end_date&&t.duration&&(t.end_date=this.calculateEndDate(t.start_date,t.duration)),gantt.config.work_time&&gantt.config.correct_work_time&&(t.start_date&&(t.start_date=gantt.getClosestWorkTime(t.start_date)),t.end_date&&(t.end_date=gantt.getClosestWorkTime(t.end_date))),gantt._init_task_timing(t),t.$source=[],t.$target=[],t.parent=t.parent||this.config.root_id,t.$open=dhtmlx.defined(t.open)?t.open:!1,t.$level=this._item_level(t),t},gantt._init_task_timing=function(t){void 0===t.$rendered_type?t.$rendered_type=t.type:t.$rendered_type!=t.type&&(delete t.$no_end,delete t.$no_start,t.$rendered_type=t.type),void 0!==t.$no_end&&void 0!==t.$no_start||t.type==this.config.types.milestone||(t.type==this.config.types.project?t.$no_end=t.$no_start=!0:(t.$no_end=!(t.end_date||t.duration),t.$no_start=!t.start_date)),t.type==this.config.types.milestone&&(t.end_date=t.start_date),t.start_date&&t.end_date&&(t.duration=this.calculateDuration(t.start_date,t.end_date)),t.duration=t.duration||0},gantt._is_flex_task=function(t){return!(!t.$no_end&&!t.$no_start)},gantt._update_parents=function(t,e){if(t){for(var n=this.getTask(t);!n.$no_end&&!n.$no_start&&n.parent&&this.isTaskExists(n.parent);)n=this.getTask(n.parent);if(n.$no_end){var i=0;this.eachTask(function(t){t.end_date&&+t.end_date>+i&&(i=new Date(t.end_date))},n.id),i&&(n.end_date=i)}if(n.$no_start){var a=1/0;this.eachTask(function(t){t.start_date&&+t.start_date<+a&&(a=new Date(t.start_date))},n.id),1/0!=a&&(n.start_date=a)}(n.$no_end||n.$no_start)&&(this._init_task_timing(n),e||this.refreshTask(n.id,!0)),n.parent&&this.isTaskExists(n.parent)&&this._update_parents(n.parent,e)}},gantt.isChildOf=function(t,e){if(!this.isTaskExists(t))return!1;if(e===this.config.root_id)return this.isTaskExists(t);for(var n=this.getTask(t);n&&this.isTaskExists(n.parent);)if(n=this.getTask(n.parent),n&&n.id==e)return!0;return!1},gantt._get_closest_date=function(t){for(var e=t.date,n=t.step,i=t.unit,a=gantt.date[i+"_start"](new Date(this._min_date));+e>+a;)a=gantt.date.add(a,n,i);var s=gantt.date.add(a,-1*n,i);return t.dir&&"future"==t.dir?a:t.dir&&"past"==t.dir?s:Math.abs(e-s)<Math.abs(a-e)?s:a},gantt.attachEvent("onBeforeTaskUpdate",function(t,e){return gantt._init_task_timing(e),!0}),gantt.attachEvent("onBeforeTaskAdd",function(t,e){return gantt._init_task_timing(e),!0}),gantt._item_level=function(t){for(var e=0;t.parent&&dhtmlx.defined(this._pull[t.parent]);)t=this._pull[t.parent],e++;return e},gantt.sort=function(t,e,n){var i=!arguments[3];dhtmlx.defined(n)||(n=this.config.root_id),dhtmlx.defined(t)||(t="order");var a="string"==typeof t?function(n,i){var a=n[t]>i[t];return e&&(a=!a),a?1:-1}:t,s=this._branches[n];if(s){for(var r=[],o=s.length-1;o>=0;o--)r[o]=this._pull[s[o]];r.sort(a);for(var o=0;o<r.length;o++)s[o]=r[o].id,this.sort(t,e,s[o],!0)}i&&this.refreshData()},gantt.getNext=function(t){for(var e=0;e<this._order.length-1;e++)if(this._order[e]==t)return this._order[e+1];return null},gantt.getPrev=function(t){for(var e=1;e<this._order.length;e++)if(this._order[e]==t)return this._order[e-1];return null},gantt._dp_init=function(t){t.setTransactionMode("POST",!0),t.serverProcessor+=(-1!=t.serverProcessor.indexOf("?")?"&":"?")+"editing=true",t._serverProcessor=t.serverProcessor,t.styles={updated:"gantt_updated",inserted:"gantt_inserted",deleted:"gantt_deleted",invalid:"gantt_invalid",error:"gantt_error",clear:""},t._methods=["_row_style","setCellTextStyle","_change_id","_delete_task"],this.attachEvent("onAfterTaskAdd",function(e){t._ganttMode="tasks",t.setUpdated(e,!0,"inserted")}),this.attachEvent("onAfterTaskUpdate",function(e){t._ganttMode="tasks",t.setUpdated(e,!0)}),this.attachEvent("onAfterTaskDelete",function(e){t._ganttMode="tasks",t.setUpdated(e,!0,"deleted")}),this.attachEvent("onAfterLinkUpdate",function(e){t._ganttMode="links",t.setUpdated(e,!0)}),this.attachEvent("onAfterLinkAdd",function(e){t._ganttMode="links",t.setUpdated(e,!0,"inserted")}),this.attachEvent("onAfterLinkDelete",function(e){t._ganttMode="links",t.setUpdated(e,!0,"deleted")}),this.attachEvent("onRowDragEnd",function(e,n){t._ganttMode="tasks",this.getTask(e).target=n,t.setUpdated(e,!0,"order")}),t.attachEvent("onBeforeDataSending",function(){return this.serverProcessor=this._serverProcessor+getUrlSymbol(this._serverProcessor)+"gantt_mode="+this._ganttMode,!0}),t._getRowData=dhtmlx.bind(function(e){var n;n="tasks"==t._ganttMode?this.isTaskExists(e)?this.getTask(e):{id:e}:this.isLinkExists(e)?this.getLink(e):{id:e};var i={};for(var a in n)if("$"!=a.substr(0,1)){var s=n[a];i[a]=s instanceof Date?this.templates.xml_format(s):s}return n.$no_start&&(n.start_date="",n.duration=""),n.$no_end&&(n.end_date="",n.duration=""),i[t.action_param]=this.getUserData(e,t.action_param),i},this),this._change_id=dhtmlx.bind(function(e,n){"tasks"!=t._ganttMode?this.changeLinkId(e,n):this.changeTaskId(e,n)},this),this._row_style=function(e,n){if("tasks"==t._ganttMode){var i=gantt.getTaskRowNode(e);if(i)if(n)i.className+=" "+n;else{var a=/ (gantt_updated|gantt_inserted|gantt_deleted|gantt_invalid|gantt_error)/g;i.className=i.className.replace(a,"")}}},this._delete_task=function(){},this._dp=t},gantt.getUserData=function(t,e){return this.userdata||(this.userdata={}),this.userdata[t]&&this.userdata[t][e]?this.userdata[t][e]:""},gantt.setUserData=function(t,e,n){this.userdata||(this.userdata={}),this.userdata[t]||(this.userdata[t]={}),this.userdata[t][e]=n},gantt._init_link=function(t){return dhtmlx.defined(t.id)||(t.id=dhtmlx.uid()),t},gantt._sync_links=function(){for(var t in this._pull)this._pull[t].$source=[],this._pull[t].$target=[];for(var t in this._lpull){var e=this._lpull[t];this._pull[e.source]&&this._pull[e.source].$source.push(t),this._pull[e.target]&&this._pull[e.target].$target.push(t)}},gantt.getLink=function(t){return dhtmlx.assert(this._lpull[t],"Link doesn't exist"),this._lpull[t]},gantt.isLinkExists=function(t){return dhtmlx.defined(this._lpull[t])},gantt.addLink=function(t){return t=this._init_link(t),this.callEvent("onBeforeLinkAdd",[t.id,t])===!1?!1:(this._lpull[t.id]=t,this._sync_links(),this._render_link(t.id),this.callEvent("onAfterLinkAdd",[t.id,t]),t.id)},gantt.updateLink=function(t,e){return dhtmlx.defined(e)||(e=this.getLink(t)),this.callEvent("onBeforeLinkUpdate",[t,e])===!1?!1:(this._lpull[t]=e,this._sync_links(),this._render_link(t),this.callEvent("onAfterLinkUpdate",[t,e]),!0)},gantt.deleteLink=function(t){return this._deleteLink(t)},gantt._deleteLink=function(t,e){var n=this.getLink(t);return e||this.callEvent("onBeforeLinkDelete",[t,n])!==!1?(delete this._lpull[t],this._sync_links(),this.refreshLink(t),e||this.callEvent("onAfterLinkDelete",[t,n]),!0):!1},gantt.changeLinkId=function(t,e){this._lpull[e]=this._lpull[t],this._lpull[e].id=e,delete this._lpull[t],this._sync_links(),this.callEvent("onLinkIdChange",[t,e])},gantt.getChildren=function(t){return dhtmlx.defined(this._branches[t])?this._branches[t]:[]},gantt.hasChild=function(t){return dhtmlx.defined(this._branches[t])},gantt.refreshData=function(){this._sync_order(),this._render_data()},gantt._configure=function(t,e){for(var n in e)"undefined"==typeof t[n]&&(t[n]=e[n])},gantt._init_skin=function(){if(!gantt.skin)for(var t=document.getElementsByTagName("link"),e=0;e<t.length;e++){var n=t[e].href.match("dhtmlxgantt_([a-z]+).css");if(n){gantt.skin=n[1];break}}gantt.skin||(gantt.skin="terrace");var i=gantt.skins[gantt.skin];this._configure(gantt.config,i.config);var a=gantt.config.columns;a[1]&&"undefined"==typeof a[1].width&&(a[1].width=i._second_column_width),a[2]&&"undefined"==typeof a[2].width&&(a[2].width=i._third_column_width),i._lightbox_template&&(gantt._lightbox_template=i._lightbox_template),gantt._init_skin=function(){}},gantt.skins={},gantt._lightbox_methods={},gantt._lightbox_template="<div class='dhx_cal_ltitle'><span class='dhx_mark'>&nbsp;</span><span class='dhx_time'></span><span class='dhx_title'></span></div><div class='dhx_cal_larea'></div>",gantt.showLightbox=function(t){if(t&&!this.config.readonly&&this.callEvent("onBeforeLightbox",[t])){var e=this.getTask(t),n=this.getLightbox(this._get_safe_type(e.type));this._center_lightbox(n),this.showCover(),this._fill_lightbox(t,n),this.callEvent("onLightbox",[t])}},gantt._get_timepicker_step=function(){if(this.config.round_dnd_dates){var t=gantt._tasks,e=this._get_line(t.unit)*t.step/60;return e>=1440&&(e=this.config.time_step),e}return this.config.time_step},gantt.getLabel=function(t,e){for(var n=this._get_typed_lightbox_config(),i=0;i<n.length;i++)if(n[i].map_to==t)for(var a=n[i].options,s=0;s<a.length;s++)if(a[s].key==e)return a[s].label;return""},gantt.updateCollection=function(t,e){var e=e.slice(0),n=gantt.serverList(t);return n?(n.splice(0,n.length),n.push.apply(n,e||[]),void gantt.resetLightbox()):!1},gantt.getLightboxType=function(){return this._get_safe_type(this._lightbox_type)},gantt.getLightbox=function(t){if(void 0===t&&(t=this.getLightboxType()),!this._lightbox||this.getLightboxType()!=this._get_safe_type(t)){this._lightbox_type=this._get_safe_type(t);var e=document.createElement("DIV");e.className="dhx_cal_light";var n=this._is_lightbox_timepicker();(gantt.config.wide_form||n)&&(e.className+=" dhx_cal_light_wide"),n&&(gantt.config.wide_form=!0,e.className+=" dhx_cal_light_full"),e.style.visibility="hidden";var i=this._lightbox_template,a=this.config.buttons_left;for(var s in a)i+="<div class='dhx_btn_set dhx_left_btn_set "+a[s]+"_set'><div dhx_button='1' class='"+a[s]+"'></div><div>"+this.locale.labels[a[s]]+"</div></div>";a=this.config.buttons_right;for(var s in a)i+="<div class='dhx_btn_set dhx_right_btn_set "+a[s]+"_set' style='float:right;'><div dhx_button='1' class='"+a[s]+"'></div><div>"+this.locale.labels[a[s]]+"</div></div>";i+="</div>",e.innerHTML=i,gantt.config.drag_lightbox&&(e.firstChild.onmousedown=gantt._ready_to_dnd,e.firstChild.onselectstart=function(){return!1},e.firstChild.style.cursor="pointer",gantt._init_dnd_events()),document.body.insertBefore(e,document.body.firstChild),this._lightbox=e;var r=this._get_typed_lightbox_config(t);i=this._render_sections(r);for(var o=e.getElementsByTagName("div"),s=0;s<o.length;s++){var d=o[s];if("dhx_cal_larea"==d.className){d.innerHTML=i;break}}this.resizeLightbox(),this._init_lightbox_events(this),e.style.display="none",e.style.visibility="visible"}return this._lightbox},gantt._render_sections=function(t){for(var e="",n=0;n<t.length;n++){var i=this.form_blocks[t[n].type];
if(i){t[n].id="area_"+dhtmlx.uid();var a=t[n].hidden?" style='display:none'":"",s="";t[n].button&&(s="<div class='dhx_custom_button' index='"+n+"'><div class='dhx_custom_button_"+t[n].button+"'></div><div>"+this.locale.labels["button_"+t[n].button]+"</div></div>"),this.config.wide_form&&(e+="<div class='dhx_wrap_section' "+a+">"),e+="<div id='"+t[n].id+"' class='dhx_cal_lsection'>"+s+this.locale.labels["section_"+t[n].name]+"</div>"+i.render.call(this,t[n]),e+="</div>"}}return e},gantt.resizeLightbox=function(){var t=this._lightbox;if(t){var e=t.childNodes[1];e.style.height="0px",e.style.height=e.scrollHeight+"px",t.style.height=e.scrollHeight+this.config.lightbox_additional_height+"px",e.style.height=e.scrollHeight+"px"}},gantt._center_lightbox=function(t){if(t){t.style.display="block";var e=window.pageYOffset||document.body.scrollTop||document.documentElement.scrollTop,n=window.pageXOffset||document.body.scrollLeft||document.documentElement.scrollLeft,i=window.innerHeight||document.documentElement.clientHeight;t.style.top=e?Math.round(e+Math.max((i-t.offsetHeight)/2,0))+"px":Math.round(Math.max((i-t.offsetHeight)/2,0)+9)+"px",t.style.left=document.documentElement.scrollWidth>document.body.offsetWidth?Math.round(n+(document.body.offsetWidth-t.offsetWidth)/2)+"px":Math.round((document.body.offsetWidth-t.offsetWidth)/2)+"px"}},gantt.showCover=function(){if(!this._cover){this._cover=document.createElement("DIV"),this._cover.className="dhx_cal_cover";var t=void 0!==document.height?document.height:document.body.offsetHeight,e=document.documentElement?document.documentElement.scrollHeight:0;this._cover.style.height=Math.max(t,e)+"px",document.body.appendChild(this._cover)}},gantt._init_lightbox_events=function(){gantt.lightbox_events={},gantt.lightbox_events.dhx_save_btn=function(){gantt._save_lightbox()},gantt.lightbox_events.dhx_delete_btn=function(){gantt.callEvent("onLightboxDelete",[gantt._lightbox_id])&&gantt.$click.buttons.delete(gantt._lightbox_id)},gantt.lightbox_events.dhx_cancel_btn=function(){gantt._cancel_lightbox()},gantt.lightbox_events.default=function(t,e){if(e.getAttribute("dhx_button"))gantt.callEvent("onLightboxButton",[e.className,e,t]);else{var n,i,a;-1!=e.className.indexOf("dhx_custom_button")&&(-1!=e.className.indexOf("dhx_custom_button_")?(n=e.parentNode.getAttribute("index"),a=e.parentNode.parentNode):(n=e.getAttribute("index"),a=e.parentNode,e=e.firstChild));var s=gantt._get_typed_lightbox_config();n&&(i=gantt.form_blocks[s[n].type],i.button_click(n,e,a,a.nextSibling))}},dhtmlxEvent(gantt.getLightbox(),"click",function(t){t=t||window.event;var e=t.target?t.target:t.srcElement;if(e.className||(e=e.previousSibling),e&&e.className&&0===e.className.indexOf("dhx_btn_set")&&(e=e.firstChild),e&&e.className){var n=dhtmlx.defined(gantt.lightbox_events[e.className])?gantt.lightbox_events[e.className]:gantt.lightbox_events.default;return n(t,e)}return!1}),gantt.getLightbox().onkeydown=function(t){switch((t||event).keyCode){case gantt.keys.edit_save:if((t||event).shiftKey)return;gantt._save_lightbox();break;case gantt.keys.edit_cancel:gantt._cancel_lightbox()}}},gantt._cancel_lightbox=function(){var t=this.getLightboxValues();this.callEvent("onLightboxCancel",[this._lightbox_id,t.$new]),t.$new&&(this._deleteTask(t.id,!0),this.refreshData()),this.hideLightbox()},gantt._save_lightbox=function(){var t=this.getLightboxValues();this.callEvent("onLightboxSave",[this._lightbox_id,t,!!t.$new])&&(t.$new?(delete t.$new,this.addTask(t)):(dhtmlx.mixin(this.getTask(t.id),t,!0),this.updateTask(t.id)),this.refreshData(),this.hideLightbox())},gantt.getLightboxValues=function(){for(var t=dhtmlx.mixin({},this.getTask(this._lightbox_id)),e=this._get_typed_lightbox_config(),n=0;n<e.length;n++){var i=document.getElementById(e[n].id);i=i?i.nextSibling:i;var a=this.form_blocks[e[n].type],s=a.get_value.call(this,i,t,e[n]);"auto"!=e[n].map_to&&(t[e[n].map_to]=s)}return t},gantt.hideLightbox=function(){var t=this.getLightbox();t&&(t.style.display="none"),this._lightbox_id=null,this.hideCover(),this.callEvent("onAfterLightbox",[])},gantt.hideCover=function(){this._cover&&this._cover.parentNode.removeChild(this._cover),this._cover=null},gantt.resetLightbox=function(){gantt._lightbox&&!gantt._custom_lightbox&&gantt._lightbox.parentNode.removeChild(gantt._lightbox),gantt._lightbox=null},gantt._set_lightbox_values=function(t,e){var n=t,i=e.getElementsByTagName("span");gantt.templates.lightbox_header?(i[1].innerHTML="",i[2].innerHTML=gantt.templates.lightbox_header(n.start_date,n.end_date,n)):(i[1].innerHTML=this.templates.task_time(n.start_date,n.end_date,n),i[2].innerHTML=(this.templates.task_text(n.start_date,n.end_date,n)||"").substr(0,70));for(var a=this._get_typed_lightbox_config(this.getLightboxType()),s=0;s<a.length;s++){var r=a[s];if(this.form_blocks[r.type]){var o=document.getElementById(r.id).nextSibling,d=this.form_blocks[r.type],l=dhtmlx.defined(n[r.map_to])?n[r.map_to]:r.default_value;d.set_value.call(this,o,l,n,r),r.focus&&d.focus.call(this,o)}}t.id&&(gantt._lightbox_id=t.id)},gantt._fill_lightbox=function(t,e){var n=this.getTask(t);this._set_lightbox_values(n,e)},gantt.getLightboxSection=function(t){var e=this._get_typed_lightbox_config(),n=0;for(n;n<e.length&&e[n].name!=t;n++);var i=e[n];this._lightbox||this.getLightbox();var a=document.getElementById(i.id),s=a.nextSibling,r={section:i,header:a,node:s,getValue:function(t){return this.form_blocks[i.type].get_value(s,t||{},i)},setValue:function(t,e){return this.form_blocks[i.type].set_value(s,t,e||{},i)}},o=this._lightbox_methods["get_"+i.type+"_control"];return o?o(r):r},gantt._lightbox_methods.get_template_control=function(t){return t.control=t.node,t},gantt._lightbox_methods.get_select_control=function(t){return t.control=t.node.getElementsByTagName("select")[0],t},gantt._lightbox_methods.get_textarea_control=function(t){return t.control=t.node.getElementsByTagName("textarea")[0],t},gantt._lightbox_methods.get_time_control=function(t){return t.control=t.node.getElementsByTagName("select"),t},gantt._init_dnd_events=function(){dhtmlxEvent(document.body,"mousemove",gantt._move_while_dnd),dhtmlxEvent(document.body,"mouseup",gantt._finish_dnd),gantt._init_dnd_events=function(){}},gantt._move_while_dnd=function(t){if(gantt._dnd_start_lb){document.dhx_unselectable||(document.body.className+=" dhx_unselectable",document.dhx_unselectable=!0);var e=gantt.getLightbox(),n=t&&t.target?[t.pageX,t.pageY]:[event.clientX,event.clientY];e.style.top=gantt._lb_start[1]+n[1]-gantt._dnd_start_lb[1]+"px",e.style.left=gantt._lb_start[0]+n[0]-gantt._dnd_start_lb[0]+"px"}},gantt._ready_to_dnd=function(t){var e=gantt.getLightbox();gantt._lb_start=[parseInt(e.style.left,10),parseInt(e.style.top,10)],gantt._dnd_start_lb=t&&t.target?[t.pageX,t.pageY]:[event.clientX,event.clientY]},gantt._finish_dnd=function(){gantt._lb_start&&(gantt._lb_start=gantt._dnd_start_lb=!1,document.body.className=document.body.className.replace(" dhx_unselectable",""),document.dhx_unselectable=!1)},gantt._focus=function(t,e){t&&t.focus&&(gantt.config.touch||(e&&t.select&&t.select(),t.focus()))},gantt.form_blocks={getTimePicker:function(t,e){var n=t.time_format;if(!n){var n=["%d","%m","%Y"];gantt._get_line(gantt._tasks.unit)<gantt._get_line("day")&&n.push("%H:%i")}t._time_format_order={size:0};var i=this.config,a=this.date.date_part(new Date(gantt._min_date.valueOf())),s=1440,r=0;gantt.config.limit_time_select&&(s=60*i.last_hour+1,r=60*i.first_hour,a.setHours(i.first_hour));for(var o="",d=0;d<n.length;d++){var l=n[d];d>0&&(o+=" ");var _="";switch(l){case"%Y":t._time_format_order[2]=d,t._time_format_order.size++;for(var h=a.getFullYear()-5,c=0;10>c;c++)_+="<option value='"+(h+c)+"'>"+(h+c)+"</option>";break;case"%m":t._time_format_order[1]=d,t._time_format_order.size++;for(var c=0;12>c;c++)_+="<option value='"+c+"'>"+this.locale.date.month_full[c]+"</option>";break;case"%d":t._time_format_order[0]=d,t._time_format_order.size++;for(var c=1;32>c;c++)_+="<option value='"+c+"'>"+c+"</option>";break;case"%H:%i":var s=1440,r=0;t._time_format_order[3]=d,t._time_format_order.size++;var c=r,g=a.getDate();for(t._time_values=[];s>c;){var u=this.templates.time_picker(a);_+="<option value='"+c+"'>"+u+"</option>",t._time_values.push(c),a.setTime(a.valueOf()+60*this._get_timepicker_step()*1e3);var f=a.getDate()!=g?1:0;c=24*f*60+60*a.getHours()+a.getMinutes()}}if(_){var p=t.readonly?"disabled='disabled'":"",m=e?" style='display:none'":"";o+="<select "+p+m+">"+_+"</select>"}}return o},_fill_lightbox_select:function(t,e,n,i){if(t[e+i[0]].value=n.getDate(),t[e+i[1]].value=n.getMonth(),t[e+i[2]].value=n.getFullYear(),dhtmlx.defined(i[3])){var a=60*n.getHours()+n.getMinutes();a=Math.round(a/gantt._get_timepicker_step())*gantt._get_timepicker_step(),t[e+i[3]].value=a}},template:{render:function(t){var e=(t.height||"30")+"px";return"<div class='dhx_cal_ltext dhx_cal_template' style='height:"+e+";'></div>"},set_value:function(t,e){t.innerHTML=e||""},get_value:function(t){return t.innerHTML||""},focus:function(){}},textarea:{render:function(t){var e=(t.height||"130")+"px";return"<div class='dhx_cal_ltext' style='height:"+e+";'><textarea></textarea></div>"},set_value:function(t,e){t.firstChild.value=e||""},get_value:function(t){return t.firstChild.value},focus:function(t){var e=t.firstChild;gantt._focus(e,!0)}},select:{render:function(t){for(var e=(t.height||"23")+"px",n="<div class='dhx_cal_ltext' style='height:"+e+";'><select style='width:100%;'>",i=0;i<t.options.length;i++)n+="<option value='"+t.options[i].key+"'>"+t.options[i].label+"</option>";return n+="</select></div>"},set_value:function(t,e,n,i){var a=t.firstChild;!a._dhx_onchange&&i.onchange&&(a.onchange=i.onchange,a._dhx_onchange=!0),"undefined"==typeof e&&(e=(a.options[0]||{}).value),a.value=e||""},get_value:function(t){return t.firstChild.value},focus:function(t){var e=t.firstChild;gantt._focus(e,!0)}},time:{render:function(t){var e=this.form_blocks.getTimePicker.call(this,t),n=["<div style='height:30px;padding-top:0px;font-size:inherit;text-align:center;' class='dhx_section_time'>"];return n.push(e),t.single_date?(e=this.form_blocks.getTimePicker.call(this,t,!0),n.push("<span></span>")):n.push("<span style='font-weight:normal; font-size:10pt;'> &nbsp;&ndash;&nbsp; </span>"),n.push(e),n.push("</div>"),n.join("")},set_value:function(t,e,n,i){var a=this.config,s=t.getElementsByTagName("select"),r=i._time_format_order;if(i._time_format_size,a.auto_end_date)for(var o=function(){var t=new Date(s[r[2]].value,s[r[1]].value,s[r[0]].value,0,0),e=gantt.calculateEndDate(t,1);this.form_blocks._fill_lightbox_select(s,r.size,e,r,a)},d=0;4>d;d++)s[d].onchange=o;this.form_blocks._fill_lightbox_select(s,0,n.start_date,r,a),this.form_blocks._fill_lightbox_select(s,r.size,n.end_date,r,a)},get_value:function(t,e,n){var i=t.getElementsByTagName("select"),a=n._time_format_order,s=0,r=0;if(dhtmlx.defined(a[3])){var o=parseInt(i[a[3]].value,10);s=Math.floor(o/60),r=o%60}if(e.start_date=new Date(i[a[2]].value,i[a[1]].value,i[a[0]].value,s,r),s=r=0,dhtmlx.defined(a[3])){var o=parseInt(i[a.size+a[3]].value,10);s=Math.floor(o/60),r=o%60}return e.end_date=new Date(i[a[2]+a.size].value,i[a[1]+a.size].value,i[a[0]+a.size].value,s,r),e.end_date<=e.start_date&&(e.end_date=gantt.date.add(e.start_date,gantt._get_timepicker_step(),"minute")),{start_date:new Date(e.start_date),end_date:new Date(e.end_date)}},focus:function(t){gantt._focus(t.getElementsByTagName("select")[0])}},duration:{render:function(t){var e=this.form_blocks.getTimePicker.call(this,t);e="<div class='dhx_time_selects'>"+e+"</div>";var n=this.locale.labels[this.config.duration_unit+"s"],i=t.single_date?' style="display:none"':"",a=t.readonly?" disabled='disabled'":"",s="<div class='dhx_gantt_duration' "+i+"><input type='button' class='dhx_gantt_duration_dec' value='-'"+a+"><input type='text' value='5' class='dhx_gantt_duration_value'"+a+"><input type='button' class='dhx_gantt_duration_inc' value='+'"+a+"> "+n+" <span></span></div>",r="<div style='height:30px;padding-top:0px;font-size:inherit;' class='dhx_section_time'>"+e+" "+s+"</div>";return r},set_value:function(t,e,n,i){function a(){var e=gantt.form_blocks.duration._get_start_date.call(gantt,t,i),n=gantt.form_blocks.duration._get_duration.call(gantt,t,i),a=gantt.calculateEndDate(e,n);h.innerHTML=gantt.templates.task_date(a)}function s(t){var e=l.value;e=parseInt(e,10),window.isNaN(e)&&(e=0),e+=t,1>e&&(e=1),l.value=e,a()}var r=this.config,o=t.getElementsByTagName("select"),d=t.getElementsByTagName("input"),l=d[1],_=[d[0],d[2]],h=t.getElementsByTagName("span")[0],c=i._time_format_order;_[0].onclick=dhtmlx.bind(function(){s(-1*this.config.duration_step)},this),_[1].onclick=dhtmlx.bind(function(){s(1*this.config.duration_step)},this),o[0].onchange=a,o[1].onchange=a,o[2].onchange=a,o[3]&&(o[3].onchange=a),l.onkeydown=dhtmlx.bind(function(t){t=t||window.event;var e=t.charCode||t.keyCode||t.which;return 40==e?(s(-1*this.config.duration_step),!1):38==e?(s(1*this.config.duration_step),!1):void window.setTimeout(function(){a()},1)},this),l.onchange=dhtmlx.bind(function(){a()},this),this.form_blocks._fill_lightbox_select(o,0,n.start_date,c,r);var g;g=n.end_date?gantt.calculateDuration(n.start_date,n.end_date):n.duration,g=Math.round(g),l.value=g,a()},_get_start_date:function(t,e){var n=t.getElementsByTagName("select"),i=e._time_format_order,a=0,s=0;if(dhtmlx.defined(i[3])){var r=parseInt(n[i[3]].value,10);a=Math.floor(r/60),s=r%60}return new Date(n[i[2]].value,n[i[1]].value,n[i[0]].value,a,s)},_get_duration:function(t){var e=t.getElementsByTagName("input")[1];return e=parseInt(e.value,10),window.isNaN(e)&&(e=1),0>e&&(e*=-1),e},get_value:function(t,e,n){e.start_date=this.form_blocks.duration._get_start_date(t,n);var i=this.form_blocks.duration._get_duration(t,n);return e.end_date=this.calculateEndDate(e.start_date,i),e.duration=i,{start_date:new Date(e.start_date),end_date:new Date(e.end_date)}},focus:function(t){gantt._focus(t.getElementsByTagName("select")[0])}},typeselect:{render:function(t){var e=gantt.config.types,n=gantt.locale.labels,i=[];for(var a in e)i.push({key:e[a],label:n["type_"+a]});t.options=i;var s=t.onchange;return t.onchange=function(){gantt.getState().lightbox,gantt.changeLightboxType(this.value),"function"==typeof s&&s.apply(this,arguments)},gantt.form_blocks.select.render.apply(this,arguments)},set_value:function(){return gantt.form_blocks.select.set_value.apply(this,arguments)},get_value:function(){return gantt.form_blocks.select.get_value.apply(this,arguments)},focus:function(){return gantt.form_blocks.select.focus.apply(this,arguments)}},parent:{_filter:function(t,e,n){var i=e.filter||function(){return!0};t=t.slice(0);for(var a=0;a<t.length;a++){var s=t[a];(s.id==n||gantt.isChildOf(s.id,n)||i(s.id,s)===!1)&&(t.splice(a,1),a--)}return t},_display:function(t,e){var n=[],i=[];e&&(n=gantt.getTaskByTime(),t.allow_root&&n.unshift({id:gantt.config.root_id,text:t.root_label||""}),n=this._filter(n,t,e),t.sort&&n.sort(t.sort));for(var a=t.template||gantt.templates.task_text,s=0;s<n.length;s++){var r=a.apply(gantt,[n[s].start_date,n[s].end_date,n[s]]);void 0===r&&(r=""),i.push({key:n[s].id,label:r})}return t.options=i,t.map_to=t.map_to||"parent",gantt.form_blocks.select.render.apply(this,arguments)},render:function(t){return gantt.form_blocks.parent._display(t,!1)},set_value:function(t,e,n,i){var a=document.createElement("div");a.innerHTML=gantt.form_blocks.parent._display(i,n.id);var s=a.removeChild(a.firstChild);return t.onselect=null,t.parentNode.replaceChild(s,t),gantt.form_blocks.select.set_value.apply(this,[s,e,n,i])},get_value:function(){return gantt.form_blocks.select.get_value.apply(this,arguments)},focus:function(){return gantt.form_blocks.select.focus.apply(this,arguments)}}},gantt._is_lightbox_timepicker=function(){for(var t=this._get_typed_lightbox_config(),e=0;e<t.length;e++)if("time"==t[e].name&&"time"==t[e].type)return!0;return!1},gantt._dhtmlx_confirm=function(t,e,n,i){if(!t)return n();var a={text:t};e&&(a.title=e),i&&(a.ok=i),n&&(a.callback=function(t){t&&n()}),dhtmlx.confirm(a)},gantt._get_typed_lightbox_config=function(t){void 0===t&&(t=this.getLightboxType());var e=this._get_type_name(t);return gantt.config.lightbox[e+"_sections"]?gantt.config.lightbox[e+"_sections"]:gantt.config.lightbox.sections},gantt._silent_redraw_lightbox=function(t){var e=this.getLightboxType();if(this.getState().lightbox){var n=this.getState().lightbox,i=this.getLightboxValues(),a=dhtmlx.copy(this.getTask(n));this.resetLightbox();var s=dhtmlx.mixin(a,i,!0),r=this.getLightbox(t?t:void 0);this._set_lightbox_values(s,r),this._center_lightbox(this.getLightbox()),this.callEvent("onLightboxChange",[e,this.getLightboxType()])}else this.resetLightbox(),this.getLightbox(t?t:void 0);this.callEvent("onLightboxChange",[e,this.getLightboxType()])},dataProcessor.prototype={setTransactionMode:function(t,e){this._tMode=t,this._tSend=e},escape:function(t){return this._utf?encodeURIComponent(t):escape(t)},enableUTFencoding:function(t){this._utf=convertStringToBoolean(t)},setDataColumns:function(t){this._columns="string"==typeof t?t.split(","):t},getSyncState:function(){return!this.updatedRows.length},enableDataNames:function(t){this._endnm=convertStringToBoolean(t)},enablePartialDataSend:function(t){this._changed=convertStringToBoolean(t)},setUpdateMode:function(t,e){this.autoUpdate="cell"==t,this.updateMode=t,this.dnd=e},ignore:function(t,e){this._silent_mode=!0,t.call(e||window),this._silent_mode=!1},setUpdated:function(t,e,n){if(!this._silent_mode){var i=this.findRow(t);n=n||"updated";var a=this.obj.getUserData(t,this.action_param);a&&"updated"==n&&(n=a),e?(this.set_invalid(t,!1),this.updatedRows[i]=t,this.obj.setUserData(t,this.action_param,n),this._in_progress[t]&&(this._in_progress[t]="wait")):this.is_invalid(t)||(this.updatedRows.splice(i,1),this.obj.setUserData(t,this.action_param,"")),e||this._clearUpdateFlag(t),this.markRow(t,e,n),e&&this.autoUpdate&&this.sendData(t)}},_clearUpdateFlag:function(){},markRow:function(t,e,n){var i="",a=this.is_invalid(t);if(a&&(i=this.styles[a],e=!0),this.callEvent("onRowMark",[t,e,n,a])&&(i=this.styles[e?n:"clear"]+i,this.obj[this._methods[0]](t,i),a&&a.details)){i+=this.styles[a+"_cell"];for(var s=0;s<a.details.length;s++)a.details[s]&&this.obj[this._methods[1]](t,s,i)}},getState:function(t){return this.obj.getUserData(t,this.action_param)},is_invalid:function(t){return this._invalid[t]},set_invalid:function(t,e,n){n&&(e={value:e,details:n,toString:function(){return this.value.toString()}}),this._invalid[t]=e},checkBeforeUpdate:function(){return!0},sendData:function(t){return!this._waitMode||"tree"!=this.obj.mytype&&!this.obj._h2?(this.obj.editStop&&this.obj.editStop(),"undefined"==typeof t||this._tSend?this.sendAllData():this._in_progress[t]?!1:(this.messages=[],!this.checkBeforeUpdate(t)&&this.callEvent("onValidationError",[t,this.messages])?!1:void this._beforeSendData(this._getRowData(t),t))):void 0},_beforeSendData:function(t,e){return this.callEvent("onBeforeUpdate",[e,this.getState(e),t])?void this._sendData(t,e):!1},serialize:function(t,e){if("string"==typeof t)return t;if("undefined"!=typeof e)return this.serialize_one(t,"");var n=[],i=[];for(var a in t)t.hasOwnProperty(a)&&(n.push(this.serialize_one(t[a],a+this.post_delim)),i.push(a));return n.push("ids="+this.escape(i.join(","))),dhtmlx.security_key&&n.push("dhx_security="+dhtmlx.security_key),n.join("&")},serialize_one:function(t,e){if("string"==typeof t)return t;var n=[];for(var i in t)t.hasOwnProperty(i)&&n.push(this.escape((e||"")+i)+"="+this.escape(t[i]));return n.join("&")},_sendData:function(t,e){if(t){if(!this.callEvent("onBeforeDataSending",e?[e,this.getState(e),t]:[null,null,t]))return!1;e&&(this._in_progress[e]=(new Date).valueOf());var n=new dtmlXMLLoaderObject(this.afterUpdate,this,!0),i=this.serverProcessor+(this._user?getUrlSymbol(this.serverProcessor)+["dhx_user="+this._user,"dhx_version="+this.obj.getUserData(0,"version")].join("&"):"");"POST"!=this._tMode?n.loadXML(i+(-1!=i.indexOf("?")?"&":"?")+this.serialize(t,e)):n.loadXML(i,!0,this.serialize(t,e)),this._waitMode++}},sendAllData:function(){if(this.updatedRows.length){this.messages=[];for(var t=!0,e=0;e<this.updatedRows.length;e++)t&=this.checkBeforeUpdate(this.updatedRows[e]);if(!t&&!this.callEvent("onValidationError",["",this.messages]))return!1;if(this._tSend)this._sendData(this._getAllData());else for(var e=0;e<this.updatedRows.length;e++)if(!this._in_progress[this.updatedRows[e]]){if(this.is_invalid(this.updatedRows[e]))continue;if(this._beforeSendData(this._getRowData(this.updatedRows[e]),this.updatedRows[e]),this._waitMode&&("tree"==this.obj.mytype||this.obj._h2))return}}},_getAllData:function(){for(var t={},e=!1,n=0;n<this.updatedRows.length;n++){var i=this.updatedRows[n];this._in_progress[i]||this.is_invalid(i)||this.callEvent("onBeforeUpdate",[i,this.getState(i)])&&(t[i]=this._getRowData(i,i+this.post_delim),e=!0,this._in_progress[i]=(new Date).valueOf())}return e?t:null},setVerificator:function(t,e){this.mandatoryFields[t]=e||function(t){return""!==t}},clearVerificator:function(t){this.mandatoryFields[t]=!1},findRow:function(t){var e=0;for(e=0;e<this.updatedRows.length&&t!=this.updatedRows[e];e++);return e},defineAction:function(t,e){this._uActions||(this._uActions=[]),this._uActions[t]=e},afterUpdateCallback:function(t,e,n,i){var a=t,s="error"!=n&&"invalid"!=n;if(s||this.set_invalid(t,n),this._uActions&&this._uActions[n]&&!this._uActions[n](i))return delete this._in_progress[a];"wait"!=this._in_progress[a]&&this.setUpdated(t,!1);var r=t;switch(n){case"inserted":case"insert":e!=t&&(this.obj[this._methods[2]](t,e),t=e);break;case"delete":case"deleted":return this.obj.setUserData(t,this.action_param,"true_deleted"),this.obj[this._methods[3]](t),delete this._in_progress[a],this.callEvent("onAfterUpdate",[t,n,e,i])}"wait"!=this._in_progress[a]?(s&&this.obj.setUserData(t,this.action_param,""),delete this._in_progress[a]):(delete this._in_progress[a],this.setUpdated(e,!0,this.obj.getUserData(t,this.action_param))),this.callEvent("onAfterUpdate",[r,n,e,i])},afterUpdate:function(t,e,n,i,a){if(a.getXMLTopNode("data"),a.xmlDoc.responseXML){for(var s=a.doXPath("//data/action"),r=0;r<s.length;r++){var o=s[r],d=o.getAttribute("type"),l=o.getAttribute("sid"),_=o.getAttribute("tid");t.afterUpdateCallback(l,_,d,o)}t.finalizeUpdate()}},finalizeUpdate:function(){this._waitMode&&this._waitMode--,("tree"==this.obj.mytype||this.obj._h2)&&this.updatedRows.length&&this.sendData(),this.callEvent("onAfterUpdateFinish",[]),this.updatedRows.length||this.callEvent("onFullSync",[])},init:function(t){this.obj=t,this.obj._dp_init&&this.obj._dp_init(this)},setOnAfterUpdate:function(t){this.attachEvent("onAfterUpdate",t)},enableDebug:function(){},setOnBeforeUpdateHandler:function(t){this.attachEvent("onBeforeDataSending",t)},setAutoUpdate:function(t,e){t=t||2e3,this._user=e||(new Date).valueOf(),this._need_update=!1,this._loader=null,this._update_busy=!1,this.attachEvent("onAfterUpdate",function(t,e,n,i){this.afterAutoUpdate(t,e,n,i)}),this.attachEvent("onFullSync",function(){this.fullSync()});var n=this;window.setInterval(function(){n.loadUpdate()},t)},afterAutoUpdate:function(t,e){return"collision"==e?(this._need_update=!0,!1):!0},fullSync:function(){return this._need_update===!0&&(this._need_update=!1,this.loadUpdate()),!0},getUpdates:function(t,e){return this._update_busy?!1:(this._update_busy=!0,this._loader=this._loader||new dtmlXMLLoaderObject(!0),this._loader.async=!0,this._loader.waitCall=e,void this._loader.loadXML(t))},_v:function(t){return t.firstChild?t.firstChild.nodeValue:""},_a:function(t){for(var e=[],n=0;n<t.length;n++)e[n]=this._v(t[n]);return e},loadUpdate:function(){var t=this,e=this.obj.getUserData(0,"version"),n=this.serverProcessor+getUrlSymbol(this.serverProcessor)+["dhx_user="+this._user,"dhx_version="+e].join("&");n=n.replace("editing=true&",""),this.getUpdates(n,function(){var e=t._loader.doXPath("//userdata");t.obj.setUserData(0,"version",t._v(e[0]));var n=t._loader.doXPath("//update");if(n.length){t._silent_mode=!0;for(var i=0;i<n.length;i++){var a=n[i].getAttribute("status"),s=n[i].getAttribute("id"),r=n[i].getAttribute("parent");switch(a){case"inserted":t.callEvent("insertCallback",[n[i],s,r]);break;case"updated":t.callEvent("updateCallback",[n[i],s,r]);break;case"deleted":t.callEvent("deleteCallback",[n[i],s,r])}}t._silent_mode=!1}t._update_busy=!1,t=null})}},dhtmlx.assert=function(t,e){t||dhtmlx.message({type:"error",text:e,expire:-1})},gantt.init=function(t,e,n){e&&n&&(this.config.start_date=this._min_date=new Date(e),this.config.end_date=this._max_date=new Date(n)),this._init_skin(),this.config.scroll_size||(this.config.scroll_size=this._detectScrollSize()),this._reinit(t),this.attachEvent("onLoadEnd",this.render),dhtmlxEvent(window,"resize",this._on_resize),this.init=function(t){this.$container&&(this.$container.innerHTML=""),this._reinit(t)},this.callEvent("onGanttReady",[])},gantt._reinit=function(t){this._init_html_area(t),this._set_sizes(),this._task_area_pulls={},this._task_area_renderers={},this._init_touch_events(),this._init_templates(),this._init_grid(),this._init_tasks(),this.render(),this._set_scroll_events(),dhtmlxEvent(this.$container,"click",this._on_click),dhtmlxEvent(this.$container,"dblclick",this._on_dblclick),dhtmlxEvent(this.$container,"mousemove",this._on_mousemove),dhtmlxEvent(this.$container,"contextmenu",this._on_contextmenu)},gantt._init_html_area=function(t){this._obj="string"==typeof t?document.getElementById(t):t,dhtmlx.assert(this._obj,"Invalid html container: "+t);var e="<div class='gantt_container'><div class='gantt_grid'></div><div class='gantt_task'></div>";e+="<div class='gantt_ver_scroll'><div></div></div><div class='gantt_hor_scroll'><div></div></div></div>",this._obj.innerHTML=e,this.$container=this._obj.firstChild;var n=this.$container.childNodes;this.$grid=n[0],this.$task=n[1],this.$scroll_ver=n[2],this.$scroll_hor=n[3],this.$grid.innerHTML="<div class='gantt_grid_scale'></div><div class='gantt_grid_data'></div>",this.$grid_scale=this.$grid.childNodes[0],this.$grid_data=this.$grid.childNodes[1],this.$task.innerHTML="<div class='gantt_task_scale'></div><div class='gantt_data_area'><div class='gantt_task_bg'></div><div class='gantt_links_area'></div><div class='gantt_bars_area'></div></div>",this.$task_scale=this.$task.childNodes[0],this.$task_data=this.$task.childNodes[1],this.$task_bg=this.$task_data.childNodes[0],this.$task_links=this.$task_data.childNodes[1],this.$task_bars=this.$task_data.childNodes[2]},gantt.$click={buttons:{edit:function(t){gantt.showLightbox(t)},delete:function(t){var e=gantt.locale.labels.confirm_deleting,n=gantt.locale.labels.confirm_deleting_title;gantt._dhtmlx_confirm(e,n,function(){var e=gantt.getTask(t);e.$new?(gantt._deleteTask(t,!0),gantt.refreshData()):gantt.deleteTask(t),gantt.hideLightbox()})}}},gantt._calculate_content_height=function(){var t=this.config.scale_height,e=this._order.length*this.config.row_height,n=this._scroll_hor?this.config.scroll_size+1:0;return this._is_grid_visible()||this._is_chart_visible()?t+e+2+n:0},gantt._calculate_content_width=function(){var t=this._get_grid_width(),e=this._tasks?this._tasks.full_width:0;return this._scroll_ver?this.config.scroll_size+1:0,this._is_chart_visible()||(e=0),this._is_grid_visible()||(t=0),t+e+1},gantt._get_resize_options=function(){var t={x:!1,y:!1};return"xy"==this.config.autosize?t.x=t.y=!0:"y"==this.config.autosize||this.config.autosize===!0?t.y=!0:"x"==this.config.autosize&&(t.x=!0),t},gantt._set_sizes=function(){var t=this._get_resize_options();if(t.y&&(this._obj.style.height=this._calculate_content_height()+"px"),t.x&&(this._obj.style.width=this._calculate_content_width()+"px"),this._y=this._obj.clientHeight,!(this._y<20)){this.$grid.style.height=this.$task.style.height=Math.max(this._y-this.$scroll_hor.offsetHeight-2,0)+"px";var e=Math.max(this._y-(this.config.scale_height||0)-this.$scroll_hor.offsetHeight-2,0);this.$grid_data.style.height=this.$task_data.style.height=e+"px";var n=Math.max(this._get_grid_width()-1,0);this.$grid.style.width=n+"px",this.$grid.style.display=0===n?"none":"",this._x=this._obj.clientWidth,this._x<20||(this.$grid_data.style.width=Math.max(this._get_grid_width()-1,0)+"px",this.$task.style.width=Math.max(this._x-this._get_grid_width()-2,0)+"px")}},gantt.getScrollState=function(){return{x:this.$task.scrollLeft,y:this.$task_data.scrollTop}},gantt.scrollTo=function(t,e){1*t==t&&(this.$task.scrollLeft=t),1*e==e&&(this.$task_data.scrollTop=e,this.$grid_data.scrollTop=e)},gantt.showDate=function(t){var e=this.posFromDate(t),n=Math.max(e-this.config.task_scroll_offset,0);this.scrollTo(n)},gantt.showTask=function(t){var e=this.getTaskNode(t);if(e){var n=Math.max(e.offsetLeft-this.config.task_scroll_offset,0),i=e.offsetTop-(this.$task_data.offsetHeight-this.config.row_height)/2;this.scrollTo(n,i)}},gantt._on_resize=gantt.setSizes=function(){gantt._set_sizes(),gantt._scroll_resize()},gantt.render=function(){if(this._render_grid(),this._render_tasks_scales(),this._scroll_resize(),this._on_resize(),this._render_data(),this.config.initial_scroll){var t=this._order[0]||this.config.root_id;t&&this.showTask(t)}this.callEvent("onGanttRender",[])},gantt._set_scroll_events=function(){dhtmlxEvent(this.$scroll_hor,"scroll",function(){if(!gantt._touch_scroll_active){var t=gantt.$scroll_hor.scrollLeft;gantt.scrollTo(t)}}),dhtmlxEvent(this.$scroll_ver,"scroll",function(){if(!gantt._touch_scroll_active){var t=gantt.$scroll_ver.scrollTop;gantt.$grid_data.scrollTop=t,gantt.scrollTo(null,t)}}),dhtmlxEvent(this.$task,"scroll",function(){var t=gantt.$task.scrollLeft,e=gantt.$scroll_hor.scrollLeft;e!=t&&(gantt.$scroll_hor.scrollLeft=t)}),dhtmlxEvent(this.$task_data,"scroll",function(){var t=gantt.$task_data.scrollTop,e=gantt.$scroll_ver.scrollTop;e!=t&&(gantt.$scroll_ver.scrollTop=t)}),dhtmlxEvent(gantt.$container,"mousewheel",function(t){var e=gantt._get_resize_options();if(t.wheelDeltaX){if(e.x)return!0;var n=t.wheelDeltaX/-40,i=gantt.$task.scrollLeft+30*n;gantt.scrollTo(i,null),gantt.$scroll_hor.scrollTop=a}else{if(e.y)return!0;var n=t.wheelDelta/-40;"undefined"==typeof t.wheelDelta&&(n=t.detail);var a=gantt.$grid_data.scrollTop+30*n;gantt.scrollTo(null,a),gantt.$scroll_ver.scrollTop=a}return t.preventDefault&&t.preventDefault(),t.cancelBubble=!0,!1})},gantt._scroll_resize=function(){if(!(this._x<20||this._y<20)){var t=this._get_grid_width(),e=this._x-t,n=this._y-this.config.scale_height,i=this.config.scroll_size+1,a=this.$task_data.offsetWidth-i,s=this.config.row_height*this._order.length,r=this._get_resize_options(),o=this._scroll_hor=r.x?!1:a>e,d=this._scroll_ver=r.y?!1:s>n;this.$scroll_hor.style.display=o?"block":"none",this.$scroll_hor.style.height=(o?i:0)+"px",this.$scroll_hor.style.width=this._x-(d?i:2)+"px",this.$scroll_hor.firstChild.style.width=a+t+i+2+"px",this.$scroll_ver.style.display=d?"block":"none",this.$scroll_ver.style.width=(d?i:0)+"px",this.$scroll_ver.style.height=this._y-(o?i:0)-this.config.scale_height+"px",this.$scroll_ver.style.top=this.config.scale_height+"px",this.$scroll_ver.firstChild.style.height=this.config.scale_height+s+"px"}},gantt.locate=function(t){var e=gantt._get_target_node(t);if("gantt_task_cell"==e.className)return null;for(var n=arguments[1]||this.config.task_attribute;e;){if(e.getAttribute){var i=e.getAttribute(n);if(i)return i}e=e.parentNode}return null},gantt._get_target_node=function(t){var e;return t.tagName?e=t:(t=t||window.event,e=t.target||t.srcElement),e},gantt._trim=function(t){var e=String.prototype.trim||function(){return this.replace(/^\s+|\s+$/g,"")};return e.apply(t)},gantt._locate_css=function(t,e,n){void 0===n&&(n=!0);for(var i=gantt._get_target_node(t),a="";i;){if(a=i.className){var s=a.indexOf(e);if(s>=0){if(!n)return i;var r=0===s||!gantt._trim(a.charAt(s-1)),o=s+e.length>=a.length||!gantt._trim(a.charAt(s+e.length));
if(r&&o)return i}}i=i.parentNode}return null},gantt._locateHTML=function(t,e){var n=gantt._get_target_node(t);for(e=e||this.config.task_attribute;n;){if(n.getAttribute){var i=n.getAttribute(e);if(i)return n}n=n.parentNode}return null},gantt.getTaskRowNode=function(t){for(var e=this.$grid_data.childNodes,n=this.config.task_attribute,i=0;i<e.length;i++)if(e[i].getAttribute){var a=e[i].getAttribute(n);if(a==t)return e[i]}return null},gantt.getState=function(){return{drag_id:this._tasks_dnd.drag.id,drag_mode:this._tasks_dnd.drag.mode,drag_from_start:this._tasks_dnd.drag.left,selected_task:this._selected_task,min_date:new Date(this._min_date),max_date:new Date(this._max_date),lightbox:this._lightbox_id}},gantt._checkTimeout=function(t,e){if(!e)return!0;var n=1e3/e;return 1>n?!0:t._on_timeout?!1:(setTimeout(function(){delete t._on_timeout},n),t._on_timeout=!0,!0)},gantt.selectTask=function(t){if(!this.config.select_task)return!1;if(t){if(this._selected_task==t)return this._selected_task;if(!this.callEvent("onBeforeTaskSelected",[t]))return!1;this.unselectTask(),this._selected_task=t,this.refreshTask(t),this.callEvent("onTaskSelected",[t])}return this._selected_task},gantt.unselectTask=function(){var t=this._selected_task;t&&(this._selected_task=null,this.refreshTask(t),this.callEvent("onTaskUnselected",[t]))},gantt.getSelectedId=function(){return dhtmlx.defined(this._selected_task)?this._selected_task:null},gantt.changeLightboxType=function(t){return this.getLightboxType()==t?!0:void gantt._silent_redraw_lightbox(t)},gantt.date={init:function(){for(var t=gantt.locale.date.month_short,e=gantt.locale.date.month_short_hash={},n=0;n<t.length;n++)e[t[n]]=n;for(var t=gantt.locale.date.month_full,e=gantt.locale.date.month_full_hash={},n=0;n<t.length;n++)e[t[n]]=n},date_part:function(t){return t.setHours(0),t.setMinutes(0),t.setSeconds(0),t.setMilliseconds(0),t.getHours()&&t.setTime(t.getTime()+36e5*(24-t.getHours())),t},time_part:function(t){return(t.valueOf()/1e3-60*t.getTimezoneOffset())%86400},week_start:function(t){var e=t.getDay();return gantt.config.start_on_monday&&(0===e?e=6:e--),this.date_part(this.add(t,-1*e,"day"))},month_start:function(t){return t.setDate(1),this.date_part(t)},year_start:function(t){return t.setMonth(0),this.month_start(t)},day_start:function(t){return this.date_part(t)},hour_start:function(t){var e=t.getHours();return this.day_start(t),t.setHours(e),t},minute_start:function(t){var e=t.getMinutes();return this.hour_start(t),t.setMinutes(e),t},_add_days:function(t,e){var n=new Date(t.valueOf());return n.setDate(n.getDate()+e),!t.getHours()&&n.getHours()&&n.setTime(n.getTime()+36e5*(24-n.getHours())),n},add:function(t,e,n){var i=new Date(t.valueOf());switch(n){case"day":i=gantt.date._add_days(i,e);break;case"week":i=gantt.date._add_days(i,7*e);break;case"month":i.setMonth(i.getMonth()+e);break;case"year":i.setYear(i.getFullYear()+e);break;case"hour":i.setTime(i.getTime()+60*e*60*1e3);break;case"minute":i.setTime(i.getTime()+60*e*1e3);break;default:return gantt.date["add_"+n](t,e,n)}return i},to_fixed:function(t){return 10>t?"0"+t:t},copy:function(t){return new Date(t.valueOf())},date_to_str:function(t,e){return t=t.replace(/%[a-zA-Z]/g,function(t){switch(t){case"%d":return'"+gantt.date.to_fixed(date.getDate())+"';case"%m":return'"+gantt.date.to_fixed((date.getMonth()+1))+"';case"%j":return'"+date.getDate()+"';case"%n":return'"+(date.getMonth()+1)+"';case"%y":return'"+gantt.date.to_fixed(date.getFullYear()%100)+"';case"%Y":return'"+date.getFullYear()+"';case"%D":return'"+gantt.locale.date.day_short[date.getDay()]+"';case"%l":return'"+gantt.locale.date.day_full[date.getDay()]+"';case"%M":return'"+gantt.locale.date.month_short[date.getMonth()]+"';case"%F":return'"+gantt.locale.date.month_full[date.getMonth()]+"';case"%h":return'"+gantt.date.to_fixed((date.getHours()+11)%12+1)+"';case"%g":return'"+((date.getHours()+11)%12+1)+"';case"%G":return'"+date.getHours()+"';case"%H":return'"+gantt.date.to_fixed(date.getHours())+"';case"%i":return'"+gantt.date.to_fixed(date.getMinutes())+"';case"%a":return'"+(date.getHours()>11?"pm":"am")+"';case"%A":return'"+(date.getHours()>11?"PM":"AM")+"';case"%s":return'"+gantt.date.to_fixed(date.getSeconds())+"';case"%W":return'"+gantt.date.to_fixed(gantt.date.getISOWeek(date))+"';default:return t}}),e&&(t=t.replace(/date\.get/g,"date.getUTC")),new Function("date",'return "'+t+'";')},str_to_date:function(t,e){for(var n="var temp=date.match(/[a-zA-Z]+|[0-9]+/g);",i=t.match(/%[a-zA-Z]/g),a=0;a<i.length;a++)switch(i[a]){case"%j":case"%d":n+="set[2]=temp["+a+"]||1;";break;case"%n":case"%m":n+="set[1]=(temp["+a+"]||1)-1;";break;case"%y":n+="set[0]=temp["+a+"]*1+(temp["+a+"]>50?1900:2000);";break;case"%g":case"%G":case"%h":case"%H":n+="set[3]=temp["+a+"]||0;";break;case"%i":n+="set[4]=temp["+a+"]||0;";break;case"%Y":n+="set[0]=temp["+a+"]||0;";break;case"%a":case"%A":n+="set[3]=set[3]%12+((temp["+a+"]||'').toLowerCase()=='am'?0:12);";break;case"%s":n+="set[5]=temp["+a+"]||0;";break;case"%M":n+="set[1]=gantt.locale.date.month_short_hash[temp["+a+"]]||0;";break;case"%F":n+="set[1]=gantt.locale.date.month_full_hash[temp["+a+"]]||0;"}var s="set[0],set[1],set[2],set[3],set[4],set[5]";return e&&(s=" Date.UTC("+s+")"),new Function("date","var set=[0,0,1,0,0,0]; "+n+" return new Date("+s+");")},getISOWeek:function(t){if(!t)return!1;var e=t.getDay();0===e&&(e=7);var n=new Date(t.valueOf());n.setDate(t.getDate()+(4-e));var i=n.getFullYear(),a=Math.round((n.getTime()-new Date(i,0,1).getTime())/864e5),s=1+Math.floor(a/7);return s},getUTCISOWeek:function(t){return this.getISOWeek(t)},convert_to_utc:function(t){return new Date(t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate(),t.getUTCHours(),t.getUTCMinutes(),t.getUTCSeconds())},parseDate:function(t,e){return"string"==typeof t&&(dhtmlx.defined(e)&&(e="string"==typeof e?dhtmlx.defined(gantt.templates[e])?gantt.templates[e]:gantt.date.str_to_date(e):gantt.templates.xml_date),t=e(t)),t}},gantt.config||(gantt.config={}),gantt.config||(gantt.config={}),gantt.templates||(gantt.templates={}),function(){dhtmlx.mixin(gantt.config,{links:{finish_to_start:"0",start_to_start:"1",finish_to_finish:"2",start_to_finish:"3"},types:{task:"task",project:"project",milestone:"milestone"},duration_unit:"day",work_time:!1,correct_work_time:!1,skip_off_time:!1,autosize:!1,show_links:!0,show_task_cells:!0,show_chart:!0,show_grid:!0,min_duration:36e5,xml_date:"%d-%m-%Y %H:%i",api_date:"%d-%m-%Y %H:%i",start_on_monday:!0,server_utc:!1,show_progress:!0,fit_tasks:!1,select_task:!0,readonly:!1,date_grid:"%Y-%m-%d",drag_links:!0,drag_progress:!0,drag_resize:!0,drag_move:!0,drag_mode:{resize:"resize",progress:"progress",move:"move",ignore:"ignore"},round_dnd_dates:!0,link_wrapper_width:20,root_id:0,autofit:!0,columns:[{name:"text",tree:!0,width:"*"},{name:"start_date",align:"center"},{name:"duration",align:"center"},{name:"add",width:"44"}],step:1,scale_unit:"day",subscales:[],time_step:60,duration_step:1,date_scale:"%d %M",task_date:"%d %F %Y",time_picker:"%H:%i",task_attribute:"task_id",link_attribute:"link_id",buttons_left:["dhx_save_btn","dhx_cancel_btn"],buttons_right:["dhx_delete_btn"],lightbox:{sections:[{name:"description",height:70,map_to:"text",type:"textarea",focus:!0},{name:"time",height:72,type:"duration",map_to:"auto"}],project_sections:[{name:"description",height:70,map_to:"text",type:"textarea",focus:!0},{name:"type",type:"typeselect",map_to:"type"},{name:"time",height:72,type:"duration",readonly:!0,map_to:"auto"}],milestone_sections:[{name:"description",height:70,map_to:"text",type:"textarea",focus:!0},{name:"type",type:"typeselect",map_to:"type"},{name:"time",height:72,type:"duration",single_date:!0,map_to:"auto"}]},drag_lightbox:!0,sort:!1,details_on_create:!0,details_on_dblclick:!0,initial_scroll:!0,task_scroll_offset:100,task_height:"full",min_column_width:70}),gantt.keys={edit_save:13,edit_cancel:27},gantt._init_template=function(t,e){var n=this._reg_templates||{};this.config[t]&&n[t]!=this.config[t]&&(e&&this.templates[t]||(this.templates[t]=this.date.date_to_str(this.config[t]),n[t]=this.config[t])),this._reg_templates=n},gantt._init_templates=function(){var t=gantt.locale.labels;t.dhx_save_btn=t.icon_save,t.dhx_cancel_btn=t.icon_cancel,t.dhx_delete_btn=t.icon_delete;var e=this.date.date_to_str,n=this.config;gantt._init_template("date_scale",!0),gantt._init_template("date_grid",!0),gantt._init_template("task_date",!0),dhtmlx.mixin(this.templates,{xml_date:this.date.str_to_date(n.xml_date,n.server_utc),xml_format:e(n.xml_date,n.server_utc),api_date:this.date.str_to_date(n.api_date),progress_text:function(){return""},grid_header_class:function(){return""},task_text:function(t,e,n){return n.text},task_class:function(){return""},grid_row_class:function(){return""},task_row_class:function(){return""},task_cell_class:function(){return""},scale_cell_class:function(){return""},scale_row_class:function(){return""},grid_indent:function(){return"<div class='gantt_tree_indent'></div>"},grid_folder:function(t){return"<div class='gantt_tree_icon gantt_folder_"+(t.$open?"open":"closed")+"'></div>"},grid_file:function(){return"<div class='gantt_tree_icon gantt_file'></div>"},grid_open:function(t){return"<div class='gantt_tree_icon gantt_"+(t.$open?"close":"open")+"'></div>"},grid_blank:function(){return"<div class='gantt_tree_icon gantt_blank'></div>"},task_time:function(t,e){return gantt.templates.task_date(t)+" - "+gantt.templates.task_date(e)},time_picker:e(n.time_picker),link_class:function(){return""},link_description:function(t){var e=gantt.getTask(t.source),n=gantt.getTask(t.target);return"<b>"+e.text+"</b> &ndash; <b>"+n.text+"</b>"},drag_link:function(t,e,n,i){t=gantt.getTask(t);var a=gantt.locale.labels,s="<b>"+t.text+"</b> "+(e?a.link_start:a.link_end)+"<br/>";return n&&(n=gantt.getTask(n),s+="<b> "+n.text+"</b> "+(i?a.link_start:a.link_end)+"<br/>"),s},drag_link_class:function(t,e,n,i){var a="";if(t&&n){var s=gantt.isLinkAllowed(t,n,e,i);a=" "+(s?"gantt_link_allow":"gantt_link_deny")}return"gantt_link_tooltip"+a}}),this.callEvent("onTemplatesReady",[])}}(),window.jQuery&&!function(t){var e=[];t.fn.dhx_gantt=function(n){if(n=n||{},"string"!=typeof n){var i=[];return this.each(function(){if(this&&this.getAttribute&&!this.getAttribute("dhxgantt")){for(var t in n)"data"!=t&&(gantt.config[t]=n[t]);gantt.init(this),n.data&&gantt.parse(n.data),i.push(gantt)}}),1===i.length?i[0]:i}return e[n]?e[n].apply(this,[]):void t.error("Method "+n+" does not exist on jQuery.dhx_gantt")}}(jQuery),window.dhtmlx&&(dhtmlx.attaches||(dhtmlx.attaches={}),dhtmlx.attaches.attachGantt=function(t,e){var n=document.createElement("DIV");n.id="gantt_"+dhtmlx.uid(),n.style.width="100%",n.style.height="100%",n.cmp="grid",document.body.appendChild(n),this.attachObject(n.id);var i=this.vs[this.av];i.grid=gantt,gantt.init(n.id,t,e),n.firstChild.style.border="none",i.gridId=n.id,i.gridObj=n;var a="_viewRestore";return this.vs[this[a]()].grid}),gantt.locale={date:{month_full:["January","February","March","April","May","June","July","August","September","October","November","December"],month_short:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],day_full:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],day_short:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},labels:{new_task:"New task",icon_save:"Save",icon_cancel:"Cancel",icon_details:"Details",icon_edit:"Edit",icon_delete:"Delete",confirm_closing:"",confirm_deleting:"Task will be deleted permanently, are you sure?",section_description:"Description",section_time:"Time period",section_type:"Type",column_text:"Task name",column_start_date:"Start time",column_duration:"Duration",column_add:"",link:"Link",confirm_link_deleting:"will be deleted",link_start:" (start)",link_end:" (end)",type_task:"Task",type_project:"Project",type_milestone:"Milestone",minutes:"Minutes",hours:"Hours",days:"Days",weeks:"Week",months:"Months",years:"Years"}},gantt.skins.skyblue={config:{grid_width:350,row_height:27,scale_height:27,task_height:24,link_line_width:1,link_arrow_size:8,lightbox_additional_height:75},_second_column_width:95,_third_column_width:80},gantt.skins.meadow={config:{grid_width:350,row_height:27,scale_height:30,task_height:24,link_line_width:2,link_arrow_size:6,lightbox_additional_height:72},_second_column_width:95,_third_column_width:80},gantt.skins.terrace={config:{grid_width:360,row_height:35,scale_height:35,task_height:24,link_line_width:2,link_arrow_size:6,lightbox_additional_height:75},_second_column_width:90,_third_column_width:70},gantt.skins.broadway={config:{grid_width:360,row_height:35,scale_height:35,task_height:24,link_line_width:1,link_arrow_size:7,lightbox_additional_height:86},_second_column_width:90,_third_column_width:80,_lightbox_template:"<div class='dhx_cal_ltitle'><span class='dhx_mark'>&nbsp;</span><span class='dhx_time'></span><span class='dhx_title'></span><div class='dhx_cancel_btn'></div></div><div class='dhx_cal_larea'></div>",_config_buttons_left:{},_config_buttons_right:{dhx_delete_btn:"icon_delete",dhx_save_btn:"icon_save"}},gantt.config.touch_drag=50,gantt.config.touch=!0,gantt._init_touch_events=function(){"force"!=this.config.touch&&(this.config.touch=this.config.touch&&(-1!=navigator.userAgent.indexOf("Mobile")||-1!=navigator.userAgent.indexOf("iPad")||-1!=navigator.userAgent.indexOf("Android")||-1!=navigator.userAgent.indexOf("Touch"))),this.config.touch&&(window.navigator.msPointerEnabled?this._touch_events(["MSPointerMove","MSPointerDown","MSPointerUp"],function(t){return t.pointerType==t.MSPOINTER_TYPE_MOUSE?null:t},function(t){return!t||t.pointerType==t.MSPOINTER_TYPE_MOUSE}):this._touch_events(["touchmove","touchstart","touchend"],function(t){return t.touches&&t.touches.length>1?null:t.touches[0]?{target:t.target,pageX:t.touches[0].pageX,pageY:t.touches[0].pageY}:t},function(){return!1}))},gantt._touch_events=function(t,e,n){function i(t){return t&&t.preventDefault&&t.preventDefault(),(t||event).cancelBubble=!0,!1}var a,s=0,r=!1,o=!1,d=null;this._gantt_touch_event_ready||(this._gantt_touch_event_ready=1,dhtmlxEvent(document.body,t[0],function(t){if(!n(t)&&r){var l=e(t);if(l&&d){var _=d.pageX-l.pageX,h=d.pageY-l.pageY;!o&&(Math.abs(_)>5||Math.abs(h)>5)&&(gantt._touch_scroll_active=o=!0,s=0,a=gantt.getScrollState()),o&&gantt.scrollTo(a.x+_,a.y+h)}return i(t)}})),dhtmlxEvent(this.$container,"contextmenu",function(t){return r?i(t):void 0}),dhtmlxEvent(this.$container,t[1],function(t){if(!n(t)){if(t.touches&&t.touches.length>1)return void(r=!1);if(r=!0,d=e(t),d&&s){var a=new Date;500>a-s?(gantt._on_dblclick(d),i(t)):s=a}else s=new Date}}),dhtmlxEvent(this.$container,t[2],function(t){n(t)||(gantt._touch_scroll_active=r=o=!1)})};var et2_gantt=function(){"use strict";return et2_inputWidget.extend([et2_IResizeable,et2_IInput],{createNamespace:!0,attributes:{autoload:{name:"Autoload",type:"string",default:"",description:"JSON URL or menuaction to be called for projects with no, GET parameter selected contains id"},ajax_update:{name:"AJAX update method",type:"string",default:"",description:"AJAX menuaction to be called when the user changes a task. The function should take two parameters: the updated element, and all template values."},duration_unit:{name:"Duration unit",type:"string",default:"minute",description:"The unit for task duration values. One of minute, hour, week, year."},columns:{name:"Columns",type:"any",default:[{name:"text",label:egw.lang("Title"),tree:!0,width:"*"}],description:"Columns for the grid portion of the gantt chart. An array of objects with keys name, label, etc. See http://docs.dhtmlx.com/gantt/api__gantt_columns_config.html"},value:{type:"any"},needed:{ignore:!0},onfocus:{ignore:!0},tabindex:{ignore:!0}},gantt_config:{api_date:"%Y-%n-%d %H:%i:%s",xml_date:"%Y-%n-%d %H:%i:%s",duration_unit:"minute",duration_step:1,show_progress:!0,order_branch:!1,min_column_width:30,min_grid_column_width:30,task_height:25,fit_tasks:!0,autosize:"",round_dnd_dates:!1,time_step:parseInt(this.egw().preference("interval","calendar")||15),min_duration:6e4,scale_unit:"day",date_scale:"%d",subscales:[{unit:"month",step:1,date:"%F, %Y"}],columns:[{name:"text",label:egw.lang("Title"),tree:!0,width:"*"}]},init:function(_parent,_attrs){this._super.apply(this,arguments),this.gantt=null,this.filters=$j(document.createElement("div")).addClass("et2_gantt_header"),this.gantt_node=$j('<div style="width:100%;height:100%"></div>'),this.htmlNode=$j(document.createElement("div")).css("height",this.options.height).addClass("et2_gantt"),this.htmlNode.prepend(this.filters),this.htmlNode.append(this.gantt_node),this.dynheight=new et2_dynheight(this.getParent().getDOMNode(this.getParent())||this.getInstanceManager().DOMContainer,this.gantt_node,300),this.setDOMNode(this.htmlNode[0])},destroy:function(){null!==this.gantt&&(this.gantt.unselectTask(),this.gantt.detachAllEvents(),this.gantt.clearAll(),this.gantt=null,this.dynheight&&this.dynheight.free(),this._super.apply(this,arguments)),this.htmlNode.remove(),this.htmlNode=null},doLoadingFinished:function(){if(this._super.apply(this,arguments),null!=this.gantt)return!1;var config=jQuery.extend({},this.gantt_config),start_date=this.getWidgetById("start_date"),end_date=this.getWidgetById("end_date");return start_date&&(config.start_date=start_date.getValue()?new Date(1e3*start_date.getValue()):null),end_date&&(config.end_date=end_date.getValue()?new Date(1e3*end_date.getValue()):null),this.options.duration_unit&&(config.duration_unit=this.options.duration_unit),this.gantt=this.gantt_node.dhx_gantt(config),this.options.zoom&&this.set_zoom(this.options.zoom),this.options.value&&this.set_value(this.options.value),this.options.columns&&this.set_columns(this.options.columns),start_date&&this.options.value.data&&this.options.value.data.length&&start_date.set_value(this.gantt.getState().min_date),end_date&&this.options.value.data&&this.options.value.data.length&&end_date.set_value(this.gantt.getState().max_date),this._bindGanttEvents(),this._bindChildren(),!0},getDOMNode:function(_sender){return _sender!=this&&-1!=this._children.indexOf(_sender)?this.filters[0]:this._super.apply(this,arguments)},resize:function(){this.dynheight?this.dynheight.update(function(w,h){this.gantt&&this.gantt.setSizes()},this):this.gantt.setSizes()},set_duration_unit:function(duration_unit){this.options.duration_unit=duration_unit,this.gantt&&this.gantt.config.duration_unit!=duration_unit&&(this.gantt.config.duration_unit=duration_unit,this.gantt.config.end_date=null,this.gantt.refreshData())},set_columns:function(columns){this.gantt_config.columns=columns;var displayed_columns=[],gantt_widget=this,width=0;for(var col in columns)columns[col]._width||(columns[col]._width=columns[col].width),columns[col].width=columns[col]._width,columns[col].template||(columns[col].template=function(task){var value="undefined"==typeof task[this.name]||null==task[this.name]?"":task[this.name];if(!value&&0==this.name.indexOf("pe_")&&task.pm_title){var pm_col=this.name.replace("pe_","pm_");value="undefined"==typeof task[pm_col]||null==task[pm_col]?"":task[pm_col]}if(this.widget&&"string"==typeof this.widget){var attrs=jQuery.extend({readonly:!0},this.widget_attributes||{});this.widget=et2_createWidget(this.widget,attrs,gantt_widget)}return this.widget&&(this.widget.set_value(value),value=$j(this.widget.getDOMNode()).html()),'<div class="gantt_column_'+this.name+'">'+value+"</div>"}),columns[col].hide||(displayed_columns.push(columns[col]),width+=parseInt(columns[col]._width)||0);displayed_columns.push({name:"add",width:26}),width+=26,width==this.gantt_config.grid_width&&"undefined"!=typeof this.gantt_config.grid_width||(this.gantt_config.grid_width=Math.min(Math.max(200,width),this.htmlNode.width())),null!=this.gantt&&(this.gantt.config.columns=displayed_columns,this.gantt.config.grid_width=this.gantt_config.grid_width,this.gantt.render())},set_value:function(value){if(null==this.gantt)return!1;this.gantt.unselectTask(),this.gantt.clearAll(),this.gantt.config.end_date=null,value.duration_unit&&this.set_duration_unit(value.duration_unit),this.gantt.showCover(),this.set_zoom(value.zoom||5);var gantt_widget=this,zoom_wait=this.gantt.attachEvent("onGanttRender",function(){this.detachEvent(zoom_wait);var safe_value={data:value.data||[],links:value.links||[]};this.config.start_date=value.start_date||null,this.config.end_date=value.end_date||null,this.parse(safe_value),gantt_widget._apply_sort(),gantt_widget.gantt_loading=!1;var range=this.attachEvent("onGanttRender",function(){this.detachEvent(range),(value.start_date||value.end_date)&&this.scrollTo(this.posFromDate(new Date(value.end_date||value.start_date)),0);var auto_zoom=this.attachEvent("onGanttRender",function(){this.detachEvent(auto_zoom);var old_zoom;do this.render(),old_zoom=gantt_widget.options.zoom,gantt_widget.set_zoom(value.zoom||!1);while(gantt_widget.options.zoom!=old_zoom);this.hideCover(),console.timeEnd&&console.timeEnd("Gantt set_value"),console.groupEnd&&console.groupEnd(),console.profile&&console.profileEnd()})})});this.gantt.render()},getValue:function(){return jQuery.extend({},this.value,{zoom:this.options.zoom,duration_unit:this.gantt.config.duration_unit})},refresh:function(_task_ids,_type){if(this.gantt&&this.gantt_node&&this.options.autoload){"undefined"==typeof _type&&(_type="edit"),"string"!=typeof _task_ids&&"number"!=typeof _task_ids||(_task_ids=[_task_ids]),"undefined"!=typeof _task_ids&&null!==_task_ids||(_task_ids=this.gantt._branches[0]);id_loop:for(var i=0;i<_task_ids.length;i++){var task=this.gantt.getTask(_task_ids[i]);switch(task||(_type=null),_type){case"edit":case"update":var value=this.getInstanceManager().getValues(this.getInstanceManager().widgetContainer);this.gantt.showCover(),this.egw().json(this.options.autoload,[_task_ids[i],value,task.parent||!1],function(data){this.gantt.parse(data),this._apply_sort(),this.gantt.hideCover()},this,!0,this).sendRequest();break;case"delete":this.gantt.deleteTask(_task_ids[i]);break;case"add":var data=this.egw().dataGetUIDdata(_task_ids[i])&&data.data;if(!data){this.refresh();break id_loop}this.gantt.parse(data.data),this._apply_sort();break;default:this.refresh()}}$j(this).triggerHandler("refresh",[this,_task_ids,_type])}},isDirty:function(){return null!=this.value},resetDirty:function(){this.value=null},isValid:function(messages){return!0},set_autoload:function(url){if(null==this.gantt)return!1;throw this.options.autoloading=url,new Exception("Not implemented yet - apparently loading segments is not supported automatically")},set_zoom:function(level){var subscales=[],scale_unit="day",date_scale="%d",step=1,time_step=this.gantt_config.time_step,min_column_width=this.gantt_config.min_column_width;if(level>5&&(level=5),!level||1>level){try{this.gantt.refreshData()}catch(e){}var difference=(this.gantt.getState().max_date-this.gantt.getState().min_date)/1e3;level=difference>94608e3?5:difference>7776e3?4:difference>259200?3:2}switch(level){case 5:scale_unit="year",date_scale="%Y";break;case 4:subscales.push({unit:"month",step:1,date:"%F %Y"}),scale_unit="week",date_scale="#%W";break;case 3:subscales.push({unit:"month",step:1,date:"%F %Y",class:"et2_clickable"});break;case 2:default:subscales.push({unit:"day",step:1,date:"%F %d"}),scale_unit="hour",date_scale="24"==this.egw().preference("timeformat")?"%G":"%g";break;case 1:subscales.push({unit:"day",step:1,date:"%F %d"}),date_scale="24"==this.egw().preference("timeformat")?"%G:%i":"%g:%i",step=parseInt(this.egw().preference("interval","calendar")||15),time_step=1,scale_unit="minute",min_column_width=50}return this.gantt.config.subscales=subscales,this.gantt.config.scale_unit=scale_unit,this.gantt.config.date_scale=date_scale,this.gantt.config.step=step,this.gantt.config.time_step=time_step,this.gantt.config.min_column_width=min_column_width,this.options.zoom=level,this.gantt.refreshData(),level},_apply_sort:function(){switch(egw.preference("gantt_pm_elementbars_order","projectmanager")){case"pe_start":case"pe_start,pe_end":this.gantt.sort("start_date",!1);break;case"pe_end":this.gantt.sort("end_date",!1);break;case"pe_title":this.gantt.sort("pe_title",!1)}},_export:function(to){var w=egw.open_link(egw.link("/etemplate/gantt_print.php"),"_blank","400x400"),self=this;jQuery(w).load(function(){w.egw_LAB.wait(function(){w.gantt=jQuery.extend(!0,{},self.gantt),"undefined"==typeof w.gantt.exportToPNG&&w.egw_LAB.script("https://export.dhtmlx.com/gantt/api.js"),w.egw_LAB.wait(function(){$j(w.gantt.$container).parent().clone().appendTo(w.document.body);var css="";$j("link[type='text/css']").each(function(){css+=this.outerHTML});var options={name:(w.gantt.getTask(w.gantt._order[0]).text||"gantt").replace(/ /g,"_")+"."+to.toLowerCase(),header:css+egw.config("site_title","phpgwapi"),footer:$j("#egw_fw_footer",w.opener).html()};switch(console.log(options),to){case"PNG":w.gantt.exportToPNG(options);break;case"PDF":w.gantt.exportToPDF(options)}w.setTimeout(function(){w.close()},5e3)})})})},exportToPDF:function(){this._export("PDF")},exportToPNG:function(){this._export("PNG")},_bindGanttEvents:function(){var gantt_widget=this;this.gantt.attachEvent("onGanttRender",function(){window.setTimeout(function(){gantt_widget.resize()},100)}),this.gantt_node.on("click",".gantt_scale_line",function(e){var current_position=e.target.offsetLeft/$j(e.target.parentNode).width(),id=gantt_widget.gantt.attachEvent("onGanttRender",function(){gantt_widget.gantt.detachEvent(id),gantt_widget.gantt.scrollTo(parseInt($j(".gantt_task_scale",gantt_widget.gantt_node).width()*current_position),0),window.setTimeout(function(){gantt_widget.gantt.scrollTo(parseInt($j(".gantt_task_scale",gantt_widget.gantt_node).width()*current_position),0)},100)});this.parentNode&&this.parentNode.firstChild==this&&this.parentNode.childElementCount>1?(gantt_widget.set_zoom(gantt_widget.options.zoom+1),gantt_widget.gantt.render()):gantt_widget.options.zoom>1&&(gantt_widget.set_zoom(gantt_widget.options.zoom-1),gantt_widget.gantt.render())}),this.gantt.attachEvent("onGridHeaderClick",function(column_name,e){"add"===column_name&&gantt_widget._column_selection(e)}),this.gantt.attachEvent("onContextMenu",function(taskId,linkId,e){return gantt_widget.options.readonly?!1:(taskId?gantt_widget._link_task(taskId):linkId&&(this._delete_link_handler(linkId,e),e.stopPropagation()),!1)}),this.gantt.attachEvent("onBeforeLightbox",function(id){return gantt_widget._link_task(id),!1}),this.gantt.attachEvent("onAfterTaskDrag",function(id,mode,e){if(gantt_widget.options.readonly)return!1;var task=this.getTask(id);"progress"===mode&&(task.progress=Math.round(10*task.progress)/10,this.updateTask(task.id));var task=jQuery.extend({},this.getTask(id)),date_parser=this.date.date_to_str(this.config.api_date);task.start_date&&(task.start_date=date_parser(task.start_date)),task.end_date&&(task.end_date=date_parser(task.end_date));var value=gantt_widget.getInstanceManager().getValues(gantt_widget.getInstanceManager().widgetContainer),set=!0;if(gantt_widget.options.onchange&&(e.data={task:task,mode:mode,value:value},set=gantt_widget.change(e,gantt_widget)),gantt_widget.options.ajax_update&&set){gantt_widget.egw().json(gantt_widget.options.ajax_update,[task,mode,value]).sendRequest(!0)}});var link_update=function(id,link){if(gantt_widget.options.readonly)return!1;if(gantt_widget.options.ajax_update){link.parent=this.getTask(link.source).parent;var value=gantt_widget.getInstanceManager().getValues(gantt_widget.getInstanceManager().widgetContainer);gantt_widget.egw().json(gantt_widget.options.ajax_update,[link,value],function(new_id){new_id&&(link.id=new_id)}).sendRequest(!0)}};this.gantt.attachEvent("onAfterLinkAdd",link_update),this.gantt.attachEvent("onAfterLinkDelete",link_update),this.gantt.attachEvent("onTaskOpened",function(id,item){gantt_widget.refresh(id)}),this.gantt.attachEvent("onBeforeTaskDisplay",function(id,task){var display=!0;return gantt_widget.iterateOver(function(_widget){switch(_widget.id){case"end_date":return void(_widget.getValue()&&(display=display&&task.start_date.valueOf()/1e3<new Date(_widget.getValue()).valueOf()/1e3+86400));case"start_date":return void(_widget.getValue()&&(display=display&&("undefined"==typeof task.end_date||!task.end_date||task.end_date.valueOf()/1e3>=new Date(_widget.getValue()).valueOf()/1e3)))}if(_widget.getValue()&&"undefined"!=typeof task[_widget.id]&&(task[_widget.id]!=_widget.getValue()&&(display=!1),!display&&"object"==typeof task[_widget.id]||"object"==typeof _widget.getValue())){var a="object"==typeof task[_widget.id]?task[_widget.id]:_widget.getValue(),b=a==task[_widget.id]?_widget.getValue():task[_widget.id];display="object"==typeof b?jQuery.map(a,function(x){return jQuery.inArray(x,b)>=0}):jQuery.inArray(b,a)>=0}},gantt_widget,et2_inputWidget),display})},_bindChildren:function(){var gantt_widget=this;this.iterateOver(function(_widget){if(!_widget.instanceOf(et2_gantt)){var widget_change=_widget.change,change=function(_node){var result=widget_change.call(_widget,_node);if(result){if(_widget._oldValue=_widget.getValue(),"start_date"==_widget.id||"end_date"==_widget.id){var start=this.getWidgetById("start_date"),end=this.getWidgetById("end_date");gantt_widget.gantt.config.start_date=start&&start.getValue()?new Date(start.getValue()):gantt_widget.gantt.getState().min_date,gantt_widget.gantt.config.end_date=end&&end.getValue()?new Date(new Date(end.getValue()).valueOf()+864e5):gantt_widget.gantt.getState().max_date,gantt_widget.gantt.config.end_date<=gantt_widget.gantt.config.start_date&&(gantt_widget.gantt.config.end_date=null,end&&end.set_value(null)),gantt_widget.set_zoom(),gantt_widget.gantt.render()}gantt_widget.gantt.refreshData()}return!0};_widget.change!=change&&(_widget.change=change)}},this,et2_inputWidget)},_column_selection:function(e){for(var self=this,columns=[],columns_selected=[],i=0;i<this.gantt_config.columns.length;i++){var col=this.gantt_config.columns[i];columns.push({value:col.name,label:col.label}),col.hide||columns_selected.push(col.name)}if(this.selectPopup)this.selectPopup.toggle();else{var select=et2_createWidget("select",{multiple:!0,rows:8,empty_label:this.egw().lang("select columns"),selected_first:!1},this);select.set_select_options(columns),select.set_value(columns_selected);var okButton=et2_createWidget("buttononly",{},this);okButton.set_label(this.egw().lang("ok")),okButton.onclick=function(){for(var value=select.getValue()||[],i=0;i<columns.length;i++)self.gantt_config.columns[i].hide=value.indexOf(columns[i].value)<0;self.set_columns(self.gantt_config.columns),this.egw().set_preference(self.getInstanceManager().app,"gantt_columns_"+self.id,value),self.selectPopup.toggle(),self.selectPopup.remove(),self.selectPopup=null,$j("body").off("click.gantt")};var cancelButton=et2_createWidget("buttononly",{},this);cancelButton.set_label(this.egw().lang("cancel")),cancelButton.onclick=function(){self.selectPopup.toggle(),self.selectPopup.remove(),self.selectPopup=null,$j("body").off("click.gantt")},this.selectPopup=jQuery(document.createElement("div")).addClass("colselection ui-dialog ui-widget-content").append(select.getDOMNode()).append(okButton.getDOMNode()).append(cancelButton.getDOMNode()).appendTo(this.getInstanceManager().DOMContainer),window.setTimeout(function(){$j(document).one("mouseup.gantt",function(e){self.selectPopup.is(e.target)||0!==self.selectPopup.has(e.target).length||cancelButton.onclick()})},1)}this.selectPopup.position({my:"right top",at:"right bottom",of:e.target})},_link_actions:function(actions){this._super.apply(this,arguments),this._actionManager.setDefaultExecute(jQuery.proxy(function(action,selected){for(var ids=[],i=0;i<selected.length;i++)ids.push(selected[i].id);this.value={action:action.id,selected:ids},action.data.postSubmit?this.getInstanceManager().postSubmit():this.getInstanceManager().submit()},this));var objectManager=egw_getAppObjectManager(!0),widget_object=objectManager.getObjectById(this.id);
widget_object.flags=EGW_AO_FLAG_IS_CONTAINER},_link_task:function(taskId){if(taskId){var objectManager=egw_getObjectManager(this.id,!1),obj=null;(obj=objectManager.getObjectById(taskId))||(obj=objectManager.addObject(taskId,this.dhtmlxGanttItemAOI(this.gantt,taskId)),obj.data=this.gantt.getTask(taskId),obj.updateActionLinks(objectManager.actionLinks)),objectManager.setAllSelected(!1),obj.setSelected(!0),objectManager.updateSelectedChildren(obj,!0)}},dhtmlxGanttItemAOI:function(gantt,task_id){var aoi=new egwActionObjectInterface;return aoi.node=gantt.getTaskNode(task_id),aoi.id=task_id,aoi.doGetDOMNode=function(){return aoi.node},aoi.doTriggerEvent=function(_event){_event==EGW_AI_DRAG_OVER&&$j(this.node).addClass("draggedOver"),_event==EGW_AI_DRAG_OUT&&$j(this.node).removeClass("draggedOver")},aoi.doSetState=function(_state){gantt&&gantt.isTaskExists(this.id)&&(egwBitIsSet(_state,EGW_AO_STATE_SELECTED)?gantt.selectTask(this.id):gantt.unselectTask(this.id))},aoi}})}.call(this);et2_register_widget(et2_gantt,["gantt"]),$j(function(){"use strict";gantt.templates.grid_file=function(item){return item.pe_icon&&egw.image(item.pe_icon)?"<div class='gantt_tree_icon' style='background-image: url(\""+egw.image(item.pe_icon)+"\");'/></div>":"<div class='gantt_tree_icon gantt_file'></div>"},gantt.templates.scale_row_class=function(scale){return"minute"!=scale.unit&&"month"!=scale.unit?scale.class||"et2_clickable":scale.class},gantt.templates.progress_text=function(start,end,task){return"<span>"+Math.round(100*task.progress)+"% </span>"},gantt.templates.scale_cell_class=function(date){return 0==date.getDay()||6==date.getDay()?"weekend":void 0},gantt.templates.task_cell_class=function(item,date){return 0==date.getDay()||6==date.getDay()?"weekend":void 0},gantt.templates.leftside_text=function(start,end,task){var text="";if(task.planned_start){"string"==typeof task.planned_start&&(task.planned_start=gantt.date.parseDate(task.planned_start,"xml_date"));var p_start=gantt.posFromDate(task.planned_start)-gantt.posFromDate(start);text="<div class='gantt_task_line gantt_task_planned' style='width:"+Math.abs(p_start)+"px; right:"+(p_start>0?-p_start:0)+"px;'><span>"+gantt.date.date_to_str(gantt.config.api_date)(task.planned_start)+"</span></div>"}return text},gantt.templates.rightside_text=function(start,end,task){var text="";if(task.planned_end){"string"==typeof task.planned_end&&(task.planned_end=gantt.date.parseDate(task.planned_end,"xml_date"));var p_end=gantt.posFromDate(task.planned_end)-gantt.posFromDate(end);text="<div class='gantt_task_line gantt_task_planned' style='left:"+(p_end>0?0:p_end)+"px; width:"+Math.abs(p_end)+"px'><span>"+gantt.date.date_to_str(gantt.config.api_date)(task.planned_end)+"</span></div>"}return text},gantt.templates.link_class=function(link){var link_class="",source=gantt.getTask(link.source),target=gantt.getTask(link.target),valid=!0,types=gantt.config.links;switch(link.type){case types.finish_to_start:valid=source.end_date<=target.start_date;break;case types.start_to_start:valid=source.start_date<=target.start_date;break;case types.finish_to_finish:valid=source.end_date>=target.end_date;break;case types.start_to_finish:valid=source.start_date>=target.end_date}return link_class+=valid?"":"invalid_constraint"}});var et2_html=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{label:{default:"",description:"The label is displayed by default in front (for radiobuttons behind) each widget (if not empty). If you want to specify a different position, use a '%s' in the label, which gets replaced by the widget itself. Eg. '%s Name' to have the label Name behind a checkbox. The label can contain variables, as descript for name. If the label starts with a '@' it is replaced by the value of the content-array at this index (with the '@'-removed and after expanding the variables).",ignore:!1,name:"Label",translate:!0,type:"string"},needed:{ignore:!0},value:{name:"Value",description:"The value of the widget",type:"html",default:et2_no_init}},init:function(){this._super.apply(this,arguments),this.supportedWidgetClasses=[],this.htmlNode=$j(document.createElement("span")),"htmlarea"==this._type&&this.htmlNode.addClass("et2_textbox_ro"),this.options.label&&this.htmlNode.append('<span class="et2_label">'+this.options.label+"</span>"),this.setDOMNode(this.htmlNode[0])},loadContent:function(_data){var html={html:_data?_data:"",js:""};egw_seperateJavaScript(html),this.options.label&&this.htmlNode.append('<span class="et2_label">'+this.options.label+"</span>"),this.htmlNode.append(html.html),this.htmlNode.append(html.js)},set_value:function(_value){this.htmlNode.empty(),this.loadContent(_value)},getDetachedAttributes:function(_attrs){_attrs.push("value","class")},getDetachedNodes:function(){return[this.htmlNode[0]]},setDetachedAttributes:function(_nodes,_values){this.htmlNode=jQuery(_nodes[0]),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_html,["html","htmlarea_ro"]),function(a){if("undefined"==typeof a)throw Error("jQuery should be loaded before CKEditor jQuery adapter.");if("undefined"==typeof CKEDITOR)throw Error("CKEditor should be loaded before CKEditor jQuery adapter.");CKEDITOR.config.jqueryOverrideVal="undefined"==typeof CKEDITOR.config.jqueryOverrideVal?!0:CKEDITOR.config.jqueryOverrideVal,a.extend(a.fn,{ckeditorGet:function(){var a=this.eq(0).data("ckeditorInstance");if(!a)throw"CKEditor is not initialized yet, use ckeditor() with a callback.";return a},ckeditor:function(g,d){if(!CKEDITOR.env.isCompatible)throw Error("The environment is incompatible.");if(!a.isFunction(g)){var m=d;d=g,g=m}var k=[];d=d||{},this.each(function(){var b=a(this),c=b.data("ckeditorInstance"),f=b.data("_ckeditorInstanceLock"),h=this,l=new a.Deferred;k.push(l.promise()),c&&!f?(g&&g.apply(c,[this]),l.resolve()):f?c.once("instanceReady",function(){setTimeout(function(){c.element?(c.element.$==h&&g&&g.apply(c,[h]),l.resolve()):setTimeout(arguments.callee,100)},0)},null,null,9999):((d.autoUpdateElement||"undefined"==typeof d.autoUpdateElement&&CKEDITOR.config.autoUpdateElement)&&(d.autoUpdateElementJquery=!0),d.autoUpdateElement=!1,b.data("_ckeditorInstanceLock",!0),c=a(this).is("textarea")?CKEDITOR.replace(h,d):CKEDITOR.inline(h,d),b.data("ckeditorInstance",c),c.on("instanceReady",function(d){var e=d.editor;setTimeout(function(){if(e.element){if(d.removeListener(),e.on("dataReady",function(){b.trigger("dataReady.ckeditor",[e])}),e.on("setData",function(a){b.trigger("setData.ckeditor",[e,a.data])}),e.on("getData",function(a){b.trigger("getData.ckeditor",[e,a.data])},999),e.on("destroy",function(){b.trigger("destroy.ckeditor",[e])}),e.on("save",function(){return a(h.form).submit(),!1},null,null,20),e.config.autoUpdateElementJquery&&b.is("textarea")&&a(h.form).length){var c=function(){b.ckeditor(function(){e.updateElement()})};a(h.form).submit(c),a(h.form).bind("form-pre-serialize",c),b.bind("destroy.ckeditor",function(){a(h.form).unbind("submit",c),a(h.form).unbind("form-pre-serialize",c)})}e.on("destroy",function(){b.removeData("ckeditorInstance")}),b.removeData("_ckeditorInstanceLock"),b.trigger("instanceReady.ckeditor",[e]),g&&g.apply(e,[h]),l.resolve()}else setTimeout(arguments.callee,100)},0)},null,null,9999))});var f=new a.Deferred;return this.promise=f.promise(),a.when.apply(this,k).then(function(){f.resolve()}),this.editor=this.eq(0).data("ckeditorInstance"),this}}),CKEDITOR.config.jqueryOverrideVal&&(a.fn.val=CKEDITOR.tools.override(a.fn.val,function(g){return function(d){if(arguments.length){var m=this,k=[],f=this.each(function(){var b=a(this),c=b.data("ckeditorInstance");if(b.is("textarea")&&c){var f=new a.Deferred;return c.setData(d,function(){f.resolve()}),k.push(f.promise()),!0}return g.call(b,d)});if(k.length){var b=new a.Deferred;return a.when.apply(this,k).done(function(){b.resolveWith(m)}),b.promise()}return f}var f=a(this).eq(0),c=f.data("ckeditorInstance");return f.is("textarea")&&c?c.getData():g.call(f)}}))}(window.jQuery);var et2_htmlarea=function(){"use strict";return et2_inputWidget.extend([et2_IResizeable],{modes:["ascii","simple","extended","advanced"],attributes:{mode:{name:"Mode",description:"One of {ascii|simple|extended|advanced}",default:"simple",type:"string"},height:{name:"Height",default:et2_no_init,type:"string"},width:{name:"Width",default:et2_no_init,type:"string"},expand_toolbar:{name:"Expand Toolbar",default:!0,type:"boolean",description:"Have the toolbar expanded (visible)"},base_href:{name:"Image base path",default:et2_no_init,type:"string",description:"activates the browser for images at the path (relative to the docroot)"},config:{name:"Internal configuration",type:"any",default:et2_no_init,description:"Internal configuration - managed by preferences & framework, passed in here",translate:"no_lang"},value:{name:"Value",description:"The value of the widget",type:"html",default:et2_no_init},imageUpload:{name:"imageUpload",description:"Url to upload images dragged in or id of link_to widget to it's vfs upload",type:"string",default:null}},legacyOptions:["mode","height","width","expand_toolbar","base_href"],init:function(_parent,_attrs){this._super.apply(this,arguments),this.ckeditor=null,this.supportedWidgetClasses=[],this.htmlNode=$j(document.createElement("textarea")).css("height",this.options.height).addClass("et2_textbox_ro"),this.setDOMNode(this.htmlNode[0])},transformAttributes:function(_attrs){if(_attrs.mode&&jQuery.inArray(_attrs.mode,this.modes)<0){this.egw().debug("warn","'%s' is an invalid mode for htmlarea '%s'. Valid options:",_attrs.mode,_attrs.id,this.modes);for(var list=_attrs.mode.split(","),i=0;i<list.length&&i<this.legacyOptions.length;i++)_attrs[this.legacyOptions[i]]=list[i]}this._super.apply(this,arguments)},doLoadingFinished:function(){if(this._super.apply(this,arguments),"ascii"!=this.mode&&null==this.ckeditor){var self=this;this.options.imageUpload?"/"!==this.options.imageUpload[0]&&"http"!=this.options.imageUpload.substr(0,4)?(self.options.config.imageUploadUrl=egw.ajaxUrl(self.egw().getAppName()+".etemplate_widget_vfs.ajax_htmlarea_upload.etemplate")+"&request_id="+self.getInstanceManager().etemplate_exec_id+"&widget_id="+this.options.imageUpload,self.options.config.imageUploadUrl=self.options.config.imageUploadUrl.substr(egw.webserverUrl.length+1)):self.options.config.imageUploadUrl=this.options.imageUpload.substr(egw.webserverUrl.length+1):delete self.options.config.imageUploadUrl;try{this.ckeditor=CKEDITOR.replace(this.dom_id,jQuery.extend({},this.options.config,this.options)),this.ckeditor.setData(self.value),delete self.value}catch(e){CKEDITOR.instances[this.dom_id]&&CKEDITOR.instances[this.dom_id].destroy(),this.htmlNode.ckeditor&&(this.ckeditor=CKEDITOR.replace(this.dom_id,this.options.config),this.ckeditor.setData(self.value),delete self.value)}if(this.ckeditor&&this.options.config.preference_style){var editor=this.ckeditor;this.ckeditor.on("instanceReady",function(e){self.options.config.preference_style&&!e.editor.getData()&&(e.editor.document.getBody().setHtml(self.options.config.preference_style),delete self.options.config.preference_style)});var replaceImgText=function(html){var ret=html.replace(/<img[^>]*src="(data:.*;base64,.*?)"[^>]*>/gi,function(img,src){return""});return ret},chkImg=function(e){if(!editor.readOnly){self.options.imageUpload||setTimeout(function(){editor.document.$.body.innerHTML=replaceImgText(editor.document.$.body.innerHTML)},200);var supportedTypesByCKEditor=/image\/(jpeg|png|gif)/;e.data.$.dataTransfer&&!CKEDITOR.fileTools.isTypeSupported(e.data.$.dataTransfer.files[0],supportedTypesByCKEditor)&&self.getRoot().iterateOver(function(widget){return widget.options.drop_target?void widget.set_value(e.data.$.dataTransfer.files,e.data.$):void 0},e.data.$,et2_file)}};editor.on("contentDom",function(){editor.document.on("drop",chkImg),editor.document.getBody().on("drop",chkImg)})}}},destroy:function(){try{this.ckeditor&&this.ckeditor.destroy(!0),this.ckeditor=null}catch(e){this.egw().debug("warn","Removing CKEDITOR: "+e.message,this,e),delete CKEDITOR.instances[this.dom_id]}this.htmlNode.remove(),this.htmlNode=null,this._super.apply(this,arguments)},set_value:function(_value){this._oldValue=_value;try{var ckeditor=CKEDITOR.instances[this.dom_id];ckeditor?ckeditor.setData(_value):(this.htmlNode.val(_value),this.value=_value)}catch(e){this.value=_value}},getValue:function(){try{var ckeditor=CKEDITOR.instances[this.dom_id];return ckeditor?ckeditor.getData():this.htmlNode.val()}catch(e){return this.egw().debug("error",e),null}},resize:function(_height){if(_height&&"0"!==this.options.resize_ratio&&(_height=""!=this.options.resize_ratio?_height*this.options.resize_ratio:_height,0!=_height))if(this.ckeditor){var h=0;h="undefined"!=typeof this.ckeditor.container&&this.ckeditor.container.$.clientHeight>0?this.ckeditor.container.$.clientHeight+_height>0?this.ckeditor.container.$.clientHeight+_height:this.ckeditor.config.height:this.ckeditor.ui.space("contents")?parseInt(this.ckeditor.ui.space("contents").getStyle("height"))+_height:this.ckeditor.config.height+_height,this.ckeditor.resize("",h)}else this.htmlNode.height(this.htmlNode.height()+_height)}})}.call(this);et2_register_widget(et2_htmlarea,["htmlarea"]);var et2_tabbox=function(){"use strict";return et2_valueWidget.extend([et2_IInput,et2_IResizeable],{attributes:{tabs:{name:"Tabs",default:et2_no_init,description:"Array of [extra] tabs. Each tab needs {label:..., template:...}. Additional optional keys are prepend, hidden and id, for access into content array"},add_tabs:{name:"Add tabs",default:!1,description:"Set to true if tabs should be added to tabs from read from template, default false if not"},tab_height:{name:"Tabs innerHeight",default:"",description:"Set the innerHeight for the tab content"},align_tabs:{name:"Tabs alignment",type:"string",default:"h",description:"Set tabs and their headers arrangment either horizental (h) or vertical (v). Default value is horizental."}},selected_index:0,init:function(){this.container=$j(document.createElement("div")).addClass("et2_tabbox"),this.flagContainer=$j(document.createElement("div")).addClass("et2_tabheader").appendTo(this.container),this.tabContainer=$j(document.createElement("div")).addClass("et2_tabs").appendTo(this.container),this._super.apply(this,arguments),this.tabData=[]},destroy:function(){this._super.apply(this,arguments),this.container=null,this.flagContainer=null,this.tabData=[]},_readTabs:function(tabData,tabs){var selected="";this.selected_index=!1;var hidden={};if(this.id){var contentMgr=this.getArrayMgr("content");if(null!=contentMgr){var val=contentMgr.getEntry(this.id);null!==val&&(selected=val)}if(contentMgr=this.getArrayMgr("readonlys"),null!=contentMgr){var val=contentMgr.getEntry(this.id);null!==val&&"undefined"!=typeof val&&(hidden=val)}}var i=0;et2_filteredNodeIterator(tabs,function(node,nodeName){if("tab"!=nodeName)throw"Error while parsing: Invalid tag '"+nodeName+"' in tabs tag";var index_name=et2_readAttrWithDefault(node,"id"),hide=!1,widget_options={};if(index_name){selected==index_name&&(this.selected_index=i),hidden[index_name]&&(hide=!0);var classAttr=et2_readAttrWithDefault(node,"class");classAttr&&(widget_options={class:classAttr})}tabData.push({id:index_name,label:this.egw().lang(et2_readAttrWithDefault(node,"label","Tab")),widget:null,widget_options:widget_options,contentDiv:null,flagDiv:null,hidden:hide,XMLNode:null,promise:null}),i++},this);for(var i=0;i<tabData.length&&this.selected_index===!1;i++)tabData[i].hidden||(this.selected_index=i)},_readTabPanels:function(tabData,tabpanels){var i=0;et2_filteredNodeIterator(tabpanels,function(node,nodeName){if(!(i<tabData.length))throw"Error while reading tabpanels tag, too many widgets!";tabData[i].XMLNode=node,i++},this)},loadFromXML:function(_node){var tabsElems=et2_directChildrenByTagName(_node,"tabs"),tabpanelsElems=et2_directChildrenByTagName(_node,"tabpanels"),tabData=[],height=et2_readAttrWithDefault(_node.parentNode,"height",null);if(height&&this.tabContainer.css("height",height),!this.options.tabs||this.options.add_tabs)if(1==tabsElems.length&&1==tabpanelsElems.length){var tabs=tabsElems[0],tabpanels=tabpanelsElems[0];this._readTabs(tabData,tabs),this._readTabPanels(tabData,tabpanels)}else this.egw().debug("error","Error while parsing tabbox, none or multiple tabs or tabpanels tags!",this);if(this.options.tabs)for(var readonly=this.getArrayMgr("readonlys").getEntry(this.id)||{},i=0;i<this.options.tabs.length;i++){var tab=this.options.tabs[i],tab_id=tab.id||tab.template,tab_options={id:tab_id,template:tab.template,url:tab.url};tab.id&&(tab_options.content=tab.id),tabData[tab.prepend?"unshift":"push"].call(tabData,{id:tab.id,label:this.egw().lang(tab.label),widget:null,widget_options:tab_options,contentDiv:null,flagDiv:null,hidden:"undefined"!=typeof tab.hidden?tab.hidden:readonly[tab_id]||!1,XMLNode:null,promise:null})}this.createTabs(tabData)},doLoadingFinished:function(){var tab_deferred=jQuery.Deferred(),promises=[],tabs=this;return this._loadTab(this.selected_index,promises),this._super.apply(this,arguments),this._children[0].loadingFinished(promises),window.setTimeout(function(){for(var i=0;i<tabs.tabData.length;i++)i!=tabs.selected_index&&tabs._loadTab(i,promises);jQuery.when.apply(jQuery,promises).then(function(){tab_deferred.resolve()})},0),tab_deferred.promise()},_loadTab:function(index,promises){var tabData=this.tabData[index];tabData&&!tabData.loaded&&(null!=tabData.XMLNode?(tabData.widget=this.createElementFromNode(tabData.XMLNode,tabData.XMLNode.nodeName.toLowerCase()),tabData.XMLNode=null):tabData.widget_options&&(tabData.widget=et2_createWidget("template",tabData.widget_options,this)),tabData.loaded=!0)},transformAttributes:function(_attrs){this._super.apply(this,arguments);var data=this.getArrayMgr("modifications").getEntry(this.id);for(var key in data)"object"!=typeof data[key]||_attrs[key]||(_attrs[key]=data[key])},createTabs:function(tabData){this.tabData=tabData,this.tabContainer.empty(),this.flagContainer.empty();for(var i=0;i<this.tabData.length;i++){var entry=this.tabData[i];entry.flagDiv=$j(document.createElement("span")).addClass("et2_tabflag").appendTo(this.flagContainer),entry.widget_options&&"undefined"!=typeof entry.widget_options.class&&entry.flagDiv.addClass(entry.widget_options.class),entry.flagDiv.text(entry.label||"Tab"),entry.hidden?entry.flagDiv.hide():entry.flagDiv.click({tabs:this,idx:i},function(e){e.data.tabs.setActiveTab(e.data.idx)}),entry.contentDiv=$j(document.createElement("div")).addClass("et2_tabcntr").appendTo(this.tabContainer),"v"==this.options.align_tabs&&(entry.flagDiv.unbind("click"),entry.flagDiv.text(""),$j(document.createElement("div")).addClass("et2_tabtitle").text(entry.label||"Tab").click({tabs:this,idx:i},function(e){e.data.tabs.flagContainer.children(":eq("+e.data.idx+")").toggleClass("active")}).appendTo(entry.flagDiv),entry.contentDiv.appendTo(entry.flagDiv))}if("v"==this.options.align_tabs&&(this.container.addClass("vertical"),this.tabContainer.hide()),this.options.value){this.selected_index=0;for(var i=0;i<this.tabData.length;i++)if(this.tabData[i].id==this.options.value){this.selected_index=i;break}}this.setActiveTab(this.selected_index)},get_active_tab:function(){return this.selected_index},setActiveTab:function(_idx){this.selected_index=_idx,$j(".et2_tabflag",this.flagContainer).removeClass("active"),this.tabContainer.children().hide(),this.flagContainer.children(":eq("+_idx+")").addClass("active"),this.tabContainer.children(":eq("+_idx+")").show()},activateTab:function(widget){for(var tab=widget;tab._parent&&"tabbox"!=tab._parent._type;)tab=tab._parent;for(var i=(this._children.indexOf(tab),0);i<this.tabData.length;i++)if(this.tabData[i].widget==tab)return this.setActiveTab(i),!0;return!1},getDOMNode:function(_sender){if(_sender==this)return this.container[0];for(var i=0;i<this.tabData.length;i++)if(this.tabData[i].widget==_sender)return this.tabData[i].contentDiv[0];return null},set_tab_height:function(_height){this.tab_height=_height,this.tabContainer.css("height",_height)},set_height:function(_value){this.height=_value,this.tabContainer.css("height",_value)},getValue:function(){return this.tabData[this.selected_index].id},isDirty:function(){return this.selected_index!=this.value},resetDirty:function(){this.value=this.selected_index},isValid:function(messages){return!0},resize:function(_height){_height?this.set_height(this.tabContainer.height()+_height):0===_height&&this.set_height(this.tabContainer.height())}})}.call(this);et2_register_widget(et2_tabbox,["tabbox"]),function($){"use strict";var MagicSuggest=function(element,options){var ms=this,defaults={allowFreeEntries:!0,allowDuplicates:!1,ajaxConfig:{},autoSelect:!0,selectFirst:!1,queryParam:"query",beforeSend:function(){},cls:"",data:null,dataUrlParams:{},disabled:!1,disabledField:null,displayField:"name",editable:!0,expanded:!1,expandOnFocus:!1,groupBy:null,hideTrigger:!1,highlight:!0,id:null,infoMsgCls:"",inputCfg:{},invalidCls:"ms-inv",matchCase:!1,maxDropHeight:290,maxEntryLength:null,maxEntryRenderer:function(v){return"Please reduce your entry by "+v+" character"+(v>1?"s":"")},maxSuggestions:null,maxSelection:10,maxSelectionRenderer:function(v){return"You cannot choose more than "+v+" item"+(v>1?"s":"")},method:"POST",minChars:0,minCharsRenderer:function(v){return"Please type "+v+" more character"+(v>1?"s":"")},mode:"local",name:null,noSuggestionText:"No suggestions",placeholder:"Type or click here",renderer:null,required:!1,resultAsString:!1,resultAsStringDelimiter:",",resultsField:"results",selectionCls:"",selectionContainer:null,selectionPosition:"inner",selectionRenderer:null,selectionStacked:!1,sortDir:"asc",sortOrder:null,strictSuggest:!1,style:"",toggleOnClick:!1,typeDelay:400,useTabKey:!1,useCommaKey:!0,useZebraStyle:!1,value:null,valueField:"id",vregex:null,vtype:null},conf=$.extend({},options),cfg=$.extend(!0,{},defaults,conf);this.addToSelection=function(items,isSilent){if(!cfg.maxSelection||_selection.length<cfg.maxSelection){$.isArray(items)||(items=[items]);var valuechanged=!1;$.each(items,function(index,json){(cfg.allowDuplicates||-1===$.inArray(json[cfg.valueField],ms.getValue()))&&(_selection.push(json),valuechanged=!0)}),valuechanged===!0&&(self._renderSelection(),this.empty(),isSilent!==!0&&$(this).trigger("selectionchange",[this,this.getSelection()]))}this.input.attr("placeholder","inner"===cfg.selectionPosition&&this.getValue().length>0?"":cfg.placeholder)},this.clear=function(isSilent){this.removeFromSelection(_selection.slice(0),isSilent)},this.collapse=function(){cfg.expanded===!0&&(this.combobox.detach(),cfg.expanded=!1,$(this).trigger("collapse",[this]))},this.disable=function(){this.container.addClass("ms-ctn-disabled"),cfg.disabled=!0,ms.input.attr("disabled",!0)},this.empty=function(){this.input.val("")},this.enable=function(){this.container.removeClass("ms-ctn-disabled"),cfg.disabled=!1,ms.input.attr("disabled",!1)},this.expand=function(){!cfg.expanded&&(this.input.val().length>=cfg.minChars||this.combobox.children().size()>0)&&(this.combobox.appendTo(this.container),self._processSuggestions(),cfg.expanded=!0,$(this).trigger("expand",[this]))},this.isDisabled=function(){return cfg.disabled},this.isValid=function(){var valid=cfg.required===!1||_selection.length>0;return(cfg.vtype||cfg.vregex)&&$.each(_selection,function(index,item){valid=valid&&self._validateSingleItem(item[cfg.valueField])}),valid},this.getDataUrlParams=function(){return cfg.dataUrlParams},this.getName=function(){return cfg.name},this.getSelection=function(){return _selection},this.getRawValue=function(){return ms.input.val()},this.getValue=function(){return $.map(_selection,function(o){return o[cfg.valueField]})},this.removeFromSelection=function(items,isSilent){$.isArray(items)||(items=[items]);var valuechanged=!1;$.each(items,function(index,json){var i=$.inArray(json[cfg.valueField],ms.getValue());i>-1&&(_selection.splice(i,1),valuechanged=!0)}),valuechanged===!0&&(self._renderSelection(),isSilent!==!0&&$(this).trigger("selectionchange",[this,this.getSelection()]),cfg.expandOnFocus&&ms.expand(),cfg.expanded&&self._processSuggestions()),this.input.attr("placeholder","inner"===cfg.selectionPosition&&this.getValue().length>0?"":cfg.placeholder)},this.getData=function(){return _cbData},this.setData=function(data){cfg.data=data,self._processSuggestions()},this.setName=function(name){cfg.name=name,name&&(cfg.name+=name.indexOf("[]")>0?"":"[]"),ms._valueContainer&&$.each(ms._valueContainer.children(),function(i,el){el.name=cfg.name})},this.setSelection=function(items){this.clear(),this.addToSelection(items)},this.setValue=function(values){var items=[];$.each(values,function(index,value){var found=!1;if($.each(_cbData,function(i,item){return item[cfg.valueField]==value?(items.push(item),found=!0,!1):void 0}),!found)if("object"==typeof value)items.push(value);else{var json={};json[cfg.valueField]=value,json[cfg.displayField]=value,items.push(json)}}),items.length>0&&this.addToSelection(items)},this.setDataUrlParams=function(params){cfg.dataUrlParams=$.extend({},params)};var _timer,_selection=[],_comboItemHeight=0,_hasFocus=!1,_groups=null,_cbData=[],_ctrlDown=!1,_cntInMf=!1,KEYCODES={BACKSPACE:8,TAB:9,ENTER:13,CTRL:17,ESC:27,SPACE:32,UPARROW:38,DOWNARROW:40,COMMA:188},self={_displaySuggestions:function(data){ms.combobox.show(),ms.combobox.empty();var resHeight=0,nbGroups=0;if(null===_groups)self._renderComboItems(data),resHeight=_comboItemHeight*data.length;else{for(var grpName in _groups)nbGroups+=1,$("<div/>",{class:"ms-res-group",html:grpName}).appendTo(ms.combobox),self._renderComboItems(_groups[grpName].items,!0);var _groupItemHeight=ms.combobox.find(".ms-res-group").outerHeight();if(null!==_groupItemHeight){var tmpResHeight=nbGroups*_groupItemHeight;resHeight=_comboItemHeight*data.length+tmpResHeight}else resHeight=_comboItemHeight*(data.length+nbGroups)}if(resHeight<ms.combobox.height()||resHeight<=cfg.maxDropHeight?ms.combobox.height(resHeight):resHeight>=ms.combobox.height()&&resHeight>cfg.maxDropHeight&&ms.combobox.height(cfg.maxDropHeight),1===data.length&&cfg.autoSelect===!0&&ms.combobox.children().filter(":not(.ms-res-item-disabled):last").addClass("ms-res-item-active"),cfg.selectFirst===!0&&ms.combobox.children().filter(":not(.ms-res-item-disabled):first").addClass("ms-res-item-active"),0===data.length&&""!==ms.getRawValue()){var noSuggestionText=cfg.noSuggestionText.replace(/\{\{.*\}\}/,ms.input.val());self._updateHelper(noSuggestionText),ms.collapse()}cfg.allowFreeEntries===!1&&(0===data.length?($(ms.input).addClass(cfg.invalidCls),ms.combobox.hide()):$(ms.input).removeClass(cfg.invalidCls))},_getEntriesFromStringArray:function(data){var json=[];return $.each(data,function(index,s){var entry={};entry[cfg.displayField]=entry[cfg.valueField]=$.trim(s),json.push(entry)}),json},_highlightSuggestion:function(html){var q=ms.input.val(),specialCharacters=["^","$","*","+","?",".","(",")",":","!","|","{","}","[","]"];if($.each(specialCharacters,function(index,value){q=q.replace(value,"\\"+value)}),0===q.length)return html;var glob=cfg.matchCase===!0?"g":"gi";return html.replace(new RegExp("("+q+")(?!([^<]+)?>)",glob),"<em>$1</em>")},_moveSelectedRow:function(dir){cfg.expanded||ms.expand();var list,start,active,scrollPos;list=ms.combobox.find(".ms-res-item:not(.ms-res-item-disabled)"),start="down"===dir?list.eq(0):list.filter(":last"),active=ms.combobox.find(".ms-res-item-active:not(.ms-res-item-disabled):first"),active.length>0&&("down"===dir?(start=active.nextAll(".ms-res-item:not(.ms-res-item-disabled)").first(),0===start.length&&(start=list.eq(0)),scrollPos=ms.combobox.scrollTop(),ms.combobox.scrollTop(0),start[0].offsetTop+start.outerHeight()>ms.combobox.height()&&ms.combobox.scrollTop(scrollPos+_comboItemHeight)):(start=active.prevAll(".ms-res-item:not(.ms-res-item-disabled)").first(),0===start.length&&(start=list.filter(":last"),ms.combobox.scrollTop(_comboItemHeight*list.length)),start[0].offsetTop<ms.combobox.scrollTop()&&ms.combobox.scrollTop(ms.combobox.scrollTop()-_comboItemHeight))),list.removeClass("ms-res-item-active"),start.addClass("ms-res-item-active")},_processSuggestions:function(source){var json=null,data=source||cfg.data;if(null!==data){if("function"==typeof data&&(data=data.call(ms,ms.getRawValue())),"string"==typeof data){$(ms).trigger("beforeload",[ms]);var queryParams={};queryParams[cfg.queryParam]=ms.input.val();var params=$.extend(queryParams,cfg.dataUrlParams);return void $.ajax($.extend({type:cfg.method,url:data,data:params,beforeSend:cfg.beforeSend,success:function(asyncData){json="string"==typeof asyncData?JSON.parse(asyncData):asyncData,self._processSuggestions(json),$(ms).trigger("load",[ms,json]),self._asyncValues&&(ms.setValue("string"==typeof self._asyncValues?JSON.parse(self._asyncValues):self._asyncValues),self._renderSelection(),delete self._asyncValues)},error:function(){throw"Could not reach server"}},cfg.ajaxConfig))}_cbData=data.length>0&&"string"==typeof data[0]?self._getEntriesFromStringArray(data):data[cfg.resultsField]||data;var sortedData="remote"===cfg.mode?_cbData:self._sortAndTrim(_cbData);self._displaySuggestions(self._group(sortedData))}},_render:function(el){if(ms.setName(cfg.name),ms.container=$("<div/>",{class:"ms-ctn form-control "+(cfg.resultAsString?"ms-as-string ":"")+cfg.cls+($(el).hasClass("input-lg")?" input-lg":"")+($(el).hasClass("input-sm")?" input-sm":"")+(cfg.disabled===!0?" ms-ctn-disabled":"")+(cfg.editable===!0?"":" ms-ctn-readonly")+(cfg.hideTrigger===!1?"":" ms-no-trigger"),style:cfg.style,id:cfg.id}),ms.container.focus($.proxy(handlers._onFocus,this)),ms.container.blur($.proxy(handlers._onBlur,this)),ms.container.keydown($.proxy(handlers._onKeyDown,this)),ms.container.keyup($.proxy(handlers._onKeyUp,this)),ms.input=$("<input/>",$.extend({type:"text",class:cfg.editable===!0?"":" ms-input-readonly",readonly:!cfg.editable,placeholder:cfg.placeholder,disabled:cfg.disabled},cfg.inputCfg)),ms.input.focus($.proxy(handlers._onInputFocus,this)),ms.input.click($.proxy(handlers._onInputClick,this)),ms.combobox=$("<div/>",{class:"ms-res-ctn dropdown-menu"}).height(cfg.maxDropHeight),ms.combobox.on("click","div.ms-res-item",$.proxy(handlers._onComboItemSelected,this)),ms.combobox.on("mouseover","div.ms-res-item",$.proxy(handlers._onComboItemMouseOver,this)),cfg.selectionContainer?(ms.selectionContainer=cfg.selectionContainer,$(ms.selectionContainer).addClass("ms-sel-ctn")):ms.selectionContainer=$("<div/>",{class:"ms-sel-ctn"}),ms.selectionContainer.click($.proxy(handlers._onFocus,this)),"inner"!==cfg.selectionPosition||cfg.selectionContainer?ms.container.append(ms.input):ms.selectionContainer.append(ms.input),ms.helper=$("<span/>",{class:"ms-helper "+cfg.infoMsgCls}),self._updateHelper(),ms.container.append(ms.helper),$(el).replaceWith(ms.container),!cfg.selectionContainer)switch(cfg.selectionPosition){case"bottom":ms.selectionContainer.insertAfter(ms.container),cfg.selectionStacked===!0&&(ms.selectionContainer.width(ms.container.width()),ms.selectionContainer.addClass("ms-stacked"));break;case"right":ms.selectionContainer.insertAfter(ms.container),ms.container.css("float","left");break;default:ms.container.append(ms.selectionContainer)}cfg.hideTrigger===!1&&(ms.trigger=$("<div/>",{class:"ms-trigger",html:'<div class="ms-trigger-ico"></div>'}),ms.trigger.click($.proxy(handlers._onTriggerClick,this)),ms.container.append(ms.trigger)),$(window).resize($.proxy(handlers._onWindowResized,this)),null===cfg.value&&null===cfg.data||("string"==typeof cfg.data?(self._asyncValues=cfg.value,self._processSuggestions()):(self._processSuggestions(),null!==cfg.value&&(ms.setValue(cfg.value),self._renderSelection()))),$("body").click(function(e){ms.container.hasClass("ms-ctn-focus")&&0===ms.container.has(e.target).length&&e.target.className.indexOf("ms-res-item")<0&&e.target.className.indexOf("ms-close-btn")<0&&ms.container[0]!==e.target&&handlers._onBlur();
}),cfg.expanded===!0&&(cfg.expanded=!1,ms.expand())},_renderComboItems:function(items,isGrouped){var ref=this,html="";$.each(items,function(index,value){var displayed=null!==cfg.renderer?cfg.renderer.call(ref,value):value[cfg.displayField],disabled=null!==cfg.disabledField&&value[cfg.disabledField]===!0,resultItemEl=$("<div/>",{class:"ms-res-item "+(isGrouped?"ms-res-item-grouped ":"")+(disabled?"ms-res-item-disabled ":"")+(index%2===1&&cfg.useZebraStyle===!0?"ms-res-odd":""),html:cfg.highlight===!0?self._highlightSuggestion(displayed):displayed,"data-json":JSON.stringify(value)});html+=$("<div/>").append(resultItemEl).html()}),ms.combobox.append(html),_comboItemHeight=ms.combobox.find(".ms-res-item:first").outerHeight()},_renderSelection:function(){var ref=this,w=0,inputOffset=0,items=[],asText=cfg.resultAsString===!0&&!_hasFocus;ms.selectionContainer.find(".ms-sel-item").remove(),void 0!==ms._valueContainer&&ms._valueContainer.remove(),$.each(_selection,function(index,value){var selectedItemEl,delItemEl,selectedItemHtml=null!==cfg.selectionRenderer?cfg.selectionRenderer.call(ref,value):value[cfg.displayField],validCls=self._validateSingleItem(value[cfg.displayField])?"":" ms-sel-invalid";asText===!0?selectedItemEl=$("<div/>",{class:"ms-sel-item ms-sel-text "+cfg.selectionCls+validCls,html:selectedItemHtml+(index===_selection.length-1?"":cfg.resultAsStringDelimiter)}).data("json",value):(selectedItemEl=$("<div/>",{class:"ms-sel-item "+cfg.selectionCls+validCls,html:selectedItemHtml}).data("json",value),cfg.disabled===!1&&(delItemEl=$("<span/>",{class:"ms-close-btn"}).data("json",value).appendTo(selectedItemEl),delItemEl.click($.proxy(handlers._onTagTriggerClick,ref)),cfg.allowFreeEntries===!0&&selectedItemEl.dblclick($.proxy(handlers._onTagEditTriggerDblClick,ref)))),items.push(selectedItemEl)}),ms.selectionContainer.prepend(items),ms._valueContainer=$("<div/>",{style:"display: none;"}),$.each(ms.getValue(),function(i,val){var el=$("<input/>",{type:"hidden",name:cfg.name,value:val});el.appendTo(ms._valueContainer)}),ms._valueContainer.appendTo(ms.selectionContainer),"inner"!==cfg.selectionPosition||cfg.selectionContainer||(ms.input.width(0),inputOffset=ms.input.offset().left-ms.selectionContainer.offset().left,w=ms.container.width()-inputOffset-42,ms.input.width(w)),_selection.length===cfg.maxSelection?self._updateHelper(cfg.maxSelectionRenderer.call(this,_selection.length)):ms.helper.hide()},_selectItem:function(item){1===cfg.maxSelection&&(_selection=[]),ms.addToSelection(item.data("json")),item.removeClass("ms-res-item-active"),cfg.expandOnFocus!==!1&&_selection.length!==cfg.maxSelection||ms.collapse(),_hasFocus?_hasFocus&&(cfg.expandOnFocus||_ctrlDown)&&(self._processSuggestions(),_ctrlDown&&ms.expand()):ms.input.focus()},_sortAndTrim:function(data){var q=ms.getRawValue(),filtered=[],newSuggestions=[],selectedValues=ms.getValue();return q.length>0?$.each(data,function(index,obj){var name=obj[cfg.displayField];(cfg.matchCase===!0&&name.indexOf(q)>-1||cfg.matchCase===!1&&name.toLowerCase().indexOf(q.toLowerCase())>-1)&&(cfg.strictSuggest!==!1&&0!==name.toLowerCase().indexOf(q.toLowerCase())||filtered.push(obj))}):filtered=data,$.each(filtered,function(index,obj){(cfg.allowDuplicates||-1===$.inArray(obj[cfg.valueField],selectedValues))&&newSuggestions.push(obj)}),null!==cfg.sortOrder&&newSuggestions.sort(function(a,b){return a[cfg.sortOrder]<b[cfg.sortOrder]?"asc"===cfg.sortDir?-1:1:a[cfg.sortOrder]>b[cfg.sortOrder]?"asc"===cfg.sortDir?1:-1:0}),cfg.maxSuggestions&&cfg.maxSuggestions>0&&(newSuggestions=newSuggestions.slice(0,cfg.maxSuggestions)),newSuggestions},_group:function(data){return null!==cfg.groupBy&&(_groups={},$.each(data,function(index,value){var props=cfg.groupBy.indexOf(".")>-1?cfg.groupBy.split("."):cfg.groupBy,prop=value[cfg.groupBy];if("string"!=typeof props)for(prop=value;props.length>0;)prop=prop[props.shift()];void 0===_groups[prop]?_groups[prop]={title:prop,items:[value]}:_groups[prop].items.push(value)})),data},_updateHelper:function(html){ms.helper.html(html),ms.helper.is(":visible")||ms.helper.fadeIn()},_validateSingleItem:function(value){if(null!==cfg.vregex&&cfg.vregex instanceof RegExp)return cfg.vregex.test(value);if(null!==cfg.vtype)switch(cfg.vtype){case"alpha":return/^[a-zA-Z_]+$/.test(value);case"alphanum":return/^[a-zA-Z0-9_]+$/.test(value);case"email":return/^(\w+)([\-+.][\w]+)*@(\w[\-\w]*\.){1,5}([A-Za-z]){2,6}$/.test(value);case"url":return/(((^https?)|(^ftp)):\/\/([\-\w]+\.)+\w{2,3}(\/[%\-\w]+(\.\w{2,})?)*(([\w\-\.\?\\\/+@&#;`~=%!]*)(\.\w{2,})?)*\/?)/i.test(value);case"ipaddress":return/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(value)}return!0}},handlers={_onBlur:function(){if(ms.container.removeClass("ms-ctn-focus"),ms.collapse(),_cntInMf=!1,_hasFocus=!1,""!==ms.getRawValue()&&cfg.allowFreeEntries===!0){var obj={};obj[cfg.displayField]=obj[cfg.valueField]=ms.getRawValue().trim(),ms.addToSelection(obj)}self._renderSelection(),ms.isValid()===!1?ms.container.addClass(cfg.invalidCls):""!==ms.input.val()&&cfg.allowFreeEntries===!1&&(ms.empty(),self._updateHelper("")),$(ms).trigger("blur",[ms])},_onComboItemMouseOver:function(e){var target=$(e.currentTarget);target.hasClass("ms-res-item-disabled")||(ms.combobox.children().removeClass("ms-res-item-active"),target.addClass("ms-res-item-active"))},_onComboItemSelected:function(e){var target=$(e.currentTarget);target.hasClass("ms-res-item-disabled")||self._selectItem($(e.currentTarget))},_onFocus:function(){_cntInMf?_cntInMf=!1:ms.input.focus()},_onInputClick:function(){ms.isDisabled()===!1&&_hasFocus&&!_cntInMf&&cfg.toggleOnClick===!0&&(cfg.expanded?ms.collapse():ms.expand())},_onInputFocus:function(){if(ms.isDisabled()===!1&&!_hasFocus&&!_cntInMf){_hasFocus=!0,ms.container.addClass("ms-ctn-focus"),ms.container.removeClass(cfg.invalidCls);var curLength=ms.getRawValue().length;cfg.expandOnFocus===!0&&ms.expand(),_selection.length===cfg.maxSelection?self._updateHelper(cfg.maxSelectionRenderer.call(this,_selection.length)):curLength<cfg.minChars&&self._updateHelper(cfg.minCharsRenderer.call(this,cfg.minChars-curLength)),setTimeout(function(){self._renderSelection()},400),$(ms).trigger("focus",[ms])}},_onKeyDown:function(e){var active=ms.combobox.find(".ms-res-item-active:not(.ms-res-item-disabled):first"),freeInput=ms.input.val();if($(ms).trigger("keydown",[ms,e]),e.keyCode===KEYCODES.TAB&&(cfg.useTabKey===!1||cfg.useTabKey===!0&&0===active.length&&0===ms.input.val().length))return void handlers._onBlur();switch(e.keyCode){case KEYCODES.BACKSPACE:0===freeInput.length&&ms.getSelection().length>0&&"inner"===cfg.selectionPosition&&(_selection.pop(),self._renderSelection(),$(ms).trigger("selectionchange",[ms,ms.getSelection()]),ms.input.attr("placeholder","inner"===cfg.selectionPosition&&ms.getValue().length>0?"":cfg.placeholder),ms.input.focus(),e.preventDefault());break;case KEYCODES.TAB:case KEYCODES.ESC:e.preventDefault();break;case KEYCODES.ENTER:(""!==freeInput||cfg.expanded)&&e.preventDefault();break;case KEYCODES.COMMA:cfg.useCommaKey===!0&&e.preventDefault();break;case KEYCODES.CTRL:_ctrlDown=!0;break;case KEYCODES.DOWNARROW:e.preventDefault(),self._moveSelectedRow("down");break;case KEYCODES.UPARROW:e.preventDefault(),self._moveSelectedRow("up");break;default:_selection.length===cfg.maxSelection&&e.preventDefault()}},_onKeyUp:function(e){var selected,freeInput=ms.getRawValue(),inputValid=$.trim(ms.input.val()).length>0&&(!cfg.maxEntryLength||$.trim(ms.input.val()).length<=cfg.maxEntryLength),obj={};if($(ms).trigger("keyup",[ms,e]),clearTimeout(_timer),e.keyCode===KEYCODES.ESC&&cfg.expanded&&ms.combobox.hide(),e.keyCode===KEYCODES.TAB&&cfg.useTabKey===!1||e.keyCode>KEYCODES.ENTER&&e.keyCode<KEYCODES.SPACE)return void(e.keyCode===KEYCODES.CTRL&&(_ctrlDown=!1));switch(e.keyCode){case KEYCODES.UPARROW:case KEYCODES.DOWNARROW:e.preventDefault();break;case KEYCODES.ENTER:case KEYCODES.TAB:case KEYCODES.COMMA:if(e.keyCode!==KEYCODES.COMMA||cfg.useCommaKey===!0){if(e.preventDefault(),cfg.expanded===!0&&(selected=ms.combobox.find(".ms-res-item-active:not(.ms-res-item-disabled):first"),selected.length>0))return void self._selectItem(selected);inputValid===!0&&cfg.allowFreeEntries===!0&&(obj[cfg.displayField]=obj[cfg.valueField]=freeInput.trim(),ms.addToSelection(obj),ms.collapse(),ms.input.focus());break}default:_selection.length===cfg.maxSelection?self._updateHelper(cfg.maxSelectionRenderer.call(this,_selection.length)):freeInput.length<cfg.minChars?(self._updateHelper(cfg.minCharsRenderer.call(this,cfg.minChars-freeInput.length)),cfg.expanded===!0&&ms.collapse()):cfg.maxEntryLength&&freeInput.length>cfg.maxEntryLength?(self._updateHelper(cfg.maxEntryRenderer.call(this,freeInput.length-cfg.maxEntryLength)),cfg.expanded===!0&&ms.collapse()):(ms.helper.hide(),cfg.minChars<=freeInput.length&&(_timer=setTimeout(function(){cfg.expanded===!0?self._processSuggestions():ms.expand()},cfg.typeDelay)))}},_onTagTriggerClick:function(e){ms.removeFromSelection($(e.currentTarget).data("json"))},_onTagEditTriggerDblClick:function(e){var itemData=$(e.currentTarget).data("json");""===ms.input.val()&&(ms.input.val(itemData.label),ms.removeFromSelection(itemData),ms.input.select(),_cntInMf=!0)},_onTriggerClick:function(){if(ms.isDisabled()===!1&&(cfg.expandOnFocus!==!0||_selection.length!==cfg.maxSelection))if($(ms).trigger("triggerclick",[ms]),cfg.expanded===!0)ms.collapse();else{var curLength=ms.getRawValue().length;curLength>=cfg.minChars?(ms.input.focus(),ms.expand()):self._updateHelper(cfg.minCharsRenderer.call(this,cfg.minChars-curLength))}},_onWindowResized:function(){self._renderSelection()}};null!==element&&self._render(element)};$.fn.magicSuggest=function(options){var obj=$(this);return 1===obj.size()&&obj.data("magicSuggest")?obj.data("magicSuggest"):(obj.each(function(i){var cntr=$(this);if(!cntr.data("magicSuggest")){"select"===this.nodeName.toLowerCase()&&(options.data=[],options.value=[],$.each(this.children,function(index,child){child.nodeName&&"option"===child.nodeName.toLowerCase()&&(options.data.push({id:child.value,name:child.text}),$(child).attr("selected")&&options.value.push(child.value))}));var def={};$.each(this.attributes,function(i,att){def[att.name]="value"===att.name&&""!==att.value?JSON.parse(att.value):att.value});var field=new MagicSuggest(this,$.extend([],$.fn.magicSuggest.defaults,options,def));cntr.data("magicSuggest",field),field.container.data("magicSuggest",field)}}),1===obj.size()?obj.data("magicSuggest"):obj)},$.fn.magicSuggest.defaults={}}(jQuery);var et2_taglist=function(){"use strict";return et2_selectbox.extend({attributes:{empty_label:{name:"Empty label",type:"string",default:"",description:"Textual label for when nothing is selected",translate:!0},select_options:{type:"any",name:"Select options",default:{},description:"Internaly used to hold the select options."},value:{type:"any"},autocomplete_url:{name:"Autocomplete source",type:"string",default:"home.etemplate_widget_taglist.ajax_search.etemplate",description:"Menuaction (app.class.function) for autocomplete data source. Must return actual JSON, and nothing more."},autocomplete_params:{name:"Autocomplete parameters",type:"any",default:{app:"addressbook"},description:"Extra parameters passed to autocomplete URL. It should be a stringified JSON object."},allowFreeEntries:{name:"Allow free entries",type:"boolean",default:!0,description:"Restricts or allows the user to type in arbitrary entries"},onchange:{description:"Callback when tags are changed. Argument is the new selection."},onclick:{description:"Callback when a tag is clicked. The clicked tag is passed."},tagRenderer:{name:"Tag renderer",type:"js",default:et2_no_init,description:"Callback to provide a custom renderer for what's _inside_ each tag. Function parameter is the select_option data for that ID."},listRenderer:{name:"List renderer",type:"js",default:et2_no_init,description:"Callback to provide a custom renderer for each suggested item. Function parameter is the select_option data for that ID."},width:{default:"100%"},height:{description:"Maximum allowed height of the result list in pixels"},maxSelection:{name:"max Selection",type:"integer",default:null,description:"The maximum number of items the user can select if multiple selection is allowed."},multiple:{ignore:!0},rows:{ignore:!0},tags:{ignore:!0},useCommaKey:{name:"comma will start validation",type:"boolean",default:!0,description:"Set to false to allow comma in entered content"}},lib_options:{},init:function(){this._super.apply(this,arguments),this.div=jQuery("<div></div>").addClass("et2_taglist"),this.taglist=null,this.setDOMNode(this.div[0])},destroy:function(){null!=this.div,this._super.apply(this,arguments)},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),"string"==typeof _attrs.autocomplete_params)try{_attrs.autocomplete_params=JSON.parse(_attrs.autocomplete_params)}catch(e){this.egw().debug("warn","Invalid autocomplete_params: "+_attrs.autocomplete_params)}},doLoadingFinished:function(){if(this._super.apply(this,arguments),null==this.taglist){if(null!==this.options.select_options||this.options.autocomplete_url||this.set_select_options(this.getArrayMgr("sel_options").getEntry(this.id)),this.taglist=$j("<div/>").appendTo(this.div),this.taglist_options=jQuery.extend({data:this.options.autocomplete_url?this.options.autocomplete_url:this.options.select_options||{},dataUrlParams:this.options.autocomplete_params,method:"GET",displayField:"label",invalidCls:"invalid ui-state-error",placeholder:this.options.empty_label,hideTrigger:!0,noSuggestionText:this.egw().lang("No suggestions"),required:this.options.required,allowFreeEntries:this.options.allowFreeEntries,useTabKey:!0,useCommaKey:this.options.useCommaKey,disabled:this.options.disabled||this.options.readonly,editable:!(this.options.disabled||this.options.readonly),selectionRenderer:jQuery.proxy(this.options.tagRenderer||this.selectionRenderer,this),renderer:jQuery.proxy(this.options.listRenderer||this.selectionRenderer,this),maxSelection:this.options.maxSelection,maxSelectionRenderer:jQuery.proxy(function(v){this.egw().lang("You can not choose more then %1 item(s)!",v)},this),width:this.options.width,highlight:!1,selectFirst:!0},this.lib_options),this.options.height&&(this.div.css("height",""),this.taglist_options.maxDropHeight=parseInt(this.options.height)),this.taglist=this.taglist.magicSuggest(this.taglist_options),this.$taglist=$j(this.taglist),this.options.value&&this.taglist.addToSelection(this.options.value,!0),this.options.autocomplete_url&&!jQuery.isEmptyObject(this.options.select_options)){var widget=this;this.taglist.setData(function(query){return widget._data.call(widget,query)})}if(this.$taglist.on("beforeload",function(){this.container.prepend('<div class="ui-icon loading"/>')}).on("load",function(){$j(".loading",this.container).remove()}).on("selectionchange",function(){$j("input",this.container).focus()}).on("keyup.start_search",jQuery.proxy(this._keyup,this)),$j(this.getDOMNode()).unbind("change.et2_inputWidget"),this.options.onchange&&"function"==typeof this.onchange&&this.$taglist.on("selectionchange",jQuery.proxy(this.change,this)),"function"==typeof this.onclick&&this.div.unbind("click.et2_baseWidget").on("click.et2_baseWidget",".ms-sel-item",jQuery.proxy(function(event){this.click($j(event.target).parent().data("json"))},this)),"function"==typeof this.onfocus){var widget=this;this.$taglist.focus(function(e){widget.onfocus.call(widget.taglist,e,widget)})}return!0}},_options2data:function(_options){var options=jQuery.isArray(_options)?jQuery.extend({},_options):_options,data=[];for(var id in options){var option={id:id};"object"==typeof options[id]?(jQuery.extend(option,options[id]),option.value&&(option.id=option.value)):option.label=options[id],data.push(option)}return data},_data:function(query){var return_value=this.options.select_options||{};if(!jQuery.isEmptyObject(this.options.select_options)&&!this._query_server||query.trim().length<this.taglist_options.minChars||!this.options.autocomplete_url){var filtered=[],selected=this.taglist.getSelection();$j.each(this.options.select_options,function(index,obj){var name=obj.label;selected.indexOf(obj)<0&&name.toLowerCase().indexOf(query.toLowerCase())>-1&&filtered.push(obj)}),return_value=filtered.length>0?filtered:this.options.autocomplete_url}else if(query.trim().length>=this.taglist_options.minChars||this._query_server)return this.options.autocomplete_url;return this._query_server=!1,return_value},_keyup:function(e,taglist,event){return event.which===jQuery.ui.keyCode.ENTER&&0==taglist.combobox.find(".ms-res-item.ms-res-item-active").length?(event.keyCode=jQuery.ui.keyCode.DOWN,this._query_server=!0,this.taglist.collapse(),this.taglist.expand(),this._query_server=!1,this.div.find(".ms-res-item-active").removeClass("ms-res-item-active"),event.preventDefault(),!1):void 0},select_all:function(){var all=[];for(var id in this.options.select_options)all.push(id);this.set_value(all)},selectionRenderer:function(item){var label=jQuery("<span>").text(item.label);return"undefined"!=typeof item.title&&label.attr("title",item.title),label},set_autocomplete_url:function(source){if(source&&"/"!=source[0]&&0!=source.indexOf("http")&&(source=this.egw().ajaxUrl(source)),this.options.autocomplete_url!=source){if(this.options.autocomplete_url=source,null==this.taglist||!source)return;var widget=this;this.taglist.setData(function(query){return widget._data.call(widget,query)})}},set_select_options:function(_options){if(this.options.select_options=this._options2data(_options),null!=this.taglist){var widget=this;this.taglist.setData(function(query){return widget._data.call(widget,query)})}},set_disabled:function(disabled){this.options.disabled=disabled,null!=this.taglist&&(disabled?this.taglist.disable():this.taglist.enable())},set_value:function(value){""!==value&&null!==value||(value=[]);var values=jQuery.isArray(value)?jQuery.extend([],value):[value];if(!value&&this.taglist)return void this.taglist.clear(!0);for(var result=[],i=0;i<values.length;++i){var v=values[i];v&&"object"==typeof v&&"undefined"!=typeof v.id&&"undefined"!=typeof v.label||(this.options.select_options&&(result=$j.grep(this.options.select_options,function(e){return e.id==v}))||(result=$j.grep(this.taglist.getSelection(),function(e){return e.id==v}))?(null==this.options.select_options&&(this.options.select_options=[]),values[i]=result[0]?result[0]:{id:v,label:v}):"undefined"==typeof values[i].id&&(values[i]={id:v,label:v}))}this.options.value=values,null!=this.taglist&&this.taglist.setSelection(values)},getValue:function(){return null==this.taglist?null:(jQuery(this.taglist.container).trigger("blur"),this.taglist.getValue())}})}.call(this);et2_register_widget(et2_taglist,["taglist"]);var et2_taglist_account=function(){"use strict";return et2_taglist.extend({attributes:{autocomplete_url:{default:"home.etemplate_widget_taglist.ajax_search.etemplate"},allowFreeEntries:{default:!1,ignore:!0},account_type:{name:"Account type",default:"accounts",type:"string",description:"Limit type of accounts. One of {accounts,groups,both,owngroups}."}},lib_options:{minChars:2},init:function(){this._super.apply(this,arguments),this.deferred_loading=0,this.options.autocomplete_params.type="account"},set_account_type:function(value){value!=this.options.account_type&&(this.options.select_options=[]),this.options.autocomplete_params.account_type=this.options.account_type=value,this.set_select_options(this._get_accounts())},_get_accounts:function(){if(!jQuery.isArray(this.options.select_options)){var options=jQuery.extend({},this.options.select_options);this.options.select_options=[];for(var key in options)"object"==typeof options[key]?("undefined"==typeof options[key].key&&(options[key].value=key),this.options.select_options.push(options[key])):this.options.select_options.push({value:key,label:options[key]})}var type=this.egw().preference("account_selection","common"),accounts=[];return"primary_group"==type&&"accounts"!=this.options.account_type?("both"==this.options.account_type&&(accounts=this.egw().accounts("accounts")),accounts=accounts.concat(this.egw().accounts("owngroups"))):accounts=this.egw().accounts(this.options.account_type),this.options.select_options.concat(accounts)},int_reg_exp:/^-?[0-9]+$/,set_value:function(value){if(!value)return this._super.call(this,value);for(var values=jQuery.isArray(value)?jQuery.extend([],value):[value],i=0;i<values.length;++i){var v=values[i],result=[];if("object"==typeof v&&v.id===v.label&&(v=v.id),this.options.select_options&&(result=$j.grep(this.options.select_options,function(e){return e.id==v}))||(result=$j.grep(this.taglist.getSelection(),function(e){return e.id==v})))null==this.options.select_options&&(this.options.select_options=[]),values[i]=result[0]?result[0]:{id:v,label:v};else if("object"!=typeof v&&!isNaN(v)&&("string"!=typeof v||v.match(this.int_reg_exp))){v=parseInt(v);var label=this.egw().link_title("home-accounts",v);label?values[i]={id:v,label:label}:this.deferred_loading||(this.deferred_loading++,this.egw().link_title("home-accounts",v,function(label){this.deferred_loading--,label&&this.set_value(values)},this))}}this.deferred_loading<=0&&this._super.call(this,values)}})}.call(this);et2_register_widget(et2_taglist_account,["taglist-account"]);var et2_taglist_email=function(){"use strict";return et2_taglist.extend({attributes:{autocomplete_url:{default:"home.etemplate_widget_taglist.ajax_email.etemplate"},autocomplete_params:{default:{}},allowFreeEntries:{default:!0,ignore:!0},include_lists:{name:"Include lists",description:"Include mailing lists in search results",default:!1,type:"boolean"},useCommaKey:{name:"comma will start validation",type:"boolean",default:!1,description:"Set to false to allow comma in entered content"}},lib_options:{minChars:3},init:function(){this._super.apply(this,arguments),this.options.include_lists&&(this.options.autocomplete_params.include_lists=!0)},selectionRenderer:function(item){"string"==typeof item.id&&(item.id=item.id.trim()),"string"==typeof item.label&&(item.label=item.label.trim());var valid=item.id!=item.label||et2_url.prototype.EMAIL_PREG.test(item.id||"");if(!valid&&item.id){var matches=item.id.match(/^(.*) ?<(.*)>$/);if(matches&&et2_url.prototype.EMAIL_PREG.test('"'+matches[1].trim()+'" <'+matches[2].trim()+">")&&(item.id=item.label='"'+matches[1].trim()+'" <'+matches[2].trim()+">",valid=!0),!valid){var parts=item.id.split(/, */);if(parts.length>1){valid=!0;for(var i=0;i<parts.length;++i)if(parts[i]=parts[i].trim(),!et2_url.prototype.EMAIL_PREG.test(parts[i])){valid=!1;break}if(valid){item.id=item.label=parts.shift();var taglist=this.taglist;window.setTimeout(function(){for(var items=[],i=0;i<parts.length;++i)items.push({id:parts[i],label:parts[i]});taglist.addToSelection(items)},10)}}}}var label=jQuery("<span>").text(item.label);return item.class&&label.addClass(item.class),"undefined"!=typeof item.title&&label.attr("title",item.title),"undefined"!=typeof item.data&&label.attr("data",item.data),valid?label:(label.addClass("ui-state-error"),window.setTimeout(jQuery.proxy(function(){this.taglist.removeFromSelection(item),this.set_validation_error(egw.lang("'%1' has an invalid format",item.label)),this.taglist.input.val(item.label).focus()},this),1),null)}})}.call(this);et2_register_widget(et2_taglist_email,["taglist-email"]);var et2_taglist_category=function(){"use strict";return et2_taglist.extend({attributes:{autocomplete_url:{default:""},autocomplete_params:{default:{}},allowFreeEntries:{default:!1,ignore:!0}},lib_options:{toggleOnClick:!0},init:function(){this._super.apply(this,arguments),this.div.addClass("et2_taglist_category")},transformAttributes:function(_attrs){var type=this._type;this._type="select-cat",this._super.apply(this,arguments),this._type=type},_options2data:function(_options){var options=jQuery.isArray(_options)?jQuery.extend({},_options):_options,data=[];for(var id in options){var option={};"object"==typeof options[id]?(jQuery.extend(option,options[id]),option.value&&(option.id=option.value)):option.label=options[id],data.push(option)}return data},selectionRenderer:function(item){var label=jQuery("<span>").text(item.label);return item.class&&label.addClass(item.class),jQuery('<span class="cat_'+item.id+'"/>').prependTo(label),"undefined"!=typeof item.title&&label.attr("title",item.title),"undefined"!=typeof item.data&&label.attr("data",item.data),label}})}.call(this);et2_register_widget(et2_taglist_category,["taglist-cat"]);var et2_taglist_ro=function(){"use strict";return et2_selectbox_ro.extend({init:function(){this._super.apply(this,arguments),this.span=jQuery("<div><ul /></div>").addClass("et2_taglist_ro"),this.setDOMNode(this.span[0]),this.span=$j("ul",this.span).addClass("ms-sel-ctn")},set_value:function(_value){this._super.apply(this,arguments),$j("li",this.span).addClass("ms-sel-item")}})}.call(this);et2_register_widget(et2_taglist_ro,["taglist_ro","taglist_email_ro","taglist_account_ro"]),"function"==typeof egw&&egw(window).includeCSS(egw.webserverUrl+"/phpgwapi/js/jquery/magicsuggest/magicsuggest.css");var et2_toolbar=function(){"use strict";return et2_DOMWidget.extend([et2_IInput],{attributes:{view_range:{name:"View range",type:"string",default:"5",description:"Define minimum action view range to show actions by both icons and caption"},flat_list:{name:"Flat list",type:"boolean",default:!0,description:"Define whether the actions with children should be shown as dropdown or flat list"}},default_toolbar:{view:{caption:"View",icons:{primary:"ui-icon-check"},group:1,toolbarDefault:!0},edit:{caption:"Edit",group:1,toolbarDefault:!0},save:{caption:"Save",group:2,toolbarDefault:!0}},value:null,init:function(){this._super.apply(this,arguments),this.div=$j(document.createElement("div")).addClass("et2_toolbar ui-widget-header ui-corner-all"),this.set_id(this.id),this.actionbox=$j(document.createElement("div")).addClass("et2_toolbar_more").attr("id",this.id+"-actionbox"),this.actionlist=$j(document.createElement("div")).addClass("et2_toolbar_actionlist").attr("id",this.id+"-actionlist"),this.countActions=0,this.dropdowns={},this.preference={},this._build_menu(this.default_toolbar,!0)},destroy:function(){this.div&&this.div.data("ui-menu")&&this.menu.menu("destroy"),this.div.empty().remove(),this.actionbox.empty().remove(),this.actionlist.empty().remove()},_fix_preference:function(_action){if("mail-display_displayToolbar"===this.dom_id||"mail-index_toolbar"===this.dom_id)switch(_action.id){case"read":case"label1":case"label2":case"label3":case"label4":case"label5":this.set_prefered(_action.id,!_action.toolbarDefault);break;default:this.set_prefered(_action.id,!1)}else this.set_prefered(_action.id,!1)},_build_menu:function(actions,isDefault){this.div.empty(),this.actionbox.empty(),this.actionlist.empty(),this.actionbox.append('<h class="ui-toolbar-menulistHeader">'+egw.lang("more")+" ...</h>"),this.actionbox.append('<div id="'+this.id+'-menulist" class="ui-toolbar-menulist" ></div>');var that=this,pref=egwIsMobile()?void 0:egw.preference(this.dom_id,this.egw().getAppName());if(pref&&!jQuery.isArray(pref)&&(this.preference=pref),"undefined"!=typeof pref||isDefault){if(!isDefault)for(var name in actions)"undefined"!=typeof actions[name].children&&this.options.flat_list||"undefined"!=typeof pref[name]||this._fix_preference(actions[name])}else for(var name in actions)"undefined"!=typeof actions[name].children&&this.options.flat_list||!actions[name].id||this.set_prefered(actions[name].id,!actions[name].toolbarDefault);var countActions=function(actions){var totalCount=0,childCounter=function(action,count){var children=action.children||0,returnCounter=count||0;if(children){returnCounter-=1;for(var nChild in children)returnCounter+=1;returnCounter=childCounter(children[nChild],returnCounter)}else returnCounter=count;return returnCounter};for(var nAction in actions)that.flat_list?totalCount+=childCounter(actions[nAction],1):totalCount++;return totalCount},menuLen=0;for(var key in this.preference)this.preference[key]&&menuLen++;this.countActions=countActions(actions)-menuLen;var last_group=!1,last_group_id=!1;for(var name in actions){var action=actions[name];if("string"==typeof action&&(action={id:name,caption:action}),last_group_id!=action.group&&(last_group=$j('[data-group="'+action.group+'"]',this.actionlist),0==last_group.length&&$j('<span data-group="'+action.group+'">').appendTo(this.actionlist),last_group_id=action.group),action.caption||action.icon||action.iconUrl)if(action.children){var children={},add_children=function(root,children){for(var id in root.children){var info={id:id||root.children[id].id,label:root.children[id].caption},childaction={};root.children[id].iconUrl&&(info.icon=root.children[id].iconUrl),root.children[id].children&&add_children(root.children[id],info),children[id]=info,that.flat_list&&(childaction=root.children[id],"undefined"!=typeof pref||isDefault?isDefault||"undefined"==typeof pref[childaction.id]&&that._fix_preference(childaction):childaction.toolbarDefault?that.set_prefered(childaction.id,!1):that.set_prefered(childaction.id,!0),"undefined"!=typeof root.children[id].group&&"undefined"!=typeof root.group&&(childaction.group=root.group),that._make_button(childaction))}};if(add_children(action,children),this.flat_list&&children)continue;var dropdown=et2_createWidget("dropdown_button",{id:action.id},this);if(dropdown.set_select_options(children),dropdown.set_label(action.caption),"undefined"!=typeof action.children)for(var child in action.children)action.children[child].default&&dropdown.set_label(action.children[child].caption);dropdown.set_image(action.iconUrl||""),dropdown.onchange=jQuery.proxy(function(selected,dropdown){var action=that._actionManager.getActionById(selected.attr("data-id"));dropdown.set_label(action.caption),action&&(this.value=action.id,action.execute([]))},action),dropdown.onclick=jQuery.proxy(function(selected,dropdown){var action=that._actionManager.getActionById(this.getValue());action&&(this.value=action.id,action.execute([]))},dropdown),$j(dropdown.getDOMNode()).attr("id",this.id+"-"+dropdown.id).addClass(this.preference[action.id]?"et2_toolbar-dropdown et2_toolbar-dropdown-menulist":"et2_toolbar-dropdown").appendTo(this.preference[action.id]?this.actionbox.children()[1]:$j("[data-group="+action.group+"]",this.actionlist))}else this._make_button(action)}this.actionlist.find("span[data-group]").sort(function(lg,g){return+lg.getAttribute("data-group")-+g.getAttribute("data-group")}).appendTo(this.actionlist),this.actionlist.appendTo(this.div),this.actionbox.appendTo(this.div);var toolbar=this.actionlist.find("span[data-group]").children(),toolbox=this.actionbox,menulist=jQuery(this.actionbox.children()[1]);toolbar.draggable({cancel:!0,zIndex:1e3,delay:500,containment:"document",cursor:"move",helper:"clone",appendTo:"body",stop:function(event,ui){that._build_menu(actions)}}),menulist.children().draggable({cancel:!0,containment:"document",helper:"clone",appendTo:"body",zIndex:1e3,cursor:"move",start:function(){jQuery(that.actionlist).addClass("et2_toolbarDropArea")},stop:function(){jQuery(that.actionlist).removeClass("et2_toolbarDropArea")}}),toolbox.children().droppable({accept:toolbar,drop:function(event,ui){that.set_prefered(ui.draggable.attr("id").replace(that.id+"-",""),!0),ui.draggable.appendTo(menulist),0==that.actionlist.find(".ui-draggable").length&&(that.preference={},egw.set_preference(that.egw().getAppName(),that.dom_id,that.preference))},tolerance:"touch"}),this.actionlist.droppable({tolerance:"pointer",drop:function(event,ui){that.set_prefered(ui.draggable.attr("id").replace(that.id+"-",""),!1),ui.draggable.appendTo(that.actionlist),that._build_menu(actions)}}),toolbox.accordion({heightStyle:"fill",collapsible:!0,active:"none",activate:function(event,ui){var menubox=event.target;0==ui.oldHeader.length&&$j("html").on("click.outsideOfMenu",function(event){
$j(menubox).accordion("option","active",2),$j(this).unbind(event),$j(menubox).children().removeClass("ui-state-focus")})},create:function(event,ui){$j("html").unbind("click.outsideOfMenu")},beforeActivate:function(){return 0==menulist.children().length?!1:void 0}})},set_prefered:function(_action,_state){this.preference[_action]=_state,egwIsMobile()||egw.set_preference(this.egw().getAppName(),this.dom_id,this.preference)},_make_button:function(action){var button_options={},button=$j(document.createElement("button")).addClass("et2_button et2_button_text et2_button_with_image").attr("id",this.id+"-"+action.id).attr("title",action.hint?action.hint:action.caption).attr("type","button").appendTo(this.preference[action.id]?this.actionbox.children()[1]:$j("[data-group="+action.group+"]",this.actionlist));if(action&&action.checkbox)if(action.data.toggle_on||action.data.toggle_off){var toggle=et2_createWidget("checkbox",{id:this.id+"-"+action.id,toggle_on:action.data.toggle_on,toggle_off:action.data.toggle_off},this);toggle.doLoadingFinished(),toggle.set_value(action.checked),action.data.widget=toggle,toggle=toggle.toggle,toggle.appendTo(button.parent()).attr("id",this.id+"-"+action.id),button.remove(),button=toggle}else this.checkbox(action.id)&&button.addClass("toolbar_toggled"+("undefined"!=typeof action.toggledClass?" "+action.toggledClass:""));action.iconUrl&&button.attr("style","background-image:url("+action.iconUrl+")"),action.caption&&(!(this.countActions<=parseInt(this.options.view_range)||this.preference[action.id])&&action.iconUrl||"undefined"==typeof button[0]||action.checkbox&&action.data&&(action.data.toggle_on||action.data.toggle_off)||(button.addClass(action.iconUrl?"et2_toolbar_hasCaption":"et2_toolbar_onlyCaption"),button[0].textContent=action.caption)),action.icon&&(button_options.icon=action.icon),jQuery.isEmptyObject(button_options)||button.button(button_options);var self=this,click=function(e){var action=this._actionManager.getActionById(e.data);action&&(action.checkbox&&self.checkbox(action.id,!action.checked),this.value=action.id,action.data.event=e,action.execute([]))};button.click(action.id,jQuery.proxy(click,this))},_link_actions:function(actions){this._build_menu(actions)},checkbox:function(_action,_value){if(_action&&"undefined"!=typeof this._actionManager){var action_event=this._actionManager.getActionById(_action);if(!action_event||"undefined"==typeof _value)return action_event?action_event.checked:void 0;action_event.set_checked(_value);var btn=jQuery("#"+this.id+"-"+_action);action_event.data&&action_event.data.widget?action_event.data.widget.set_value(_value):btn.length>0&&btn.toggleClass("toolbar_toggled"+("undefined"!=typeof action_event.data.toggledClass?" "+action_event.data.toggledClass:""))}},getDOMNode:function(asker){return this.div[0]},getValue:function(){return this.value},isDirty:function(){return null!=this.value},resetDirty:function(){this.value=null},isValid:function(messages){return!0},doLoadingFinished:function(){return this._super.apply(this,arguments),!1}})}.call(this);et2_register_widget(et2_toolbar,["toolbar"]);var et2_tree=function(){"use strict";return et2_inputWidget.extend({attributes:{multiple:{name:"multiple",type:"boolean",default:!1,description:"Allow selecting multiple options"},select_options:{type:"any",name:"Select options",default:{},description:"Used to set the tree options."},onclick:{description:"JS code which gets executed when clicks on text of a node"},onselect:{name:"onSelect",type:"js",default:et2_no_init,description:"Javascript executed when user selects a node"},oncheck:{name:"onCheck",type:"js",default:et2_no_init,description:"Javascript executed when user checks a node"},onopenstart:{name:"onOpenStart",type:"js",default:et2_no_init,description:"Javascript function executed when user opens a node: function(_id, _widget, _hasChildren) returning true to allow opening!"},onopenend:{name:"onOpenEnd",type:"js",default:et2_no_init,description:"Javascript function executed when opening a node is finished: function(_id, _widget, _hasChildren)"},image_path:{name:"Image directory",type:"string",default:this.egw().webserverUrl+"/phpgwapi/templates/default/images/dhtmlxtree/",description:"Directory for tree structure images, set on server-side to 'dhtmlx' subdir of templates image-directory"},value:{type:"any",default:{}},actions:{name:"Actions array",type:"any",default:et2_no_init,description:"List of egw actions that can be done on the tree. This includes context menu, drag and drop. TODO: Link to action documentation"},autoloading:{name:"Autoloading",type:"string",default:"",description:"JSON URL or menuaction to be called for nodes marked with child=1, but not having children, GET parameter selected contains node-id"},std_images:{name:"Standard images",type:"string",default:"",description:"comma-separated names of icons for a leaf, closed and opend folder (default: leaf.png,folderClosed.png,folderOpen.png), images with extension get loaded from image_path, just 'image' or 'appname/image' are allowed too"},multimarking:{name:"multimarking",type:"any",default:!1,description:"Allow marking multiple nodes, default is false which means disabled multiselection, true or 'strict' activates it and 'strict' makes it strick to only same level marking"},highlighting:{name:"highlighting",type:"boolean",default:!1,description:"Add highlighting class on hovered over item, highlighting is disabled by default"}},init:function(){this._super.apply(this,arguments),this.input=null,this.div=$j(document.createElement("div")).addClass("dhtmlxTree"),this.setDOMNode(this.div[0])},destroy:function(){this.input&&this.input.destructor(),this.input=null,this._super.apply(this,arguments)},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),!this.options||!this.options.select_options||jQuery.isEmptyObject(this.options.select_options)){var name_parts=this.id.replace(/]/g,"").split("[");if(this.getArrayMgr("sel_options")){var content_options=this.getArrayMgr("sel_options").getRoot().getEntry(name_parts[name_parts.length-1]);content_options||(content_options=this.getArrayMgr("sel_options").getEntry(this.id)),_attrs.select_options&&!jQuery.isEmptyObject(_attrs.select_options)&&content_options?_attrs.select_options=jQuery.extend({},_attrs.select_options,content_options):content_options&&(_attrs.select_options=content_options)}if(null==_attrs.select_options){var content_options=this.getArrayMgr("content").getRoot().getEntry(name_parts[name_parts.length-1]);_attrs.select_options=content_options?content_options:this.getArrayMgr("content").getEntry("options-"+this.id)}null==_attrs.select_options&&(_attrs.select_options={})}},click:function(_node){},createTree:function(widget){if(widget.input=new dhtmlXTreeObject({parent:widget.div[0],width:"100%",height:"100%",image_path:widget.options.image_path,checkbox:widget.options.multiple}),widget.input.dlmtr=":}-*(",widget.options.std_images?widget.setImages.apply(widget,widget.options.std_images.split(",")):widget.setImages(),widget.input.AJAX_callback=function(dxmlObject){widget._dhtmlxtree_json_callback(JSON.parse(dxmlObject.xmlDoc.responseText),widget.input.lastLoadedXMLId),widget.options.multiple&&widget.set_value(widget.value)},widget.options.autoloading){var url=widget.options.autoloading;widget.input.setEscapingMode("utf8"),"/"!=url.charAt(0)&&"http"!=url.substr(0,4)&&(url="/json.php?menuaction="+url),this.autoloading_url=url,widget.input.setXMLAutoLoading(egw.link(url)),widget.input.setDataMode("JSON")}widget.options.multimarking&&widget.input.enableMultiselection(!!widget.options.multimarking,"strict"===widget.options.multimarking),widget.input.enableHighlighting(!!widget.options.highlighting);var open=egw.image("dhtmlxtree/open"),close=egw.image("dhtmlxtree/close");open&&close&&(widget.input.enableTreeLines(!1),open=this._rel_url(open),widget.input.setImageArrays("plus",open,open,open,open,open),close=this._rel_url(close),widget.input.setImageArrays("minus",close,close,close,close,close))},_install_handler:function(_name,_handler){if("function"==typeof _handler){null==this.input&&this.createTree(this),"onchange"==_name&&(_name=this.options.multiple?"oncheck":"onselect");var handler=_handler,widget=this;this.input.attachEvent(_name,function(_id){var args=jQuery.makeArray(arguments);return args.splice(1,0,widget),handler.apply(this,args)})}},set_onchange:function(_handler){this._install_handler("onchange",_handler)},set_onclick:function(_handler){this._install_handler("onclick",_handler)},set_onselect:function(_handler){this._install_handler("onselect",_handler)},set_onopenstart:function(_handler){this._install_handler("onOpenStart",_handler)},set_onopenend:function(_handler){this._install_handler("onOpenEnd",_handler)},set_select_options:function(options){var custom_images=!1;if(this.options.select_options=options,null==this.input&&this.createTree(this),"tree-cat"==this._type){for(var data={id:0,item:[]},stack={},key=0;key<options.length;key++){if(options[key].data&&"undefined"!=typeof options[key].data.icon&&options[key].data.icon){var img=this.egw().image(options[key].data.icon,options[key].appname);img&&(custom_images=!0,options[key].im0=options[key].im1=options[key].im2=img)}options[key].data&&"undefined"!=typeof options[key].data.color&&options[key].data.color&&(options[key].style=options[key].style||"background-color:'"+options[key].data.color+"';"),options[key].description&&!options[key].tooltip&&(options[key].tooltip=options[key].description);var parent_id=parseInt(options[key].parent);isNaN(parent_id)&&(parent_id=0),stack[parent_id]||(stack[parent_id]=[]),stack[parent_id].push(options[key])}if(custom_images){var path=this.input.iconURL;this.input.setIconPath("");for(var k=0;k<this.input.imageArray.length;k++)this.input.imageArray[k]=path+this.input.imageArray[k]}var f=function(data,f){if(stack[data.id]){data.item=stack[data.id];for(var j=0;j<data.item.length;j++)f(data.item[j],f)}};f(data,f),options=data}"undefined"==typeof options.id&&this.input.XMLsource?this.input.loadJSON(this.input.XMLsource):this.input.loadJSONObject(this._htmlencode_node(options))},_lt_regexp:/</g,_htmlencode:function(_text){return _text&&_text.indexOf("<")>=0&&(_text=_text.replace(this._lt_regexp,"&lt;")),_text},_htmlencode_node:function(_item){if(_item.text=this._htmlencode(_item.text),_item.item&&jQuery.isArray(_item.item))for(var i=0;i<_item.item.length;++i)this._htmlencode_node(_item.item[i]);return _item},set_value:function(new_value){if(this.value=this._oldValue="string"==typeof new_value&&this.options.multiple?new_value.split(","):new_value,null!=this.input)if(this.options.multiple){for(var checked=this.input.getAllChecked().split(this.input.dlmtr),i=0;i<checked.length;i++)this.input.setCheck(checked[i],!1);for(var i=0;i<this.value.length;i++)this.input.setCheck(this.value[i],!0),this.options.autoloading||this.input.openItem(this.value[i])}else this.input.selectItem(this.value,!1),this.input.focusItem(this.value),this.input.openItem(this.value)},_link_actions:function(actions){var objectManager=egw_getObjectManager(this.egw().appName,!0,1),treeObj=objectManager.getObjectById(this.id);null==treeObj&&(treeObj=objectManager.addObject(new egwActionObject(this.id,objectManager,null,this._actionManager,EGW_AO_FLAG_IS_CONTAINER),null,EGW_AO_FLAG_IS_CONTAINER)),treeObj.clear();var action_links=this._get_action_links(actions);if("undefined"!=typeof this.options.select_options){var apply_actions=function(treeObj,option){var obj=treeObj.addObject("number"==typeof option.id?String(option.id):option.id,new dhtmlxtreeItemAOI(this.input,option.id));if(obj.updateActionLinks(action_links),option.item&&option.item.length>0)for(var i=0;i<option.item.length;i++)apply_actions.call(this,treeObj,option.item[i])};apply_actions.call(this,treeObj,this.options.select_options)}},getValue:function(){if(null==this.input)return null;if(this.options.multiple){var allChecked=this.input.getAllChecked().split(this.input.dlmtr),allUnchecked=this.input.getAllUnchecked().split(this.input.dlmtr);if(this.options.autoloading){for(var res={},i=0;i<allChecked.length;i++)res[allChecked[i]]={value:!0};for(var i=0;i<allUnchecked.length;i++)res[allUnchecked[i]]={value:!1};return res}return allChecked}return this.input.getSelectedItemId()},getSelectedLabel:function(){return null==this.input?null:this.options.multiple?null:this.input.getSelectedItemText()},renameItem:function(_id,_newItemId,_label){if(null==this.input)return null;this.input.changeItemId(_id,_newItemId);for(var treeObj=egw_getAppObjectManager().getObjectById(this.id),i=0;i<treeObj.children.length;i++)if(treeObj.children[i].id==_id){treeObj.children[i].id=_newItemId,treeObj.children[i].iface&&(treeObj.children[i].iface.id=_newItemId);break}"undefined"!=typeof _label&&this.setLabel(_newItemId,_label)},deleteItem:function(_id,_selectParent){if(null==this.input)return null;this.input.deleteItem(_id,_selectParent);for(var treeObj=egw_getAppObjectManager().getObjectById(this.id),i=0;i<treeObj.children.length;i++)treeObj.children[i].id==_id&&treeObj.children.splice(i,1)},refreshItem:function(_id,data){if(null==this.input)return null;this.input.deleteChildItems(_id),this.input.setDataMode("JSON");var self=this;"undefined"!=typeof data&&null!=data?this.input.loadJSONObject(data,function(){self._dhtmlxtree_json_callback(data,_id)}):this.input.loadJSON(this.egw().link(this.autoloading_url,{id:_id}),function(dxmlObject){self._dhtmlxtree_json_callback(JSON.parse(dxmlObject.xmlDoc.responseText),_id)})},focusItem:function(_id){return null==this.input?null:void this.input.focusItem(_id)},hasChildren:function(_id){return null==this.input?null:this.input.hasChildren(_id)},_dhtmlxtree_json_callback:function(new_data,update_option_id){var parent_id="undefined"!=typeof update_option_id&&-1!=update_option_id?update_option_id:new_data.id,option=this._find_in_item(parent_id,this.options.select_options);option?jQuery.extend(option,new_data||{}):this.options.select_options=new_data,this.set_actions(this.options.actions||{})},_find_in_item:function(_id,_item){if(_item&&_item.id==_id)return _item;if(_item&&"undefined"!=typeof _item.item)for(var i=0;i<_item.item.length;++i){var found=this._find_in_item(_id,_item.item[i]);if(found)return found}return null},getNode:function(_id){return this._find_in_item(_id,this.options.select_options)},setLabel:function(_id,_label){return null==this.input?null:void this.input.setItemText(_id,this._htmlencode(_label))},setStyle:function(_id,_style){return null==this.input?null:void this.input.setItemStyle(_id,_style)},getLabel:function(_id){return null==this.input?null:this.input.getItemText(_id)},getSelectedNode:function(){return null==this.input?null:this.options.multiple?null:this.input._selected[0]},getTreeNodeOpenItems:function(_nodeID,mode){if(null==this.input)return null;var oS,PoS,rv,z=this.input.getSubItems(_nodeID).split(this.input.dlmtr),returnValue=[_nodeID],modetorun="none";if(mode&&(modetorun=mode),PoS=this.input.getOpenState(_nodeID),"forced"==modetorun&&(PoS=1),1==PoS)for(var i=0;i<z.length;i++)if(oS=this.input.getOpenState(z[i]),-1==oS&&returnValue.push(z[i]),0==oS&&returnValue.push(z[i]),1==oS){rv=this.getTreeNodeOpenItems(z[i]);for(var j=0;j<rv.length;j++)returnValue.push(rv[j])}return returnValue},getUserData:function(_nodeId,_name){return null==this.input?null:this.input.getUserData(_nodeId,_name)},setUserData:function(_nodeId,_name,_value){return null==this.input?null:this.input.setUserData(_nodeId,_name,_value)},openItem:function(_id,_open){if(null==this.input)return null;var is_open=1==this.input.getOpenState(_id);return"undefined"!=typeof _open&&is_open!==_open&&(is_open?this.input.closeItem(_id):this.input.openItem(_id)),is_open},reSelectItem:function(_id){return null==this.input?null:void this.input.selectItem(_id,!1,!1)},setImages:function(_leaf,_closed,_open,_id){for(var images=[_leaf||"dhtmlxtree/leaf",_closed||"dhtmlxtree/folderClosed",_open||"dhtmlxtree/folderOpen"],image_extensions=/\.(gif|png|jpe?g|svg)/i,i=0;3>i;++i){var image=images[i];image.match(image_extensions)||(images[i]=this._rel_url(this.egw().image(image)||image))}"undefined"==typeof _id?this.input.setStdImages.apply(this.input,images):(images.unshift(_id),this.input.setItemImage2.apply(this.input,images))},setSubChecked:function(_id,_state){"toggle"===_state&&(_state=!this.input.isItemChecked(_id)),this.input.setSubChecked(_id,_state)},_rel_url:function(_url){var path_parts=this.options.image_path.split(this.egw().webserverUrl);path_parts=path_parts[1].split("/");var url_parts=_url.split(this.egw().webserverUrl);url_parts=url_parts[1].split("/");for(var i=0;i<path_parts.length;++i){if(path_parts[i]!=url_parts[i]){for(;++i<path_parts.length;)url_parts.unshift("..");break}url_parts.shift()}return url_parts.join("/")}})}.call(this);et2_register_widget(et2_tree,["tree","tree-cat"]);var et2_historylog=function(){"use strict";return et2_valueWidget.extend([et2_IDataProvider,et2_IResizeable],{createNamespace:!0,attributes:{value:{name:"Value",type:"any",description:"Object {app: ..., id: ..., status-widgets: {}} where status-widgets is a map of fields to widgets used to display those fields"},status_id:{name:"status_id",type:"string",default:"status",description:"The history widget is traditionally named 'status'. If you name another widget in the same template 'status', you can use this attribute to re-name the history widget. "}},legacyOptions:["status_id"],columns:[{id:"user_ts",caption:"Date",width:"120px",widget_type:"date-time"},{id:"owner",caption:"User",width:"150px",widget_type:"select-account"},{id:"status",caption:"Changed",width:"120px",widget_type:"select"},{id:"new_value",caption:"New Value",width:"50%"},{id:"old_value",caption:"Old Value",width:"50%"}],TIMESTAMP:0,OWNER:1,FIELD:2,NEW_VALUE:3,OLD_VALUE:4,init:function(){this._super.apply(this,arguments),this.div=$j(document.createElement("div")).addClass("et2_historylog"),this.innerDiv=$j(document.createElement("div")).appendTo(this.div)},set_status_id:function(_new_id){this.options.status_id=_new_id},doLoadingFinished:function(){this._super.apply(this,arguments);var tabs=this;do tabs=tabs._parent;while(tabs!=this.getRoot()&&"tabbox"!=tabs._type);if(tabs!=this.getRoot()){for(var i=0;i<tabs.tabData.length;i++)if(tabs.tabData[i].contentDiv.has(this.div).length){var handler=function(e){e.data.div.unbind("click.history"),e.data.div.bind("click.history",{history:e.data.history,div:tabs.tabData[i].flagDiv},function(e){e.data.history.dynheight.update(function(_w,_h){e.data.history.dataview.resize(_w,_h)})}),"undefined"==typeof e.data.history.dataview&&e.data.history.finishInit(),e.data.history.dynheight.update(function(_w,_h){e.data.history.dataview.resize(_w,_h)})};tabs.tabData[i].flagDiv.bind("click.history",{history:this,div:tabs.tabData[i].flagDiv},handler),i==tabs.get_active_tab()&&"undefined"==typeof this.dataview&&tabs.tabData[i].flagDiv.trigger("click.history");break}}else this.finishInit()},finishInit:function(){if(this.options.value&&this.options.value.id){this._filters={record_id:this.options.value.id,appname:this.options.value.app,get_rows:"historylog::get_rows"},this.dynheight=new et2_dynheight(this.div.parent(),this.innerDiv,250),this.dataview=new et2_dataview(this.innerDiv,this.egw());for(var dataview_columns=[],i=0;i<this.columns.length;i++)dataview_columns[i]={id:this.columns[i].id,caption:this.columns[i].caption,width:this.columns[i].width};this.dataview.setColumns(dataview_columns),this.createWidgets();var linkCallback=function(){};this.controller=new et2_dataview_controller(null,this.dataview.grid,this,this.rowCallback,linkCallback,this,null),this.controller.update();for(var i=0;i<this.columns.length;i++)$j(this.dataview.getHeaderContainerNode(i)).text(this.columns[i].caption);var self=this;$j(window).on("resize."+this.options.value.app+this.options.value.id,function(){self&&"undefined"!=typeof self.dynheight&&self.dynheight.update(function(_w,_h){self.dataview.resize(_w,_h)})})}},destroy:function(){this.options.value&&!this.options.value.id&&$j(window).off("."+this.options.value.app+this.options.value.id);for(var i=0;i<this.columns.length;i++)this.columns[i].widget&&this.columns[i].widget.destroy();for(var key in this.fields)this.fields[key].widget.destroy();this.diff&&this.diff.widget.destroy(),this.dataview&&this.dataview.free(),this.rowProvider&&this.rowProvider.free(),this.controller&&this.controller.free(),this.dynheight&&this.dynheight.free(),this._super.apply(this,arguments)},createWidgets:function(){for(var i=0;i<this.columns.length;i++)if(this.columns[i].widget_type){var attrs={readonly:!0,id:i==this.FIELD?this.options.status_id:this.columns[i].id};this.columns[i].widget=et2_createWidget(this.columns[i].widget_type,attrs,this),this.columns[i].widget.transformAttributes(attrs),this.columns[i].nodes=$j(this.columns[i].widget.getDetachedNodes())}"undefined"==typeof this.options.value["status-widgets"]["~link~"]&&(this.columns[this.FIELD].widget.optionValues["~link~"]=this.egw().lang("link"),this.options.value["status-widgets"]["~link~"]="link"),"undefined"==typeof this.options.value["status-widgets"]["~file~"]&&(this.columns[this.FIELD].widget.optionValues["~file~"]=this.egw().lang("File"),this.options.value["status-widgets"]["~file~"]="vfs"),"undefined"==typeof this.options.value["status-widgets"].user_agent_action&&(this.columns[this.FIELD].widget.optionValues.user_agent_action=this.egw().lang("User-agent & action")),this.fields={};var labels=this.columns[this.FIELD].widget.optionValues,cf_widget=et2_createWidget("customfields",{readonly:!0},this);cf_widget.loadFields(),cf_widget.getValue=function(){return null};for(var key in cf_widget.widgets)if(labels[cf_widget.prefix+key]=cf_widget.options.customfields[key].label,cf_widget.widgets[key].getDetachedNodes){for(var nodes=cf_widget.widgets[key].getDetachedNodes(),i=0;i<nodes.length;i++)null==nodes[i]&&nodes.splice(i,1);this.fields[cf_widget.prefix+key]={attrs:cf_widget.widgets[key].options,widget:cf_widget.widgets[key],nodes:jQuery(nodes)}}this.columns[this.FIELD].widget.set_select_options(labels);for(var key in this.options.value["status-widgets"]){var field=this.options.value["status-widgets"][key],attrs={readonly:!0,id:key},options=null,widget=null;if("object"==typeof field){var need_box=!1;for(var j in field)if(et2_registry[field[j]]&&et2_registry[field[j]].prototype.instanceOf(et2_valueWidget)){need_box=!0;break}if(need_box){widget=et2_createWidget("vbox",attrs,this);for(var i in field){"object"==typeof field[i]?attrs.select_options=field[i]:delete attrs.select_options;var child=et2_createWidget("string"==typeof field[i]?field[i]:"select",attrs,widget);child.transformAttributes(attrs)}}else attrs.select_options=field}else if(field.indexOf(":")>0){var options=field.split(":");field=options.shift()}if(null==widget&&(widget=et2_createWidget("string"==typeof field?field:"select",attrs,this)),options)for(var mgr=this.getArrayMgr("content"),i=0;i<options.length&&i<widget.legacyOptions.length;i++)if(""!=options[i]){var attr=widget.attributes[widget.legacyOptions[i]],attrValue=options[i];attrValue="boolean"==attr.type?mgr.parseBoolExpression(attrValue):mgr.expandName(attrValue),attrs[widget.legacyOptions[i]]=attrValue,"function"==typeof widget["set_"+widget.legacyOptions[i]]?widget["set_"+widget.legacyOptions[i]].call(widget,attrValue):widget.options[widget.legacyOptions[i]]=attrValue}widget.instanceOf(et2_selectbox)&&(widget.options.multiple=!0),widget.transformAttributes(attrs);for(var nodes=widget._children.length?[]:jQuery(widget.getDetachedNodes()),i=0;i<widget._children.length;i++)nodes.push(jQuery(widget._children[i].getDetachedNodes()));this.fields[key]={attrs:attrs,widget:widget,nodes:nodes}}var diff=et2_createWidget("diff",{},this);this.diff={widget:diff,nodes:jQuery(diff.getDetachedNodes())}},getDOMNode:function(_sender){if(_sender==this)return this.div[0];for(var i=0;i<this.columns.length;i++)if(_sender==this.columns[i].widget)return this.dataview.getHeaderContainerNode(i);return null},dataFetch:function(_queriedRange,_callback,_context){this.value.id&&this.egw().dataFetch(this.getInstanceManager().etemplate_exec_id,_queriedRange,this._filters,this.id,_callback,_context,[])},dataRegisterUID:function(_uid,_callback,_context){this.egw().dataRegisterUID(_uid,_callback,_context,this.getInstanceManager().etemplate_exec_id,this.id)},dataUnregisterUID:function(_uid,_callback,_context){},rowCallback:function(_data,_row,_idx,_entry){var tr=_row.getDOMNode();jQuery(tr).attr("valign","top");var row=this.dataview.rowProvider.getPrototype("default"),self=this;return $j("div",row).each(function(i){var nodes=[],widget=self.columns[i].widget;if("undefined"==typeof widget&&"undefined"!=typeof self.fields[_data.status]){widget=self.fields[_data.status].widget,widget._children.length||(nodes=self.fields[_data.status].nodes.clone());for(var j=0;j<widget._children.length;j++)nodes.push(self.fields[_data.status].nodes[j].clone())}else if(widget)nodes=self.columns[i].nodes.clone();else if("object"==typeof _data[self.columns[self.NEW_VALUE].id]&&"undefined"!=typeof _data[self.columns[self.NEW_VALUE].id].new||self._needsDiffWidget(_data.status,_data[self.columns[self.OLD_VALUE].id])||self._needsDiffWidget(_data.status,_data[self.columns[self.NEW_VALUE].id])){var jthis=jQuery(this);i==self.NEW_VALUE&&(widget=self.diff.widget,nodes=self.diff.nodes.clone(),"string"==typeof _data[self.columns[self.NEW_VALUE].id]&&(_data[self.columns[i].id]={old:_data[self.columns[i+1].id],new:_data[self.columns[i].id]}),jthis.parents("td").attr("colspan",2).css("border-right","none"),jthis.css("width",self.dataview.columnMgr.columnWidths[i]+self.dataview.columnMgr.columnWidths[i+1]-10+"px"),widget&&widget.setDetachedAttributes(nodes,{value:_data[self.columns[i].id],label:jthis.parents("td").prev().text()}),jthis.parents("td").next().remove())}else nodes="<span>"+_data[self.columns[i].id]+"</span>";if(widget)if(widget._children.length){for(var box=$j(widget.getDOMNode()).clone(),j=0;j<widget._children.length;j++)widget._children[j].setDetachedAttributes(nodes[j],{value:_data[self.columns[i].id][j]}),box.append(nodes[j]);nodes=box}else widget.setDetachedAttributes(nodes,{value:_data[self.columns[i].id]});$j(this).append(nodes)}),$j(tr).append(row.children()),tr},_needsDiffWidget:function(columnName,value){return"string"!=typeof value?(this.egw().debug("warn","Crazy diff value",value),!1):"note"==columnName||"description"==columnName||value&&(value.length>50||value.match(/\n/g))},resize:function(_height){"undefined"!=typeof this.options&&_height&&"undefined"!=typeof this.options.resize_ratio&&(_height=""!=this.options.resize_ratio?_height*this.options.resize_ratio:_height,0!=_height&&(0==this.div.height()&&(_height+=250),this.div.height(this.div.height()+_height),this.div.trigger("resize."+this.options.value.app+this.options.value.id)))}})}.call(this);et2_register_widget(et2_historylog,["historylog"]);var et2_hrule=function(){"use strict";return et2_baseWidget.extend({init:function(){this._super.apply(this,arguments),this.setDOMNode(document.createElement("hr"))}})}.call(this);et2_register_widget(et2_hrule,["hrule"]);var et2_image=function(){"use strict";return expose(et2_baseWidget.extend([et2_IDetachedDOM],{attributes:{src:{name:"Image",type:"string",description:"Displayed image"},default_src:{name:"Default image",type:"string",description:"Image to use if src is not found"},href:{name:"Link Target",type:"string",description:"Link URL, empty if you don't wan't to display a link.",default:et2_no_init},extra_link_target:{name:"Link target",type:"string",default:"_self",description:"Link target descriptor"},extra_link_popup:{name:"Popup",type:"string",description:"widthxheight, if popup should be used, eg. 640x480"},imagemap:{name:"Image map",description:"Currently not implemented"},label:{name:"Label",type:"string",description:"Label for image"},expose_view:{name:"Expose view",type:"boolean",default:!1,description:"Clicking on an image with href value would popup an expose view, and will show image referenced by href."}},legacyOptions:["href","extra_link_target","imagemap","extra_link_popup","id"],init:function(){this._super.apply(this,arguments),this.image=$j(document.createElement("img")),this.options.label&&this.image.attr("alt",this.options.label).attr("title",this.options.label),this.options.href&&this.image.addClass("et2_clickable"),this.options.class&&this.image.addClass(this.options.class),this.setDOMNode(this.image[0])},click:function(){this.options.href?this.egw().open_link(this.options.href,this.options.extra_link_target,this.options.extra_link_popup):this._super.apply(this,arguments)},transformAttributes:function(_attrs){if(this._super.apply(arguments),"undefined"!=typeof _attrs.src){var manager=this.getArrayMgr("content");if(manager){var src=manager.getEntry(_attrs.src);"undefined"!=typeof src&&null!==src&&("object"==typeof src&&(src=egw().link("/index.php",src)),_attrs.src=src)}}},set_label:function(_value){this.options.label=_value,_value=this.egw().lang(_value),this.image.attr("alt",_value).attr("title",_value)},setValue:function(_value){this.set_src(_value)},set_href:function(_value){if(!this.isInTree())return!1;this.options.href=_value,this.image.wrapAll('<a href="'+_value+'"></a>"');var href=this.options.href,popup=this.options.extra_link_popup,target=this.options.extra_link_target,self=this;return this.image.click(function(e){return self.options.expose_view?(self._init_blueimp_gallery(e,_value),e.stopImmediatePropagation()):egw.open_link(href,target,popup),e.preventDefault(),!1}),!0},set_src:function(_value){if(!this.isInTree())return!1;this.options.src=_value;var src=this.egw().image(_value);return src?(this.image.attr("src",src).show(),!0):"/"==_value[0]||"http"==_value.substr(0,4)?(this.image.attr("src",_value).show(),!0):(src=null,this.options.default_src&&(src=this.egw().image(this.options.default_src)),src?this.image.attr("src",src).show():this.image.css("display","none"),!1)},getMedia:function(_value){var base_url=egw.webserverUrl.match(/^\//,"ig")?egw(window).window.location.origin+egw.webserverUrl+"/":egw.webserverUrl+"/",mediaContent=[];return _value&&(mediaContent=[{title:this.options.label,href:base_url+_value,type:this.options.type+"/*",thumbnail:base_url+_value}]),mediaContent},getDetachedAttributes:function(_attrs){_attrs.push("src","label","href")},getDetachedNodes:function(){return[this.image[0]]},setDetachedAttributes:function(_nodes,_values){this.image=$j(_nodes[0]),_values.src&&this.set_src(_values.src),_values.label&&this.set_label(_values.label),_values.href&&(this.image.addClass("et2_clickable"),this.set_href(_values.href))}}))}.call(this);et2_register_widget(et2_image,["image"]);var et2_appicon=function(){"use strict";return et2_image.extend({attributes:{default_src:{name:"Default image",type:"string",default:"nonav",description:"Image to use if there is no application icon"}},set_src:function(_app){_app||(_app=this.egw().app_name()),this.image.addClass("et2_appicon"),this._super.call(this,"sitemgr-link"==_app?"sitemgr/sitemgr-link":(this.egw().app(_app,"icon_app")||_app)+"/"+(this.egw().app(_app,"icon")||"navbar"))}})}.call(this);et2_register_widget(et2_appicon,["appicon"]);var et2_iframe=function(){"use strict";return et2_valueWidget.extend({attributes:{label:{default:"",description:"The label is displayed by default in front (for radiobuttons behind) each widget (if not empty). If you want to specify a different position, use a '%s' in the label, which gets replaced by the widget itself. Eg. '%s Name' to have the label Name behind a checkbox. The label can contain variables, as descript for name. If the label starts with a '@' it is replaced by the value of the content-array at this index (with the '@'-removed and after expanding the variables).",ignore:!1,name:"Label",translate:!0,type:"string"},needed:{ignore:!0},seamless:{name:"Seamless",default:!0,
description:"Specifies that the iframe should be rendered in a manner that makes it appear to be part of the containing document",translate:!1,type:"boolean"},name:{name:"Name",default:"",description:"Specifies name of frame, to be used as target for links",type:"string"},fullscreen:{name:"Fullscreen",default:!1,description:"Make the iframe compatible to be a fullscreen video player mode",type:"boolean"}},init:function(){this._super.apply(this,arguments),this.supportedWidgetClasses=[],this.htmlNode=$j(document.createElement("iframe")),this.options.label&&this.htmlNode.append('<span class="et2_label">'+this.options.label+"</span>"),this.options.fullscreen&&this.htmlNode.attr("allowfullscreen",!0),this.setDOMNode(this.htmlNode[0])},set_name:function(_name){this.htmlNode.attr("name",this.htmlNode.name=_name)},set_seamless:function(_seamless){this.options.seamless=_seamless,this.htmlNode.attr("seamless",_seamless)},set_value:function(_value){"undefined"==typeof _value&&(_value=""),0==_value.trim().indexOf("http")||0==_value.indexOf("about:")||"/"==_value[0]?this.set_src(_value):this.set_srcdoc(_value)},set_src:function(_value){if(""!=_value.trim())if("about:blank"==_value.trim())this.htmlNode.attr("src",_value);else{var loader=$j('<div class="et2_iframe loading"/>');this.htmlNode.before(loader),window.setTimeout(jQuery.proxy(function(){this.htmlNode.attr("src",_value).one("load",function(){loader.remove()})},this),0)}},set_srcdoc:function(_value){this.htmlNode.attr("srcdoc",_value)}})}.call(this);et2_register_widget(et2_iframe,["iframe"]),function(){"use strict";var Resumable=function(opts){function ResumableFile(resumableObj,file){var $=this;$.opts={},$.getOpt=resumableObj.getOpt,$._prevProgress=0,$.resumableObj=resumableObj,$.file=file,$.fileName=file.fileName||file.name,$.size=file.size,$.relativePath=file.webkitRelativePath||$.fileName,$.uniqueIdentifier=$h.generateUniqueIdentifier(file),$._pause=!1,$.container="";var _error=!1,chunkEvent=function(event,message){switch(event){case"progress":$.resumableObj.fire("fileProgress",$);break;case"error":$.abort(),_error=!0,$.chunks=[],$.resumableObj.fire("fileError",$,message);break;case"success":if(_error)return;$.resumableObj.fire("fileProgress",$),$.isComplete()&&$.resumableObj.fire("fileSuccess",$,message);break;case"retry":$.resumableObj.fire("fileRetry",$)}};return $.chunks=[],$.abort=function(){var abortCount=0;$h.each($.chunks,function(c){"uploading"==c.status()&&(c.abort(),abortCount++)}),abortCount>0&&$.resumableObj.fire("fileProgress",$)},$.cancel=function(){var _chunks=$.chunks;$.chunks=[],$h.each(_chunks,function(c){"uploading"==c.status()&&(c.abort(),$.resumableObj.uploadNextChunk())}),$.resumableObj.removeFile($),$.resumableObj.fire("fileProgress",$)},$.retry=function(){$.bootstrap();var firedRetry=!1;$.resumableObj.on("chunkingComplete",function(){firedRetry||$.resumableObj.upload(),firedRetry=!0})},$.bootstrap=function(){$.abort(),_error=!1,$.chunks=[],$._prevProgress=0;for(var round=$.getOpt("forceChunkSize")?Math.ceil:Math.floor,maxOffset=Math.max(round($.file.size/$.getOpt("chunkSize")),1),offset=0;maxOffset>offset;offset++)!function(offset){window.setTimeout(function(){$.chunks.push(new ResumableChunk($.resumableObj,$,offset,chunkEvent)),$.resumableObj.fire("chunkingProgress",$,offset/maxOffset)},0)}(offset);window.setTimeout(function(){$.resumableObj.fire("chunkingComplete",$)},0)},$.progress=function(){if(_error)return 1;var ret=0,error=!1;return $h.each($.chunks,function(c){"error"==c.status()&&(error=!0),ret+=c.progress(!0)}),ret=error?1:ret>.999?1:ret,ret=Math.max($._prevProgress,ret),$._prevProgress=ret,ret},$.isUploading=function(){var uploading=!1;return $h.each($.chunks,function(chunk){return"uploading"==chunk.status()?(uploading=!0,!1):void 0}),uploading},$.isComplete=function(){var outstanding=!1;return $h.each($.chunks,function(chunk){var status=chunk.status();return"pending"==status||"uploading"==status||1===chunk.preprocessState?(outstanding=!0,!1):void 0}),!outstanding},$.pause=function(pause){"undefined"==typeof pause?$._pause=!$._pause:$._pause=pause},$.isPaused=function(){return $._pause},$.resumableObj.fire("chunkingStart",$),$.bootstrap(),this}function ResumableChunk(resumableObj,fileObj,offset,callback){var $=this;$.opts={},$.getOpt=resumableObj.getOpt,$.resumableObj=resumableObj,$.fileObj=fileObj,$.fileObjSize=fileObj.size,$.fileObjType=fileObj.file.type,$.offset=offset,$.callback=callback,$.lastProgressCallback=new Date,$.tested=!1,$.retries=0,$.pendingRetry=!1,$.preprocessState=0;var chunkSize=$.getOpt("chunkSize");return $.loaded=0,$.startByte=$.offset*chunkSize,$.endByte=Math.min($.fileObjSize,($.offset+1)*chunkSize),$.fileObjSize-$.endByte<chunkSize&&!$.getOpt("forceChunkSize")&&($.endByte=$.fileObjSize),$.xhr=null,$.test=function(){$.xhr=new XMLHttpRequest;var testHandler=function(e){$.tested=!0;var status=$.status();"success"==status?($.callback(status,$.message()),$.resumableObj.uploadNextChunk()):$.send()};$.xhr.addEventListener("load",testHandler,!1),$.xhr.addEventListener("error",testHandler,!1);var params=[],customQuery=$.getOpt("query");"function"==typeof customQuery&&(customQuery=customQuery($.fileObj,$)),$h.each(customQuery,function(k,v){params.push([encodeURIComponent(k),encodeURIComponent(v)].join("="))}),params.push(["resumableChunkNumber",encodeURIComponent($.offset+1)].join("=")),params.push(["resumableChunkSize",encodeURIComponent($.getOpt("chunkSize"))].join("=")),params.push(["resumableCurrentChunkSize",encodeURIComponent($.endByte-$.startByte)].join("=")),params.push(["resumableTotalSize",encodeURIComponent($.fileObjSize)].join("=")),params.push(["resumableType",encodeURIComponent($.fileObjType)].join("=")),params.push(["resumableIdentifier",encodeURIComponent($.fileObj.uniqueIdentifier)].join("=")),params.push(["resumableFilename",encodeURIComponent($.fileObj.fileName)].join("=")),params.push(["resumableRelativePath",encodeURIComponent($.fileObj.relativePath)].join("=")),params.push(["resumableTotalChunks",encodeURIComponent($.fileObj.chunks.length)].join("=")),$.xhr.open("GET",$h.getTarget(params)),$.xhr.timeout=$.getOpt("xhrTimeout"),$.xhr.withCredentials=$.getOpt("withCredentials"),$h.each($.getOpt("headers"),function(k,v){$.xhr.setRequestHeader(k,v)}),$.xhr.send(null)},$.preprocessFinished=function(){$.preprocessState=2,$.send()},$.send=function(){var preprocess=$.getOpt("preprocess");if("function"==typeof preprocess)switch($.preprocessState){case 0:return preprocess($),void($.preprocessState=1);case 1:return;case 2:}if($.getOpt("testChunks")&&!$.tested)return void $.test();$.xhr=new XMLHttpRequest,$.xhr.upload.addEventListener("progress",function(e){new Date-$.lastProgressCallback>1e3*$.getOpt("throttleProgressCallbacks")&&($.callback("progress"),$.lastProgressCallback=new Date),$.loaded=e.loaded||0},!1),$.loaded=0,$.pendingRetry=!1,$.callback("progress");var doneHandler=function(e){var status=$.status();if("success"==status||"error"==status)$.callback(status,$.message()),$.resumableObj.uploadNextChunk();else{$.callback("retry",$.message()),$.abort(),$.retries++;var retryInterval=$.getOpt("chunkRetryInterval");void 0!==retryInterval?($.pendingRetry=!0,setTimeout($.send,retryInterval)):$.send()}};$.xhr.addEventListener("load",doneHandler,!1),$.xhr.addEventListener("error",doneHandler,!1);var query={resumableChunkNumber:$.offset+1,resumableChunkSize:$.getOpt("chunkSize"),resumableCurrentChunkSize:$.endByte-$.startByte,resumableTotalSize:$.fileObjSize,resumableType:$.fileObjType,resumableIdentifier:$.fileObj.uniqueIdentifier,resumableFilename:$.fileObj.fileName,resumableRelativePath:$.fileObj.relativePath,resumableTotalChunks:$.fileObj.chunks.length},customQuery=$.getOpt("query");"function"==typeof customQuery&&(customQuery=customQuery($.fileObj,$)),$h.each(customQuery,function(k,v){query[k]=v});var func=$.fileObj.file.slice?"slice":$.fileObj.file.mozSlice?"mozSlice":$.fileObj.file.webkitSlice?"webkitSlice":"slice",bytes=$.fileObj.file[func]($.startByte,$.endByte),data=null,target=$.getOpt("target");if("octet"===$.getOpt("method")){data=bytes;var params=[];$h.each(query,function(k,v){params.push([encodeURIComponent(k),encodeURIComponent(v)].join("="))}),target=$h.getTarget(params)}else data=new FormData,$h.each(query,function(k,v){data.append(k,v)}),data.append($.getOpt("fileParameterName"),bytes);$.xhr.open("POST",target),$.xhr.timeout=$.getOpt("xhrTimeout"),$.xhr.withCredentials=$.getOpt("withCredentials"),$h.each($.getOpt("headers"),function(k,v){$.xhr.setRequestHeader(k,v)}),$.xhr.send(data)},$.abort=function(){$.xhr&&$.xhr.abort(),$.xhr=null},$.status=function(){return $.pendingRetry?"uploading":$.xhr?$.xhr.readyState<4?"uploading":200==$.xhr.status?"success":$h.contains($.getOpt("permanentErrors"),$.xhr.status)||$.retries>=$.getOpt("maxChunkRetries")?"error":($.abort(),"pending"):"pending"},$.message=function(){return $.xhr?$.xhr.responseText:""},$.progress=function(relative){"undefined"==typeof relative&&(relative=!1);var factor=relative?($.endByte-$.startByte)/$.fileObjSize:1;if($.pendingRetry)return 0;var s=$.status();switch(s){case"success":case"error":return 1*factor;case"pending":return 0*factor;default:return $.loaded/($.endByte-$.startByte)*factor}},this}if(!(this instanceof Resumable))return new Resumable(opts);if(this.version=1,this.support=!("undefined"==typeof File||"undefined"==typeof Blob||"undefined"==typeof FileList||!Blob.prototype.webkitSlice&&!Blob.prototype.mozSlice&&!Blob.prototype.slice),!this.support)return!1;var $=this;$.files=[],$.defaults={chunkSize:1048576,forceChunkSize:!1,simultaneousUploads:3,fileParameterName:"file",throttleProgressCallbacks:.5,query:{},headers:{},preprocess:null,method:"multipart",prioritizeFirstAndLastChunk:!1,target:"/",testChunks:!0,generateUniqueIdentifier:null,maxChunkRetries:void 0,chunkRetryInterval:void 0,permanentErrors:[404,415,500,501],maxFiles:void 0,withCredentials:!1,xhrTimeout:0,maxFilesErrorCallback:function(files,errorCount){var maxFiles=$.getOpt("maxFiles");alert("Please upload "+maxFiles+" file"+(1===maxFiles?"":"s")+" at a time.")},minFileSize:1,minFileSizeErrorCallback:function(file,errorCount){alert(file.fileName||file.name+" is too small, please upload files larger than "+$h.formatSize($.getOpt("minFileSize"))+".")},maxFileSize:void 0,maxFileSizeErrorCallback:function(file,errorCount){alert(file.fileName||file.name+" is too large, please upload files less than "+$h.formatSize($.getOpt("maxFileSize"))+".")},fileType:[],fileTypeErrorCallback:function(file,errorCount){alert(file.fileName||file.name+" has type not allowed, please upload files of type "+$.getOpt("fileType")+".")}},$.opts=opts||{},$.getOpt=function(o){var $opt=this;if(o instanceof Array){var options={};return $h.each(o,function(option){options[option]=$opt.getOpt(option)}),options}if($opt instanceof ResumableChunk){if("undefined"!=typeof $opt.opts[o])return $opt.opts[o];$opt=$opt.fileObj}if($opt instanceof ResumableFile){if("undefined"!=typeof $opt.opts[o])return $opt.opts[o];$opt=$opt.resumableObj}return $opt instanceof Resumable?"undefined"!=typeof $opt.opts[o]?$opt.opts[o]:$opt.defaults[o]:void 0},$.events=[],$.on=function(event,callback){$.events.push(event.toLowerCase(),callback)},$.fire=function(){for(var args=[],i=0;i<arguments.length;i++)args.push(arguments[i]);for(var event=args[0].toLowerCase(),i=0;i<=$.events.length;i+=2)$.events[i]==event&&$.events[i+1].apply($,args.slice(1)),"catchall"==$.events[i]&&$.events[i+1].apply(null,args);"fileerror"==event&&$.fire("error",args[2],args[1]),"fileprogress"==event&&$.fire("progress")};var $h={stopEvent:function(e){e.stopPropagation(),e.preventDefault()},each:function(o,callback){if("undefined"!=typeof o.length){for(var i=0;i<o.length;i++)if(callback(o[i])===!1)return}else for(i in o)if(callback(i,o[i])===!1)return},generateUniqueIdentifier:function(file){var custom=$.getOpt("generateUniqueIdentifier");if("function"==typeof custom)return custom(file);var relativePath=file.webkitRelativePath||file.fileName||file.name,size=file.size;return size+"-"+relativePath.replace(/[^0-9a-zA-Z_-]/gim,"")},contains:function(array,test){var result=!1;return $h.each(array,function(value){return value==test?(result=!0,!1):!0}),result},formatSize:function(size){return 1024>size?size+" bytes":1048576>size?(size/1024).toFixed(0)+" KB":1073741824>size?(size/1024/1024).toFixed(1)+" MB":(size/1024/1024/1024).toFixed(1)+" GB"},getTarget:function(params){var target=$.getOpt("target");return target+=target.indexOf("?")<0?"?":"&",target+params.join("&")}},onDrop=function(event){$h.stopEvent(event),appendFilesFromFileList(event.dataTransfer.files,event)},onDragOver=function(e){e.preventDefault()},appendFilesFromFileList=function(fileList,event){var errorCount=0,o=$.getOpt(["maxFiles","minFileSize","maxFileSize","maxFilesErrorCallback","minFileSizeErrorCallback","maxFileSizeErrorCallback","fileType","fileTypeErrorCallback"]);if("undefined"!=typeof o.maxFiles&&o.maxFiles<fileList.length+$.files.length){if(1!==o.maxFiles||1!==$.files.length||1!==fileList.length)return o.maxFilesErrorCallback(fileList,errorCount++),!1;$.removeFile($.files[0])}var files=[];$h.each(fileList,function(file){var fileName=file.name.split("."),fileType=fileName[fileName.length-1].toLowerCase();return o.fileType.length>0&&!$h.contains(o.fileType,fileType)?(o.fileTypeErrorCallback(file,errorCount++),!1):"undefined"!=typeof o.minFileSize&&file.size<o.minFileSize?(o.minFileSizeErrorCallback(file,errorCount++),!1):"undefined"!=typeof o.maxFileSize&&file.size>o.maxFileSize?(o.maxFileSizeErrorCallback(file,errorCount++),!1):void($.getFromUniqueIdentifier($h.generateUniqueIdentifier(file))||!function(){var f=new ResumableFile($,file);window.setTimeout(function(){$.files.push(f),files.push(f),f.container="undefined"!=typeof event?event.srcElement:null,$.fire("fileAdded",f,event)},0)}())}),window.setTimeout(function(){$.fire("filesAdded",files)},0)};return $.uploadNextChunk=function(){var found=!1;if($.getOpt("prioritizeFirstAndLastChunk")&&($h.each($.files,function(file){return file.chunks.length&&"pending"==file.chunks[0].status()&&0===file.chunks[0].preprocessState?(file.chunks[0].send(),found=!0,!1):file.chunks.length>1&&"pending"==file.chunks[file.chunks.length-1].status()&&0===file.chunks[file.chunks.length-1].preprocessState?(file.chunks[file.chunks.length-1].send(),found=!0,!1):void 0}),found))return!0;if($h.each($.files,function(file){return file.isPaused()===!1&&$h.each(file.chunks,function(chunk){return"pending"==chunk.status()&&0===chunk.preprocessState?(chunk.send(),found=!0,!1):void 0}),found?!1:void 0}),found)return!0;var outstanding=!1;return $h.each($.files,function(file){return file.isComplete()?void 0:(outstanding=!0,!1)}),outstanding||$.fire("complete"),!1},$.assignBrowse=function(domNodes,isDirectory){"undefined"==typeof domNodes.length&&(domNodes=[domNodes]),$h.each(domNodes,function(domNode){var input;"INPUT"===domNode.tagName&&"file"===domNode.type?input=domNode:(input=document.createElement("input"),input.setAttribute("type","file"),input.style.display="none",domNode.addEventListener("click",function(){input.style.opacity=0,input.style.display="block",input.focus(),input.click(),input.style.display="none"},!1),domNode.appendChild(input));var maxFiles=$.getOpt("maxFiles");"undefined"==typeof maxFiles||1!=maxFiles?input.setAttribute("multiple","multiple"):input.removeAttribute("multiple"),isDirectory?input.setAttribute("webkitdirectory","webkitdirectory"):input.removeAttribute("webkitdirectory"),input.addEventListener("change",function(e){appendFilesFromFileList(e.target.files,e),e.target.value=""},!1)})},$.assignDrop=function(domNodes){"undefined"==typeof domNodes.length&&(domNodes=[domNodes]),$h.each(domNodes,function(domNode){domNode.addEventListener("dragover",onDragOver,!1),domNode.addEventListener("drop",onDrop,!1)})},$.unAssignDrop=function(domNodes){"undefined"==typeof domNodes.length&&(domNodes=[domNodes]),$h.each(domNodes,function(domNode){domNode.removeEventListener("dragover",onDragOver),domNode.removeEventListener("drop",onDrop)})},$.isUploading=function(){var uploading=!1;return $h.each($.files,function(file){return file.isUploading()?(uploading=!0,!1):void 0}),uploading},$.upload=function(){if(!$.isUploading()){$.fire("uploadStart");for(var num=1;num<=$.getOpt("simultaneousUploads");num++)$.uploadNextChunk()}},$.pause=function(){$h.each($.files,function(file){file.abort()}),$.fire("pause")},$.cancel=function(){for(var i=$.files.length-1;i>=0;i--)$.files[i].cancel();$.fire("cancel")},$.progress=function(){var totalDone=0,totalSize=0;return $h.each($.files,function(file){totalDone+=file.progress()*file.size,totalSize+=file.size}),totalSize>0?totalDone/totalSize:0},$.addFile=function(file,event){appendFilesFromFileList([file],event)},$.removeFile=function(file){for(var i=$.files.length-1;i>=0;i--)$.files[i]===file&&$.files.splice(i,1)},$.getFromUniqueIdentifier=function(uniqueIdentifier){var ret=!1;return $h.each($.files,function(f){f.uniqueIdentifier==uniqueIdentifier&&(ret=f)}),ret},$.getSize=function(){var totalSize=0;return $h.each($.files,function(file){totalSize+=file.size}),totalSize},this};"undefined"!=typeof module?module.exports=Resumable:"function"==typeof define&&define.amd?define(function(){return Resumable}):window.Resumable=Resumable}();var et2_file=function(){"use strict";return et2_inputWidget.extend({attributes:{multiple:{name:"Multiple files",type:"boolean",default:!1,description:"Allow the user to select more than one file to upload at a time. Subject to browser support."},max_file_size:{name:"Maximum file size",type:"integer",default:0,description:"Largest file accepted, in bytes. Subject to server limitations. 8MB = 8388608"},mime:{name:"Allowed file types",type:"string",default:et2_no_init,description:"Mime type (eg: image/png) or regex (eg: /^text//i) for allowed file types"},blur:{name:"Placeholder",type:"string",default:"",description:"This text get displayed if an input-field is empty and does not have the input-focus (blur). It can be used to show a default value or a kind of help-text."},progress:{name:"Progress node",type:"string",default:et2_no_init,description:"The ID of an alternate node (div) to display progress and results. The Node is fetched with et2 getWidgetById so you MUST use the id assigned in XET-File (it may not be available at creation time, so we (re)check on createStatus time)"},onStart:{name:"Start event handler",type:"any",default:et2_no_init,description:"A (js) function called when an upload starts. Return true to continue with upload, false to cancel."},onFinish:{name:"Finish event handler",type:"any",default:et2_no_init,description:"A (js) function called when all files to be uploaded are finished."},drop_target:{name:"Optional, additional drop target for HTML5 uploads",type:"string",default:et2_no_init,description:"The ID of an additional drop target for HTML5 drag-n-drop file uploads"},label:{name:"Label of file upload",type:"string",default:"Choose file...",description:"String caption to be displayed on file upload span"},progress_dropdownlist:{name:"List on files in progress like dropdown",type:"boolean",default:!1,description:"Style list of files in uploading progress like dropdown list with a total upload progress indicator"},onFinishOne:{name:"Finish event handler for each one",type:"any",default:et2_no_init,description:"A (js) function called when a file to be uploaded is finished."}},asyncOptions:{},init:function(){this._super.apply(this,arguments),this.node=null,this.input=null,this.progress=null,this.span=null,this.options.id||(console.warn("File widget needs an ID. Used 'file_widget'."),this.options.id="file_widget"),"[]"==this.options.id.substr(-2)&&(this.options.multiple=!0);var self=(this.getInstanceManager(),this);this.asyncOptions=jQuery.extend({onStart:function(event,file_count){return self.onStart(event,file_count)},onFinish:function(event,file_count){self.onFinish.apply(self,[event,file_count])},onStartOne:function(event,file_name,index,file_count){},onFinishOne:function(event,response,name,number,total){return self.finishUpload(event,response,name,number,total)},onProgress:function(event,progress,name,number,total){return self.onProgress(event,progress,name,number,total)},onError:function(event,name,error){return self.onError(event,name,error)},beforeSend:function(form){return self.beforeSend(form)},target:egw.ajaxUrl(self.egw().getAppName()+".etemplate_widget_file.ajax_upload.etemplate"),query:function(file){return self.beforeSend(file)},testChunks:!1},this.asyncOptions),this.asyncOptions.fieldName=this.options.id,this.createInputWidget()},destroy:function(){this._super.apply(this,arguments),this.set_drop_target(null),this.node=null,this.input=null,this.span=null,this.progress=null},createInputWidget:function(){this.node=$j(document.createElement("div")).addClass("et2_file"),this.span=$j(document.createElement("span")).addClass("et2_file_span et2_button et2_button_text").appendTo(this.node);var span=this.span;if(this.input=$j(document.createElement("input")).attr("type","file").attr("placeholder",this.options.blur).addClass("et2_file_upload").appendTo(this.node).hover(function(e){$j(span).toggleClass("et2_file_spanHover")}).on({mousedown:function(e){$j(span).addClass("et2_file_spanActive")},mouseup:function(e){$j(span).removeClass("et2_file_spanActive")}}),"undefined"!=typeof File&&"undefined"!=typeof(new XMLHttpRequest).upload&&(this.resumable=new Resumable(this.asyncOptions),this.resumable.assignBrowse(this.input),this.resumable.on("fileAdded",jQuery.proxy(this._fileAdded,this)),this.resumable.on("fileProgress",jQuery.proxy(this._fileProgress,this)),this.resumable.on("fileSuccess",jQuery.proxy(this.finishUpload,this)),this.resumable.on("complete",jQuery.proxy(this.onFinish,this))),this.options.progress){var widget=this.getRoot().getWidgetById(this.options.progress);widget&&(this.progress=$j(widget.getDOMNode()))}this.progress||(this.progress=$j(document.createElement("div")).appendTo(this.node)),this.progress.addClass("progress"),this.options.multiple&&this.input.attr("multiple","multiple"),this.setDOMNode(this.node[0])},set_drop_target:function(new_target){if(this.options.drop_target){var widget=this.getRoot().getWidgetById(this.options.drop_target),drop_target=widget&&widget.getDOMNode()||document.getElementById(this.options.drop_target);drop_target&&this.resumable.unAssignDrop(drop_target)}if(this.options.drop_target=new_target,this.options.drop_target){var widget=this.getRoot().getWidgetById(this.options.drop_target),drop_target=widget&&widget.getDOMNode()||document.getElementById(this.options.drop_target);drop_target?this.resumable.assignDrop([drop_target]):this.egw().debug("warn","Did not find file drop target %s",this.options.drop_target)}},attachToDOM:function(){this._super.apply(this,arguments),this.input.unbind("change.et2_inputWidget")},getValue:function(){var value=this.options.value?this.options.value:this.input.val();return value},set_value:function(value,event){if(value&&"undefined"!=typeof value||(value={}),jQuery.isEmptyObject(value))return this.options.value={},1==this.resumable.progress()&&this.progress.empty(),this.input.wrap("<form>").closest("form").get(0).reset(),void this.input.unwrap();if("object"==typeof value&&value.length&&"object"==typeof value[0]&&value[0].name)try{this.input[0].files=value}catch(e){var self=this;jQuery.each(value,function(i,file){self.resumable.addFile(this,event)})}},set_label:function(value){null!=this.span&&null!=value&&this.span.text(value)},getInputNode:function(){return"undefined"==typeof this.input?!1:this.input[0]},set_mime:function(mime){if(mime||(this.options.mime=null),0!=mime.indexOf("/"))this.options.mime=mime.toLowerCase();else{var parts=mime.substr(1).match(/(.*)\/([igm]?)$/);this.options.mime=new RegExp(parts[1],parts.length>2?parts[2]:"")}},set_multiple:function(_multiple){return this.options.multiple=_multiple,_multiple?this.input.attr("multiple","multiple"):this.input.removeAttr("multiple")},checkMime:function(f){if(!this.options.mime||!f.type)return!0;var is_preg="object"==typeof this.options.mime;return!!(!is_preg&&f.type.toLowerCase()==this.options.mime||is_preg&&this.options.mime.test(f.type))},_fileAdded:function(file,event){return"undefined"==typeof event&&(event={}),this.resumable.isUploading()||this.onStart(event,this.resumable.files.length)?this.checkMime(file.file)?void(this.createStatus(event,file)&&this.resumable.upload()):this.createStatus(this.egw().lang("File is of wrong type (%1 != %2)!",file.file.type,this.options.mime),file):void 0},beforeSend:function(form){var instance=this.getInstanceManager();return{request_id:instance.etemplate_exec_id,widget_id:this.id}},onStart:function(event,file_count){return this.hideMessage(),this.disabled_buttons=$j("input[type='submit'], button").not("[disabled]").attr("disabled",!0).addClass("et2_button_ro").removeClass("et2_clickable").css("cursor","default"),event.data=this,this.options.progress_dropdownlist&&this._build_progressDropDownList(),this.options.onStart?et2_call(this.options.onStart,event,file_count):!0},onFinish:function(){this.disabled_buttons.attr("disabled",!1).css("cursor","pointer");for(var file_count=this.resumable.files.length;this.resumable.files.length>0;)this.resumable.removeFile(this.resumable.files[this.resumable.files.length-1]);var event=jQuery.Event("upload");event.data=this;var result=!1;this.options.progress_dropdownlist&&(this.progress.removeClass("progress_dropDown_fileList"),jQuery(this.node).find("span").removeClass("totalProgress_loader"),jQuery("body").off("click")),result=this.options.onFinish&&!jQuery.isEmptyObject(this.getValue())?et2_call(this.options.onFinish,event,file_count):0==file_count||!jQuery.isEmptyObject(this.getValue()),result&&this.change(this.input)},_build_progressDropDownList:function(){this.progress.addClass("progress_dropDown_fileList"),jQuery(this.node).find("span").addClass("totalProgress_loader"),jQuery(this.node).find("input").hover(function(){jQuery(".progress_dropDown_fileList").show()}),jQuery("body").on("click",function(event){"remove"!=event.target.className&&jQuery(".progress_dropDown_fileList").hide()})},createStatus:function(_event,file){var error="object"==typeof _event?"":_event;if(this.options.max_file_size&&file.size>this.options.max_file_size&&(error=this.egw().lang("File too large. Maximum %1",et2_vfsSize.prototype.human_size(this.options.max_file_size))),this.options.progress){var widget=this.getRoot().getWidgetById(this.options.progress);widget&&(this.progress=$j(widget.getDOMNode()),this.progress.addClass("progress"))}if(this.progress){var fileName=file.fileName||"file",status=$j("<li data-file='"+fileName+"'>"+fileName+"<div class='remove'/><span class='progressBar'><p/></span></li>").appendTo(this.progress);$j("div.remove",status).on("click",file,jQuery.proxy(this.cancel,this)),""!=error&&(status.addClass("message ui-state-error"),status.append("<div>"+error+"</diff>"),$j(".progressBar",status).css("display","none"))}return""==error},_fileProgress:function(file){return this.progress&&$j("li[data-file='"+file.fileName+"'] > span.progressBar > p").css("width",Math.ceil(100*file.progress())+"%"),!0},onError:function(event,name,error){console.warn(event,name,error)},finishUpload:function(file,response){var name=file.fileName||"file";if("string"==typeof response&&(response=jQuery.parseJSON(response)),response.response[0]&&"undefined"==typeof response.response[0].data.length){"object"!=typeof this.options.value&&(this.options.value={});for(var key in response.response[0].data)"string"==typeof response.response[0].data[key]?$j("[data-file='"+name+"']",this.progress).addClass("error").css("display","block").text(response.response[0].data[key]):(this.options.value[key]=response.response[0].data[key],this.progress&&$j("[data-file='"+name+"']",this.progress).addClass("message success"))}else this.progress&&$j("[data-file='"+name+"']",this.progress).addClass("ui-state-error").css("display","block").text(this.egw().lang("Server error"));var event=jQuery.Event("upload");return event.data=this,this.options.onFinishOne?et2_call(this.options.onFinishOne,event,response,name):!0},remove_file:function(file){"string"==typeof file&&(file={fileName:file});for(var key in this.options.value)if(this.options.value[key].name==file.fileName)return delete this.options.value[key],void $j('[data-file="'+file.fileName+'"]',this.node).remove();file.isComplete&&!file.isComplete()&&file.cancel&&file.cancel()},cancel:function(e){e.preventDefault();var target=$j(e.target).parents("li");this.remove_file(e.data),target.remove(),$j(e.target).remove()}})}.call(this);et2_register_widget(et2_file,["file"]);var et2_progress=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{href:{name:"Link Target",type:"string",description:"Link URL, empty if you don't wan't to display a link."},extra_link_target:{name:"Link target",type:"string",default:"_self",description:"Link target descriptor"},extra_link_popup:{name:"Popup",type:"string",description:"widthxheight, if popup should be used, eg. 640x480"},label:{name:"Label",default:"",type:"string",description:"The label is displayed as the title. The label can contain variables, as descript for name. If the label starts with a '@' it is replaced by the value of the content-array at this index (with the '@'-removed and after expanding the variables).",translate:!0}},legacyOptions:["href","extra_link_target","imagemap","extra_link_popup","id"],init:function(){this._super.apply(this,arguments);var outer=document.createElement("div");outer.className="et2_progress",this.progress=document.createElement("div"),this.progress.style.width="0",outer.appendChild(this.progress),this.options.href&&(outer.className+=" et2_clickable"),this.options.class&&(outer.className+=" "+this.options.class),this.setDOMNode(outer)},click:function(){this._super.apply(this,arguments),this.options.href&&this.egw().open_link(this.options.href,this.options.extra_link_target,this.options.extra_link_popup)},set_value:function(_value){_value=parseInt(_value)+"%",this.progress.style.width=_value,this.options.label||this.set_label(_value)},set_label:function(_value){this.node.title=_value},set_class:function(_value){var baseClass="et2_progress";this.options.href&&(baseClass+=" et2_clickable"),this.node.setAttribute("class",baseClass+" "+_value)},set_href:function(_value){if(!this.isInTree())return!1;if(this.options.href=_value,_value){jQuery(this.node).addClass("et2_clickable").wrapAll('<a href="'+_value+'"></a>"');var href=this.options.href,popup=this.options.extra_link_popup,target=this.options.extra_link_target;jQuery(this.node).parent().click(function(e){return egw.open_link(href,target,popup),e.preventDefault(),!1})}else jQuery(this.node).parent("a").length&&jQuery(this.node).removeClass("et2_clickable").unwrap();return!0},getDetachedAttributes:function(_attrs){_attrs.push("value","label","href")},getDetachedNodes:function(){return[this.node,this.progress]},setDetachedAttributes:function(_nodes,_values){this.node=_nodes[0],this.progress=_nodes[1],_values.label&&this.set_label(_values.label),_values.value?this.set_value(_values.value):_values.label&&this.set_value(_values.label),_values.href&&(jQuery(this.node).addClass("et2_clickable"),this.set_href(_values.href))}})}.call(this);et2_register_widget(et2_progress,["progress"]);var et2_portlet=function(){"use strict";return et2_valueWidget.extend({attributes:{title:{name:"Title",description:"Goes in the little bit at the top with the icons",type:"string",default:""},edit_template:{name:"Edit template",description:"Custom eTemplate used to customize / set up the portlet",type:"string",default:window.egw_webserverUrl+"/home/templates/default/edit.xet"},color:{name:"Color",description:"Set the portlet color",type:"string",default:""},settings:{name:"Customization settings",description:"Array of customization settings, similar in structure to preference settings",
type:"any",default:et2_no_init},actions:{default:{}},width:{default:2,ignore:!0},height:{default:1,type:"integer"},rows:{ignore:!0,default:et2_no_init},cols:{ignore:!0,default:et2_no_init},resize_ratio:{ignore:!0,default:et2_no_init},row:{name:"Row",description:"Home page location (row) - handled by home app",default:1},col:{name:"Column",description:"Home page location(column) - handled by home app",default:1}},createNamespace:!0,GRID:55,default_actions:{edit_settings:{icon:"edit",caption:"Configure",default:!0,hideOnDisabled:!0,group:"portlet"},remove_portlet:{icon:"delete",caption:"Remove",group:"portlet"}},init:function(){this._super.apply(this,arguments);var self=this;this.div=$j(document.createElement("div")).addClass(this.options.class).addClass("ui-widget ui-widget-content ui-corner-all").addClass("et2_portlet").attr("data-sizex",this.options.width).attr("data-sizey",this.options.height).attr("data-row",this.options.row).attr("data-col",this.options.col).resizable({autoHide:!0,grid:this.GRID,stop:function(event,ui){self.set_width(Math.round(ui.size.width/self.GRID)),self.set_height(Math.round(ui.size.height/self.GRID)),self.egw().jsonq("home.home_ui.ajax_set_properties",[self.id,{},{width:self.options.width,height:self.options.height}],null,self,!0,self),self.iterateOver(function(widget){widget.resize()},null,et2_IResizeable)}}),this.header=$j(document.createElement("div")).attr("id",this.getInstanceManager().uniqueId+"_"+this.id.replace(/\./g,"-")+"_header").addClass("ui-widget-header ui-corner-all").appendTo(this.div).html(this.options.title),this.content=$j(document.createElement("div")).attr("id",this.getInstanceManager().uniqueId+"_"+this.id.replace(/\./g,"-")+"_content").appendTo(this.div),this.setDOMNode(this.div[0])},destroy:function(){for(var i=0;i<this._children.length;i++)this._children[i]._inst!=this._inst&&this._children[i]._inst.clear();this._super.apply(this,arguments)},getDOMNode:function(_sender){return"undefined"!=typeof _sender&&_sender!=this?this.content[0]:this._super.apply(this,arguments)},set_actions:function(actions){var defaults={};for(var action_name in this.default_actions)defaults[action_name]=this.default_actions[action_name],defaults[action_name].caption=this.egw().lang(this.default_actions[action_name].caption),"function"==typeof this[action_name]&&(defaults[action_name].onExecute=jQuery.proxy(this[action_name],this));this.options.actions=jQuery.extend(!0,{},defaults,actions),this._super.apply(this,[this.options.actions])},_link_actions:function(actions){var objectManager=egw_getAppObjectManager(!0),widget_object=objectManager.getObjectById(this.id);null==widget_object&&(widget_object=objectManager.insertObject(!1,new egwActionObject(this.id,objectManager,new et2_action_object_impl(this),this._actionManager||objectManager.manager.getActionById(this.id)||objectManager.manager))),widget_object.clear();var action_links=[];for(var i in actions){var id="undefined"!=typeof actions[i].id?actions[i].id:i,action={actionId:id,enabled:!0};"edit_settings"!=id||this.options.settings&&!jQuery.isEmptyObject(this.options.settings)||(this.egw().debug("log","No settings for portlet %o, edit_settings action removed",this),action.enabled=!1),action_links.push(action)}widget_object.updateActionLinks(action_links)},edit_settings:function(action,sender){var dialog=et2_createWidget("dialog",{callback:jQuery.proxy(this._process_edit,this),template:this.options.edit_template,value:{content:this.options.settings},buttons:et2_dialog.BUTTONS_OK_CANCEL},this);dialog.set_title(this.egw().lang("Edit")+" "+(this.options.title||""))},_process_edit:function(button_id,value){if(button_id==et2_dialog.OK_BUTTON){this.div.addClass("loading");var settings="string"==typeof value?{}:this.options.settings||{};this.egw().jsonq("home.home_ui.ajax_set_properties",[this.id,settings,value,this.settings?this.settings.group:!1],function(data){if(!data||"undefined"==typeof data.attributes)return!1;this.div.removeClass("loading"),this.set_value(data.content);for(var key in data.attributes)"function"==typeof this["set_"+key]?this["set_"+key].call(this,data.attributes[key]):this.attributes[key]&&(this.options[key]=data.attributes[key]);if("undefined"!=typeof data.edit_settings&&data.edit_settings&&this.edit_settings(),data.attributes.width||data.attributes.height)try{this.iterateOver(function(widget){widget.resize()},null,et2_IResizeable)}catch(e){egw.debug("warn",e,this)}},this,!0,this),"object"==typeof value&&jQuery.extend(this.options.settings,value)}},remove_portlet:function(){var self=this;et2_dialog.show_dialog(function(button_id){button_id==et2_dialog.OK_BUTTON&&(self._process_edit(button_id,"~remove~"),self._parent.removeChild(self),self.destroy())},"Remove",this.options.title,{},et2_dialog.BUTTONS_OK_CANCEL,et2_dialog.QUESTION_MESSAGE)},set_value:function(value){this.content.html(value)},set_title:function(value){this.header.contents().filter(function(){return 3===this.nodeType}).remove(),this.options.title=value,this.header.append(value)},set_color:function(color){this.header.css("backgroundColor",color),this.content.css("backgroundColor",color)},set_width:function(value){this.options.width=value,this.div.attr("data-sizex",value),this.div.css("width","")},set_height:function(value){this.options.height=value,this.div.attr("data-sizey",value),this.div.css("height","")}})}.call(this);et2_register_widget(et2_portlet,["portlet"]);var et2_ajaxSelect=function(){"use strict";return et2_inputWidget.extend({attributes:{get_rows:{name:"Data source",type:"any",default:"",description:"Function to get search results, either a javascript function or server-side."},get_title:{name:"Title function",type:"any",default:"",description:"Function to get title for selected entry. Used when closed, and if no template is given."},id_field:{name:"Result ID field",type:"string",default:"value",description:"Which key in result sub-array to look for row ID. If omitted, the key for the row will be used."},template:{name:"Row template",type:"string",default:"",description:"ID of the template to use to display rows. If omitted, title will be shown for each result."},filter:{name:"Filter",type:"string",default:"",description:"Apply filter to search results. Same as nextmatch."},filter2:{name:"Filter 2",type:"string",default:"",description:"Apply filter to search results. Same as nextmatch."},link:{name:"Read only link",type:"boolean",default:"true",description:"If readonly, widget will be text. If link is set, widget will be a link."},values:{name:"Values",type:"any",default:{},description:"Specify the available options. Use this, or Data source."}},init:function(parent,attrs){this._super.apply(this,arguments),"string"==typeof attrs.get_rows&&(attrs.get_rows=this.egw().link("/index.php",{menuaction:this.options.get_rows})),this.createInputWidget(),this.input=null,this.createInputWidget()},createInputWidget:function(){this.input=$j(document.createElement("input")),this.input.addClass("et2_textbox"),this.setDOMNode(this.input[0]);var widget=this;this.input.autocomplete({delay:100,source:this.options.get_rows?this.options.get_rows:et2_selectbox.find_select_options(this,this.options.values),select:function(event,ui){return widget.value=ui.item[widget.options.id_field],widget.options.get_title?"function"==typeof widget.options.get_title?widget.input.val(widget.options.get_title.call(widget.value)):"string"==typeof widget.options.get_title:widget.input.val(ui.item.label),!1}})},getValue:function(){return this.options.blur&&this.input.val()==this.options.blur?"":this.value},set_value:function(_value){if(this.value=_value,this.input.autocomplete("instance")){var source=this.input.autocomplete("option","source");if("object"==typeof source)for(var i in source)if("undefined"!=typeof source[i].value&&"undefined"!=typeof source[i].label&&source[i].value===_value)this.input.val(source[i].label);else if("string"==typeof source[i]){this.input.val(source[_value]);break}}},set_blur:function(_value){_value?(this.input.attr("placeholder",_value+""),this.input[0].placeholder||(""==this.input.val()&&this.input.val(this.options.blur),this.input.focus(this,function(e){e.data.input.val()==e.data.options.blur&&e.data.input.val("")}).blur(this,function(e){""==e.data.input.val()&&e.data.input.val(e.data.options.blur)}))):this.input.removeAttr("placeholder")}})}.call(this);et2_register_widget(et2_ajaxSelect,["ajax_select"]);var et2_ajaxSelect_ro=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{multiline:{ignore:!0}},init:function(){this._super.apply(this,arguments),this.value="",this.span=$j(document.createElement("span")),this.setDOMNode(this.span[0])},set_value:function(_value){this.value=_value,_value||(_value=""),this.span.text(_value)},getDetachedAttributes:function(_attrs){_attrs.push("value")},getDetachedNodes:function(){return[this.span[0]]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_ajaxSelect_ro,["ajax_select_ro"]);var et2_vfs=function(){"use strict";return et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{value:{type:"any",description:"Array of (stat) information about the file"}},DIR_MIME_TYPE:"httpd/unix-directory",init:function(){this._super.apply(this,arguments),this.value="",this.span=$j(document.createElement("ul")).addClass("et2_vfs"),this.setDOMNode(this.span[0])},getValue:function(){return this.value},set_value:function(_value){if("object"!=typeof _value)return _value&&this.egw().debug("warn","%s only has path, needs full array",this.id,_value),void this.span.empty().text(_value);this.span.empty(),this.value=_value;var path=_value.path?_value.path:"/";if(_value.path.indexOf(_value.name)>=0){path=path.substr(0,_value.path.length-_value.name.length-1);var path_offset=path.split("/").length,path_parts=_value.path.split("/")}else var path_offset=0,path_parts=[_value.name];for(var text,i=path_offset;i<path_parts.length;i++){if(path+=("/"==path?"":"/")+path_parts[i],text=egw.decodePath(path_parts[i]),"apps"==path_parts[1])switch(path_parts.length){case 2:1==i&&(text=this.egw().lang("applications"));break;case 3:2==i&&(text=this.egw().lang(path_parts[2]));break;case 4:if(!isNaN(text)){var link_title=this.egw().link_title(path_parts[2],path_parts[3],function(title){title&&this.value.name!=title&&$j("li",this.span).last().text(title)},this);link_title&&"undefined"!=typeof link_title&&(text=link_title)}}var self=this,data={path:path,type:i<path_parts.length-1?this.DIR_MIME_TYPE:_value.mime};$j(document.createElement("li")).addClass("vfsFilename").text(text+(i<path_parts.length-1?"/":"")).addClass("et2_clickable et2_link").click({data:data,egw:this.egw()},function(e){self.onclick?self.click(e)&&e.data.egw.open(e.data.data,"file"):e.data.egw.open(e.data.data,"file")}).appendTo(this.span)}},getDetachedAttributes:function(_attrs){_attrs.push("value")},getDetachedNodes:function(){return[this.span[0]]},setDetachedAttributes:function(_nodes,_values){this.span=jQuery(_nodes[0]),"undefined"!=typeof _values.value&&this.set_value(_values.value)}})}.call(this);et2_register_widget(et2_vfs,["vfs"]);var et2_vfsName=function(){"use strict";return et2_textbox.extend({init:function(){this._super.apply(this,arguments),this.input.addClass("et2_vfs")},set_value:function(_value){_value.path&&(_value=_value.path),_value=egw.decodePath(_value),this._super.apply(this,[_value])},getValue:function(){return egw.encodePath(this._super.apply(this)||"")}})}.call(this);et2_register_widget(et2_vfsName,["vfs-name"]);var et2_vfsName_ro=function(){"use strict";return et2_textbox_ro.extend({init:function(){this._super.apply(this,arguments)},set_value:function(_value){_value.path&&(_value=_value.path),_value=egw.decodePath(_value),this._super.apply(this,[_value])},getValue:function(){return egw.encodePath(this._super.apply(this))}})}.call(this);et2_register_widget(et2_vfsName_ro,["vfs-name_ro"]);var et2_vfsMime=function(){"use strict";return expose(et2_valueWidget.extend([et2_IDetachedDOM],{attributes:{value:{type:"any",description:"Array of (stat) information about the file"},size:{name:"Icon size",type:"integer",description:"Size of icon / thumbnail, in pixels",default:et2_no_init},expose_callback:{name:"expose_callback",type:"js",default:et2_no_init,description:"JS code which is executed when expose slides."},expose_view:{name:"Expose view",type:"boolean",default:!0,description:"Clicking on an image would popup an expose view"},thumb_mime_size:{name:"Image thumbnail size",type:"string",default:"",description:" Size of thumbnail in pixel for specified mime type with syntax of: mime_type(s),size (eg. image,video,128)"}},legacyOptions:["size"],init:function(){this._super.apply(this,arguments),this.iconOverlayContainer=jQuery(document.createElement("span")).addClass("iconOverlayContainer"),this.image=jQuery(document.createElement("img")),this.image.addClass("et2_vfs vfsMimeIcon"),this.iconOverlayContainer.append(this.image),this.setDOMNode(this.iconOverlayContainer[0])},expose_onslide:function(gallery,index,slide){var content=!1;return this.options.expose_callback&&"function"==typeof this.options.expose_callback&&(content=this.options.expose_callback.call(this,[gallery,index]),content&&this.add(content)),content},getMedia:function(_value){var base_url=egw.webserverUrl.match(/^\//,"ig")?egw(window).window.location.origin+egw.webserverUrl:egw.webserverUrl,mediaContent=[{title:_value.name,type:_value.mime,href:_value.download_url}];return!_value.download_url||"/"!=_value.download_url[0]&&"http"==_value.download_url.substr(0,4)||(mediaContent[0].href=base_url+_value.download_url,mediaContent[0].href&&mediaContent[0].href.match(/\/webdav.php/,"ig")&&(mediaContent[0].download_href=mediaContent[0].href+"?download")),_value&&_value.mime&&_value.mime.match(/video\//,"ig")?mediaContent[0].thumbnail=this.egw().mime_icon(_value.mime,_value.path,void 0,_value.mtime):mediaContent[0].thumbnail=_value.path&&_value.mime?this.egw().mime_icon(_value.mime,_value.path,void 0,_value.mtime):this.image.attr("src")+"&thheight=128",mediaContent},set_value:function(_value){"object"!=typeof _value&&this.egw().debug("warn","%s only has path, needs array with path & mime",this.id,_value);var src=this.egw().mime_icon(_value.mime,_value.path,void 0,_value.mtime);if(src){if(src.indexOf("thumbnail.php")>-1){if(this.options.size)src+="&thsize="+this.options.size;else if(this.options.thumb_mime_size){var mime_size=this.options.thumb_mime_size.split(","),mime_regex=RegExp(_value.mime.split("/")[0]);"undefined"!=typeof mime_size&&jQuery.isArray(mime_size)&&!isNaN(mime_size[mime_size.length-1])&&isNaN(mime_size[0])&&this.options.thumb_mime_size.match(mime_regex[0],"ig")&&(src+="&thsize="+mime_size[mime_size.length-1])}this.image.css("max-width","100%")}this.image.attr("src",src)}(_value.mode&et2_vfsMode.prototype.types.l)==et2_vfsMode.prototype.types.l?"undefined"==typeof this.overlayContainer&&(this.overlayContainer=jQuery(document.createElement("span")).addClass("overlayContainer"),this.overlayContainer.append(jQuery(document.createElement("img")).addClass("overlay").attr("src",this.egw().image("link","etemplate"))),this.iconOverlayContainer.append(this.overlayContainer)):"undefined"!=typeof this.overlayContainer&&(this.overlayContainer.remove(),delete this.overlayContainer)},getDetachedAttributes:function(_attrs){_attrs.push("value","class")},getDetachedNodes:function(){return[this.node,this.iconOverlayContainer[0],this.image[0]]},setDetachedAttributes:function(_nodes,_values){this.iconOverlayContainer=jQuery(_nodes[1]),this.image=jQuery(_nodes[2]),this.node=_nodes[0],this.overlayContainer=_nodes[0].children[1],"undefined"!=typeof _values.class&&this.image.addClass(_values.class),"undefined"!=typeof _values.value&&this.set_value(_values.value)}}))}.call(this);et2_register_widget(et2_vfsMime,["vfs-mime"]);var et2_vfsSize=function(){"use strict";return et2_description.extend({attributes:{value:{type:"integer"}},init:function(){this._super.apply(this,arguments),this.span.addClass("et2_vfs")},human_size:function(size){"number"!=typeof size&&(size=parseInt(size)),size||(size=0);for(var units=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],i=0;size>=1024;)size/=1024,++i;return size.toFixed(0==i?0:1)+" "+units[i]},set_value:function(_value){_value.size&&(_value=_value.size),jQuery(this.node).text(this.human_size(_value))},setDetachedAttributes:function(_nodes,_values){"undefined"!=typeof _values.value&&(this.node=_nodes[0],this.set_value(_values.value),delete _values.value),this._super.apply(this,arguments)}})}.call(this);et2_register_widget(et2_vfsSize,["vfs-size"]);var et2_vfsMode=function(){"use strict";return et2_description.extend({types:{l:40960,s:49152,p:4096,c:8192,d:16384,b:24576,"-":32768},sticky:[{mask:512,char:"T",position:9},{mask:1024,char:"S",position:6},{mask:2048,char:"S",position:3}],perms:{x:1,w:2,r:4},init:function(){this._super.apply(this,arguments),this.span.addClass("et2_vfs")},text_mode:function(_value){var text=[];if("number"!=typeof _value&&(_value=parseInt(_value)),!_value)return"----------";var type="u";for(var flag in this.types)if((_value&this.types[flag])==this.types[flag]){type=flag;break}for(var i=0;3>i;i++){for(var perm in this.perms)_value&this.perms[perm]?text.unshift(perm):text.unshift("-");_value>>=3}for(var i=0;i<this.sticky.length;i++)this.sticky[i].mask&_value&&(current=text[this.sticky[i].position],text[this.sticky[i].position]=this.sticky[i].char,"x"==current&&text[this.sticky[i].position].toLowerCase());return type+text.join("")},set_value:function(_value){_value.size&&(_value=_value.size);var text=this.text_mode(_value);jQuery(this.node).text(text)},setDetachedAttributes:function(_nodes,_values){"undefined"!=typeof _values.value&&(this.node=_nodes[0],this.set_value(_values.value),delete _values.value),this._super.apply(this,arguments)}})}.call(this);et2_register_widget(et2_vfsMode,["vfs-mode"]);var et2_vfsUid=function(){"use strict";return et2_selectAccount_ro.extend({set_title:function(_node,_value){""==_value&&(arguments[1]="root"),this._super.apply(this,arguments)}})}.call(this);et2_register_widget(et2_vfsUid,["vfs-uid","vfs-gid"]);var et2_vfsUpload=function(){"use strict";return et2_file.extend({attributes:{value:{type:"any"},path:{name:"Path",description:"Upload files to the specified VFS path",type:"string",default:""}},legacyOptions:["mime"],asyncOptions:{target:egw.ajaxUrl(self.egw().getAppName()+".etemplate_widget_vfs.ajax_upload.etemplate")},init:function(_parent,attrs){this._super.apply(this,arguments),$j(this.node).addClass("et2_vfs"),this.options.path||(this.options.path=this.options.id),"/"==this.options.path.substr(-1)&&this.set_multiple(!0),this.list=$j(document.createElement("table")).appendTo(this.node)},set_value:function(_value){for(;this._children.length>0;){var node=this._children[this._children.length-1];this.removeChild(node),node.free()}if(this.progress.empty(),this.list.empty(),"object"==typeof _value&&_value&&_value.length)for(var i=0;i<_value.length;i++)this._addFile(_value[i])},getValue:function(){return null},getDOMNode:function(sender){if(sender!==this&&sender._type.indexOf("vfs")>=0){var value=sender.getValue&&sender.getValue()||sender.options.value||{},row=$j('[data-path="'+value.path+'"]',this.list);return"vfs-mime"===sender._type?$j(".icon",row).get(0)||null:$j(".title",row).get(0)||null}return this._super.apply(this,arguments)},beforeSend:function(form){var extra=(this.getInstanceManager(),this._super.apply(this,arguments));return extra.path=this.options.path,extra},_addFile:function(file_data){var row=$j(document.createElement("tr")).attr("data-path",file_data.path).attr("draggable","true").appendTo(this.list);$j(document.createElement("td")).addClass("icon").appendTo(row),$j(document.createElement("td")).addClass("title").appendTo(row),et2_createWidget("vfs-mime",{value:file_data},this),et2_createWidget("vfs",{value:file_data},this);if(!this.options.readonly){var self=this,delete_button=$j(document.createElement("td")).appendTo(row);$j("<div />").appendTo(delete_button).addClass("delete icon").bind("click",function(){et2_dialog.show_dialog(function(button){button==et2_dialog.YES_BUTTON&&egw.json("filemanager_ui::ajax_action",["delete",[row.attr("data-path")],""],function(data){data&&0==data.errs&&row.slideUp(row.remove),data&&data.msg&&self.egw().message(data.msg,0==data.errs?"success":"error")}).sendRequest()},egw.lang("Delete file?"))})}}})}.call(this);et2_register_widget(et2_vfsUpload,["vfs-upload"]);var et2_vfsSelect=function(){"use strict";return et2_inputWidget.extend({modes:["open","open-multiple","saveas","select-dir"],attributes:{mode:{name:"Dialog mode",type:"string",description:"One of {open|open-multiple|saveas|select-dir}",default:"open-multiple"},method:{name:"Server side callback",type:"string",description:"Server side callback to process selected value(s) in app.class.method or class::method format. The first parameter will be Method ID, the second the file list."},method_id:{name:"Method ID",type:"any",description:"optional parameter passed to server side callback. Can be a string or a function.",default:""},path:{name:"Path",type:"string",description:"Start path in VFS. Leave unset to use the last used path."},mime:{name:"Mime type",type:"string",description:"Limit display to the given mime-type"},button_label:{name:"Button label",description:"Set the label on the dialog's OK button.",default:"open"},value:{type:"any",description:"Array of paths (strings)"},button_caption:{name:"button caption",type:"string",default:"Select files from Filemanager ...",description:"Caption for vfs-select button.",translate:!0}},init:function(_parent,_attrs){this._super.apply(this,arguments),this.supportedWidgetClasses=[],this.button=$j(document.createElement("button")).attr("title",this.egw().lang("Select file(s) from VFS")).addClass("et2_button et2_button_text et2_vfs_btn").css("background-image","url("+this.egw().image("filemanager/navbar")+")"),""!=this.options.button_caption&&this.button.text(this.options.button_caption),this.setDOMNode(egw.app("filemanager")?this.button[0]:document.createElement("span"))},click:function(e){if(egw.app("filemanager")){var self=this,attrs={menuaction:"filemanager.filemanager_select.select",mode:this.options.mode,method:this.options.method,label:this.options.button_label,id:"function"==typeof this.options.method_id?this.options.method_id.call():this.options.method_id};this.options.path&&(attrs.path=this.options.path),this.options.mime&&(attrs.mime=this.options.mime);var popup=this.egw(window).open_link(this.egw().link("/index.php",attrs),"link_existing","680x400");if(popup){self.egw().window.setTimeout(function(){jQuery(popup).bind("unload",function(){self.value=this.selected_files,"undefined"!=typeof this.etemplate2&&(self.options.path=this.etemplate2.getByApplication("filemanager")[0].widgetContainer.getArrayMgr("content").getEntry("path"))})},1e3);var poll=self.egw().window.setInterval(function(){popup.closed&&(self.egw().window.clearInterval(poll),$j(self.node).change())},1e3)}}},set_mode:function(mode){return jQuery.inArray(mode,this.modes)<0?void this.egw().debug("warn","Invalid mode for '%s': %s Valid options:",this.id,mode,this.modes):void(this.options.mode=mode)},set_button_label:function(label){this.options.button_label=label},set_button_caption:function(caption){this.options.button_caption=caption},set_method_id:function(id){this.options.method_id=id},getValue:function(){return this.value}})}.call(this);et2_register_widget(et2_vfsSelect,["vfs-select"]);var et2_video=function(){"use strict";return et2_baseWidget.extend(et2_IDOMNode,{attributes:{video_src:{name:"Video",type:"string",description:"Source of video to display"},src_type:{name:"Source type",type:"string",description:"Defines the type the stream source provided"},muted:{name:"Audio control",type:"boolean",default:!1,description:"Defines that the audio output of the video should be muted"},autoplay:{name:"Autoply",type:"boolean",default:!1,description:"Defines if Video will start playing as soon as it is ready"},controls:{name:"Control buttons",type:"boolean",default:!1,description:"Defines if Video controls, play/pause buttons should be displayed"},poster:{name:"Video Poster",type:"string",default:"",description:"Specifies an image to be shown while video is loading or before user play it"},loop:{name:"Video loop",type:"boolean",default:!1,description:"Defines if the video should be played repeatedly"}},init:function(){this._super.apply(this,arguments),this.video=jQuery(document.createElement("video")),this.options.controls&&this.video.attr("controls",!0),this.options.autoplay&&this.video.attr("autoplay",!0),this.options.muted&&this.video.attr("muted",!0),this.options.video_src&&this.set_src(this.options.video_src),this.options.loop&&this.video.attr("loop",!0),this.setDOMNode(this.video[0])},set_src:function(_value){if(_value){var source=jQuery(document.createElement("source")).attr("src",_value).appendTo(this.video);this.options.src_type&&source.attr("type",this.options.src_type)}},set_autoplay:function(_value){_value&&this.video.attr("autoplay",_value)},set_controls:function(_value){_value&&this.video.attr("controls",_value)},set_poster:function(_url){_url&&this.video.attr("poster",_url)}})}.call(this);et2_register_widget(et2_video,["video"]),function(b){var a={settings:{barWidth:1,barHeight:50,moduleSize:5,showHRI:!0,addQuietZone:!0,marginHRI:5,bgColor:"#FFFFFF",color:"#000000",fontSize:10,output:"css",posX:0,posY:0},intval:function(d){var c=typeof d;return"string"==c?(d=d.replace(/[^0-9-.]/g,""),d=parseInt(1*d,10),isNaN(d)||!isFinite(d)?0:d):"number"==c&&isFinite(d)?Math.floor(d):0},i25:{encoding:["NNWWN","WNNNW","NWNNW","WWNNN","NNWNW","WNWNN","NWWNN","NNNWW","WNNWN","NWNWN"],compute:function(g,j,f){if(j){"int25"==f&&g.length%2==0&&(g="0"+g);for(var c,h=!0,e=0,d=g.length-1;d>-1;d--){if(c=a.intval(g.charAt(d)),isNaN(c))return"";e+=h?3*c:c,h=!h}g+=((10-e%10)%10).toString()}else g.length%2!=0&&(g="0"+g);return g},getDigit:function(k,l,h){if(k=this.compute(k,l,h),""==k)return"";result="";var f,d;if("int25"==h){result+="1010";var g,e;for(f=0;f<k.length/2;f++)for(g=k.charAt(2*f),e=k.charAt(2*f+1),d=0;5>d;d++)result+="1","W"==this.encoding[g].charAt(d)&&(result+="1"),result+="0","W"==this.encoding[e].charAt(d)&&(result+="0");result+="1101"}else if("std25"==h){result+="11011010";var m;for(f=0;f<k.length;f++)for(m=k.charAt(f),d=0;5>d;d++)result+="1","W"==this.encoding[m].charAt(d)&&(result+="11"),result+="0";result+="11010110"}return result}},ean:{encoding:[["0001101","0100111","1110010"],["0011001","0110011","1100110"],["0010011","0011011","1101100"],["0111101","0100001","1000010"],["0100011","0011101","1011100"],["0110001","0111001","1001110"],["0101111","0000101","1010000"],["0111011","0010001","1000100"],["0110111","0001001","1001000"],["0001011","0010111","1110100"]],first:["000000","001011","001101","001110","010011","011001","011100","010101","010110","011010"],getDigit:function(j,h){var e="ean8"==h?7:12;if(j=j.substring(0,e),j.length!=e)return"";for(var k,g=0;g<j.length;g++)if(k=j.charAt(g),"0">k||k>"9")return"";j=this.compute(j,h);var d="101";if("ean8"==h){for(var g=0;4>g;g++)d+=this.encoding[a.intval(j.charAt(g))][0];d+="01010";for(var g=4;8>g;g++)d+=this.encoding[a.intval(j.charAt(g))][2]}else{for(var f=this.first[a.intval(j.charAt(0))],g=1;7>g;g++)d+=this.encoding[a.intval(j.charAt(g))][a.intval(f.charAt(g-1))];d+="01010";for(var g=7;13>g;g++)d+=this.encoding[a.intval(j.charAt(g))][2]}return d+="101"},compute:function(f,e){var c="ean13"==e?12:7;f=f.substring(0,c);var d=0,g=!0;for(i=f.length-1;i>-1;i--)d+=(g?3:1)*a.intval(f.charAt(i)),g=!g;return f+((10-d%10)%10).toString()}},upc:{getDigit:function(c){return c.length<12&&(c="0"+c),a.ean.getDigit(c,"ean13")},compute:function(c){return c.length<12&&(c="0"+c),a.ean.compute(c,"ean13").substr(1)}},msi:{encoding:["100100100100","100100100110","100100110100","100100110110","100110100100","100110100110","100110110100","100110110110","110100100100","110100100110"],compute:function(c,d){return"object"==typeof d?("mod10"==d.crc1?c=this.computeMod10(c):"mod11"==d.crc1&&(c=this.computeMod11(c)),"mod10"==d.crc2?c=this.computeMod10(c):"mod11"==d.crc2&&(c=this.computeMod11(c))):"boolean"==typeof d&&d&&(c=this.computeMod10(c)),c},computeMod10:function(h){var e,c=h.length%2,g=0,f=0;for(e=0;e<h.length;e++)c?g=10*g+a.intval(h.charAt(e)):f+=a.intval(h.charAt(e)),c=!c;var d=(2*g).toString();for(e=0;e<d.length;e++)f+=a.intval(d.charAt(e));return h+((10-f%10)%10).toString()},computeMod11:function(e){for(var d=0,f=2,c=e.length-1;c>=0;c--)d+=f*a.intval(e.charAt(c)),f=7==f?2:f+1;return e+((11-d%11)%11).toString()},getDigit:function(f,g){var e="0123456789",d=0,c="";for(f=this.compute(f,!1),c="110",i=0;i<f.length;i++){if(d=e.indexOf(f.charAt(i)),0>d)return"";c+=this.encoding[d]}return c+="1001"}},code11:{encoding:["101011","1101011","1001011","1100101","1011011","1101101","1001101","1010011","1101001","110101","101101"],getDigit:function(e){var j,m,p="0123456789-",q="",f="0";for(q="1011001"+f,j=0;j<e.length;j++){if(m=p.indexOf(e.charAt(j)),0>m)return"";q+=this.encoding[m]+f}var o=0,h=0,l=1,d=0;for(j=e.length-1;j>=0;j--)o=10==o?1:o+1,l=10==l?1:l+1,m=p.indexOf(e.charAt(j)),h+=o*m,d+=l*m;var n=h%11;d+=n;var g=d%11;return q+=this.encoding[n]+f,e.length>=10&&(q+=this.encoding[g]+f),q+="1011001"}},code39:{encoding:["101001101101","110100101011","101100101011","110110010101","101001101011","110100110101","101100110101","101001011011","110100101101","101100101101","110101001011","101101001011","110110100101","101011001011","110101100101","101101100101","101010011011","110101001101","101101001101","101011001101","110101010011","101101010011","110110101001","101011010011","110101101001","101101101001","101010110011","110101011001","101101011001","101011011001","110010101011","100110101011","110011010101","100101101011","110010110101","100110110101","100101011011","110010101101","100110101101","100100100101","100100101001","100101001001","101001001001","100101101101"],getDigit:function(h){var f,e,g="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%*",d="",c="0";if(h.indexOf("*")>=0)return"";for(h=("*"+h+"*").toUpperCase(),f=0;f<h.length;f++){if(e=g.indexOf(h.charAt(f)),0>e)return"";f>0&&(d+=c),d+=this.encoding[e]}return d}},code93:{encoding:["100010100","101001000","101000100","101000010","100101000","100100100","100100010","101010000","100010010","100001010","110101000","110100100","110100010","110010100","110010010","110001010","101101000","101100100","101100010","100110100","100011010","101011000","101001100","101000110","100101100","100010110","110110100","110110010","110101100","110100110","110010110","110011010","101101100","101100110","100110110","100111010","100101110","111010100","111010010","111001010","101101110","101110110","110101110","100100110","111011010","111010110","100110010","101011110"],getDigit:function(e,j){var l,n="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%____*",o="";if(e.indexOf("*")>=0)return"";for(e=e.toUpperCase(),o+=this.encoding[47],i=0;i<e.length;i++){if(l=e.charAt(i),index=n.indexOf(l),"_"==l||index<0)return"";o+=this.encoding[index]}if(j){var m=0,g=0,h=1,d=0;for(i=e.length-1;i>=0;i--)m=20==m?1:m+1,h=15==h?1:h+1,index=n.indexOf(e.charAt(i)),g+=m*index,d+=h*index;var l=g%47;d+=l;var f=d%47;o+=this.encoding[l],o+=this.encoding[f]}return o+=this.encoding[47],o+="1"}},code128:{encoding:["11011001100","11001101100","11001100110","10010011000","10010001100","10001001100","10011001000","10011000100","10001100100","11001001000","11001000100","11000100100","10110011100","10011011100","10011001110","10111001100","10011101100","10011100110","11001110010","11001011100","11001001110","11011100100","11001110100","11101101110","11101001100","11100101100","11100100110","11101100100","11100110100","11100110010","11011011000","11011000110","11000110110","10100011000","10001011000","10001000110","10110001000","10001101000","10001100010","11010001000","11000101000","11000100010","10110111000","10110001110","10001101110","10111011000","10111000110","10001110110","11101110110","11010001110","11000101110","11011101000","11011100010","11011101110","11101011000","11101000110","11100010110","11101101000","11101100010","11100011010","11101111010","11001000010","11110001010","10100110000","10100001100","10010110000","10010000110","10000101100","10000100110","10110010000","10110000100","10011010000","10011000010","10000110100","10000110010","11000010010","11001010000","11110111010","11000010100","10001111010","10100111100","10010111100","10010011110","10111100100","10011110100","10011110010","11110100100","11110010100","11110010010","11011011110","11011110110","11110110110","10101111000","10100011110","10001011110","10111101000","10111100010","11110101000","11110100010","10111011110","10111101110","11101011110","11110101110","11010000100","11010010000","11010011100","11000111010"],
getDigit:function(e){var d=" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~",o="",l=0,f=0,k=0,h=0,n=0;for(k=0;k<e.length;k++)if(-1==d.indexOf(e.charAt(k)))return"";var g=e.length>1,m="";for(k=0;3>k&&k<e.length;k++)m=e.charAt(k),g&=m>="0"&&"9">=m;for(l=g?105:104,o=this.encoding[l],k=0;k<e.length;){if(g)(k==e.length||e.charAt(k)<"0"||e.charAt(k)>"9"||e.charAt(k+1)<"0"||e.charAt(k+1)>"9")&&(g=!1,o+=this.encoding[100],l+=100*++f);else{for(h=0;k+h<e.length&&e.charAt(k+h)>="0"&&e.charAt(k+h)<="9";)h++;g=h>5||k+h-1==e.length&&h>3,g&&(o+=this.encoding[99],l+=99*++f)}g?(n=a.intval(e.charAt(k)+e.charAt(k+1)),k+=2):(n=d.indexOf(e.charAt(k)),k+=1),o+=this.encoding[n],l+=++f*n}return o+=this.encoding[l%103],o+=this.encoding[106],o+="11"}},codabar:{encoding:["101010011","101011001","101001011","110010101","101101001","110101001","100101011","100101101","100110101","110100101","101001101","101100101","1101011011","1101101011","1101101101","1011011011","1011001001","1010010011","1001001011","1010011001"],getDigit:function(h){var f,e,g="0123456789-$:/.+",d="",c="0";for(d+=this.encoding[16]+c,f=0;f<h.length;f++){if(e=g.indexOf(h.charAt(f)),0>e)return"";d+=this.encoding[e]+c}return d+=this.encoding[16]}},datamatrix:{lengthRows:[10,12,14,16,18,20,22,24,26,32,36,40,44,48,52,64,72,80,88,96,104,120,132,144,8,8,12,12,16,16],lengthCols:[10,12,14,16,18,20,22,24,26,32,36,40,44,48,52,64,72,80,88,96,104,120,132,144,18,32,26,36,36,48],dataCWCount:[3,5,8,12,18,22,30,36,44,62,86,114,144,174,204,280,368,456,576,696,816,1050,1304,1558,5,10,16,22,32,49],solomonCWCount:[5,7,10,12,14,18,20,24,28,36,42,48,56,68,84,112,144,192,224,272,336,408,496,620,7,11,14,18,24,28],dataRegionRows:[8,10,12,14,16,18,20,22,24,14,16,18,20,22,24,14,16,18,20,22,24,18,20,22,6,6,10,10,14,14],dataRegionCols:[8,10,12,14,16,18,20,22,24,14,16,18,20,22,24,14,16,18,20,22,24,18,20,22,16,14,24,16,16,22],regionRows:[1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,4,4,4,4,4,4,6,6,6,1,1,1,1,1,1],regionCols:[1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,4,4,4,4,4,4,6,6,6,1,2,1,2,2,2],interleavedBlocks:[1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,4,4,4,4,6,6,8,8,1,1,1,1,1,1],logTab:[-255,255,1,240,2,225,241,53,3,38,226,133,242,43,54,210,4,195,39,114,227,106,134,28,243,140,44,23,55,118,211,234,5,219,196,96,40,222,115,103,228,78,107,125,135,8,29,162,244,186,141,180,45,99,24,49,56,13,119,153,212,199,235,91,6,76,220,217,197,11,97,184,41,36,223,253,116,138,104,193,229,86,79,171,108,165,126,145,136,34,9,74,30,32,163,84,245,173,187,204,142,81,181,190,46,88,100,159,25,231,50,207,57,147,14,67,120,128,154,248,213,167,200,63,236,110,92,176,7,161,77,124,221,102,218,95,198,90,12,152,98,48,185,179,42,209,37,132,224,52,254,239,117,233,139,22,105,27,194,113,230,206,87,158,80,189,172,203,109,175,166,62,127,247,146,66,137,192,35,252,10,183,75,216,31,83,33,73,164,144,85,170,246,65,174,61,188,202,205,157,143,169,82,72,182,215,191,251,47,178,89,151,101,94,160,123,26,112,232,21,51,238,208,131,58,69,148,18,15,16,68,17,121,149,129,19,155,59,249,70,214,250,168,71,201,156,64,60,237,130,111,20,93,122,177,150],aLogTab:[1,2,4,8,16,32,64,128,45,90,180,69,138,57,114,228,229,231,227,235,251,219,155,27,54,108,216,157,23,46,92,184,93,186,89,178,73,146,9,18,36,72,144,13,26,52,104,208,141,55,110,220,149,7,14,28,56,112,224,237,247,195,171,123,246,193,175,115,230,225,239,243,203,187,91,182,65,130,41,82,164,101,202,185,95,190,81,162,105,210,137,63,126,252,213,135,35,70,140,53,106,212,133,39,78,156,21,42,84,168,125,250,217,159,19,38,76,152,29,58,116,232,253,215,131,43,86,172,117,234,249,223,147,11,22,44,88,176,77,154,25,50,100,200,189,87,174,113,226,233,255,211,139,59,118,236,245,199,163,107,214,129,47,94,188,85,170,121,242,201,191,83,166,97,194,169,127,254,209,143,51,102,204,181,71,142,49,98,196,165,103,206,177,79,158,17,34,68,136,61,122,244,197,167,99,198,161,111,222,145,15,30,60,120,240,205,183,67,134,33,66,132,37,74,148,5,10,20,40,80,160,109,218,153,31,62,124,248,221,151,3,6,12,24,48,96,192,173,119,238,241,207,179,75,150,1],champGaloisMult:function(d,c){return d&&c?this.aLogTab[(this.logTab[d]+this.logTab[c])%255]:0},champGaloisDoub:function(d,c){return d?c?this.aLogTab[(this.logTab[d]+c)%255]:d:0},champGaloisSum:function(d,c){return d^c},selectIndex:function(d,c){if((1>d||d>1558)&&!c)return-1;if((1>d||d>49)&&c)return-1;var e=0;for(c&&(e=24);this.dataCWCount[e]<d;)e++;return e},encodeDataCodeWordsASCII:function(f){var d,g,e=new Array,h=0;for(d=0;d<f.length;d++)g=f.charCodeAt(d),g>127?(e[h]=235,g-=127,h++):g>=48&&57>=g&&d+1<f.length&&f.charCodeAt(d+1)>=48&&f.charCodeAt(d+1)<=57?(g=10*(g-48)+(f.charCodeAt(d+1)-48),g+=130,d++):g++,e[h]=g,h++;return e},addPadCW:function(d,g,f){if(!(g>=f)){d[g]=129;var e,c;for(c=g+1;f>c;c++)e=149*(c+1)%253+1,d[c]=(129+e)%254}},calculSolFactorTable:function(c){var e,d,f=new Array;for(e=0;c>=e;e++)f[e]=1;for(e=1;c>=e;e++)for(d=e-1;d>=0;d--)f[d]=this.champGaloisDoub(f[d],e),d>0&&(f[d]=this.champGaloisSum(f[d],f[d-1]));return f},addReedSolomonCW:function(e,d,n,m,c){var h,g,f,p=0,o=e/c,l=new Array;for(f=0;c>f;f++){for(h=0;o>h;h++)l[h]=0;for(h=f;n>h;h+=c)for(p=this.champGaloisSum(m[h],l[o-1]),g=o-1;g>=0;g--)p?l[g]=this.champGaloisMult(p,d[g]):l[g]=0,g>0&&(l[g]=this.champGaloisSum(l[g-1],l[g]));for(g=n+f,h=o-1;h>=0;h--)m[g]=l[h],g+=c}return m},getBits:function(c){for(var e=new Array,d=0;8>d;d++)e[d]=c&128>>d?1:0;return e},next:function(h,j,f,k,e,g){var d=0,l=4,c=0;do{l==j&&0==c?(this.patternShapeSpecial1(e,g,k[d],j,f),d++):3>h&&l==j-2&&0==c&&f%4!=0?(this.patternShapeSpecial2(e,g,k[d],j,f),d++):l==j-2&&0==c&&f%8==4?(this.patternShapeSpecial3(e,g,k[d],j,f),d++):l==j+4&&2==c&&f%8==0&&(this.patternShapeSpecial4(e,g,k[d],j,f),d++);do j>l&&c>=0&&1!=g[l][c]&&(this.patternShapeStandard(e,g,k[d],l,c,j,f),d++),l-=2,c+=2;while(l>=0&&f>c);l+=1,c+=3;do l>=0&&f>c&&1!=g[l][c]&&(this.patternShapeStandard(e,g,k[d],l,c,j,f),d++),l+=2,c-=2;while(j>l&&c>=0);l+=3,c+=1}while(j>l||f>c)},patternShapeStandard:function(g,d,h,j,c,e,f){this.placeBitInDatamatrix(g,d,h[0],j-2,c-2,e,f),this.placeBitInDatamatrix(g,d,h[1],j-2,c-1,e,f),this.placeBitInDatamatrix(g,d,h[2],j-1,c-2,e,f),this.placeBitInDatamatrix(g,d,h[3],j-1,c-1,e,f),this.placeBitInDatamatrix(g,d,h[4],j-1,c,e,f),this.placeBitInDatamatrix(g,d,h[5],j,c-2,e,f),this.placeBitInDatamatrix(g,d,h[6],j,c-1,e,f),this.placeBitInDatamatrix(g,d,h[7],j,c,e,f)},patternShapeSpecial1:function(f,c,g,d,e){this.placeBitInDatamatrix(f,c,g[0],d-1,0,d,e),this.placeBitInDatamatrix(f,c,g[1],d-1,1,d,e),this.placeBitInDatamatrix(f,c,g[2],d-1,2,d,e),this.placeBitInDatamatrix(f,c,g[3],0,e-2,d,e),this.placeBitInDatamatrix(f,c,g[4],0,e-1,d,e),this.placeBitInDatamatrix(f,c,g[5],1,e-1,d,e),this.placeBitInDatamatrix(f,c,g[6],2,e-1,d,e),this.placeBitInDatamatrix(f,c,g[7],3,e-1,d,e)},patternShapeSpecial2:function(f,c,g,d,e){this.placeBitInDatamatrix(f,c,g[0],d-3,0,d,e),this.placeBitInDatamatrix(f,c,g[1],d-2,0,d,e),this.placeBitInDatamatrix(f,c,g[2],d-1,0,d,e),this.placeBitInDatamatrix(f,c,g[3],0,e-4,d,e),this.placeBitInDatamatrix(f,c,g[4],0,e-3,d,e),this.placeBitInDatamatrix(f,c,g[5],0,e-2,d,e),this.placeBitInDatamatrix(f,c,g[6],0,e-1,d,e),this.placeBitInDatamatrix(f,c,g[7],1,e-1,d,e)},patternShapeSpecial3:function(f,c,g,d,e){this.placeBitInDatamatrix(f,c,g[0],d-3,0,d,e),this.placeBitInDatamatrix(f,c,g[1],d-2,0,d,e),this.placeBitInDatamatrix(f,c,g[2],d-1,0,d,e),this.placeBitInDatamatrix(f,c,g[3],0,e-2,d,e),this.placeBitInDatamatrix(f,c,g[4],0,e-1,d,e),this.placeBitInDatamatrix(f,c,g[5],1,e-1,d,e),this.placeBitInDatamatrix(f,c,g[6],2,e-1,d,e),this.placeBitInDatamatrix(f,c,g[7],3,e-1,d,e)},patternShapeSpecial4:function(f,c,g,d,e){this.placeBitInDatamatrix(f,c,g[0],d-1,0,d,e),this.placeBitInDatamatrix(f,c,g[1],d-1,e-1,d,e),this.placeBitInDatamatrix(f,c,g[2],0,e-3,d,e),this.placeBitInDatamatrix(f,c,g[3],0,e-2,d,e),this.placeBitInDatamatrix(f,c,g[4],0,e-1,d,e),this.placeBitInDatamatrix(f,c,g[5],1,e-3,d,e),this.placeBitInDatamatrix(f,c,g[6],1,e-2,d,e),this.placeBitInDatamatrix(f,c,g[7],1,e-1,d,e)},placeBitInDatamatrix:function(g,d,j,h,c,e,f){0>h&&(h+=e,c+=4-(e+4)%8),0>c&&(c+=f,h+=4-(f+4)%8),1!=d[h][c]&&(g[h][c]=j,d[h][c]=1)},addFinderPattern:function(k,m,h,l,c){var n=(l+2)*m,d=(c+2)*h,e=new Array;e[0]=new Array;for(var f=0;d+2>f;f++)e[0][f]=0;for(var g=0;n>g;g++){e[g+1]=new Array,e[g+1][0]=0,e[g+1][d+1]=0;for(var f=0;d>f;f++)g%(l+2)==0?f%2==0?e[g+1][f+1]=1:e[g+1][f+1]=0:g%(l+2)==l+1?e[g+1][f+1]=1:f%(c+2)==c+1?g%2==0?e[g+1][f+1]=0:e[g+1][f+1]=1:f%(c+2)==0?e[g+1][f+1]=1:(e[g+1][f+1]=0,e[g+1][f+1]=k[g-1-2*parseInt(g/(l+2))][f-1-2*parseInt(f/(c+2))])}e[n+1]=new Array;for(var f=0;d+2>f;f++)e[n+1][f]=0;return e},getDigit:function(l,q){var p=this.encodeDataCodeWordsASCII(l),j=p.length,f=this.selectIndex(j,q),m=this.dataCWCount[f],x=this.solomonCWCount[f],c=m+x,y=this.lengthRows[f],z=this.lengthCols[f],e=this.regionRows[f],d=this.regionCols[f],k=this.dataRegionRows[f],w=this.dataRegionCols[f],t=y-2*e,h=z-2*d,u=this.interleavedBlocks[f],s=x/u;this.addPadCW(p,j,m);var r=this.calculSolFactorTable(s);this.addReedSolomonCW(x,r,m,p,u);for(var o=new Array,n=0;c>n;n++)o[n]=this.getBits(p[n]);for(var A=new Array,v=new Array,n=0;h>n;n++)A[n]=new Array,v[n]=new Array;return t*h%8==4&&(A[t-2][h-2]=1,A[t-1][h-1]=1,A[t-1][h-2]=0,A[t-2][h-1]=0,v[t-2][h-2]=1,v[t-1][h-1]=1,v[t-1][h-2]=1,v[t-2][h-1]=1),this.next(0,t,h,o,A,v),A=this.addFinderPattern(A,e,d,k,w)}},lec:{cInt:function(e,f){for(var d="",c=0;f>c;c++)d+=String.fromCharCode(255&e),e>>=8;return d},cRgb:function(e,d,c){return String.fromCharCode(c)+String.fromCharCode(d)+String.fromCharCode(e)},cHexColor:function(h){var d=parseInt("0x"+h.substr(1)),c=255&d;d>>=8;var f=255&d,e=d>>8;return this.cRgb(e,f,c)}},hexToRGB:function(h){var d=parseInt("0x"+h.substr(1)),c=255&d;d>>=8;var f=255&d,e=d>>8;return{r:e,g:f,b:c}},isHexColor:function(d){var c=new RegExp("#[0-91-F]","gi");return d.match(c)},base64Encode:function(o){for(var h,f,e,n,m,l,j,c="",d="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",g=0;g<o.length;)h=o.charCodeAt(g++),f=o.charCodeAt(g++),e=o.charCodeAt(g++),n=h>>2,m=(3&h)<<4|f>>4,l=(15&f)<<2|e>>6,j=63&e,isNaN(f)?l=j=64:isNaN(e)&&(j=64),c+=d.charAt(n)+d.charAt(m)+d.charAt(l)+d.charAt(j);return c},bitStringTo2DArray:function(f){var e=[];e[0]=[];for(var c=0;c<f.length;c++)e[0][c]=f.charAt(c);return e},resize:function(d,c){return d.css("padding","0px").css("overflow","auto").css("width",c+"px").html(""),d},digitToBmpRenderer:function(t,v,o,g,n,z){var e=o.length,f=o[0].length,u=0,r=this.isHexColor(v.bgColor)?this.lec.cHexColor(v.bgColor):this.lec.cRgb(255,255,255),q=this.isHexColor(v.color)?this.lec.cHexColor(v.color):this.lec.cRgb(0,0,0),d="",c="";for(u=0;n>u;u++)d+=r,c+=q;var m=(4-n*f*3%4)%4,C=(n*f+m)*z*e,w="";for(u=0;m>u;u++)w+="\x00";for(var A="BM"+this.lec.cInt(54+C,4)+"\x00\x00\x00\x00"+this.lec.cInt(54,4)+this.lec.cInt(40,4)+this.lec.cInt(n*f,4)+this.lec.cInt(z*e,4)+this.lec.cInt(1,2)+this.lec.cInt(24,2)+"\x00\x00\x00\x00"+this.lec.cInt(C,4)+this.lec.cInt(2835,4)+this.lec.cInt(2835,4)+this.lec.cInt(0,4)+this.lec.cInt(0,4),h=e-1;h>=0;h--){for(var l="",j=0;f>j;j++)l+="0"==o[h][j]?d:c;l+=w;for(var s=0;z>s;s++)A+=l}var B=document.createElement("object");B.setAttribute("type","image/bmp"),B.setAttribute("data","data:image/bmp;base64,"+this.base64Encode(A)),this.resize(t,n*f+m).append(B)},digitToBmp:function(g,f,j,d){var c=a.intval(f.barWidth),e=a.intval(f.barHeight);this.digitToBmpRenderer(g,f,this.bitStringTo2DArray(j),d,c,e)},digitToBmp2D:function(f,e,g,c){var d=a.intval(e.moduleSize);this.digitToBmpRenderer(f,e,g,c,d,d)},digitToCssRenderer:function(q,c,m,e,p,g){for(var f,h,r=m.length,d=m[0].length,j="",o='<div style="float: left; font-size: 0px; background-color: '+c.bgColor+"; height: "+g+'px; width: &Wpx"></div>',l='<div style="float: left; font-size: 0px; width:0; border-left: &Wpx solid '+c.color+"; height: "+g+'px;"></div>',k=0;r>k;k++){f=0,h=m[k][0];for(var n=0;d>n;n++)h==m[k][n]?f++:(j+=("0"==h?o:l).replace("&W",f*p),h=m[k][n],f=1);f>0&&(j+=("0"==h?o:l).replace("&W",f*p))}c.showHRI&&(j+='<div style="clear:both; width: 100%; background-color: '+c.bgColor+"; color: "+c.color+"; text-align: center; font-size: "+c.fontSize+"px; margin-top: "+c.marginHRI+'px;">'+e+"</div>"),this.resize(q,p*d).html(j)},digitToCss:function(g,f,j,d){var c=a.intval(f.barWidth),e=a.intval(f.barHeight);this.digitToCssRenderer(g,f,this.bitStringTo2DArray(j),d,c,e)},digitToCss2D:function(f,e,g,c){var d=a.intval(e.moduleSize);this.digitToCssRenderer(f,e,g,c,d,d)},digitToSvgRenderer:function(q,s,m,f,k,t){var d=m.length,e=m[0].length,p=k*e,l=t*d;if(s.showHRI){var g=a.intval(s.fontSize);l+=a.intval(s.marginHRI)+g}var n='<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="'+p+'" height="'+l+'">';n+='<rect width="'+p+'" height="'+l+'" x="0" y="0" fill="'+s.bgColor+'" />';for(var r,o,c='<rect width="&W" height="'+t+'" x="&X" y="&Y" fill="'+s.color+'" />',h=0;d>h;h++){r=0,o=m[h][0];for(var j=0;e>j;j++)o==m[h][j]?r++:("1"==o&&(n+=c.replace("&W",r*k).replace("&X",(j-r)*k).replace("&Y",h*t)),o=m[h][j],r=1);r>0&&"1"==o&&(n+=c.replace("&W",r*k).replace("&X",(e-r)*k).replace("&Y",h*t))}s.showHRI&&(n+='<g transform="translate('+Math.floor(p/2)+' 0)">',n+='<text y="'+(l-Math.floor(g/2))+'" text-anchor="middle" style="font-family: Arial; font-size: '+g+'px;" fill="'+s.color+'">'+f+"</text>",n+="</g>"),n+="</svg>";var u=document.createElement("object");u.setAttribute("type","image/svg+xml"),u.setAttribute("data","data:image/svg+xml,"+n),this.resize(q,p).append(u)},digitToSvg:function(g,f,j,d){var c=a.intval(f.barWidth),e=a.intval(f.barHeight);this.digitToSvgRenderer(g,f,this.bitStringTo2DArray(j),d,c,e)},digitToSvg2D:function(f,e,g,c){var d=a.intval(e.moduleSize);this.digitToSvgRenderer(f,e,g,c,d,d)},digitToCanvasRenderer:function(s,e,o,g,m,f,q,k){var c=s.get(0);if(c&&c.getContext){var t=o.length,d=o[0].length,r=c.getContext("2d");r.lineWidth=1,r.lineCap="butt",r.fillStyle=e.bgColor,r.fillRect(m,f,d*q,t*k),r.fillStyle=e.color;for(var n=0;t>n;n++){for(var j=0,l=o[n][0],p=0;d>p;p++)l==o[n][p]?j++:("1"==l&&r.fillRect(m+(p-j)*q,f+n*k,q*j,k),l=o[n][p],j=1);j>0&&"1"==l&&r.fillRect(m+(d-j)*q,f+n*k,q*j,k)}if(e.showHRI){var h=r.measureText(g);r.fillText(g,m+Math.floor((d*q-h.width)/2),f+t*k+e.fontSize+e.marginHRI)}}},digitToCanvas:function(j,g,l,e){var d=a.intval(g.barWidth),f=a.intval(g.barHeight),c=a.intval(g.posX),k=a.intval(g.posY);this.digitToCanvasRenderer(j,g,this.bitStringTo2DArray(l),e,c,k,d,f)},digitToCanvas2D:function(g,f,j,d){var e=a.intval(f.moduleSize),c=a.intval(f.posX),h=a.intval(f.posY);this.digitToCanvasRenderer(g,f,j,d,c,h,e,e)}};b.fn.extend({barcode:function(h,m,f){var n="",g="",d="",k=!0,o=!1,j=!1;if("string"==typeof h?d=h:"object"==typeof h&&(d="string"==typeof h.code?h.code:"",k="undefined"!=typeof h.crc?h.crc:!0,o="undefined"!=typeof h.rect?h.rect:!1),""==d)return!1;"undefined"==typeof f&&(f=[]);for(var c in a.settings)void 0==f[c]&&(f[c]=a.settings[c]);switch(m){case"std25":case"int25":n=a.i25.getDigit(d,k,m),g=a.i25.compute(d,k,m);break;case"ean8":case"ean13":n=a.ean.getDigit(d,m),g=a.ean.compute(d,m);break;case"upc":n=a.upc.getDigit(d),g=a.upc.compute(d);break;case"code11":n=a.code11.getDigit(d),g=d;break;case"code39":n=a.code39.getDigit(d),g=d;break;case"code93":n=a.code93.getDigit(d,k),g=d;break;case"code128":n=a.code128.getDigit(d),g=d;break;case"codabar":n=a.codabar.getDigit(d),g=d;break;case"msi":n=a.msi.getDigit(d,k),g=a.msi.compute(d,k);break;case"datamatrix":n=a.datamatrix.getDigit(d,o),g=d,j=!0}if(0==n.length)return b(this);!j&&f.addQuietZone&&(n="0000000000"+n+"0000000000");var l=b(this),e="digitTo"+f.output.charAt(0).toUpperCase()+f.output.substr(1)+(j?"2D":"");return"function"==typeof a[e]&&a[e](l,f,n,g),l}})}(jQuery);var et2_barcode=function(){"use strict";return et2_valueWidget.extend({attributes:{code_type:{name:"code type",type:"string",default:"datamatrix",description:"Barcode type to be generated, default is QR barcode"},bgColor:{name:"bgColor",type:"string",default:"#FFFFFF",description:"Defines backgorund color of barcode container"},barColor:{name:"barColor",type:"string",default:"#000000",description:"Defines color of the bars in barcode."},format:{name:"format",type:"string",default:"css",description:"Defines in which format the barcode should be rendered. Default is SVG."},barWidth:{name:"bar width",type:"string",default:"1",description:"Defines width of each bar in the barcode."},barHeight:{name:"bar height",type:"string",default:"50",description:"Defines heigh of each bar in the barcode."}},init:function(){this._super.apply(this,arguments),this.div=jQuery(document.createElement("div")).attr({class:"et2_barcode"}),this.set_id(this.id),this.setDOMNode(this.div[0]),this.createWidget()},createWidget:function(){this.settings={output:this.options.format,bgColor:this.options.bgColor,color:this.options.barColor,barWidth:this.options.barWidth,barHeight:this.options.barHeight},this.get_value()&&this.div.barcode(this.get_value(),this.options.code_type,this.settings)},set_value:function(_val){"undefined"!=typeof _val&&(this.value=_val,this.createWidget())},get_value:function(){return this.value}})}.call(this);et2_register_widget(et2_barcode,["barcode"]),jQuery.extend(et2_barcode,{TYPE_CODEBAR:"codebar",TYPE_CODE11:"code11",TYPE_CODE39:"code39",TYPE_CODE128:"code128",TYPE_EAN8:"ean8",TYPE_EAN13:"ean13",TYPE_STD25:"std25",TYPE_INT25:"int25",TYPE_MSI:"msi",TYPE_DATAMATRIX:"datamatrix",FORMAT_CSS:"css",FORMAT_SVG:"svg",FORMAT_bmp:"bmp",FORMAT_CANVAS:"canvas"});var et2_itempicker=function(){"use strict";return et2_inputWidget.extend({attributes:{action:{name:"Action callback",type:"string",default:!1,description:"Callback for action. Must be a function(context, data)"},action_label:{name:"Action label",type:"string",default:"Action",description:"Label for action button"},application:{name:"Application",type:"string",default:"",description:"Limit to the listed application or applications (comma separated)"},blur:{name:"Placeholder",type:"string",default:et2_no_init,description:"This text get displayed if an input-field is empty and does not have the input-focus (blur). It can be used to show a default value or a kind of help-text."},value:{name:"value",type:"any",default:"",description:"Optional itempicker value(s) - can be used for e.g. environmental information"},query:{name:"Query callback",type:"any",default:!1,description:"Callback before query to server. Must return true, or false to abort query."}},legacyOptions:["application"],search_timeout:200,minimum_characters:2,last_search:"",action:null,current_app:"",init:function(){this._super.apply(this,arguments),this.div=null,this.left=null,this.right=null,this.right_container=null,this.app_select=null,this.search=null,this.button_action=null,this.itemlist=null,null!==this.options.action&&"string"==typeof this.options.action?this.action=new egwFnct(this,"javaScript:"+this.options.action):console.log("itempicker widget: no action provided for button"),this.createInputWidget()},clearSearchResults:function(){this.search.val(""),this.itemlist.html(""),this.search.focus(),this.clear.hide()},createInputWidget:function(){var _self=this;this.div=$j(document.createElement("div")),this.left=$j(document.createElement("div")),this.right=$j(document.createElement("div")),this.right_container=$j(document.createElement("div")),this.app_select=$j(document.createElement("ul")),this.search=$j(document.createElement("input")),this.clear=$j(document.createElement("span")),this.itemlist=$j(document.createElement("div")),this.div.addClass("et2_itempicker"),this.left.addClass("et2_itempicker_left"),this.right.addClass("et2_itempicker_right"),this.right_container.addClass("et2_itempicker_right_container"),this.app_select.addClass("et2_itempicker_app_select");var item_count=0;for(var key in this.options.select_options){var img_icon=this.egw().image(key+"/navbar");if(null!==img_icon){var img=$j(document.createElement("img"));img.attr("src",img_icon);var item=$j(document.createElement("li"));item.attr("id",key).click(function(){_self.selectApplication($j(this))}).append(img),0==item_count&&this.selectApplication(item),this.app_select.append(item),item_count++}}this.search.addClass("et2_itempicker_search"),this.search.keyup(function(){var request={};request.term=$j(this).val(),_self.query(request)}),this.set_blur(this.options.blur,this.search),this.clear.addClass("et2_itempicker_clear ui-icon ui-icon-close").click(function(e){_self.clearSearchResults()}).hide(),this.button_action=et2_createWidget("button"),$j(this.button_action.getDOMNode()).addClass("et2_itempicker_button_action"),this.button_action.set_label(this.egw().lang(this.options.action_label)),this.button_action.click=function(){_self.doAction()},this.itemlist.attr("id","itempicker_itemlist"),this.itemlist.addClass("et2_itempicker_itemlist"),this.left.append(this.app_select),this.right_container.append(this.search),this.right_container.append(this.clear),this.right_container.append(this.button_action.getDOMNode()),this.right_container.append(this.itemlist),this.right.append(this.right_container),this.div.append(this.right),this.div.append(this.left),this.setDOMNode(this.div[0])},doAction:function(){if(null!==this.action){var data={};return data.app=this.current_app,data.value=this.options.value,data.checked=this.getSelectedItems(),this.action.exec(this,data)}return!1},getSelectedItems:function(){var items=[];return $j(this.itemlist).children("ul").children("li.selected").each(function(index){items[index]=$j(this).attr("id")}),items},query:function(request){return request.term.length<3?!0:(this.last_search=request.term,this.options.query&&"function"==typeof this.options.query&&!this.options.query(request,response)?!1:(this.itemlist.addClass("loading"),this.clear.css("display","inline-block"),void egw._json("etemplate_widget_itempicker::ajax_item_search::etemplate",[this.current_app,"",request.term,request.options],this.queryResults,this,!0,this).sendRequest()))},queryResults:function(data){this.itemlist.removeClass("loading"),this.updateItemList(data)},selectApplication:function(app){return this.clearSearchResults(),$j(".et2_itempicker_app_select li").removeClass("selected"),app.addClass("selected"),this.current_app=app.attr("id"),!0},set_blur:function(_value,input){"undefined"==typeof input&&(input=this.search),_value?(input.attr("placeholder",_value),input[0].placeholder||(""==input.val()&&input.val(_value),input.focus(input,function(e){var placeholder=_value;e.data.val()==placeholder&&e.data.val("")}).blur(input,function(e){var placeholder=_value;""==e.data.val()&&e.data.val(placeholder)}),""==input.val()&&input.val(_value))):this.search.removeAttr("placeholder")},transformAttributes:function(_attrs){if(this._super.apply(this,arguments),_attrs.select_options={},_attrs.application)for(var apps=et2_csvSplit(_attrs.application,null,","),i=0;i<apps.length;i++)_attrs.select_options[apps[i]]=this.egw().lang(apps[i]);else _attrs.select_options=this.egw().link_app_list("query");null==_attrs.select_options&&(_attrs.select_options=this.getArrayMgr("content").getEntry("options-"+this.id)),null==_attrs.select_options&&(_attrs.select_options={})},updateItemList:function(data){var list=$j(document.createElement("ul")),item_count=0;for(var id in data){var item=$j(document.createElement("li"));item_count%2==0?item.addClass("row_on"):item.addClass("row_off"),item.attr("id",id).html(data[id]).click(function(e){if(e.ctrlKey||e.metaKey)$j(this).addClass("selected");else if(e.shiftKey){var start=$j(this).siblings(".selected").first();if(0==start)return $j(this).addClass("selected"),!0;var end=$j(this);if(start.index()>end.index()){var startOld=start;start=end,end=startOld}start.addClass("selected"),start.nextUntil(end).addClass("selected"),end.addClass("selected")}else $j(this).siblings(".selected").removeClass("selected"),$j(this).addClass("selected")}),list.append(item),item_count++}this.itemlist.html(list)}})}.call(this);et2_register_widget(et2_itempicker,["itempicker"]);var et2_script=function(){"use strict";return et2_widget.extend({init:function(){this._super.apply(this,arguments),this.supportedWidgetClasses=[]},loadContent:function(_content){try{var func=new Function(_content);func.call(window)}catch(e){this.egw.debug("error","Error while executing script: ",_content,e)}}})}.call(this);et2_register_widget(et2_script,["script"]),function(){"use strict";function js_pseudo_funcs(_val,widget){if(-1!=_val.indexOf("egw::link(")&&(_val=_val.replace(/egw::link\(/g,"egw.link(")),-1!=_val.indexOf("form::name(")){var _cname=widget.getPath()?widget.getPath().join("["):!1;_val=_val.replace(/form::name\(/g,"'"+widget.getRoot()._inst.uniqueId+"_'+"+(_cname?"et2_form_name('"+_cname+"',":"("))}return-1!=_val.indexOf("egw::lang(")&&(_val=_val.replace(/egw::lang\(/g,"egw.lang(")),-1!=_val.indexOf("confirm(")&&(_val=_val.replace(/confirm\((['"])(.*?)(\?)?['"]\)/,"confirm(egw.lang($1$2$1)+'$3')")),-1!=_val.indexOf("window.open(")&&(_val=_val.replace(/window.open\('(.*)','(.*)','dependent=yes,width=([^,]*),height=([^,]*),scrollbars=yes,status=(.*)'\)/,"egw_openWindowCentered2('$1', '$2', $3, $4, '$5')")),-1!=_val.indexOf("xajax_doXMLHTTP('etemplate.")&&(_val=_val.replace(/^xajax_doXMLHTTP\('etemplate\.([a-z]+_widget\.[a-zA-Z0-9_]+)\'/,"xajax_doXMLHTTP('"+egw.getAppName()+".$1.etemplate'")),-1!=_val.indexOf("this.form.submit()")&&(_val=_val.replace("this.form.submit()","widget.getInstanceManager().submit()")),_val}this.et2_compileLegacyJS=function(_code,_widget,_context){if(_code=js_pseudo_funcs(_code,_widget),"1"===_code&&(_code="widget.getInstanceManager().submit(); return false;"),_code.indexOf("$")>=0||_code.indexOf("@")>=0){var mgr=_widget.getArrayMgr("content");mgr&&(_code=mgr.expandName(_code))}var context=_context?_context:null;!context&&_widget.implements(et2_IDOMNode)&&(context=_widget.getDOMNode());try{"string"==typeof _code&&0==_code.indexOf("app")&&_code.split(".").length>=3&&-1==_code.indexOf("(")&&(_code+="(ev,widget)");var func=new Function("ev","widget",_code)}catch(e){return _widget.egw().debug("error","Error while compiling JS code ",_code),function(){return!1}}return function(ev){return egw.debug("log","Executing legacy JS code: ",_code),arguments&&arguments.length>2&&egw.debug("warn","Legacy JS code only supports 2 arguments (event and widget)",_code,arguments),func.call(context,ev,_widget)}}}.call(window);try{opener&&opener.etemplate2?etemplate2.prototype.templates=opener.etemplate2.prototype.templates:top.etemplate2&&(etemplate2.prototype.templates=top.etemplate2.prototype.templates)}catch(e){console.log("Security exception accessing etemplate2.prototype of opener or top!")}"undefined"==typeof etemplate2.prototype.templates&&(etemplate2.prototype.templates={}),etemplate2.prototype.resize=function(e){var event=e,self=this,excess_height=!1;"undefined"!=typeof window.framework&&"undefined"!=typeof window.framework.get_wExcessHeight&&(excess_height=window.framework.get_wExcessHeight(window)),"undefined"!=typeof event&&"resize"==event.type?(this.resize_timeout&&clearTimeout(this.resize_timeout),this.resize_timeout=setTimeout(function(){if(self.resize_timeout=!1,self.widgetContainer){var appHeader=$j("#divAppboxHeader");excess_height=egw(window).is_popup()?$j(window).height()-$j(self.DOMContainer).height()-appHeader.outerHeight()+11:!1,appHeader.length>0&&appHeader.is(":visible")&&(excess_height-=appHeader.outerHeight()-9),screen.availHeight<$j(self.DOMContainer).height()&&(excess_height=0),self.widgetContainer.iterateOver(function(_widget){_widget.resize(excess_height)},self,et2_IResizeable)}},100)):this.widgetContainer&&this.widgetContainer.iterateOver(function(_widget){_widget.resize(excess_height)},this,et2_IResizeable)},etemplate2.prototype.clear=function(){$j(this.DOMContainer).trigger("clear"),this.uniqueId&&$j(window).off("."+this.uniqueId),this.destroy_session&&(this.destroy_session(),this.unbind_unload()),null!=this.widgetContainer&&(this.widgetContainer.egw().unregisterJSONPlugin(etemplate2_handle_assign,this,"assign"),this.widgetContainer.free(),this.widgetContainer=null),$j(this.DOMContainer).empty();for(name in this.templates)if("undefined"!=typeof etemplate2._byTemplate[name])for(var i=0;i<etemplate2._byTemplate[name].length;i++)etemplate2._byTemplate[name][i]==this&&etemplate2._byTemplate[name].splice(i,1)},etemplate2.prototype._createArrayManagers=function(_data){"undefined"==typeof _data&&(_data={});for(var neededEntries=["content","sel_options","readonlys","modifications","validation_errors"],i=0;i<neededEntries.length;i++)"undefined"!=typeof _data[neededEntries[i]]&&_data[neededEntries[i]]||(egw.debug("log","Created not passed entry '"+neededEntries[i]+"' in data array."),_data[neededEntries[i]]={});var result={};for(var key in _data)switch(key){case"etemplate_exec_id":case"app_header":break;case"readonlys":result[key]=new et2_readonlysArrayMgr(_data[key]),result[key].perspectiveData.owner=this.widgetContainer;break;default:result[key]=new et2_arrayMgr(_data[key]),result[key].perspectiveData.owner=this.widgetContainer}return result},etemplate2.prototype.bind_unload=function(){this.etemplate_exec_id&&(this.destroy_session=jQuery.proxy(function(ev){var request=egw.json(this.app+".etemplate_new.ajax_destroy_session.etemplate",[this.etemplate_exec_id],null,null,!1);request.sendRequest()},this),window.onbeforeunload||(window.onbeforeunload=this.destroy_session))},etemplate2.prototype.unbind_unload=function(){window.onbeforeunload===this.destroy_session&&(window.onbeforeunload=null),delete this.destroy_session},etemplate2.prototype.download=function(_url){this.unbind_unload(),document.location=_url,window.setTimeout(jQuery.proxy(this.bind_unload,this),100)},etemplate2.prototype.load=function(_name,_url,_data,_callback){this.name=_name,_url&&"/"!=_url[0]?(this.template_base_url=_url.match(/https?:\/\/[^\/]+/).shift(),_url=_url.split(this.template_base_url)[1]):this.template_base_url="",this.template_base_url+=_url.split(_name.split(".").shift())[0],egw().debug("info","Loaded data",_data);var currentapp=this.app=_data.currentapp||egw().app_name(),msg=_data.content.msg;if("undefined"!=typeof msg&&(egw(window).message(msg),delete _data.content.msg),egw(currentapp,window).registerJSONPlugin(etemplate2_handle_assign,this,"assign"),egw.debug_level()>=3&&console.groupCollapsed&&egw.window.console.groupCollapsed("Loading %s into ",_name,"#"+this.DOMContainer.id),egw.debug_level()>=4){console.time&&console.time(_name),console.profile&&console.profile(_name);var start_time=(new Date).getTime()}$j.isArray(_data.langRequire)||(_data.langRequire=[]),egw(currentapp,window).langRequire(window,_data.langRequire,function(){var split=_name.split("."),appname=split[0],app_callback=null;"object"!=typeof app[appname]&&"function"==typeof app.classes[appname]?app[appname]=new app.classes[appname]:"function"==typeof app[appname]?function(){new app[appname]}.call():"object"!=typeof app[appname]&&egw.debug("warn","Did not load '%s' JS object",appname),"object"!=typeof app[this.app]&&"function"==typeof app.classes[this.app]&&(app[this.app]=new app.classes[this.app]),"object"==typeof app[appname]&&(app_callback=function(_et2,_name){app[appname].et2_ready(_et2,_name)});var frag=document.createDocumentFragment();this.clear(),this.widgetContainer=new et2_container(null),this.widgetContainer.setApiInstance(egw(currentapp,egw.elemWindow(this.DOMContainer))),this.widgetContainer.setInstanceManager(this),this.widgetContainer.setParentDOMNode(this.DOMContainer),_data&&(this.etemplate_exec_id=_data.etemplate_exec_id,"string"==typeof _data.app_header&&window.egw_app_header(_data.app_header),this.bind_unload());var _load=function(){egw.debug("log","Loading template..."),egw.debug_level()>=4&&console.timeStamp&&console.timeStamp("Begin rendering template"),"undefined"==typeof etemplate2._byTemplate[_name]&&(etemplate2._byTemplate[_name]=[]),etemplate2._byTemplate[_name].push(this),this.widgetContainer.loadFromXML(this.templates[this.name]);var deferred=[];if(this.widgetContainer.loadingFinished(deferred),
$j(window).on("resize."+this.uniqueId,this,function(e){e.data.resize(e)}),this.DOMContainer.appendChild(frag),egw.debug_level()>=3&&console.groupEnd&&egw.window.console.groupEnd(),deferred.length>0){var still_deferred=0;$j(deferred).each(function(){"pending"==this.state()&&still_deferred++}),still_deferred>0&&egw.debug("log","Template loaded, waiting for %d/%d deferred to finish...",still_deferred,deferred.length)}jQuery.when.apply(jQuery,deferred).done(jQuery.proxy(function(){if(egw.debug("log","Finished loading %s, triggering load event",_name),"undefined"!=typeof window.framework&&"undefined"!=typeof window.framework.et2_loadingFinished&&window.framework.et2_loadingFinished(egw(window).window),this.resize(),this.widgetContainer._egw.is_popup()&&0==$j("[autofocus]",this.DOMContainer).focus().length){var $input=$j("input:visible",this.DOMContainer).not(".et2_date").filter(function(){var $this=$j(this);return!$this.attr("tabindex")||$this.attr("tabIndex")>=0}).first();(egwIsMobile()&&""==$input.val()||!egwIsMobile())&&$input.focus()}if("function"==typeof _callback&&_callback.call(window,this,_name),app_callback&&_callback!=app_callback&&app_callback.call(window,this,_name),appname!=this.app&&"object"==typeof window.app[this.app]&&window.app[this.app].et2_ready(this,this.name),$j(this.DOMContainer).trigger("load",this),egw.debug_level()>=4){console.timeEnd&&console.timeEnd(_name),console.profileEnd&&console.profileEnd(_name);var end_time=(new Date).getTime(),gen_time_div=$j("#divGenTime_"+appname);gen_time_div.length||(gen_time_div=$j(".pageGenTime")),gen_time_div.find(".et2RenderTime").remove(),gen_time_div.append('<span class="et2RenderTime">'+egw.lang("eT2 rendering took %1s",(end_time-start_time)/1e3)+"</span>")}},this))};try{if(this.templates[_name])return this.widgetContainer.setArrayMgrs(this._createArrayManagers(_data)),void _load.apply(this,[])}catch(e){if("Permission denied"!=e.message)throw e;etemplate2.prototype.templates={}}et2_loadXMLFromURL(_url,function(_xmldoc){for(var i=0;i<_xmldoc.childNodes.length;i++){var template=_xmldoc.childNodes[i];"template"==template.nodeName.toLowerCase()&&(this.templates[template.getAttribute("id")]=template,_name||(this.name=template.getAttribute("id")))}_load.apply(this,[])},this),this.widgetContainer.setArrayMgrs(this._createArrayManagers(_data))},this)},etemplate2.prototype.isDirty=function(){var dirty=!1;return this.widgetContainer.iterateOver(function(_widget){_widget.isDirty&&_widget.isDirty()&&(dirty=!0)}),dirty},etemplate2.prototype.autocomplete_fixer=function(){var self=this,form=self.DOMContainer;navigator.userAgent.match(/safari/i)&&!navigator.userAgent.match(/chrome/i)&&jQuery('input[type="password"]').length>0||form&&(form.onsubmit=function(e){e.stopPropagation()},navigator.userAgent.match(/(firefox|safari|iceweasel)/i)&&!navigator.userAgent.match(/chrome/i)&&jQuery(form).attr({action:egw.webserverUrl+"/etemplate/empty.html",method:"post"}),jQuery(form).trigger("submit"))},etemplate2.prototype.submit=function(button,async,no_validation,_container){"undefined"==typeof no_validation&&(no_validation=!1);var container=_container||this.widgetContainer,values=this.getValues(container),canSubmit=!0;if(no_validation||container.iterateOver(function(_widget){_widget.submit(values)===!1&&(canSubmit=!1)},this,et2_ISubmitListener),canSubmit){if("string"==typeof button&&(button=this.widgetContainer.getWidgetById(button)),button&&!values.button){values.button={};for(var path=button.getPath(),target=values,i=0;i<path.length;i++)values[path[i]]||(values[path[i]]={}),target=values[path[i]];if(target!=values||-1!=button.id.indexOf("[")&&0==path.length){var indexes=button.id.split("[");if(indexes.length>1){indexes=[indexes.shift(),indexes.join("[")],indexes[1]=indexes[1].substring(0,indexes[1].length-1);var children=indexes[1].split("][");children.length&&(indexes=jQuery.merge([indexes[0]],children))}for(var idx="",i=0;i<indexes.length;i++)idx=indexes[i],target[idx]&&!target[idx].$row_cont||(target[idx]=i<indexes.length-1?{}:!0),target=target[idx]}else("undefined"==typeof values.button||jQuery.isEmptyObject(values.button))&&(delete values.button,values[button.id]=!0)}if(this.menuaction){this.autocomplete_fixer(),this.unbind_unload();var api=this.widgetContainer.egw(),request=api.json(this.menuaction,[this.etemplate_exec_id,values,no_validation],null,this,async);request.sendRequest()}else this.widgetContainer.egw().debug("warn","Missing menuaction for submit. Values: ",values)}return canSubmit},etemplate2.prototype.postSubmit=function(){var values=this.getValues(this.widgetContainer),canSubmit=!0;if(this.widgetContainer.iterateOver(function(_widget){_widget.submit(values)===!1&&(canSubmit=!1)},this,et2_ISubmitListener),canSubmit){this.unbind_unload();var form=jQuery("<form id='form' action='"+egw().webserverUrl+"/etemplate/process_exec.php?menuaction="+this.widgetContainer.egw().getAppName()+"&ajax=true' method='POST'>"),input=(jQuery(document.createElement("input")).attr("name","etemplate_exec_id").attr("type","hidden").val(this.etemplate_exec_id).appendTo(form),document.createElement("input"));input.type="hidden",input.name="value",input.value=egw().jsonEncode(values),form.append(input),form.appendTo(jQuery("body")).submit()}},etemplate2.prototype.getValues=function(_root){var result={};return _root.iterateOver(function(_widget){if(""!=_widget.id){var path=_widget.getPath(),id=_widget.id,indexes=id.split("[");if(indexes.length>1){indexes=[indexes.shift(),indexes.join("[")],indexes[1]=indexes[1].substring(0,indexes[1].length-1);var children=indexes[1].split("][");children.length&&(indexes=jQuery.merge([indexes[0]],children)),path=path.concat(indexes),id=path.pop()}for(var _target=result,i=0;i<path.length;i++)"undefined"==typeof _target[path[i]]&&(_target[path[i]]={}),"object"==typeof _target[path[i]]?_target=_target[path[i]]:egw.debug("error","ID collision while writing at path node '"+path[i]+"'");""===id&&(id="undefined"==typeof _target?0:Object.keys(_target).length);var value=_widget.getValue();if("undefined"==typeof _target[id]||"object"==typeof _target[id]&&"object"==typeof value||_widget.getParent().instanceOf(et2_nextmatch_header_bar)||egw.debug("warn",_widget,"Overwriting value of '"+_widget.id+"', id exists twice!"),null!==value)"object"==typeof _target[id]&&"object"==typeof value?_target[id]=jQuery.extend({},_target[id],value):_target[id]=value;else if(jQuery.isEmptyObject(_target)){_target=result;for(var i=0;i<path.length-1;i++)_target=_target[path[i]];delete _target[path[path.length-1]]}_widget.resetDirty()}},this,et2_IInput),egw().debug("info","Value",result),result},etemplate2.prototype.refresh=function(msg,app,id,type){var refresh_done=!1;return this.widgetContainer.iterateOver(function(_widget){_widget.refresh(id,type),refresh_done=!0},this,et2_nextmatch),refresh_done},etemplate2.app_refresh=function(_msg,_app,_id,_type){for(var refresh_done=!1,et2=etemplate2.getByApplication(_app),i=0;i<et2.length;i++)refresh_done=et2[i].refresh(_msg,_app,_id,_type)||refresh_done;return refresh_done},etemplate2.prototype.print=function(){var deferred=[];return jQuery(this.DOMContainer).filter(":visible").length?(this.widgetContainer.iterateOver(function(_widget){if(_widget.getInstanceManager()==this){var result=_widget.beforePrint();"object"==typeof result&&result.done&&deferred.push(result)}},this,et2_IPrint),deferred):[]},etemplate2._byTemplate={},etemplate2.getByTemplate=function(template){return"undefined"!=typeof etemplate2._byTemplate[template]?etemplate2._byTemplate[template]:[]},etemplate2.getByApplication=function(app){var list=[];for(var name in etemplate2._byTemplate)0==name.indexOf(app+".")&&(list=list.concat(etemplate2._byTemplate[name]));return list},etemplate2.getById=function(id){for(var name in etemplate2._byTemplate)for(var i=0;i<etemplate2._byTemplate[name].length;i++){var et=etemplate2._byTemplate[name][i];if(et.DOMContainer.getAttribute("id")==id)return et}return null},egw(window).registerJSONPlugin(etemplate2_handle_load,null,"et2_load"),egw(window).registerJSONPlugin(etemplate2_handle_validation_error,null,"et2_validation_error");
//# sourceMappingURL=etemplate2.min.js.map