').appendTo(self.$table),$comment=$('').addClass('OxComment OxSerif OxSelectable').html(Ox.addLinks(section.comment,true)).appendTo($section),$code=$(' ').addClass('OxCode').append(Ox.SyntaxHighlighter({replace:self.options.replaceCode,source:trim(section.code)})).appendTo($section);});setTimeout(function(){var height=that.height();if(self.$table.height()\u21A9':'')+' ',tab=(self.options.showTabs?'\u2192 ':'')+Ox.repeat(' ',self.options.tabSize-self.options.showTabs),whitespace=self.options.showWhitespace?'\u00B7':' ';tokens=Ox.isArray(self.options.source)?self.options.source:Ox.tokenize(self.options.source);tokens.forEach(function(token,i){var classNames,type=token.type=='identifier'?Ox.identify(token.value):token.type;if(!(self.options.stripComments&&type=='comment')){classNames='Ox'+Ox.toTitleCase(type);if(self.options.showWhitespace&&type=='whitespace'){if(isAfterLinebreak()&&hasIrregularSpaces()){classNames+=' OxLeading';}else if(isBeforeLinebreak()){classNames+=' OxTrailing';}}
source+=''+Ox.encodeHTMLEntities(token.value).replace(/ /g,whitespace).replace(/\t/g,tab).replace(/\n/g,linebreak)+' ';}
function isAfterLinebreak(){return i==0||tokens[i-1].type=='linebreak';}
function isBeforeLinebreak(){return i==tokens.length-1||tokens[i+1].type=='linebreak';}
function hasIrregularSpaces(){return token.value.split('').reduce(function(prev,curr){return prev+(curr==' '?1:0);},0)%self.options.tabSize;}});lines=source.split(' ');that.empty();if(self.options.showLineNumbers){$lineNumbers=Ox.Element().addClass('OxLineNumbers').html(Ox.range(lines.length).map(function(line){return(line+self.options.offset);}).join(' ')).appendTo(that);}
self.options.replace.forEach(function(replace){source=source.replace(replace[0],replace[1])});$source=Ox.Element().addClass('OxSourceCode OxSelectable').html(source).appendTo(that);if(self.options.lineLength){$line=Ox.Element().css({position:'absolute',top:'-1000px'}).html(Ox.repeat(' ',self.options.lineLength)).appendTo(that);width=$line.width()+4;$line.remove();['moz','webkit'].forEach(function(browser){$source.css({background:'-'+browser+'-linear-gradient(left, rgb(255, 255, 255) '+width+'px, rgb(192, 192, 192) '+width+'px, rgb(255, 255, 255) '+(width+1)+'px)'});});}}
return that;};'use strict';Ox.ImageElement=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({height:0,src:'',width:0}).options(options||{}).update({height:function(){!self.isAuto&&setSizes();},src:loadImage,width:function(){!self.isAuto&&setSizes();}}).addClass('OxImageElement');self.isAuto=!self.options.width&&!self.options.height;self.$screen=Ox.LoadingScreen({height:self.options.height,size:16,width:self.options.width}).start().appendTo(that);loadImage();!self.isAuto&&setSizes();function loadImage(){if(self.$image){self.$image.off({load:showImage}).remove();}
self.$image=$(' ').one({error:stopLoading,load:showImage}).attr({src:self.options.src});}
function setSizes(){var css={width:self.options.width,height:self.options.height};self.$screen&&self.$screen.options(css);css=Ox.map(css,function(value){return value+'px';});that.css(css);self.$image.css(css);}
function showImage(){self.$screen.stop().remove();self.$image.appendTo(that);that.triggerEvent('load');}
function stopLoading(){self.$screen.stop();}
that.css=function(css){that.$element.css(css);self.$screen&&self.$screen.css(css);self.$image.css(css);return that;};return that;};'use strict';Ox.ImageViewer=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({area:[],center:'auto',elasticity:0,height:384,imageHeight:0,imagePreviewURL:'',imageURL:'',imageWidth:0,maxZoom:16,overviewSize:128,width:512,zoom:'fit'}).options(options||{}).update({area:function(){if(self.options.area&&self.options.area.length==4){var centerAndZoom=getCenterAndZoom(self.options.area);self.options.center=centerAndZoom.center;self.options.zoom=centerAndZoom.zoom;setCenterAndZoom(true,true);}},center:function(){setCenterAndZoom(true,true);},height:updateSize,width:updateSize,zoom:function(){setCenterAndZoom(true,true);}}).addClass('OxImageViewer OxGrid').on({mousedown:function(){that.gainFocus();},mouseenter:function(){showInterface();},mouseleave:function(){hideInterface();},mousemove:function(){showInterface();hideInterface();}}).bindEvent({doubleclick:onDoubleclick,dragstart:onDragstart,drag:onDrag,dragend:onDragend,key_0:function(){that.options({zoom:1});},key_1:function(){that.options({center:'auto',zoom:'fit'});},key_2:function(){that.options({center:'auto',zoom:'fill'});},key_down:function(){that.options({center:[self.center[0],self.center[1]+self.options.height/2/self.zoom]});},key_equal:function(){that.options({zoom:self.zoom*2});},key_left:function(){that.options({center:[self.center[0]-self.options.width/2/self.zoom,self.center[1]]});},key_minus:function(){that.options({zoom:self.zoom/2});},key_right:function(){that.options({center:[self.center[0]+self.options.width/2/self.zoom,self.center[1]]});},key_up:function(){that.options({center:[self.center[0],self.center[1]-self.options.height/2/self.zoom]});},mousewheel:onMousewheel,singleclick:onSingleclick});if(self.options.area&&self.options.area.length==4){var centerAndZoom=getCenterAndZoom(self.options.area);self.options.center=centerAndZoom.center;self.options.zoom=centerAndZoom.zoom;}self.imageRatio=self.options.imageWidth/self.options.imageHeight;self.overviewHeight=Math.round(self.options.overviewSize/(self.imageRatio>1?self.imageRatio:1));self.overviewWidth=Math.round(self.options.overviewSize*(self.imageRatio>1?1:self.imageRatio));self.overviewZoom=self.overviewWidth/self.options.imageWidth;self.$image=Ox.Element(' ').addClass('OxImage').attr({src:self.options.imagePreviewURL}).appendTo(that);Ox.$(' ').one({load:function(){self.$image.attr({src:self.options.imageURL});}}).attr({src:self.options.imageURL});self.$scaleButton=Ox.ButtonGroup({buttons:[{id:'fit',title:'fit',tooltip:Ox._('Zoom to Fit')+' [1] '},{id:'fill',title:'fill',tooltip:Ox._('Zoom to Fill')+' [2] '}],style:'overlay',type:'image'}).addClass('OxInterface OxScaleButton').on({mouseenter:function(){self.mouseIsInInterface=true;},mouseleave:function(){self.mouseIsInInterface=false;}}).bindEvent({click:function(data){that.options({center:'auto',zoom:data.id});}}).appendTo(that);self.$zoomButton=Ox.ButtonGroup({buttons:[{id:'out',title:'remove',tooltip:Ox._('Zoom Out')+' [-] '},{id:'original',title:'equal',tooltip:Ox._('Original Size')+' [0] '},{id:'in',title:'add',tooltip:Ox._('Zoom In')+' [=] '}],style:'overlay',type:'image'}).addClass('OxInterface OxZoomButton').on({mouseenter:function(){self.mouseIsInInterface=true;},mouseleave:function(){self.mouseIsInInterface=false;}}).bindEvent({click:function(data){if(data.id=='out'){that.options({zoom:self.zoom/2});}else if(data.id=='original'){that.options({zoom:1});}else{that.options({zoom:self.zoom*2});}}}).appendTo(that);self.$overview=Ox.Element().addClass('OxInterface OxImageOverview').css({height:self.overviewHeight+'px',width:self.overviewWidth+'px'}).hide().on({mouseenter:function(){self.mouseIsInInterface=true;},mouseleave:function(){self.mouseIsInInterface=false;}}).appendTo(that);self.$overviewImage=Ox.Element(' ').attr({src:self.options.imagePreviewURL}).css({height:self.overviewHeight+'px',width:self.overviewWidth+'px'}).appendTo(self.$overview);self.$overlay=Ox.Element().addClass('OxImageOverlay').appendTo(self.$overview);self.$area={};['bottom','center','left','right','top'].forEach(function(area){self.$area[area]=Ox.Element().addClass('OxImageOverlayArea').attr({id:'OxImageOverlay'+Ox.toTitleCase(area)}).css(getAreaCSS(area)).appendTo(self.$overlay);});setSize();function getAreaCSS(area){return area=='bottom'?{height:self.overviewHeight+'px'}:area=='center'?{left:self.overviewWidth+'px',top:self.overviewHeight+'px',right:self.overviewWidth+'px',bottom:self.overviewHeight+'px'}:area=='left'?{top:self.overviewHeight+'px',bottom:self.overviewHeight+'px',width:self.overviewWidth+'px'}:area=='right'?{top:self.overviewHeight+'px',bottom:self.overviewHeight+'px',width:self.overviewWidth+'px'}:{height:self.overviewHeight+'px'};}
function getArea(center,zoom){center=Ox.clone(center);zoom=Ox.clone(zoom);self.viewerRatio=self.options.width/self.options.height;self.imageIsWider=self.imageRatio>self.viewerRatio;if(center=='auto'){center=[Math.round(self.options.imageWidth/2),Math.round(self.options.imageHeight/2)];}
if(zoom=='fit'){zoom=self.imageIsWider?self.options.width/self.options.imageWidth:self.options.height/self.options.imageHeight;}else if(zoom=='fill'){zoom=self.imageIsWider?self.options.height/self.options.imageHeight:self.options.width/self.options.imageWidth;}
return[Math.max(center[0]-self.options.width/2/zoom,0),Math.max(center[1]-self.options.height/2/zoom,0),Math.min(center[0]+self.options.width/2/zoom,self.options.imageWidth),Math.min(center[1]+self.options.height/2/zoom,self.options.imageHeight)];}
function getCenter(e){var $target=$(e.target),center,offset,offsetX,offsetY;if($target.is('.OxImage')){center=[e.offsetX/self.zoom,e.offsetY/self.zoom];}else if($target.is('.OxImageOverlayArea')){offset=that.offset();offsetX=e.clientX-offset.left-self.options.width
+self.overviewWidth+6;offsetY=e.clientY-offset.top-self.options.height
+self.overviewHeight+6;center=[offsetX/self.overviewZoom,offsetY/self.overviewZoom];}
return center;}
function getCenterAndZoom(area){if(!area||!area.length){return{center:'auto',zoom:'fit'};}
var areaWidth=area[2]-area[0],areaHeight=area[3]-area[1],areaRatio=areaWidth/areaHeight;self.viewerRatio=self.options.width/self.options.height;return{center:[(area[0]+area[2])/2,(area[1]+area[3])/2],zoom:self.viewerRatioself.options.width?self.options.width/2/self.zoom:self.options.imageWidth/2,imageHeight>self.options.height?self.options.height/2/self.zoom:self.options.imageHeight/2].map(function(value){return elastic?value-self.options.elasticity/self.zoom:value;});maxCenter=[self.options.imageWidth-minCenter[0],self.options.imageHeight-minCenter[1]];center=self.options.center=='auto'?[self.options.imageWidth/2,self.options.imageHeight/2]:[Ox.limit(self.options.center[0],minCenter[0],maxCenter[0]),Ox.limit(self.options.center[1],minCenter[1],maxCenter[1])];if(Ox.isArray(self.options.center)){self.options.center=center;}
return center;}
function limitZoom(elastic){var imageSize=self.imageIsWider?self.options.imageWidth:self.options.imageHeight,minZoom=elastic?(self.fitZoom*imageSize-2*self.options.elasticity)/imageSize:self.fitZoom,maxZoom=elastic?(self.maxZoom*imageSize+2*self.options.elasticity)/imageSize:self.maxZoom,zoom=self.options.zoom=='fill'?self.fillZoom:self.options.zoom=='fit'?self.fitZoom:Ox.limit(self.options.zoom,minZoom,maxZoom);if(Ox.isNumber(self.options.zoom)){self.options.zoom=zoom;}
return zoom;}
function onDoubleclick(e){var $target=$(e.target),factor=e.shiftKey?0.5:2;if(($target.is('.OxImage')||$target.is('.OxImageOverlayArea'))&&((!e.shiftKey&&self.zoomself.fitZoom))){that.options({center:getZoomCenter(e,factor),zoom:self.zoom*factor});}}
function onDragstart(e){var $target=$(e.target);if($target.is('.OxImage')||$target.is('#OxImageOverlayCenter')){self.drag={center:self.center,zoom:$target.is('.OxImage')?self.zoom:-self.overviewZoom};}}
function onDrag(e){if(self.drag){self.options.center=[self.drag.center[0]-e.clientDX/self.drag.zoom,self.drag.center[1]-e.clientDY/self.drag.zoom];setCenterAndZoom(false,true);}}
function onDragend(){if(self.drag){self.drag=null;setCenterAndZoom(true);}}
function onMousewheel(e){var $target=$(e.target),factor=e.deltaY>0?2:0.5;if(e.deltaX==0&&Math.abs(e.deltaY)&&!self.mousewheelTimeout){if($target.is('.OxImage')||$target.is('.OxImageOverlayArea')){self.options.center=getZoomCenter(e,factor);self.options.zoom=self.zoom*factor;setCenterAndZoom(true,true);self.mousewheelTimeout=setTimeout(function(){self.mousewheelTimeout=null;},250);}}}
function onSingleclick(e){var $target=$(e.target),offset,offsetX,offsetY;if($target.is('.OxImage')||$target.is('.OxImageOverlayArea')){that.options({center:getCenter(e)});}}
function setCenterAndZoom(animate,elastic){self.zoom=limitZoom(elastic);self.center=limitCenter(elastic);if(animate){self.$image.stop().animate(getImageCSS(),250,function(){var center=limitCenter(),zoom=limitZoom(),setCenter=center[0]!=self.center[0]||center[1]!=self.center[1],setZoom=zoom!=self.zoom;if(setCenter||setZoom){self.options.center=center;self.options.zoom=zoom;setCenterAndZoom();}
that.triggerEvent({center:{center:self.options.center},zoom:{zoom:self.options.zoom}});});self.$overlay.stop().animate(getOverlayCSS(),250);}else{self.$image.css(getImageCSS());self.$overlay.css(getOverlayCSS());}
updateInterface();showInterface();hideInterface();}
function setSize(){self.viewerRatio=self.options.width/self.options.height;self.imageIsWider=self.imageRatio>self.viewerRatio;self.fillZoom=(self.imageIsWider?self.options.height*self.imageRatio:self.options.width)/self.options.imageWidth;self.fitZoom=(self.imageIsWider?self.options.width:self.options.height*self.imageRatio)/self.options.imageWidth;self.maxZoom=Math.max(self.fillZoom,self.options.maxZoom);that.css({width:self.options.width+'px',height:self.options.height+'px'});setCenterAndZoom();}
function showInterface(){clearTimeout(self.interfaceTimeout);if(!self.interfaceIsVisible){self.interfaceIsVisible=true;self.$scaleButton.animate({opacity:1},250);self.$zoomButton.animate({opacity:1},250);self.$overview.animate({opacity:1},250);}}
function updateInterface(){var isFitZoom=self.zoom==self.fitZoom;self.$scaleButton[isFitZoom?'disableButton':'enableButton']('fit');self.$scaleButton[self.zoom==self.fillZoom&&self.center[0]==self.options.imageWidth/2&&self.center[1]==self.options.imageHeight/2?'disableButton':'enableButton']('fill');self.$zoomButton[isFitZoom?'disableButton':'enableButton']('out');self.$zoomButton[self.zoom==1?'disableButton':'enableButton']('original');self.$zoomButton[self.zoom==self.maxZoom?'disableButton':'enableButton']('in');!isFitZoom&&self.$overview.show();self.$overview.stop().animate({opacity:isFitZoom?0:1},250,function(){isFitZoom&&self.$overview.hide();});}
function updateSize(){if(!self.updateTimeout){self.updateTimeout=setTimeout(function(){self.updateTimeout=null;setSize();});}}
that.getArea=function(){return getArea(self.options.center,self.options.zoom);};that.setArea=function(area){var centerAndZoom=getCenterAndZoom(area);that.options({center:centerAndZoom.center,zoom:centerAndZoom.zoom});return that;};return that;};'use strict';Ox.AudioElement=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({autoplay:false,preload:'none',src:''}).options(options||{}).update({src:function(){self.audio.src=self.options.src;}});self.loadedMetadata=false;self.paused=true;self.$audio=$('').attr({src:self.options.src}).on({ended:function(){that.triggerEvent('ended');},loadedmetadata:function(){that.triggerEvent('loadedmetadata',{duration:self.audio.duration});},seeked:function(){that.triggerEvent('seeked');},seeking:function(){that.triggerEvent('seeking');}}).appendTo(that);self.audio=self.$audio[0];function getset(key,value){var ret;if(Ox.isUndefined(value)){ret=self.audio[key];}else{self.audio[key]=value;ret=that;}
return ret;}
that.currentTime=function(){var ret;self.ended=false;if(arguments.length==0){ret=self.audio.currentTime;}else{self.audio.currentTime=arguments[0];ret=that;}
return ret;};that.pause=function(){self.paused=true;self.audio.pause();return that;};that.play=function(){if(self.ended){that.currentTime(0);self.ended=false;}
self.paused=false;self.audio.play();return that;};that.src=function(){var ret;if(arguments.length==0){ret=self.audio.src;}else{self.options.src=arguments[0];self.audio.src=self.options.src;ret=that;}
return ret;};that.volume=function(value){return getset('volume',arguments[0]);};return that;};'use strict';Ox.AudioPlayer=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({audio:[],muted:false,paused:false,position:0,repeat:0,shuffle:false,time:'elapsed',track:0,volume:1,width:512}).options(options||{}).update({audio:function(){self.options.position=-1;self.options.track=-1;that.options({paused:true,position:0,track:0});},muted:function(){self.options.muted=!self.options.muted;toggleMuted();},paused:function(){self.options.paused=!self.options.paused;togglePaused();},position:function(){setPosition(self.options.position);},repeat:function(){setRepeat(self.options.repeat);},shuffle:function(){self.options.shuffle=!self.options.shuffle;toggleShuffle();},time:function(){self.options.time=self.options.time=='elapsed'?'remaining':'elapsed';toggleTime();},track:function(){setTrack(self.options.track);},volume:function(){setVolume(self.options.volume);},width:setSizes}).addClass('OxAudioPlayer').css({width:self.options.width+'px'}).bindEvent({key_0:toggleMuted,key_equal:function(){setVolume(Ox.min(self.options.volume+0.1,1));},key_minus:function(){setVolume(Ox.max(self.options.volume-0.1,0));},key_space:togglePaused});self.tracks=self.options.audio.length;self.volume=self.options.muted?1:self.options.volume;self.$listButton=Ox.MenuButton({items:self.options.audio.slice(Math.max(self.options.track-10,0),Math.min(self.options.track+11,self.tracks)).map(function(track,index){index+=Math.max(self.options.track-10,0);return{id:index.toString(),title:formatTrack(track),checked:index==self.options.track};}),maxWidth:256,overlap:'left',title:'select',type:'image'}).addClass('OxListButton').appendTo(that);self.$shuffleButton=Ox.Button(Ox.extend({overlap:'left',type:'image'},getButtonOptions('shuffle'))).addClass('OxShuffleButton').bindEvent({click:toggleShuffle}).appendTo(that);self.$repeatButton=Ox.Button(Ox.extend({overlap:'left',type:'image'},getButtonOptions('repeat'))).addClass('OxRepeatButton').bindEvent({click:function(){setRepeat(self.options.repeat==0?-1:self.options.repeat==-1?1:0);}}).appendTo(that);self.$trackLabel=Ox.Label({textAlign:'center',title:'',}).addClass('OxTrackLabel').appendTo(that);self.$playButtons=Ox.ButtonGroup({buttons:[{id:'current',title:'playPrevious',tooltip:Ox._('Play Current Track')},Ox.extend({id:'play'},getButtonOptions('play')),{id:'next',title:'playNext',tooltip:Ox._('Play Next Track')}],overlap:'right',type:'image',}).addClass('OxPlayButtons').bindEvent({click:function(data){if(data.id=='current'){setPosition(0);}else if(data.id=='play'){togglePaused();}else if(data.id=='next'){playNext();}}}).appendTo(that);self.$positionLabel=Ox.Label({textAlign:'center',title:'00:00:00',tooltip:Ox._('Show Remaining Time'),width:80}).addClass('OxPositionLabel').bindEvent({anyclick:toggleTime}).appendTo(that);self.$positionSlider=Ox.Range({changeOnDrag:true,max:1,min:0,step:0.0000001,}).addClass('OxPositionSlider').bindEvent({change:function(data){setPosition(data.value*self.duration);}}).appendTo(that);self.$muteButton=Ox.Button({overlap:'right',title:'mute',tooltip:Ox._('Mute'),type:'image'}).addClass('OxMuteButton').bindEvent({click:toggleMuted}).appendTo(that);self.$volumeLabel=Ox.Label({textAlign:'center',title:' 100%',width:46}).addClass('OxVolumeLabel').bindEvent({anyclick:function(){setVolume(1);}}).appendTo(that);self.$volumeSlider=Ox.Range({changeOnDrag:true,max:1,min:0,size:116,step:0.01,value:self.options.volume,}).addClass('OxVolumeSlider').bindEvent({change:function(data){setVolume(data.value);}}).appendTo(that);self.$audio=Ox.AudioElement({src:self.options.audio[self.options.track].file}).bindEvent({ended:function(){playNext();},loadedmetadata:function(data){self.duration=data.duration;}}).appendTo(that);setTrack(self.options.track);function formatTrack(data){return[data.name,data.artist,data.album,data.year].join(' · ');}
function getButtonOptions(id){var options;if(id=='mute'){options=self.options.muted||self.options.volume==0?{title:'unmute',tooltip:Ox._('Unmute')}:self.options.volume<1/3?{title:'volumeUp',tooltip:Ox._('Mute')}:self.options.volume<2/3?{title:'volumeDown',tooltip:Ox._('Mute')}:{title:'mute',tooltip:Ox._('Mute')};}else if(id=='play'){options=self.options.paused?{title:'play',tooltip:Ox._('Play')}:{title:'pause',tooltip:Ox._('Pause')};}else if(id=='repeat'){options=self.options.repeat==0?{title:'repeatNone',tooltip:Ox._('Repeat All')}:self.options.repeat==-1?{title:'repeatAll',tooltip:Ox._('Repeat One')}:{title:'repeatOne',tooltip:Ox._('Repeat None')};}else if(id=='shuffle'){options=self.options.shuffle?{title:'shuffleAll',tooltip:Ox._('Don\'t Shuffle')}:{title:'shuffleNone',tooltip:Ox._('Shuffle')};}
return options;}
function getNextTrack(){return self.options.repeat==1?self.options.track:self.options.track0){self.volume=volume;}
self.$audio.volume(volume);self.$muteButton.options(getButtonOptions('mute'));self.$volumeSlider.options({value:volume});self.$volumeLabel.options({title:' '+Math.round(volume*100)+'%'});}
function toggleMuted(){self.options.muted=!self.options.muted;setVolume(self.options.muted?0:self.volume);}
function togglePaused(){self.options.paused=!self.options.paused;self.$playButtons.buttonOptions('play',getButtonOptions('play'));if(self.options.paused){self.$audio.pause();clearInterval(self.playInterval);}else{self.$audio.play();self.playInterval=setInterval(playing,100);}
that.triggerEvent('paused',{paused:self.options.paused});}
function toggleShuffle(){self.options.shuffle=!self.options.shuffle;self.$shuffleButton.options(getButtonOptions('shuffle'))}
function toggleTime(){self.options.time=self.options.time=='remaining'?'elapsed':'remaining';setTime();}
return that;};'use strict';Ox.LeafletMap=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({clickable:false,editable:false,find:'',findPlaceholder:'Find',keys:[],markerColor:'auto',markerSize:'auto',markerTooltip:function(place){return place.name||'Unnamed ';},maxMarkers:100,places:null,selected:'',showControls:false,showLabels:false,showStatusbar:false,showToolbar:false,showZoombar:false,zoomOnlyWhenFocused:false}).options(options||{}).update({find:function(){self.$findInput.value(self.options.find).triggerEvent('submit',{value:self.options.find});},height:function(){that.css({height:self.options.height+'px'});that.resizeMap();},places:function(){if(Ox.isArray(self.options.places)){self.options.places.forEach(function(place){if(Ox.isUndefined(place.id)){place.id=Ox.encodeBase32(Ox.uid());}});if(self.options.selected&&!Ox.getObjectById(self.options.places,self.options.selected)){self.options.selected='';selectPlace(null);}
self.options.places=Ox.api(self.options.places,{geo:true,sort:'-area'});}
self.loaded&&getMapBounds(function(mapBounds){if(mapBounds){self.map.fitBounds(mapBounds);}else{self.map.setZoom(self.minZoom);self.map.setCenter([0,0]);}
self.boundsChanged=true;mapChanged();self.options.selected&&selectPlace(self.options.selected);});},selected:function(){selectPlace(self.options.selected||null);},type:function(){},width:function(){that.css({width:self.options.width+'px'});that.resizeMap();}}).addClass('OxMap').bindEvent({gainfocus:function(){self.options.zoomOnlyWhenFocused&&self.map.setOptions({scrollwheel:true});},losefocus:function(){self.options.zoomOnlyWhenFocused&&self.map.setOptions({scrollwheel:false});},key_0:function(){panToPlace()},key_c:toggleControls,key_down:function(){pan(0,1);},key_enter:pressEnter,key_escape:pressEscape,key_equal:function(){zoom(1);},key_l:toggleLabels,key_left:function(){pan(-1,0);},'key_meta':function(){self.metaKey=true;$(document).one({keyup:function(){self.metaKey=false;}});},key_minus:function(){zoom(-1);},key_right:function(){pan(1,0);},key_shift:function(){self.shiftKey=true;$(document).one({keyup:function(){self.shiftKey=false;}});},key_shift_down:function(){pan(0,2);},key_shift_0:function(){zoomToPlace();},key_shift_equal:function(){zoom(2);},key_shift_left:function(){pan(-2,0);},key_shift_minus:function(){zoom(-2);},key_shift_right:function(){pan(2,0);},key_shift_up:function(){pan(0,-2);},key_up:function(){pan(0,-1);},key_z:undo,mousedown:function(e){!$(e.target).is('input')&&that.gainFocus();}});options&&['statusbar','toolbar','zoombar'].forEach(function(key){if(options[key]){self.options['show'+Ox.toTitleCase(key)]=options[key];}});if(Ox.isArray(self.options.places)){self.options.places.forEach(function(place){if(Ox.isUndefined(place.id)){place.id=Ox.encodeBase32(Ox.uid());}});self.options.places=Ox.api(self.options.places,{geo:true,sort:'-area'});}
self.mapHeight=getMapHeight();self.metaKey=false;self.minZoom=getMinZoom();self.placeKeys=['id','name','alternativeNames','geoname','countryCode','type','lat','lng','south','west','north','east','area','editable'].concat(self.options.keys);self.places=[],self.resultPlace=null;self.scaleMeters=[50000000,20000000,10000000,5000000,2000000,1000000,500000,200000,100000,50000,20000,10000,5000,2000,1000,500,200,100,50,20,10];self.shiftKey=false,self.tileSize=256;if(self.options.showToolbar){self.$toolbar=Ox.Bar({size:24}).appendTo(that);self.$menu=Ox.MenuButton({items:[{id:'toggleLabels',title:self.options.showLabels?[Ox._('Hide Labels'),Ox._('Show Labels')]:[Ox._('Show Labels'),Ox._('Hide Labels')],keyboard:'l'},{id:'toggleControls',title:self.options.showControls?[Ox._('Hide Controls'),Ox._('Show Controls')]:[Ox._('Show Controls'),Ox._('Hide Controls')],keyboard:'c'}],title:'set',tooltip:Ox._('Map Options'),type:'image'}).css({float:'left',margin:'4px'}).bindEvent({click:function(data){if(data.id=='toggleLabels'){toggleLabels();}else if(data.id=='toggleControls'){toggleControls();}}}).appendTo(self.$toolbar);self.$findInput=Ox.Input({clear:true,placeholder:self.options.findPlaceholder,width:192}).css({float:'right',margin:'4px 4px 4px 2px'}).bindEvent({submit:submitFind}).appendTo(self.$toolbar);self.$loadingIcon=Ox.LoadingIcon({size:16}).css({float:'right',margin:'4px 2px 4px 2px'}).appendTo(self.$toolbar);}
self.$map=Ox.Element().css({left:0,top:self.options.showToolbar*24+'px',right:0,bottom:self.options.showZoombar*16+self.options.showStatusbar*24+'px'}).appendTo(that);if(self.options.showZoombar){self.$zoombar=Ox.Bar({size:16}).css({bottom:self.options.showStatusbar*24+'px'}).appendTo(that);}
if(self.options.showStatusbar){self.$statusbar=Ox.Bar({size:24}).css({bottom:0}).appendTo(that);self.$placeFlag=Ox.$(' ').addClass('OxFlag').attr({src:Ox.PATH+'Ox.Geo/png/icons/16/NTHH.png'}).css({float:'left',margin:'4px 2px 4px 4px'}).appendTo(self.$statusbar);self.$placeNameInput=Ox.Input({placeholder:'Name',width:96}).css({float:'left',margin:'4px 2px 4px 2px'}).appendTo(self.$statusbar);self.$placeGeonameInput=Ox.Input({placeholder:'Geoname',width:96}).css({float:'left',margin:'4px 2px 4px 2px'}).appendTo(self.$statusbar);self.$placeButton=Ox.Button({title:'New Place',width:96}).css({float:'right',margin:'4px 4px 4px 2px'}).bindEvent({click:clickPlaceButton}).appendTo(self.$statusbar);}
self.$controls={center:Ox.Button({title:'center',type:'image'}).addClass('OxMapControl OxMapButtonCenter').bindEvent({singleclick:function(){panToPlace();},doubleclick:function(){zoomToPlace();}}),east:Ox.Button({title:'right',type:'image'}).addClass('OxMapControl OxMapButtonEast').bindEvent({singleclick:function(){pan(1,0);},doubleclick:function(){pan(2,0);}}),north:Ox.Button({title:'up',type:'image'}).addClass('OxMapControl OxMapButtonNorth').bindEvent({singleclick:function(){pan(0,-1);},doubleclick:function(){pan(0,-2);}}),south:Ox.Button({title:'down',type:'image'}).addClass('OxMapControl OxMapButtonSouth').bindEvent({singleclick:function(){pan(0,1);},doubleclick:function(){pan(0,2);}}),west:Ox.Button({title:'left',type:'image'}).addClass('OxMapControl OxMapButtonWest').bindEvent({singleclick:function(){pan(-1,0);},doubleclick:function(){pan(-2,0);}}),scale:Ox.Label({textAlign:'center'}).addClass('OxMapControl OxMapScale')};!self.options.showControls&&Ox.forEach(self.$controls,function($control){$control.css({opacity:0}).hide();});self.$placeControls={flag:Ox.Element().addClass('OxPlaceControl OxPlaceFlag').bindEvent({anyclick:function(){var country=this.data('country');country&&getPlaceByName(country,function(place){place&&self.map.fitBounds(place.bounds);});}}),name:Ox.Label({textAlign:'center',tooltip:Ox._('Click to pan, doubleclick to zoom')}).addClass('OxPlaceControl OxPlaceName').bindEvent({singleclick:function(){panToPlace();},doubleclick:function(){zoomToPlace();}}),deselectButton:Ox.Button({title:'close',tooltip:Ox._('Deselect'),type:'image'}).addClass('OxPlaceControl OxPlaceDeselectButton').bindEvent({click:function(){selectPlace(null);}})}
Ox.forEach(self.$placeControls,function($placeControl){$placeControl.css({opacity:0}).hide();});if(window.L){setTimeout(initMap);}else{Ox.getStylesheet('https://unpkg.com/leaflet@1.9.4/dist/leaflet.css',()=>{})
$.getScript(document.location.protocol
+'//unpkg.com/leaflet@1.9.4/dist/leaflet.js',function(){console.log('loaded leaflet');console.log(window.L);initMap();});}
function addPlaceToMap(place){Ox.Log('Map','addPlaceToMap',place)
var exists=false;if(!place){var bounds=self.map.getBounds(),center=self.map.getCenter(),southwest=new google.maps.LatLngBounds(bounds.getSouthWest(),center).getCenter(),northeast=new google.maps.LatLngBounds(center,bounds.getNorthEast()).getCenter(),place=new Ox.LeafletMapPlace({alternativeNames:[],countryCode:'',editable:true,geoname:'',id:'_'+Ox.encodeBase32(Ox.uid()),map:that,name:'',type:'feature',south:southwest.lat(),west:southwest.lng(),north:northeast.lat(),east:northeast.lng()});}
Ox.forEach(self.places,function(p,i){if(place.bounds.equals(p.bounds)){place=p;exists=true;return false;}});if(!exists){self.resultPlace&&self.resultPlace.remove();self.resultPlace=place;place.add();}
selectPlace(place.id);}
function addPlaceToPlaces(data){var place=Ox.extend(getSelectedPlace()||{},data),country=Ox.getCountryByGeoname(place.geoname);place.countryCode=country?country.code:'';self.options.selected=place.id;setPlaceControls(place);place.marker.update();place.rectangle.update();self.places.push(place);self.resultPlace=null;that.triggerEvent('addplace',place)}
function boundsChanged(){setScale();self.boundsChanged=true;}
function canContain(outerBounds,innerBounds){var outerSpan=outerBounds.toSpan(),innerSpan=innerBounds.toSpan();return outerSpan.lat()>innerSpan.lat()&&outerSpan.lng()>innerSpan.lng();}
function centerChanged(){var tooltip=$('.OxMapMarkerTooltip');tooltip.length&&Ox.$elements[$(tooltip[0]).data('oxid')].hide();self.center=self.map.getCenter();self.centerChanged=true;}
function changeZoom(data){self.map.setZoom(data.value);}
function clickMap(event){var place=getSelectedPlace();if(self.options.clickable){getPlaceByLatLng(event.latLng,self.map.getBounds(),function(place){if(place){addPlaceToMap(place);}else{selectPlace(null);}});}else{pressEscape();}}
function clickPlaceButton(){var place=getSelectedPlace(),title=self.$placeButton.options('title');if(title==Ox._('New Place')){addPlaceToMap();}else if(title==Ox._('Add Place')){addPlaceToPlaces();}}
function constructZoomInput(){if(self.options.showZoombar){self.$zoomInput&&self.$zoomInput.remove();self.$zoomInput=Ox.Range({arrows:true,changeOnDrag:true,max:self.maxZoom,min:self.minZoom,size:that.width(),thumbSize:32,thumbValue:true,value:self.map.getZoom()}).bindEvent({change:changeZoom}).appendTo(self.$zoombar);}}
function crossesDateline(){var bounds=self.map.getBounds();return bounds.getSouthWest().lng()>bounds.getNorthEast().lng();}
function editing(){var place=getSelectedPlace();return place&&place.editing;}
function getElevation(point,callback){if(arguments.length==1){callback=point;point=self.map.getCenter();}
self.elevationService.getElevationForLocations({locations:[point]},function(data){callback(data.elevation);});}
function getMapBounds(callback){self.options.places({},function(result){var area=result.data.area;console.log('area',area);console.log(L.latLngBounds([area.south,area.west],[area.north,area.east]));callback(new L.latLngBounds([area.south,area.west],[area.north,area.east]));});}
function getMapHeight(){return self.options.height
-self.options.showStatusbar*24
-self.options.showToolbar*24
-self.options.showZoombar*16;}
function getMapType(){return self.options.showLabels?'HYBRID':'SATELLITE'}
function getMaxZoom(point,callback){if(arguments.length==1){callback=point;point=self.map.getCenter();}
setTimeout(function(){callback(18)});}
function getMetersPerPixel(){var degreesPerPixel=360/(self.tileSize*Math.pow(2,self.map.getZoom()));return Ox.getMetersPerDegree(self.map.getCenter().lat)*degreesPerPixel;}
function getMinZoom(){return self.mapHeight>1024?3:self.mapHeight>512?2:self.mapHeight>256?1:0;}
function getPlaceById(id){return self.resultPlace&&self.resultPlace.id==id?self.resultPlace:Ox.getObjectById(self.places,id);}
function getPlaceByLatLng(latlng,bounds,callback){var callback=arguments.length==3?callback:bounds,bounds=arguments.length==3?bounds:null;self.$loadingIcon&&self.$loadingIcon.start();self.geocoder.geocode({latLng:latlng},function(results,status){self.$loadingIcon&&self.$loadingIcon.stop();if(status==google.maps.GeocoderStatus.OK){if(bounds){Ox.forEach(results.reverse(),function(result,i){if(i==results.length-1||canContain(bounds,result.geometry.bounds||result.geometry.viewport)){callback(new Ox.LeafletMapPlace(parseGeodata(results[i])));return false;}});}else{callback(new Ox.LeafletMapPlace(parseGeodata(results[0])));}}
if(status==google.maps.GeocoderStatus.OK||status==google.maps.GeocoderStatus.ZERO_RESULTS){triggerGeocodeEvent({latLng:latlng,results:results});}else{Ox.Log('Map','geocode failed:',status);callback(null);}});}
function getPlaceByName(name,callback){self.$loadingIcon&&self.$loadingIcon.start();self.geocoder.geocode({address:name},function(results,status){self.$loadingIcon&&self.$loadingIcon.stop();if(status==google.maps.GeocoderStatus.OK){callback(new Ox.LeafletMapPlace(parseGeodata(results[0])));}
if(status==google.maps.GeocoderStatus.OK&&status!=google.maps.GeocoderStatus.ZERO_RESULTS){triggerGeocodeEvent({address:name,results:results});}else{Ox.Log('Map','geocode failed:',status);callback(null);}});}
function getPositionByName(name){var position=-1;Ox.forEach(self.options.places,function(place,i){if(place.name==name){position=i;return false;}});return position;}
function getSelectedMarker(){var id=null;if(self.resultPlace&&self.resultPlace.selected){id=self.resultPlace.id;}else{Ox.forEach(self.places,function(place){if(place.selected){id=place.id;return false;}});}
return id;}
function getSelectedPlace(){return self.options.selected?getPlaceById(self.options.selected):null;}
function initMap(){getMapBounds(function(mapBounds){console.log('map bounds',mapBounds);self.center=mapBounds?mapBounds.getCenter():new L.LatLng([0,0]);self.zoom=self.minZoom;that.map=self.map=new L.Map(self.$map[0],{center:self.center,zoom:self.zoom});console.log('that map',that.map);L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png',{maxZoom:19,attribution:'© OpenStreetMap '}).addTo(that.map);self.map.fitBounds(mapBounds);self.map.on('moveend',boundsChanged);self.map.on('moveend',centerChanged);self.map.on('click',clickMap);self.map.on('zoomend',zoomChanged);setTimeout(function(){mapChanged();});Ox.forEach(self.$controls,function($control){$control.appendTo(self.$map);});Ox.forEach(self.$placeControls,function($placeControl){$placeControl.appendTo(self.$map);});if(self.options.find){self.$findInput.value(self.options.find).triggerEvent('submit',{value:self.options.find});}else{if(self.options.selected){selectPlace(self.options.selected,true);}
if(mapBounds){if(isEmpty(mapBounds)){self.map.setZoom(self.minZoom);}else{self.map.fitBounds(mapBounds);}}
if(self.map.getZoom()zoom){self.map.setZoom(zoom);}
constructZoomInput();}});self.centerChanged=false;}
if(self.zoomChanged){self.zoomChanged=false;}}
function pan(x,y){self.map.panBy(x*self.$map.width()/2,y*self.$map.height()/2);};function panToPlace(){var place;if(!self.loaded){setTimeout(function(){panToPlace();},100);}else{place=getSelectedPlace();place&&self.map.panTo(place.center);}}
function parseGeodata(data){var bounds=data.geometry.bounds||data.geometry.viewport,northEast=bounds.getNorthEast(),southWest=bounds.getSouthWest(),place={alternativeNames:[],components:data.address_components,countryCode:getCountryCode(data.address_components),east:northEast.lng(),editable:self.options.editable,fullGeoname:getFullGeoname(data.address_components),id:'_'+Ox.encodeBase32(Ox.uid()),map:that,north:northEast.lat(),south:southWest.lat(),type:getType(data.address_components[0].types),west:southWest.lng()};place.geoname=data.formatted_address||place.fullGeoname;place.name=(place.geoname||place.fullGeoname).split(', ')[0];if(Math.abs(place.west)==180&&Math.abs(place.east)==180){place.west=-179.99999999;place.east=179.99999999;}
place.south=Ox.limit(place.south,Ox.MIN_LATITUDE,Ox.MAX_LATITUDE-0.00000001);place.north=Ox.limit(place.north,Ox.MIN_LATITUDE+0.00000001,Ox.MAX_LATITUDE);function getCountryCode(components){var countryCode='';Ox.forEach(components,function(component){if(component.types.indexOf('country')>-1){countryCode=component.short_name;return false;}});return countryCode;}
function getFullGeoname(components){var country=false;return components.map(function(component,i){var name=component.long_name;if(i&&components[i-1].types.indexOf('country')>-1){country=true;}
return!country&&(i==0||name!=components[i-1].long_name)?name:null;}).join(', ');}
function getType(types){var strings={'country':['country'],'region':['administrative_area','colloquial_area'],'city':['locality'],'borough':['neighborhood','postal_code','sublocality'],'street':['intersection','route','street_address','street_number'],'building':['airport','floor','premise','room','subpremise'],'feature':['natural_feature','park']},type;function find(type){var ret;Ox.forEach(types,function(v){ret=Ox.startsWith(v,type);if(ret){return false;}});return ret;}Ox.forEach(strings,function(values,key){Ox.forEach(values,function(value){if(find(value)){type=key;return false;}});if(type){return false;}});return type||'feature';}
return place;}
function pressEnter(){var place=getSelectedPlace();if(place){if(place.editing){place.submit();}else{place.edit();}}else if(self.resultPlace){selectPlace(self.resultPlace.id)}}
function pressEscape(){var place=getSelectedPlace();if(place){if(place.editing){place.cancel();}else{selectPlace(null);}}else if(self.resultPlace){self.resultPlace.remove();self.resultPlace=null;}}
function removePlace(){var place=getSelectedPlace();place.id='_'+place.id;self.options.selected=place.id;self.places.splice(Ox.getIndexById(self.places,place.id),1);self.resultPlace&&self.resultPlace.remove();self.resultPlace=place;place.marker.update();place.rectangle.update();}
function reset(){self.map.getZoom()==self.zoom?self.map.panTo(self.center):self.map.fitBounds(self.bounds);}
function selectPlace(id,zoom){var place,selected;if(!self.loaded){setTimeout(function(){selectPlace(id,zoom);},100);}else{selected=getSelectedMarker();Ox.Log('Map','Ox.Map selectPlace()',id,selected);if(id!=selected){place=getPlaceById(selected);place&&place.deselect();if(id!==null){place=getPlaceById(id);if(place){select();}else{self.options.places({keys:self.placeKeys,query:{conditions:[{key:'id',value:id,operator:'=='}],operator:'&'}},function(result){if(result.data.items.length){place=new Ox.LeafletMapPlace(Ox.extend({map:that},result.data.items[0])).add();self.places.push(place);select();if(zoom){zoomToPlace();}else{panToPlace();}}});}}else{place=null;select();}}}
function select(){place&&place.select();self.options.selected=id;setPlaceControls(place);setStatus();that.triggerEvent('selectplace',place);that.triggerEvent('select',place);}};function setPlaceControls(place){var $placeControls=that.find('.OxPlaceControl'),country,isVisible=self.$placeControls.name.is(':visible');if(place){country=place.geoname.indexOf(', ')>-1?place.geoname.split(', ').pop():'';self.$placeControls.flag.options({tooltip:country?'Zoom to '+country:''}).data({country:country}).empty().append(Ox.$(' ').attr({src:Ox.getFlagByGeoname(place.geoname,16)})).show();self.$placeControls.name.options({title:place.name||'Unnamed '});!isVisible&&$placeControls.show().animate({opacity:1},250);}else{isVisible&&$placeControls.animate({opacity:0},250,function(){$placeControls.hide();});}}
function setScale(){var metersPerPixel=getMetersPerPixel();Ox.forEach(self.scaleMeters,function(meters){var mapWidth=self.options.width||that.width(),scaleWidth=Math.round(meters/metersPerPixel);if(scaleWidth<=mapWidth/2-4){self.$controls.scale.options({title:'\u2190 '+(meters>1000?Ox.formatNumber(meters/1000)+' k':meters+' ')+'m \u2192'}).css({width:(scaleWidth-16)+'px'});return false;}});}
function setStatus(){var code,country,disabled,place,title;if(self.options.showStatusbar){place=getSelectedPlace();country=place?Ox.getCountryByGeoname(place.geoname):'';code=country?country.code:'NTHH';disabled=place&&!place.editable;if(place){title=place.id[0]=='_'?Ox._('Add Place'):Ox._('Remove Place');}else{title=Ox._('New Place');}
self.$placeFlag.attr({src:Ox.PATH+'Ox.Geo/png/icons/16/'+code+'.png'});self.$placeNameInput.options({disabled:disabled,value:place?place.name:''});self.$placeGeonameInput.options({disabled:disabled,value:place?place.geoname:''});self.$placeButton.options({disabled:disabled,title:title});}}
function spansGlobe(){return self.$map.width()>self.tileSize*Math.pow(2,self.map.getZoom());};function submitFind(data){self.options.find=data.value;if(data.value===''){if(self.options.selected&&self.options.selected[0]=='_'){selectPlace(null);}}else{that.findPlace(data.value,function(place){setStatus(place);});}
that.triggerEvent('find',{value:data.value});}
function toggleControls(){var $controls=that.find('.OxMapControl');self.options.showControls=!self.options.showControls;if(self.options.showControls){$controls.show().animate({opacity:1},250);}else{$controls.animate({opacity:0},250,function(){$controls.hide();});}
that.triggerEvent('togglecontrols',{visible:self.options.showControls});}
function toggleLabels(){self.options.showLabels=!self.options.showLabels;self.map.setMapTypeId(google.maps.MapTypeId[getMapType()]);that.triggerEvent('togglelabels',{visible:self.options.showLabels});}
function triggerGeocodeEvent(data){if(data.latLng){data.latLng={lat:data.latLng.lat(),lng:data.latLng.lng()}}
data.results.forEach(function(result){['bounds','viewport'].forEach(function(key){if(result.geometry[key]){result.geometry[key]={northEast:{lat:result.geometry[key].getNorthEast().lat(),lng:result.geometry[key].getNorthEast().lng()},southWest:{lat:result.geometry[key].getSouthWest().lat(),lng:result.geometry[key].getSouthWest().lng()}}}});if(result.geometry.location){result.geometry.location={lat:result.geometry.location.lat(),lng:result.geometry.location.lng()}}});that.triggerEvent('geocode',data);}
function undo(){Ox.Log('Map','Map undo')
var place=getSelectedPlace();place.editing&&place.undo();}
function updateFormElements(){var width=that.width();if(self.options.showZoombar){getMaxZoom(function(zoom){self.maxZoom=zoom;constructZoomInput();});}
if(self.options.showStatusbar){self.$placeNameInput.options({width:Math.floor((width-132)/2)});self.$placeGeonameInput.options({width:Math.ceil((width-132)/2)});}}
function zoom(z){if(!self.loaded){setTimeout(function(){zoom(z);},100);}else{self.map.setZoom(self.map.getZoom()+z);}}
function zoomChanged(){var zoom=self.map.getZoom();if(zoomself.maxZoom){self.map.setZoom(self.maxZoom);}else{self.zoomChanged=true;self.$zoomInput&&self.$zoomInput.value(zoom);that.triggerEvent('zoom',{value:zoom});}}
function zoomToPlace(){var place;if(!self.loaded){setTimeout(function(){zoomToPlace();},100);}else{place=getSelectedPlace();place&&self.map.fitBounds(place.bounds);}}
that.addPlace=function(data){addPlaceToPlaces(data);};that.getCenter=function(){var center=self.map.getCenter();return{lat:center.lat(),lng:center.lng()};};that.getKey=function(){return self.shiftKey?'shift':self.metaKey?'meta':null;};that.getSelectedPlace=function(){return getSelectedPlace();}
that.editPlace=function(){getSelectedPlace().edit();return that;};that.findPlace=function(name,callback){getPlaceByName(name,function(place){if(place){addPlaceToMap(place);self.map.fitBounds(place.bounds);}else{name&&self.$findInput.addClass('OxError');}
callback(place);});return that;};that.newPlace=function(place){addPlaceToMap(place);return that;};that.panToPlace=function(){panToPlace();return that;};that.removePlace=function(){removePlace();return that;};that.resizeMap=function(){self.options.height=that.height();self.options.width=that.width();if(self.map){self.mapHeight=getMapHeight();self.minZoom=getMinZoom();if(self.minZoom>self.map.getZoom()){self.map.setZoom(self.minZoom);}
self.$map.css({height:self.mapHeight+'px',width:self.options.width+'px'});self.options.$zoomInput&&self.$zoomInput.options({size:self.options.width});updateFormElements();Ox.Log('Map','triggering google maps resize event, height',self.options.height)
google.maps.event.trigger(self.map,'resize');}
return that;}
that.setCenter=function(center){self.map.setCenter(new google.maps.LatLng(center.lat,center.lng));return that;};that.value=function(id,key,value){Ox.Log('Map','Map.value',id,key,value);getPlaceById(id).options(key,value);if(id==self.options.selected){if(key=='name'){self.$placeControls.name.options({title:value});}else if(key=='geoname'){self.$placeControls.flag.empty().append(Ox.$(' ').attr({src:Ox.getFlagByGeoname(value,16)}));}}
return that;}
that.zoomToPlace=function(){zoomToPlace();return that;};that.zoom=function(value){zoom(value);return that;};return that;};'use strict';Ox.LeafletMapMarker=function(options){options=Ox.extend({map:null,place:null},options);var that=this,areaSize={100:10,10000:12,1000000:14,100000000:16,10000000000:18,1000000000000:20,100000000000000:22},themeData=Ox.Theme.getThemeData(),typeColor={};['country','region','city','borough','street','building','feature'].forEach(function(type){typeColor[type]=themeData['mapPlace'+Ox.toTitleCase(type)+'Color'];});Ox.forEach(options,function(val,key){that[key]=val;});console.log('place',options.place);that.marker=new L.Marker([options.place.center.lat,options.place.center.lng],{}).addTo(options.map.map);function click(){var key=that.map.getKey(),place,bounds,southWest,northEast;if(!that.place.selected){if(that.map.options('editable')&&(key=='meta'||key=='shift')){place=that.map.getSelectedPlace();}
if(place){bounds=new google.maps.LatLngBounds(new google.maps.LatLng(place.south,place.west),new google.maps.LatLng(place.north,place.east));bounds=bounds.union(that.place.bounds);southWest=bounds.getSouthWest();northEast=bounds.getNorthEast();that.map.newPlace(new Ox.LeafletMapPlace({alternativeNames:[],countryCode:'',editable:true,geoname:'',id:'_'+Ox.encodeBase32(Ox.uid()),map:that.map,name:'',type:'feature',south:southWest.lat(),west:southWest.lng(),north:northEast.lat(),east:northEast.lng()}));}else{that.map.options({selected:that.place.id});}}else{if(key=='meta'){that.map.options({selected:null});}else{that.map.panToPlace();}}}
function dblclick(){that.place.selected&&that.map.zoomToPlace();}
function dragstart(e){Ox.$body.addClass('OxDragging');}
function drag(e){var northSouth=(that.place.north-that.place.south)/2,lat=Ox.limit(e.latLng.lat(),Ox.MIN_LATITUDE+northSouth,Ox.MAX_LATITUDE-northSouth),lng=e.latLng.lng(),span=Math.min(that.place.sizeEastWest*Ox.getDegreesPerMeter(lat)/2,179.99999999),degreesPerMeter=Ox.getDegreesPerMeter(lat);that.place.south+=lat-that.place.lat;that.place.north+=lat-that.place.lat;that.place.west=lng-span;that.place.east=lng+span;if(that.place.west<-180){that.place.west+=360;}else if(that.place.east>180){that.place.east-=360;}
Ox.Log('Map','west',that.place.west,'east',that.place.east,'span',span);that.place.update();that.marker.setOptions({position:that.place.center});that.place.rectangle.update();}
function dragend(e){Ox.$body.removeClass('OxDragging');that.map.triggerEvent('changeplaceend',that.place);}
function getMarkerImage(options,callback){options=Ox.extend({background:[255,0,0],editing:false,result:false,selected:false,size:16},options);var background=options.result?[255,255,0]:[255,0,0],border=options.editing?[128,128,255]:options.selected?[255,255,255]:[0,0,0],c=Ox.canvas(options.size,options.size),image,r=options.size/2;if(Ox.isArray(background)){c.context.fillStyle='rgba('+background.join(', ')+', 0.5)';c.context.arc(r,r,r-2,0,360);c.context.fill();renderImage();}else{image=new Image();image.onload=renderImage;image.src=background;}
function renderImage(){if(Ox.isString(background)){c.context.drawImage(image,1,1,options.size-2,options.size-2);}
c.context.beginPath();c.context.lineWidth=2;c.context.strokeStyle='rgb('+border.join(', ')+')';c.context.arc(r,r,r-1,0,360);c.context.stroke();callback(new google.maps.MarkerImage(c.canvas.toDataURL(),new google.maps.Size(options.size,options.size),new google.maps.Point(0,0),new google.maps.Point(r,r)));}}
function mouseover(e){var offset=that.map.offset(),xy=that.map.overlayView.getProjection().fromLatLngToContainerPixel(e.latLng);that.tooltip.show(offset.left+Math.round(xy.x)-4,offset.top+Math.round(xy.y)+20);}
function mouseout(){that.tooltip.hide();}
function setOptions(){var fix=that.marker.getDraggable()&&!that.place.editing,color=that.map.options('markerColor'),size=that.map.options('markerSize');if(color=='auto'){that.color=typeColor[that.place.type]||typeColor['mapPlaceFeatureColor'];}else if(Ox.isArray(color)){that.color=color;}else{that.color=color(that.place);}
if(size=='auto'){that.size=8;Ox.forEach(areaSize,function(size,area){if(that.place.area>=area){that.size=size;}else{return false;}});}else if(Ox.isNumber(size)){that.size=size;}else{that.size=size(that.place);}
that.marker.setOptions({cursor:that.place.editing?'move':'pointer',draggable:that.place.editing,icon:Ox.MapMarkerImage({color:that.color,mode:that.place.editing?'editing':that.place.selected?'selected':'normal',size:that.size,type:that.place.id[0]=='_'?'result':'place'}),position:that.place.center});if(fix){that.marker.setVisible(false);setTimeout(function(){that.marker.setVisible(true);},0);}
setTooltip();}
function setTooltip(){that.tooltip&&that.tooltip.remove();that.tooltip=Ox.Tooltip({title:' '
+''
+that.map.options('markerTooltip')(that.place)+'
'}).addClass('OxMapMarkerTooltip');}
that.add=function(){that.marker.setMap(that.map.map);google.maps.event.addListener(that.marker,'click',click);google.maps.event.addListener(that.marker,'dblclick',dblclick);google.maps.event.addListener(that.marker,'mouseover',mouseover);google.maps.event.addListener(that.marker,'mouseout',mouseout);return that;};that.edit=function(){setOptions();google.maps.event.addListener(that.marker,'dragstart',dragstart);google.maps.event.addListener(that.marker,'drag',drag);google.maps.event.addListener(that.marker,'dragend',dragend);return that;};that.remove=function(){that.marker.setMap(null);google.maps.event.clearListeners(that.marker);return that;};that.submit=function(){google.maps.event.clearListeners(that.marker,'dragstart');google.maps.event.clearListeners(that.marker,'drag');google.maps.event.clearListeners(that.marker,'dragend');return that;}
that.update=function(){setOptions();return that;}
return that;};'use strict';Ox.LeafletMapPlace=function(options){options=Ox.extend({east:0,editing:false,geoname:'',map:null,name:'',north:0,selected:false,south:0,type:'',visible:false,west:0},options);var that=this;Ox.forEach(options,function(val,key){that[key]=val;});update();function update(updateMarker){that.points={ne:new L.LatLng(that.north,that.east),sw:new L.LatLng(that.south,that.west)};console.log('points',JSON.stringify(that.points,null,2));that.bounds=new L.latLngBounds(that.points.sw,that.points.ne);that.center=that.bounds.getCenter();that.lat=that.center.lat;that.lng=that.center.lng;Ox.extend(that.points,{e:new L.LatLng(that.lat,that.east),s:new L.LatLng(that.south,that.lng),se:new L.LatLng(that.south,that.east),n:new L.LatLng(that.north,that.lng),nw:new L.LatLng(that.north,that.west),w:new L.LatLng(that.lat,that.west)});that.sizeNorthSouth=(that.north-that.south)*Ox.EARTH_CIRCUMFERENCE/360;that.sizeEastWest=(that.east+(that.west>that.east?360:0)-that.west)*Ox.getMetersPerDegree(that.lat);that.area=Ox.getArea({lat:that.south,lng:that.west},{lat:that.north,lng:that.east});if(!that.marker){that.marker=new Ox.LeafletMapMarker({map:that.map,place:that});that.rectangle=new Ox.LeafletMapRectangle({map:that.map,place:that});}else if(updateMarker){that.marker.update();that.rectangle.update();}}
function editable(){return that.map.options('editable')&&that.editable;}
that.add=function(){that.visible=true;that.marker.add();return that;};that.cancel=function(){if(editable()){that.undo();that.editing=false;that.marker.update();that.rectangle.deselect();}
return that;};that.crossesDateline=function(){return that.west>that.east;}
that.deselect=function(){that.editing&&that.submit();that.selected=false;that.marker.update();that.rectangle.remove();return that;};that.edit=function(){if(editable()){that.editing=true;that.original={south:that.south,west:that.west,north:that.north,east:that.east};that.marker.edit();that.rectangle.select();}
return that;};that.options=function(options){options=Ox.makeObject(arguments);Ox.forEach(options,function(value,key){that[key]=value;});update(true);};that.remove=function(){that.editing&&that.submit();that.selected&&that.deselect();that.visible=false;that.marker.remove();return that;};that.select=function(){that.selected=true;!that.visible&&that.add();that.marker.update();that.rectangle.add();return that;};that.submit=function(){if(editable()){that.editing=false;that.marker.update();that.rectangle.deselect();}
return that;};that.update=function(updateMarker){update(updateMarker);that.map.triggerEvent('changeplace',that);return that;};that.undo=function(){if(editable()){Ox.forEach(that.original,function(v,k){that[k]=v;});that.update();that.marker.update();that.rectangle.update();}
return that;};return that;};'use strict';Ox.LeafletMapRectangle=function(options){options=Ox.extend({map:null,place:null},options);var that=this,themeData=Ox.Theme.getThemeData();Ox.forEach(options,function(val,key){that[key]=val;});that.rectangle=new L.rectangle({bounds:that.place.bounds});that.markers=Ox.map(that.place.points,function(point,position){return new Ox.LeafletMapRectangleMarker({map:that.map,place:that.place,position:position});});setOptions();function click(){if(that.map.options('editable')&&that.place.editable&&!that.place.editing){that.place.edit();}else if(that.map.getKey()=='meta'){that.place.submit();}else if(that.map.getKey()=='shift'){that.map.zoomToPlace();}else{that.map.panToPlace();}}
function setOptions(){var color='#'+Ox.toHex(themeData[that.place.editing?'mapPlaceEditingBorder':'mapPlaceSelectedBorder']);that.rectangle.setOptions({bounds:that.place.bounds,fillColor:color,fillOpacity:that.place.editing?0.1:0,strokeColor:color,strokeOpacity:that.place.id[0]=='_'?0.5:1,strokeWeight:2});}
that.add=function(){that.rectangle.addTo(that.map.map);that.rectangle.on('click',click);return that;};that.deselect=function(){setOptions();Ox.Log('Map','MARKERS',that.markers)
Ox.forEach(that.markers,function(marker){marker.remove();});return that;};that.remove=function(){that.rectangle.remove();return that;}
that.select=function(){setOptions();Ox.forEach(that.markers,function(marker){marker.add();});return that;};that.update=function(){Ox.Log('Map','UPDATE...')
setOptions();Ox.forEach(that.markers,function(marker){marker.update();});return that;}
return that;};'use strict';Ox.LeafletMapRectangleMarker=function(options){options=Ox.extend({map:null,place:null,position:''},options);var that=this;Ox.forEach(options,function(val,key){that[key]=val;});console.log('position',that.place.points,that.position);that.marker=new L.Marker({});function dragstart(e){Ox.$body.addClass('OxDragging');that.drag={lat:e.latLng.lat(),lng:e.latLng.lng()};}
function drag(e){Ox.Log('Map',e.pixel.x,e.pixel.y)
var lat=Ox.limit(e.latLng.lat(),Ox.MIN_LATITUDE,Ox.MAX_LATITUDE),lng=e.latLng.lng();that.drag={lat:lat,lng:lng};if(that.position.indexOf('s')>-1){that.place.south=lat;}
if(that.position.indexOf('n')>-1){that.place.north=lat;}
if(that.position.indexOf('w')>-1){that.place.west=lng;}
if(that.position.indexOf('e')>-1){that.place.east=lng;}
that.place.update();that.place.marker.update();that.place.rectangle.update();}
function dragend(e){var south;Ox.$body.removeClass('OxDragging');if(that.place.south>that.place.north){south=that.place.south;that.place.south=that.place.north;that.place.north=south;that.place.update();that.place.marker.update();that.place.rectangle.update();}
that.map.triggerEvent('changeplaceend',that.place);}
that.add=function(){that.marker.setMap(that.map.map);google.maps.event.addListener(that.marker,'dragstart',dragstart);google.maps.event.addListener(that.marker,'drag',drag);google.maps.event.addListener(that.marker,'dragend',dragend);};that.remove=function(){that.marker.setMap(null);google.maps.event.clearListeners(that.marker);};that.update=function(){that.marker.setOptions({icon:Ox.MapMarkerImage({mode:'editing',rectangle:true,type:that.place.id[0]=='_'?'result':'place'}),position:that.place.points[that.position]});};return that;};'use strict';Ox.Map=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({clickable:false,editable:false,find:'',findPlaceholder:'Find',keys:[],markerColor:'auto',markerSize:'auto',markerTooltip:function(place){return place.name||'Unnamed ';},maxMarkers:100,places:null,selected:'',showControls:false,showLabels:false,showStatusbar:false,showToolbar:false,showZoombar:false,zoomOnlyWhenFocused:false}).options(options||{}).update({find:function(){self.$findInput.value(self.options.find).triggerEvent('submit',{value:self.options.find});},height:function(){that.css({height:self.options.height+'px'});that.resizeMap();},places:function(){if(Ox.isArray(self.options.places)){self.options.places.forEach(function(place){if(Ox.isUndefined(place.id)){place.id=Ox.encodeBase32(Ox.uid());}});if(self.options.selected&&!Ox.getObjectById(self.options.places,self.options.selected)){self.options.selected='';selectPlace(null);}
self.options.places=Ox.api(self.options.places,{geo:true,sort:'-area'});}
self.loaded&&getMapBounds(function(mapBounds){if(mapBounds){self.map.fitBounds(mapBounds);}else{self.map.setZoom(self.minZoom);self.map.setCenter(new google.maps.LatLng(0,0));}
self.boundsChanged=true;mapChanged();self.options.selected&&selectPlace(self.options.selected);});},selected:function(){selectPlace(self.options.selected||null);},type:function(){},width:function(){that.css({width:self.options.width+'px'});that.resizeMap();}}).addClass('OxMap').bindEvent({gainfocus:function(){self.options.zoomOnlyWhenFocused&&self.map.setOptions({scrollwheel:true});},losefocus:function(){self.options.zoomOnlyWhenFocused&&self.map.setOptions({scrollwheel:false});},key_0:function(){panToPlace()},key_c:toggleControls,key_down:function(){pan(0,1);},key_enter:pressEnter,key_escape:pressEscape,key_equal:function(){zoom(1);},key_l:toggleLabels,key_left:function(){pan(-1,0);},'key_meta':function(){self.metaKey=true;$(document).one({keyup:function(){self.metaKey=false;}});},key_minus:function(){zoom(-1);},key_right:function(){pan(1,0);},key_shift:function(){self.shiftKey=true;$(document).one({keyup:function(){self.shiftKey=false;}});},key_shift_down:function(){pan(0,2);},key_shift_0:function(){zoomToPlace();},key_shift_equal:function(){zoom(2);},key_shift_left:function(){pan(-2,0);},key_shift_minus:function(){zoom(-2);},key_shift_right:function(){pan(2,0);},key_shift_up:function(){pan(0,-2);},key_up:function(){pan(0,-1);},key_z:undo,mousedown:function(e){!$(e.target).is('input')&&that.gainFocus();}});options&&['statusbar','toolbar','zoombar'].forEach(function(key){if(options[key]){self.options['show'+Ox.toTitleCase(key)]=options[key];}});if(Ox.isArray(self.options.places)){self.options.places.forEach(function(place){if(Ox.isUndefined(place.id)){place.id=Ox.encodeBase32(Ox.uid());}});self.options.places=Ox.api(self.options.places,{geo:true,sort:'-area'});}
self.mapHeight=getMapHeight();self.metaKey=false;self.minZoom=getMinZoom();self.placeKeys=['id','name','alternativeNames','geoname','countryCode','type','lat','lng','south','west','north','east','area','editable'].concat(self.options.keys);self.places=[],self.resultPlace=null;self.scaleMeters=[50000000,20000000,10000000,5000000,2000000,1000000,500000,200000,100000,50000,20000,10000,5000,2000,1000,500,200,100,50,20,10];self.shiftKey=false,self.tileSize=256;if(self.options.showToolbar){self.$toolbar=Ox.Bar({size:24}).appendTo(that);self.$menu=Ox.MenuButton({items:[{id:'toggleLabels',title:self.options.showLabels?[Ox._('Hide Labels'),Ox._('Show Labels')]:[Ox._('Show Labels'),Ox._('Hide Labels')],keyboard:'l'},{id:'toggleControls',title:self.options.showControls?[Ox._('Hide Controls'),Ox._('Show Controls')]:[Ox._('Show Controls'),Ox._('Hide Controls')],keyboard:'c'}],title:'set',tooltip:Ox._('Map Options'),type:'image'}).css({float:'left',margin:'4px'}).bindEvent({click:function(data){if(data.id=='toggleLabels'){toggleLabels();}else if(data.id=='toggleControls'){toggleControls();}}}).appendTo(self.$toolbar);self.$findInput=Ox.Input({clear:true,placeholder:self.options.findPlaceholder,width:192}).css({float:'right',margin:'4px 4px 4px 2px'}).bindEvent({submit:submitFind}).appendTo(self.$toolbar);self.$loadingIcon=Ox.LoadingIcon({size:16}).css({float:'right',margin:'4px 2px 4px 2px'}).appendTo(self.$toolbar);}
self.$map=Ox.Element().css({left:0,top:self.options.showToolbar*24+'px',right:0,bottom:self.options.showZoombar*16+self.options.showStatusbar*24+'px'}).appendTo(that);if(self.options.showZoombar){self.$zoombar=Ox.Bar({size:16}).css({bottom:self.options.showStatusbar*24+'px'}).appendTo(that);}
if(self.options.showStatusbar){self.$statusbar=Ox.Bar({size:24}).css({bottom:0}).appendTo(that);self.$placeFlag=Ox.$(' ').addClass('OxFlag').attr({src:Ox.PATH+'Ox.Geo/png/icons/16/NTHH.png'}).css({float:'left',margin:'4px 2px 4px 4px'}).appendTo(self.$statusbar);self.$placeNameInput=Ox.Input({placeholder:'Name',width:96}).css({float:'left',margin:'4px 2px 4px 2px'}).appendTo(self.$statusbar);self.$placeGeonameInput=Ox.Input({placeholder:'Geoname',width:96}).css({float:'left',margin:'4px 2px 4px 2px'}).appendTo(self.$statusbar);self.$placeButton=Ox.Button({title:'New Place',width:96}).css({float:'right',margin:'4px 4px 4px 2px'}).bindEvent({click:clickPlaceButton}).appendTo(self.$statusbar);}
self.$controls={center:Ox.Button({title:'center',type:'image'}).addClass('OxMapControl OxMapButtonCenter').bindEvent({singleclick:function(){panToPlace();},doubleclick:function(){zoomToPlace();}}),east:Ox.Button({title:'right',type:'image'}).addClass('OxMapControl OxMapButtonEast').bindEvent({singleclick:function(){pan(1,0);},doubleclick:function(){pan(2,0);}}),north:Ox.Button({title:'up',type:'image'}).addClass('OxMapControl OxMapButtonNorth').bindEvent({singleclick:function(){pan(0,-1);},doubleclick:function(){pan(0,-2);}}),south:Ox.Button({title:'down',type:'image'}).addClass('OxMapControl OxMapButtonSouth').bindEvent({singleclick:function(){pan(0,1);},doubleclick:function(){pan(0,2);}}),west:Ox.Button({title:'left',type:'image'}).addClass('OxMapControl OxMapButtonWest').bindEvent({singleclick:function(){pan(-1,0);},doubleclick:function(){pan(-2,0);}}),scale:Ox.Label({textAlign:'center'}).addClass('OxMapControl OxMapScale')};!self.options.showControls&&Ox.forEach(self.$controls,function($control){$control.css({opacity:0}).hide();});self.$placeControls={flag:Ox.Element().addClass('OxPlaceControl OxPlaceFlag').bindEvent({anyclick:function(){var country=this.data('country');country&&getPlaceByName(country,function(place){place&&self.map.fitBounds(place.bounds);});}}),name:Ox.Label({textAlign:'center',tooltip:Ox._('Click to pan, doubleclick to zoom')}).addClass('OxPlaceControl OxPlaceName').bindEvent({singleclick:function(){panToPlace();},doubleclick:function(){zoomToPlace();}}),deselectButton:Ox.Button({title:'close',tooltip:Ox._('Deselect'),type:'image'}).addClass('OxPlaceControl OxPlaceDeselectButton').bindEvent({click:function(){selectPlace(null);}})}
Ox.forEach(self.$placeControls,function($placeControl){$placeControl.css({opacity:0}).hide();});if(window.google){setTimeout(initMap);}else if(window.googleCallback){(function interval(){isLoaded()?initMap():setTimeout(interval,100);}());}else{window.googleCallback=function(){delete window.googleCallback;initMap();};$.getScript(document.location.protocol
+'//maps.google.com/maps/api/js?callback=googleCallback&sensor=false'
+(Ox.Map.GoogleApiKey?'&key='+Ox.Map.GoogleApiKey:''));}
function addPlaceToMap(place){Ox.Log('Map','addPlaceToMap',place)
var exists=false;if(!place){var bounds=self.map.getBounds(),center=self.map.getCenter(),southwest=new google.maps.LatLngBounds(bounds.getSouthWest(),center).getCenter(),northeast=new google.maps.LatLngBounds(center,bounds.getNorthEast()).getCenter(),place=new Ox.MapPlace({alternativeNames:[],countryCode:'',editable:true,geoname:'',id:'_'+Ox.encodeBase32(Ox.uid()),map:that,name:'',type:'feature',south:southwest.lat(),west:southwest.lng(),north:northeast.lat(),east:northeast.lng()});}
Ox.forEach(self.places,function(p,i){if(place.bounds.equals(p.bounds)){place=p;exists=true;return false;}});if(!exists){self.resultPlace&&self.resultPlace.remove();self.resultPlace=place;place.add();}
selectPlace(place.id);}
function addPlaceToPlaces(data){var place=Ox.extend(getSelectedPlace()||{},data),country=Ox.getCountryByGeoname(place.geoname);place.countryCode=country?country.code:'';self.options.selected=place.id;setPlaceControls(place);place.marker.update();place.rectangle.update();self.places.push(place);self.resultPlace=null;that.triggerEvent('addplace',place)}
function boundsChanged(){setScale();self.boundsChanged=true;}
function canContain(outerBounds,innerBounds){var outerSpan=outerBounds.toSpan(),innerSpan=innerBounds.toSpan();return outerSpan.lat()>innerSpan.lat()&&outerSpan.lng()>innerSpan.lng();}
function centerChanged(){var tooltip=$('.OxMapMarkerTooltip');tooltip.length&&Ox.$elements[$(tooltip[0]).data('oxid')].hide();self.center=self.map.getCenter();self.centerChanged=true;}
function changeZoom(data){self.map.setZoom(data.value);}
function clickMap(event){var place=getSelectedPlace();if(self.options.clickable){getPlaceByLatLng(event.latLng,self.map.getBounds(),function(place){if(place){addPlaceToMap(place);}else{selectPlace(null);}});}else{pressEscape();}}
function clickPlaceButton(){var place=getSelectedPlace(),title=self.$placeButton.options('title');if(title==Ox._('New Place')){addPlaceToMap();}else if(title==Ox._('Add Place')){addPlaceToPlaces();}}
function constructZoomInput(){if(self.options.showZoombar){self.$zoomInput&&self.$zoomInput.remove();self.$zoomInput=Ox.Range({arrows:true,changeOnDrag:true,max:self.maxZoom,min:self.minZoom,size:that.width(),thumbSize:32,thumbValue:true,value:self.map.getZoom()}).bindEvent({change:changeZoom}).appendTo(self.$zoombar);}}
function crossesDateline(){var bounds=self.map.getBounds();return bounds.getSouthWest().lng()>bounds.getNorthEast().lng();}
function editing(){var place=getSelectedPlace();return place&&place.editing;}
function getElevation(point,callback){if(arguments.length==1){callback=point;point=self.map.getCenter();}
self.elevationService.getElevationForLocations({locations:[point]},function(data){callback(data.elevation);});}
function getMapBounds(callback){self.options.places({},function(result){var area=result.data.area;callback(new google.maps.LatLngBounds(new google.maps.LatLng(area.south,area.west),new google.maps.LatLng(area.north,area.east)));});}
function getMapHeight(){return self.options.height
-self.options.showStatusbar*24
-self.options.showToolbar*24
-self.options.showZoombar*16;}
function getMapType(){return self.options.showLabels?'HYBRID':'SATELLITE'}
function getMaxZoom(point,callback){if(arguments.length==1){callback=point;point=self.map.getCenter();}
self.maxZoomService.getMaxZoomAtLatLng(point,function(data){callback(data.status=='OK'?data.zoom:null);});}
function getMetersPerPixel(){var degreesPerPixel=360/(self.tileSize*Math.pow(2,self.map.getZoom()));return Ox.getMetersPerDegree(self.map.getCenter().lat())*degreesPerPixel;}
function getMinZoom(){return self.mapHeight>1024?3:self.mapHeight>512?2:self.mapHeight>256?1:0;}
function getPlaceById(id){return self.resultPlace&&self.resultPlace.id==id?self.resultPlace:Ox.getObjectById(self.places,id);}
function getPlaceByLatLng(latlng,bounds,callback){var callback=arguments.length==3?callback:bounds,bounds=arguments.length==3?bounds:null;self.$loadingIcon&&self.$loadingIcon.start();self.geocoder.geocode({latLng:latlng},function(results,status){self.$loadingIcon&&self.$loadingIcon.stop();if(status==google.maps.GeocoderStatus.OK){if(bounds){Ox.forEach(results.reverse(),function(result,i){if(i==results.length-1||canContain(bounds,result.geometry.bounds||result.geometry.viewport)){callback(new Ox.MapPlace(parseGeodata(results[i])));return false;}});}else{callback(new Ox.MapPlace(parseGeodata(results[0])));}}
if(status==google.maps.GeocoderStatus.OK||status==google.maps.GeocoderStatus.ZERO_RESULTS){triggerGeocodeEvent({latLng:latlng,results:results});}else{Ox.Log('Map','geocode failed:',status);callback(null);}});}
function getPlaceByName(name,callback){self.$loadingIcon&&self.$loadingIcon.start();self.geocoder.geocode({address:name},function(results,status){self.$loadingIcon&&self.$loadingIcon.stop();if(status==google.maps.GeocoderStatus.OK){callback(new Ox.MapPlace(parseGeodata(results[0])));}
if(status==google.maps.GeocoderStatus.OK&&status!=google.maps.GeocoderStatus.ZERO_RESULTS){triggerGeocodeEvent({address:name,results:results});}else{Ox.Log('Map','geocode failed:',status);callback(null);}});}
function getPositionByName(name){var position=-1;Ox.forEach(self.options.places,function(place,i){if(place.name==name){position=i;return false;}});return position;}
function getSelectedMarker(){var id=null;if(self.resultPlace&&self.resultPlace.selected){id=self.resultPlace.id;}else{Ox.forEach(self.places,function(place){if(place.selected){id=place.id;return false;}});}
return id;}
function getSelectedPlace(){return self.options.selected?getPlaceById(self.options.selected):null;}
function initMap(){getMapBounds(function(mapBounds){self.elevationService=new google.maps.ElevationService();self.geocoder=new google.maps.Geocoder();self.maxZoomService=new google.maps.MaxZoomService();self.center=mapBounds?mapBounds.getCenter():new google.maps.LatLng(0,0);self.zoom=self.minZoom;that.map=self.map=new google.maps.Map(self.$map[0],{center:self.center,disableDefaultUI:true,disableDoubleClickZoom:true,mapTypeId:google.maps.MapTypeId[getMapType()],noClear:true,scrollwheel:!self.options.zoomOnlyWhenFocused,zoom:self.zoom});google.maps.event.addListener(self.map,'bounds_changed',boundsChanged);google.maps.event.addListener(self.map,'center_changed',centerChanged);google.maps.event.addListener(self.map,'click',clickMap);google.maps.event.addListener(self.map,'idle',mapChanged);google.maps.event.addListener(self.map,'zoom_changed',zoomChanged);google.maps.event.trigger(self.map,'resize');that.overlayView=new google.maps.OverlayView();that.overlayView.setMap(self.map);that.overlayView.draw=function(){if(!this.ready){this.ready=true;google.maps.event.trigger(this,'ready');}}
that.overlayView.draw();Ox.forEach(self.$controls,function($control){$control.appendTo(self.$map);});Ox.forEach(self.$placeControls,function($placeControl){$placeControl.appendTo(self.$map);});if(self.options.find){self.$findInput.value(self.options.find).triggerEvent('submit',{value:self.options.find});}else{if(self.options.selected){selectPlace(self.options.selected,true);}
if(mapBounds){if(isEmpty(mapBounds)){self.map.setZoom(self.minZoom);}else{self.map.fitBounds(mapBounds);}}
if(self.map.getZoom()zoom){self.map.setZoom(zoom);}
constructZoomInput();}});self.centerChanged=false;}
if(self.zoomChanged){self.zoomChanged=false;}}
function pan(x,y){self.map.panBy(x*self.$map.width()/2,y*self.$map.height()/2);};function panToPlace(){var place;if(!self.loaded){setTimeout(function(){panToPlace();},100);}else{place=getSelectedPlace();place&&self.map.panTo(place.center);}}
function parseGeodata(data){var bounds=data.geometry.bounds||data.geometry.viewport,northEast=bounds.getNorthEast(),southWest=bounds.getSouthWest(),place={alternativeNames:[],components:data.address_components,countryCode:getCountryCode(data.address_components),east:northEast.lng(),editable:self.options.editable,fullGeoname:getFullGeoname(data.address_components),id:'_'+Ox.encodeBase32(Ox.uid()),map:that,north:northEast.lat(),south:southWest.lat(),type:getType(data.address_components[0].types),west:southWest.lng()};place.geoname=data.formatted_address||place.fullGeoname;place.name=(place.geoname||place.fullGeoname).split(', ')[0];if(Math.abs(place.west)==180&&Math.abs(place.east)==180){place.west=-179.99999999;place.east=179.99999999;}
place.south=Ox.limit(place.south,Ox.MIN_LATITUDE,Ox.MAX_LATITUDE-0.00000001);place.north=Ox.limit(place.north,Ox.MIN_LATITUDE+0.00000001,Ox.MAX_LATITUDE);function getCountryCode(components){var countryCode='';Ox.forEach(components,function(component){if(component.types.indexOf('country')>-1){countryCode=component.short_name;return false;}});return countryCode;}
function getFullGeoname(components){var country=false;return components.map(function(component,i){var name=component.long_name;if(i&&components[i-1].types.indexOf('country')>-1){country=true;}
return!country&&(i==0||name!=components[i-1].long_name)?name:null;}).join(', ');}
function getType(types){var strings={'country':['country'],'region':['administrative_area','colloquial_area'],'city':['locality'],'borough':['neighborhood','postal_code','sublocality'],'street':['intersection','route','street_address','street_number'],'building':['airport','floor','premise','room','subpremise'],'feature':['natural_feature','park']},type;function find(type){var ret;Ox.forEach(types,function(v){ret=Ox.startsWith(v,type);if(ret){return false;}});return ret;}Ox.forEach(strings,function(values,key){Ox.forEach(values,function(value){if(find(value)){type=key;return false;}});if(type){return false;}});return type||'feature';}
return place;}
function pressEnter(){var place=getSelectedPlace();if(place){if(place.editing){place.submit();}else{place.edit();}}else if(self.resultPlace){selectPlace(self.resultPlace.id)}}
function pressEscape(){var place=getSelectedPlace();if(place){if(place.editing){place.cancel();}else{selectPlace(null);}}else if(self.resultPlace){self.resultPlace.remove();self.resultPlace=null;}}
function removePlace(){var place=getSelectedPlace();place.id='_'+place.id;self.options.selected=place.id;self.places.splice(Ox.getIndexById(self.places,place.id),1);self.resultPlace&&self.resultPlace.remove();self.resultPlace=place;place.marker.update();place.rectangle.update();}
function reset(){self.map.getZoom()==self.zoom?self.map.panTo(self.center):self.map.fitBounds(self.bounds);}
function selectPlace(id,zoom){var place,selected;if(!self.loaded){setTimeout(function(){selectPlace(id,zoom);},100);}else{selected=getSelectedMarker();Ox.Log('Map','Ox.Map selectPlace()',id,selected);if(id!=selected){place=getPlaceById(selected);place&&place.deselect();if(id!==null){place=getPlaceById(id);if(place){select();}else{self.options.places({keys:self.placeKeys,query:{conditions:[{key:'id',value:id,operator:'=='}],operator:'&'}},function(result){if(result.data.items.length){place=new Ox.MapPlace(Ox.extend({map:that},result.data.items[0])).add();self.places.push(place);select();if(zoom){zoomToPlace();}else{panToPlace();}}});}}else{place=null;select();}}}
function select(){place&&place.select();self.options.selected=id;setPlaceControls(place);setStatus();that.triggerEvent('selectplace',place);that.triggerEvent('select',place);}};function setPlaceControls(place){var $placeControls=that.find('.OxPlaceControl'),country,isVisible=self.$placeControls.name.is(':visible');if(place){country=place.geoname.indexOf(', ')>-1?place.geoname.split(', ').pop():'';self.$placeControls.flag.options({tooltip:country?'Zoom to '+country:''}).data({country:country}).empty().append(Ox.$(' ').attr({src:Ox.getFlagByGeoname(place.geoname,16)})).show();self.$placeControls.name.options({title:place.name||'Unnamed '});!isVisible&&$placeControls.show().animate({opacity:1},250);}else{isVisible&&$placeControls.animate({opacity:0},250,function(){$placeControls.hide();});}}
function setScale(){var metersPerPixel=getMetersPerPixel();Ox.forEach(self.scaleMeters,function(meters){var mapWidth=self.options.width||that.width(),scaleWidth=Math.round(meters/metersPerPixel);if(scaleWidth<=mapWidth/2-4){self.$controls.scale.options({title:'\u2190 '+(meters>1000?Ox.formatNumber(meters/1000)+' k':meters+' ')+'m \u2192'}).css({width:(scaleWidth-16)+'px'});return false;}});}
function setStatus(){var code,country,disabled,place,title;if(self.options.showStatusbar){place=getSelectedPlace();country=place?Ox.getCountryByGeoname(place.geoname):'';code=country?country.code:'NTHH';disabled=place&&!place.editable;if(place){title=place.id[0]=='_'?Ox._('Add Place'):Ox._('Remove Place');}else{title=Ox._('New Place');}
self.$placeFlag.attr({src:Ox.PATH+'Ox.Geo/png/icons/16/'+code+'.png'});self.$placeNameInput.options({disabled:disabled,value:place?place.name:''});self.$placeGeonameInput.options({disabled:disabled,value:place?place.geoname:''});self.$placeButton.options({disabled:disabled,title:title});}}
function spansGlobe(){return self.$map.width()>self.tileSize*Math.pow(2,self.map.getZoom());};function submitFind(data){self.options.find=data.value;if(data.value===''){if(self.options.selected&&self.options.selected[0]=='_'){selectPlace(null);}}else{that.findPlace(data.value,function(place){setStatus(place);});}
that.triggerEvent('find',{value:data.value});}
function toggleControls(){var $controls=that.find('.OxMapControl');self.options.showControls=!self.options.showControls;if(self.options.showControls){$controls.show().animate({opacity:1},250);}else{$controls.animate({opacity:0},250,function(){$controls.hide();});}
that.triggerEvent('togglecontrols',{visible:self.options.showControls});}
function toggleLabels(){self.options.showLabels=!self.options.showLabels;self.map.setMapTypeId(google.maps.MapTypeId[getMapType()]);that.triggerEvent('togglelabels',{visible:self.options.showLabels});}
function triggerGeocodeEvent(data){if(data.latLng){data.latLng={lat:data.latLng.lat(),lng:data.latLng.lng()}}
data.results.forEach(function(result){['bounds','viewport'].forEach(function(key){if(result.geometry[key]){result.geometry[key]={northEast:{lat:result.geometry[key].getNorthEast().lat(),lng:result.geometry[key].getNorthEast().lng()},southWest:{lat:result.geometry[key].getSouthWest().lat(),lng:result.geometry[key].getSouthWest().lng()}}}});if(result.geometry.location){result.geometry.location={lat:result.geometry.location.lat(),lng:result.geometry.location.lng()}}});that.triggerEvent('geocode',data);}
function undo(){Ox.Log('Map','Map undo')
var place=getSelectedPlace();place.editing&&place.undo();}
function updateFormElements(){var width=that.width();if(self.options.showZoombar){getMaxZoom(function(zoom){self.maxZoom=zoom;constructZoomInput();});}
if(self.options.showStatusbar){self.$placeNameInput.options({width:Math.floor((width-132)/2)});self.$placeGeonameInput.options({width:Math.ceil((width-132)/2)});}}
function zoom(z){if(!self.loaded){setTimeout(function(){zoom(z);},100);}else{self.map.setZoom(self.map.getZoom()+z);}}
function zoomChanged(){var zoom=self.map.getZoom();if(zoomself.maxZoom){self.map.setZoom(self.maxZoom);}else{self.zoomChanged=true;self.$zoomInput&&self.$zoomInput.value(zoom);that.triggerEvent('zoom',{value:zoom});}}
function zoomToPlace(){var place;if(!self.loaded){setTimeout(function(){zoomToPlace();},100);}else{place=getSelectedPlace();place&&self.map.fitBounds(place.bounds);}}
that.addPlace=function(data){addPlaceToPlaces(data);};that.getCenter=function(){var center=self.map.getCenter();return{lat:center.lat(),lng:center.lng()};};that.getKey=function(){return self.shiftKey?'shift':self.metaKey?'meta':null;};that.getSelectedPlace=function(){return getSelectedPlace();}
that.editPlace=function(){getSelectedPlace().edit();return that;};that.findPlace=function(name,callback){getPlaceByName(name,function(place){if(place){addPlaceToMap(place);self.map.fitBounds(place.bounds);}else{name&&self.$findInput.addClass('OxError');}
callback(place);});return that;};that.newPlace=function(place){addPlaceToMap(place);return that;};that.panToPlace=function(){panToPlace();return that;};that.removePlace=function(){removePlace();return that;};that.resizeMap=function(){self.options.height=that.height();self.options.width=that.width();if(self.map){self.mapHeight=getMapHeight();self.minZoom=getMinZoom();if(self.minZoom>self.map.getZoom()){self.map.setZoom(self.minZoom);}
self.$map.css({height:self.mapHeight+'px',width:self.options.width+'px'});self.options.$zoomInput&&self.$zoomInput.options({size:self.options.width});updateFormElements();Ox.Log('Map','triggering google maps resize event, height',self.options.height)
google.maps.event.trigger(self.map,'resize');}
return that;}
that.setCenter=function(center){self.map.setCenter(new google.maps.LatLng(center.lat,center.lng));return that;};that.value=function(id,key,value){Ox.Log('Map','Map.value',id,key,value);getPlaceById(id).options(key,value);if(id==self.options.selected){if(key=='name'){self.$placeControls.name.options({title:value});}else if(key=='geoname'){self.$placeControls.flag.empty().append(Ox.$(' ').attr({src:Ox.getFlagByGeoname(value,16)}));}}
return that;}
that.zoomToPlace=function(){zoomToPlace();return that;};that.zoom=function(value){zoom(value);return that;};return that;};'use strict';Ox.MapEditor=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({addPlace:null,collapsible:false,editPlace:null,getMatches:null,hasMatches:false,height:256,labels:false,mode:'add',pageLength:100,places:null,removePlace:null,selected:'',showControls:false,showLabels:false,showTypes:false,sort:[{key:'geoname',operator:'+'}],width:256}).options(options||{}).update({height:function(){self.$list.size();self.$map.resizeMap();},selected:function(){self.$list.options({selected:self.options.selected});},width:function(){self.$map.resizeMap();}}).css({width:self.options.width+'px',height:self.options.height+'px'});self.isAsync=Ox.isFunction(self.options.places);self.typeColor={country:[64,64,255],region:[0,192,192],city:[255,0,0],borough:[255,128,0],street:[255,255,0],building:[255,64,128],feature:[0,192,0]};self.areaSize={1000000:8,10000000000:10};self.columns=[{format:function(value,data){return data.type?Ox.$(' ').attr({src:Ox.getFlagByGeoname(data.geoname,16)}).css({width:'14px',height:'14px',borderRadius:'4px',marginLeft:'-3px',marginTop:0}):'';},id:'countryCode',operator:'+',resizable:false,sort:function(value){var names=value.split(', ');if(!Ox.getCountryByGeoname(names[names.length-1])){names.push('~');}
return names.reverse().join(', ');},title:Ox._('Flag'),titleImage:'flag',tooltip:function(data){return Ox.toTitleCase(data.geoname||'')},visible:true,width:16},{format:function(value,data){var iconSize=6;Ox.forEach(self.areaSize,function(size,area){if(data.area>=area){iconSize=size;}else{return false;}});return data.type?Ox.$('').addClass('OxTypeIcon').css({width:iconSize+'px',height:iconSize+'px',borderRadius:(iconSize+4)/2+'px',margin:[0,0,0,-3].map(function(v){return v+(10-iconSize)/2+'px';}).join(' '),background:'rgb('+self.typeColor[data.type].join(', ')+')'}):'';},id:'type',operator:'+',title:Ox._('Type'),titleImage:'icon',tooltip:function(data){return Ox.toTitleCase(data.type||'');},visible:true,width:16},{format:function(value,data){return data.type?value:Ox.$('
').addClass('OxWarning').html(value);},id:'name',operator:'+',removable:false,title:Ox._('Name'),visible:true,width:144},{format:function(value){return value.join('; ');},id:'alternativeNames',operator:'+',title:Ox._('Alternative Names'),visible:true,width:144},{id:'geoname',operator:'+',sort:function(value){var names=value.split(', ');if(!Ox.getCountryByGeoname(names[names.length-1])){names.push('~');}
return names.reverse().join(', ');},title:Ox._('Geoname'),visible:false,width:192},{align:'right',format:toFixed,id:'lat',operator:'+',title:Ox._('Latitude'),visible:true,width:64},{align:'right',format:toFixed,id:'lng',operator:'+',title:Ox._('Longitude'),visible:true,width:64},{align:'right',format:toFixed,id:'south',operator:'+',title:Ox._('South'),visible:false,width:64},{align:'right',id:'west',operator:'+',title:Ox._('West'),visible:false,width:64},{align:'right',format:toFixed,id:'north',operator:'+',title:Ox._('North'),visible:false,width:64},{align:'right',format:toFixed,id:'east',operator:'+',title:Ox._('East'),visible:false,width:64},{align:'right',format:{type:'area',args:[]},id:'area',operator:'-',title:Ox._('Area'),visible:true,width:128},{format:function(value){return Ox.encodeHTMLEntities(value);},id:'user',operator:'+',title:Ox._('User'),visible:false,width:96},{format:function(value){return value.replace('T',' ').replace('Z','');},id:'created',operator:'-',title:Ox._('Date Created'),visible:false,width:128},{format:function(value){return value.replace('T',' ').replace('Z','');},id:'modified',operator:'-',title:Ox._('Date Modified'),visible:false,width:128}];self.options.hasMatches&&self.columns.push({align:'right',id:'matches',operator:'-',title:Ox._('Matches'),visible:true,width:64});self.$listToolbar=Ox.Bar({size:24});self.$findElement=Ox.FormElementGroup({elements:[self.$findSelect=Ox.Select({items:[{id:'all',title:Ox._('Find: All')},{id:'name',title:Ox._('Find: Name')},{id:'alternativeNames',title:Ox._('Find: Alternative Names')},{id:'geoname',title:Ox._('Find: Geoname')}],overlap:'right',type:'image'}).bindEvent({change:function(data){var key=data.value,value=self.$findInput.value();value&&updateList(key,value);}}),self.$findInput=Ox.Input({clear:true,placeholder:Ox._('Find in List'),width:234}).bindEvent({submit:function(data){var key=self.$findSelect.value(),value=data.value;updateList(key,value);}})]}).css({float:'right',margin:'4px'}).appendTo(self.$listToolbar);self.$list=Ox.TableList({columns:self.columns,columnsRemovable:true,columnsVisible:true,items:Ox.clone(self.options.places),keys:['area','geoname','matches'],max:1,min:0,pageLength:self.options.pageLength,scrollbarVisible:true,selected:self.options.selected?[self.options.selected]:[],sort:self.options.sort,unique:'id'}).bindEvent({'delete':removeItem,init:initList,key_0:function(){self.$map.panToPlace();},key_equal:function(){self.$map.zoom(1);},key_minus:function(){self.$map.zoom(-1);},key_shift_0:function(){self.$map.zoomToPlace();},load:function(){that.triggerEvent('loadlist');},open:openItem,select:function(data){selectItem(data);}});self.options.selected&&self.$list.bindEventOnce({load:function(){self.$list.triggerEvent({select:{ids:[self.options.selected]}});}});self.$listStatusbar=Ox.Bar({size:16});self.$status=Ox.Element().css({paddingTop:'2px',margin:'auto',fontSize:'9px',textAlign:'center'}).appendTo(self.$listStatusbar);self.$map=Ox.Map({clickable:true,editable:true,findPlaceholder:Ox._('Find on Map'),height:self.options.height,places:self.options.places,showControls:self.options.showControls,showLabels:self.options.showLabels,showTypes:self.options.showTypes,toolbar:true,width:self.options.width-514,zoombar:true}).bindEvent({changeplace:function(data){self.$placeForm.values(data).show();self.$areaKmInput.value(Ox.formatArea(data.area));},changeplaceend:function(data){var isResult=self.selectedPlace[0]=='_';!isResult&&editPlace(['lat','lng','south','west','north','east','area']);},geocode:function(data){that.triggerEvent('geocode',data);},select:selectPlace});self.$placeTitlebar=Ox.Bar({size:24});self.$placeTitle=Ox.$('').hide().appendTo(self.$placeTitlebar);if(self.options.mode=='define'){self.$findPlaceButton=Ox.Button({title:'find',tooltip:Ox._('Find'),type:'image'}).css({float:'left',margin:'4px'}).bindEvent({click:findPlace}).hide().appendTo(self.$placeTitle);}
self.$placeFlag=Ox.$('
').addClass('OxFlag').attr({src:Ox.getFlagByGeoname('',16)}).css({float:'left',margin:'4px'}).appendTo(self.$placeTitle);self.$placeName=Ox.Label({title:'',width:208}).css({float:'left',margin:'4px 0 4px 0'}).bindEvent({singleclick:function(){self.$map.panToPlace();},doubleclick:function(){self.$map.zoomToPlace();}}).appendTo(self.$placeTitle);self.$deselectPlaceButton=Ox.Button({title:'close',tooltip:Ox._('Done'),type:'image'}).css({float:'left',margin:'4px'}).bindEvent({click:function(){self.$list.options({selected:[]});selectItem({ids:[]});}}).appendTo(self.$placeTitle);self.$placeData=Ox.Element();self.$placeForm=Ox.Form({items:[].concat([self.$nameInput=Ox.Input({id:'name',label:Ox._('Name'),labelWidth:80,width:240}),self.$alternativeNamesInput=Ox.ArrayInput({id:'alternativeNames',label:Ox._('Alternative Names'),max:10,values:[],width:240}),self.$geonameInput=Ox.Input({id:'geoname',label:Ox._('Geoname'),labelWidth:80,width:240}),Ox.Input({id:'countryCode'}).hide(),Ox.Select({id:'type',items:[{id:'country',title:Ox._('Country')},{id:'region',title:Ox._('Region')},{id:'city',title:Ox._('City')},{id:'borough',title:Ox._('Borough')},{id:'street',title:Ox._('Street')},{id:'building',title:Ox._('Building')},{id:'feature',title:Ox._('Feature')}],label:Ox._('Type'),labelWidth:80,width:240})],['Latitude','Longitude','South','West','North','East'].map(function(v){var id=(v=='Latitude'?'lat':v=='Longitude'?'lng':v).toLowerCase(),max=['Latitude','South','North'].indexOf(v)>-1?Ox.MAX_LATITUDE:180;return Ox.Input({changeOnKeypress:true,decimals:8,disabled:['lat','lng'].indexOf(id)>-1,id:id,label:Ox._(v),labelWidth:80,min:-max,max:max,type:'float',width:240});}),[self.$areaInput=Ox.Input({id:'area',type:'float'}).hide()]),width:240}).css({margin:'8px'}).hide().bindEvent({change:function(data){var isResult=self.selectedPlace[0]=='_';if(data.id=='name'){var name=data.data.value;!isResult&&self.$list.value(self.selectedPlace,'name',name);self.$placeName.options({title:name});if(!self.isAsync){Ox.getObjectById(self.options.places,self.selectedPlace).name=name;}else if(isResult){getMatches(this.values());}else{editPlace(['name']);}
self.$map.value(self.selectedPlace,'name',name);}else if(data.id=='alternativeNames'){if(!self.isAsync){}else if(isResult){getMatches(this.values());}else{editPlace(['alternativeNames']);}
self.$map.value(self.selectedPlace,'alternativeNames',data.data.value);}else if(data.id=='geoname'){var geoname=data.data.value,country=Ox.getCountryByGeoname(geoname),countryCode=country?country.code:'';self.$placeFlag.attr({src:Ox.getFlagByGeoname(geoname,16)});self.$placeForm.values({countryCode:countryCode});if(!self.isAsync){if(!isResult){self.$list.value(self.selectedPlace,'geoname',geoname);self.$list.value(self.selectedPlace,'countryCode',countryCode);}}else{!isResult&&editPlace(['countryCode','geoname']);}
self.$map.value(self.selectedPlace,'countryCode',countryCode);self.$map.value(self.selectedPlace,'geoname',geoname);}else if(data.id=='type'){if(!self.isAsync){}else{!isResult&&editPlace(['type']);}
self.$map.value(self.selectedPlace,'type',data.data.value);}else{if(!self.isAsync){}else{!isResult&&editPlace([data.id]);}
self.$map.value(self.selectedPlace,data.id,parseFloat(data.data.value));}}}).appendTo(self.$placeData);self.$areaKmInput=Ox.Input({disabled:true,id:'areaKm',label:Ox._('Area'),labelWidth:80,textAlign:'right',width:240}).css({margin:'8px 8px 0 8px'}).hide().appendTo(self.$placeData);if(self.options.hasMatches){self.$matchesInput=Ox.Input({disabled:true,id:'matches',label:Ox._('Matches'),labelWidth:80,type:'int',width:240}).css({margin:'8px'}).hide().appendTo(self.$placeData);}
self.$placeStatusbar=Ox.Bar({size:24});self.$addPlaceButton=Ox.Button({title:Ox._('Add Place'),width:90}).css({float:'left',margin:'4px'}).bindEvent({click:function(){if(this.options('title')==Ox._('Add Place')){addPlace();}else{removePlace();}}}).hide().appendTo(self.$placeStatusbar);self.$newPlaceButton=Ox.Button({title:Ox._('New Place'),width:70}).css({float:'right',margin:'4px'}).bindEvent({click:function(){self.$map.newPlace();}}).appendTo(self.$placeStatusbar);if(self.options.mode=='define'){self.$definePlaceButton=Ox.Button({title:Ox._('Define Place'),width:80}).css({float:'right',margin:'4px 0 4px 0'}).bindEvent({click:function(){if(this.options('title')==Ox._('Define Place')){definePlace();}else{clearPlace();}}}).hide().appendTo(self.$placeStatusbar);}
that.setElement(Ox.SplitPanel({elements:[{collapsible:self.options.collapsible,element:self.$listPanel=Ox.SplitPanel({elements:[{element:self.$listToolbar,size:24},{element:self.$list},{element:self.$listStatusbar,size:16}],orientation:'vertical'}),resizable:true,resize:[256,384,512],size:256},{element:self.$map.bindEvent({resize:function(){self.$map.resizeMap();}})},{collapsible:self.options.collapsible,element:Ox.SplitPanel({elements:[{element:self.$placeTitlebar,size:24},{element:self.$placeData},{element:self.$placeStatusbar,size:24}],orientation:'vertical'}).bindEvent({resize:function(data){self.$placeName.options({width:data.size-48});self.$placeForm.options('items').forEach(function($item){$item.options({width:data.size-16});});self.$areaKmInput.options({width:data.size-16});self.$matchesInput&&self.$matchesInput.options({width:data.size-16});}}),resizable:true,resize:[256,384],size:256}],orientation:'horizontal'}).addClass('OxMapEditor'));function addPlace(){var place=self.$placeForm.values(),country=Ox.getCountryByGeoname(place.geoname);place.countryCode=country?country.code:'';if(!self.isAsync){place.id=self.selectedPlace.slice(1);self.selectedPlace=place.id;self.options.selected=place.id;self.options.places.push(place);self.$list.options({items:Ox.clone(self.options.places)}).options({selected:[place.id]});self.$map.addPlace(place);self.$addPlaceButton.options({title:Ox._('Remove Place')});}else{self.$addPlaceButton.options({disabled:true,title:Ox._('Adding...')});self.options.addPlace(encodeValues(place),function(result){if(result.status.code==200){place.id=result.data.id;self.options.selected=place.id;self.selectedPlace=place.id;self.$list.reloadList().options({selected:[place.id]});self.$map.addPlace(place);self.options.hasMatches&&self.$matchesInput.value(result.data.matches).show();self.options.mode=='define'&&self.$definePlaceButton.options({disabled:!result.data.matches,title:Ox._('Clear Place')}).show();self.$addPlaceButton.options({disabled:false,title:Ox._('Remove Place')}).show();}else if(result.status.code==409){if(result.data.names.indexOf(self.$nameInput.value())>-1){self.$nameInput.addClass('OxError');}
self.$alternativeNamesInput.setErrors(result.data.names);self.$addPlaceButton.options({disabled:false,title:Ox._('Add Place')});}});}}
function clearPlace(){var values={id:self.selectedPlace,alternativeNames:[],geoname:'',type:'',lat:null,lng:null,south:null,west:null,north:null,east:null,area:null};self.$definePlaceButton.options({disabled:true,title:Ox._('Clearing...')});self.options.editPlace(values,function(){self.$map.removePlace();self.$list.reloadList();self.$findPlaceButton.show();self.$placeFlag.hide();hideForm();self.$definePlaceButton.options({disabled:false,title:Ox._('Define Place')})});}
function decodeValues(place){return Ox.map(place,function(value){var type=Ox.typeOf(value);return type=='string'?Ox.decodeHTMLEntities(value):type=='array'?Ox.map(value,function(value){return decodeValues(value);}):value;});}
function definePlace(){self.$map.newPlace();self.$definePlaceButton.options({title:Ox._('Clear Place')});}
function encodeValues(place){return Ox.map(place,function(value){var type=Ox.typeOf(value);return type=='string'?Ox.encodeHTMLEntities(value):type=='array'?Ox.map(value,function(value){return encodeValues(value);}):value;});}
function editPlace(keys){Ox.Log('Map','EDIT PLACE',keys,self.$placeForm.values())
var values=Ox.filter(self.$placeForm.values(),function(values,key){return keys.indexOf(key)>-1;});values.id=self.selectedPlace;self.options.editPlace(encodeValues(values),function(result){Ox.Log('Map','EDIT PLACE::',result)
if(result.status.code==200){if(keys.indexOf(self.$list.options('sort')[0].key)>-1||(self.options.mode=='define'&&(keys.indexOf('name')>-1||keys.indexOf('alternativeNames')>-1))){self.$list.reloadList();}else{Ox.forEach(values,function(value,key){if(key!='id'){self.$list.value(values.id,key,value);self.$map.value(values.id,key,value);}});self.$list.value(values.id,'matches',result.data.matches);}
if(self.options.mode=='define'){self.$findPlaceButton.hide();self.$placeFlag.show();}
self.options.hasMatches&&self.$matchesInput.value(result.data.matches);if(self.options.mode=='define'){self.$definePlaceButton.options({disabled:!result.data.matches,title:Ox._('Clear Place')});self.$addPlaceButton.options({disabled:!!result.data.matches});}}else{if(result.data.names.indexOf(self.$nameInput.value())>-1){self.$nameInput.addClass('OxError');}
self.$alternativeNamesInput.setErrors(result.data.names);}});}
function findPlace(){self.$map.options({find:self.$list.value(self.options.selected,'name')});}
function hideForm(){self.$placeForm.hide();self.$areaKmInput.hide();}
function getMatches(place){var names;if(self.options.hasMatches){names=Ox.filter([place.name].concat(place.alternativeNames),function(name){return name!=='';});self.options.getMatches(names,function(matches){self.$matchesInput.value(matches);});}}
function initList(data){self.$status.html(Ox.formatCount(data.items,'Place'));}
function openItem(data){selectItem(data);self.$map.zoomToPlace(data.ids[0]);}
function removeItem(data){var id=data.ids[0];self.$list.value(id,'type')&&self.$map.removePlace(id);that.triggerEvent('removeplace',{id:id});}
function removePlace(){var index;Ox.Log('Map','REMOVE PLACE',self.selectedPlace,index)
if(!self.isAsync){index=Ox.getIndexById(self.options.places,self.selectedPlace);self.options.selected='';self.options.places.splice(index,1);self.$list.options({items:Ox.clone(self.options.places)});self.$addPlaceButton.options({title:Ox._('Add Place')});}
if(self.isAsync){self.$addPlaceButton.options({disabled:true,title:Ox._('Removing...')})
self.options.removePlace({id:self.selectedPlace},function(){self.options.selected='';self.$list.options({selected:[]}).reloadList(true);self.options.hasMatches&&self.$matchesInput.hide();self.options.mode=='define'&&self.$definePlaceButton.options({disabled:true});self.$addPlaceButton.options({disabled:false,title:Ox._('Add Place')});});}
self.$map.removePlace();that.triggerEvent('removeplace',{id:self.selectedPlace});}
function selectItem(data,place){var isUndefined,selectedPlace;self.options.selected=data.ids.length?data.ids[0]:'';place=place||(self.options.selected?self.$list.value(self.options.selected):{});isUndefined=!!self.options.selected&&!place.type;selectedPlace=self.options.selected&&!isUndefined?self.options.selected:'';self.$map.options({selected:selectedPlace});selectedPlace&&self.$map.panToPlace();if(self.options.selected){self.options.mode=='define'&&self.$findPlaceButton[isUndefined?'show':'hide']();self.$placeFlag.attr({src:Ox.getFlagByGeoname(place.geoname||'',16)})[isUndefined?'hide':'show']();self.$placeName.options({title:place.name||''});self.$placeTitle.show();!isUndefined?showForm(place):hideForm();self.options.hasMatches&&self.$matchesInput.value(place.matches||0).show();self.options.mode=='define'&&self.$definePlaceButton.options({disabled:!isUndefined&&!place.matches,title:isUndefined?'Define Place':'Clear Place'}).show();self.$addPlaceButton.options({disabled:self.options.mode=='define'&&!!place.matches,title:Ox._('Remove Place')}).show();}else{self.$placeTitle.hide();hideForm();self.options.hasMatches&&self.$matchesInput.hide();self.options.mode=='define'&&self.$definePlaceButton.hide();self.$addPlaceButton.hide();}}
function selectPlace(place){var isResult=place&&place.id[0]=='_',isUndefined=!!self.options.selected&&!self.$list.value(self.options.selected,'type');self.selectedPlace=place&&place.id?place.id:'';if(isResult&&isUndefined){Ox.print('place.id',place.id,'self.options.selected',self.options.selected,'type',self.$list.value(self.options.selected));self.selectedPlace=self.options.selected;place.name=self.$list.value(self.options.selected,'name');place.id=self.options.selected;self.$map.addPlace(place);self.$findPlaceButton.hide();self.$placeFlag.attr({src:Ox.getFlagByGeoname(place.geoname||'',16)}).show();showForm(place);editPlace(['geoname','type','lat','lng','south','west','north','east','area']);}else if(self.selectedPlace&&isResult){self.$list.options({selected:[]});self.$placeFlag.attr({src:Ox.getFlagByGeoname(place.geoname||'',16)}).show();self.$placeName.options({title:place.name||''});self.$placeTitle.show();showForm(place);if(self.options.hasMatches){self.$matchesInput.value('').show();getMatches(place);}
self.options.mode=='define'&&self.$definePlaceButton.hide();self.$addPlaceButton.options({disabled:false,title:Ox._('Add Place')}).show();}else if(!self.selectedPlace&&!self.options.selected){self.$placeFlag.hide();self.$placeTitle.hide();hideForm();self.options.hasMatches&&self.$matchesInput.hide();}else if(!self.selectedPlace&&isUndefined){}else{self.options.selected=self.selectedPlace;self.$list.options({selected:self.options.selected?[self.options.selected]:[]});selectItem({ids:self.$list.options('selected')},place);}}
function showForm(place){self.$nameInput.removeClass('OxError');self.$alternativeNamesInput.setErrors([]);self.$placeForm.values(decodeValues(place)).show();self.$areaKmInput.value(Ox.formatArea(place.area)).show();}
function toFixed(val){return Ox.isNumber(val)?val.toFixed(3):'';}
function toggleList(){var list=self.$listSelect.options('value');list=='names'&&!self.namesLoaded?load():toggle();function load(){self.options.names(function(data){self.$namesList.options({items:data});self.namesLoaded=true;toggle();});}
function toggle(){self.$listPanel.replaceElement(1,self[list=='places'?'$list':'$namesList']);}}
function updateList(key,value){var query={conditions:[].concat(['all','name'].indexOf(key)>-1?[{key:'name',value:value,operator:'='}]:[],['all','alternativeNames'].indexOf(key)>-1?[{key:'alternativeNames',value:value,operator:'='}]:[],['all','geoname'].indexOf(key)>-1?[{key:'geoname',value:value,operator:'='}]:[]),operator:key=='all'?'|':'&'};self.$list.options({items:function(data,callback){return pandora.api.findPlaces(Ox.extend(data,{query:query}),callback);}});}
that.focusList=function(){self.$list.gainFocus();return that;};that.reloadList=function(){self.$list.reloadList();return that;};that.resizeMap=function(){self.$map.resizeMap();return that;};return that;};'use strict';Ox.MapImage=function(options,self){var self=self||{},that=Ox.Element('
',self).defaults({backgroundColor:[0,0,0,0],borderColor:[0,0,0,0],borderWidth:0,height:640,markers:[],place:null,type:'satellite',width:640}).options(options||{});self.src=document.location.protocol
+'//maps.google.com/maps/api/staticmap?sensor=false'+'&size='+self.options.width+'x'+self.options.height+'&maptype='+self.options.type;if(self.options.place){self.src+='&path=fillcolor:'+formatColor(self.options.backgroundColor)
+'|color:0x'+formatColor(self.options.borderColor)
+'|weight:'+self.options.borderWidth+'|'
+[['south','west'],['north','west'],['north','east'],['south','east'],['south','west']].map(function(keys){return[self.options.place[keys[0]],self.options.place[keys[1]]].join(',');}).join('|');}else{self.src+='¢er=0,0&zoom=2'}
if(self.options.markers.length){self.src+='&markers='
+self.options.markers.map(function(marker){return[marker.lat,marker.lng].join(',')}).join('|');}
that.attr({src:self.src});function formatColor(color){return color.map(function(c){return Ox.pad(c.toString(16),'left',2,'0');}).join('')}
return that;};'use strict';Ox.MapMarker=function(options){options=Ox.extend({map:null,place:null},options);var that=this,areaSize={100:10,10000:12,1000000:14,100000000:16,10000000000:18,1000000000000:20,100000000000000:22},themeData=Ox.Theme.getThemeData(),typeColor={};['country','region','city','borough','street','building','feature'].forEach(function(type){typeColor[type]=themeData['mapPlace'+Ox.toTitleCase(type)+'Color'];});Ox.forEach(options,function(val,key){that[key]=val;});that.marker=new google.maps.Marker({raiseOnDrag:false,shape:{coords:[8,8,8],type:'circle'}});setOptions();function click(){var key=that.map.getKey(),place,bounds,southWest,northEast;if(!that.place.selected){if(that.map.options('editable')&&(key=='meta'||key=='shift')){place=that.map.getSelectedPlace();}
if(place){bounds=new google.maps.LatLngBounds(new google.maps.LatLng(place.south,place.west),new google.maps.LatLng(place.north,place.east));bounds=bounds.union(that.place.bounds);southWest=bounds.getSouthWest();northEast=bounds.getNorthEast();that.map.newPlace(new Ox.MapPlace({alternativeNames:[],countryCode:'',editable:true,geoname:'',id:'_'+Ox.encodeBase32(Ox.uid()),map:that.map,name:'',type:'feature',south:southWest.lat(),west:southWest.lng(),north:northEast.lat(),east:northEast.lng()}));}else{that.map.options({selected:that.place.id});}}else{if(key=='meta'){that.map.options({selected:null});}else{that.map.panToPlace();}}}
function dblclick(){that.place.selected&&that.map.zoomToPlace();}
function dragstart(e){Ox.$body.addClass('OxDragging');}
function drag(e){var northSouth=(that.place.north-that.place.south)/2,lat=Ox.limit(e.latLng.lat(),Ox.MIN_LATITUDE+northSouth,Ox.MAX_LATITUDE-northSouth),lng=e.latLng.lng(),span=Math.min(that.place.sizeEastWest*Ox.getDegreesPerMeter(lat)/2,179.99999999),degreesPerMeter=Ox.getDegreesPerMeter(lat);that.place.south+=lat-that.place.lat;that.place.north+=lat-that.place.lat;that.place.west=lng-span;that.place.east=lng+span;if(that.place.west<-180){that.place.west+=360;}else if(that.place.east>180){that.place.east-=360;}
Ox.Log('Map','west',that.place.west,'east',that.place.east,'span',span);that.place.update();that.marker.setOptions({position:that.place.center});that.place.rectangle.update();}
function dragend(e){Ox.$body.removeClass('OxDragging');that.map.triggerEvent('changeplaceend',that.place);}
function getMarkerImage(options,callback){options=Ox.extend({background:[255,0,0],editing:false,result:false,selected:false,size:16},options);var background=options.result?[255,255,0]:[255,0,0],border=options.editing?[128,128,255]:options.selected?[255,255,255]:[0,0,0],c=Ox.canvas(options.size,options.size),image,r=options.size/2;if(Ox.isArray(background)){c.context.fillStyle='rgba('+background.join(', ')+', 0.5)';c.context.arc(r,r,r-2,0,360);c.context.fill();renderImage();}else{image=new Image();image.onload=renderImage;image.src=background;}
function renderImage(){if(Ox.isString(background)){c.context.drawImage(image,1,1,options.size-2,options.size-2);}
c.context.beginPath();c.context.lineWidth=2;c.context.strokeStyle='rgb('+border.join(', ')+')';c.context.arc(r,r,r-1,0,360);c.context.stroke();callback(new google.maps.MarkerImage(c.canvas.toDataURL(),new google.maps.Size(options.size,options.size),new google.maps.Point(0,0),new google.maps.Point(r,r)));}}
function mouseover(e){var offset=that.map.offset(),xy=that.map.overlayView.getProjection().fromLatLngToContainerPixel(e.latLng);that.tooltip.show(offset.left+Math.round(xy.x)-4,offset.top+Math.round(xy.y)+20);}
function mouseout(){that.tooltip.hide();}
function setOptions(){var fix=that.marker.getDraggable()&&!that.place.editing,color=that.map.options('markerColor'),size=that.map.options('markerSize');if(color=='auto'){that.color=typeColor[that.place.type]||typeColor['mapPlaceFeatureColor'];}else if(Ox.isArray(color)){that.color=color;}else{that.color=color(that.place);}
if(size=='auto'){that.size=8;Ox.forEach(areaSize,function(size,area){if(that.place.area>=area){that.size=size;}else{return false;}});}else if(Ox.isNumber(size)){that.size=size;}else{that.size=size(that.place);}
that.marker.setOptions({cursor:that.place.editing?'move':'pointer',draggable:that.place.editing,icon:Ox.MapMarkerImage({color:that.color,mode:that.place.editing?'editing':that.place.selected?'selected':'normal',size:that.size,type:that.place.id[0]=='_'?'result':'place'}),position:that.place.center});if(fix){that.marker.setVisible(false);setTimeout(function(){that.marker.setVisible(true);},0);}
setTooltip();}
function setTooltip(){that.tooltip&&that.tooltip.remove();that.tooltip=Ox.Tooltip({title:'
'
+'
'
+that.map.options('markerTooltip')(that.place)+'
'}).addClass('OxMapMarkerTooltip');}
that.add=function(){that.marker.setMap(that.map.map);google.maps.event.addListener(that.marker,'click',click);google.maps.event.addListener(that.marker,'dblclick',dblclick);google.maps.event.addListener(that.marker,'mouseover',mouseover);google.maps.event.addListener(that.marker,'mouseout',mouseout);return that;};that.edit=function(){setOptions();google.maps.event.addListener(that.marker,'dragstart',dragstart);google.maps.event.addListener(that.marker,'drag',drag);google.maps.event.addListener(that.marker,'dragend',dragend);return that;};that.remove=function(){that.marker.setMap(null);google.maps.event.clearListeners(that.marker);return that;};that.submit=function(){google.maps.event.clearListeners(that.marker,'dragstart');google.maps.event.clearListeners(that.marker,'drag');google.maps.event.clearListeners(that.marker,'dragend');return that;}
that.update=function(){setOptions();return that;}
return that;};'use strict';Ox.MapMarkerImage=(function(){var cache={};return function(options){options=Ox.extend({color:[255,0,0],mode:'normal',rectangle:false,size:16,type:'place'},options);var index=[options.type,options.mode,options.size,options.color.join(',')].join(';'),themeData=Ox.Theme.getThemeData();if(!cache[index]){var color=options.rectangle?[0,0,0,0]:options.color.concat([options.type=='place'?0.75:0.25]),border=(options.mode=='normal'?themeData.mapPlaceBorder:options.mode=='selected'?themeData.mapPlaceSelectedBorder:themeData.mapPlaceEditingBorder).concat([options.type=='result'?0.5:1]),c=Ox.canvas(options.size,options.size),image,r=options.size/2;c.context.fillStyle='rgba('+color.join(', ')+')';c.context.arc(r,r,r-2,0,360);c.context.fill();c.context.beginPath();c.context.lineWidth=2;c.context.strokeStyle='rgba('+border.join(', ')+')';c.context.arc(r,r,r-1,0,360);c.context.stroke();cache[index]=new google.maps.MarkerImage(c.canvas.toDataURL(),new google.maps.Size(options.size,options.size),new google.maps.Point(0,0),new google.maps.Point(r,r));}
return cache[index];}}());'use strict';Ox.MapPlace=function(options){options=Ox.extend({east:0,editing:false,geoname:'',map:null,name:'',north:0,selected:false,south:0,type:'',visible:false,west:0},options);var that=this;Ox.forEach(options,function(val,key){that[key]=val;});update();function update(updateMarker){that.points={ne:new google.maps.LatLng(that.north,that.east),sw:new google.maps.LatLng(that.south,that.west)};that.bounds=new google.maps.LatLngBounds(that.points.sw,that.points.ne);that.center=that.bounds.getCenter();that.lat=that.center.lat();that.lng=that.center.lng();Ox.extend(that.points,{e:new google.maps.LatLng(that.lat,that.east),s:new google.maps.LatLng(that.south,that.lng),se:new google.maps.LatLng(that.south,that.east),n:new google.maps.LatLng(that.north,that.lng),nw:new google.maps.LatLng(that.north,that.west),w:new google.maps.LatLng(that.lat,that.west)});that.sizeNorthSouth=(that.north-that.south)*Ox.EARTH_CIRCUMFERENCE/360;that.sizeEastWest=(that.east+(that.west>that.east?360:0)-that.west)*Ox.getMetersPerDegree(that.lat);that.area=Ox.getArea({lat:that.south,lng:that.west},{lat:that.north,lng:that.east});if(!that.marker){that.marker=new Ox.MapMarker({map:that.map,place:that});that.rectangle=new Ox.MapRectangle({map:that.map,place:that});}else if(updateMarker){that.marker.update();that.rectangle.update();}}
function editable(){return that.map.options('editable')&&that.editable;}
that.add=function(){that.visible=true;that.marker.add();return that;};that.cancel=function(){if(editable()){that.undo();that.editing=false;that.marker.update();that.rectangle.deselect();}
return that;};that.crossesDateline=function(){return that.west>that.east;}
that.deselect=function(){that.editing&&that.submit();that.selected=false;that.marker.update();that.rectangle.remove();return that;};that.edit=function(){if(editable()){that.editing=true;that.original={south:that.south,west:that.west,north:that.north,east:that.east};that.marker.edit();that.rectangle.select();}
return that;};that.options=function(options){options=Ox.makeObject(arguments);Ox.forEach(options,function(value,key){that[key]=value;});update(true);};that.remove=function(){that.editing&&that.submit();that.selected&&that.deselect();that.visible=false;that.marker.remove();return that;};that.select=function(){that.selected=true;!that.visible&&that.add();that.marker.update();that.rectangle.add();return that;};that.submit=function(){if(editable()){that.editing=false;that.marker.update();that.rectangle.deselect();}
return that;};that.update=function(updateMarker){update(updateMarker);that.map.triggerEvent('changeplace',that);return that;};that.undo=function(){if(editable()){Ox.forEach(that.original,function(v,k){that[k]=v;});that.update();that.marker.update();that.rectangle.update();}
return that;};return that;};'use strict';Ox.MapRectangle=function(options){options=Ox.extend({map:null,place:null},options);var that=this,themeData=Ox.Theme.getThemeData();Ox.forEach(options,function(val,key){that[key]=val;});that.rectangle=new google.maps.Rectangle({clickable:true,bounds:that.place.bounds});that.markers=Ox.map(that.place.points,function(point,position){return new Ox.MapRectangleMarker({map:that.map,place:that.place,position:position});});setOptions();function click(){if(that.map.options('editable')&&that.place.editable&&!that.place.editing){that.place.edit();}else if(that.map.getKey()=='meta'){that.place.submit();}else if(that.map.getKey()=='shift'){that.map.zoomToPlace();}else{that.map.panToPlace();}}
function setOptions(){var color='#'+Ox.toHex(themeData[that.place.editing?'mapPlaceEditingBorder':'mapPlaceSelectedBorder']);that.rectangle.setOptions({bounds:that.place.bounds,fillColor:color,fillOpacity:that.place.editing?0.1:0,strokeColor:color,strokeOpacity:that.place.id[0]=='_'?0.5:1,strokeWeight:2});}
that.add=function(){that.rectangle.setMap(that.map.map);google.maps.event.addListener(that.rectangle,'click',click);return that;};that.deselect=function(){setOptions();Ox.Log('Map','MARKERS',that.markers)
Ox.forEach(that.markers,function(marker){marker.remove();});return that;};that.remove=function(){that.rectangle.setMap(null);google.maps.event.clearListeners(that.rectangle);return that;}
that.select=function(){setOptions();Ox.forEach(that.markers,function(marker){marker.add();});return that;};that.update=function(){Ox.Log('Map','UPDATE...')
setOptions();Ox.forEach(that.markers,function(marker){marker.update();});return that;}
return that;};'use strict';Ox.MapRectangleMarker=function(options){options=Ox.extend({map:null,place:null,position:''},options);var that=this;Ox.forEach(options,function(val,key){that[key]=val;});that.markerImage=new google.maps.MarkerImage
that.marker=new google.maps.Marker({cursor:that.position+'-resize',draggable:true,icon:Ox.MapMarkerImage({mode:'editing',rectangle:true,type:that.place.id[0]=='_'?'result':'place'}),position:that.place.points[that.position],raiseOnDrag:false});function dragstart(e){Ox.$body.addClass('OxDragging');that.drag={lat:e.latLng.lat(),lng:e.latLng.lng()};}
function drag(e){Ox.Log('Map',e.pixel.x,e.pixel.y)
var lat=Ox.limit(e.latLng.lat(),Ox.MIN_LATITUDE,Ox.MAX_LATITUDE),lng=e.latLng.lng();that.drag={lat:lat,lng:lng};if(that.position.indexOf('s')>-1){that.place.south=lat;}
if(that.position.indexOf('n')>-1){that.place.north=lat;}
if(that.position.indexOf('w')>-1){that.place.west=lng;}
if(that.position.indexOf('e')>-1){that.place.east=lng;}
that.place.update();that.place.marker.update();that.place.rectangle.update();}
function dragend(e){var south;Ox.$body.removeClass('OxDragging');if(that.place.south>that.place.north){south=that.place.south;that.place.south=that.place.north;that.place.north=south;that.place.update();that.place.marker.update();that.place.rectangle.update();}
that.map.triggerEvent('changeplaceend',that.place);}
that.add=function(){that.marker.setMap(that.map.map);google.maps.event.addListener(that.marker,'dragstart',dragstart);google.maps.event.addListener(that.marker,'drag',drag);google.maps.event.addListener(that.marker,'dragend',dragend);};that.remove=function(){that.marker.setMap(null);google.maps.event.clearListeners(that.marker);};that.update=function(){that.marker.setOptions({icon:Ox.MapMarkerImage({mode:'editing',rectangle:true,type:that.place.id[0]=='_'?'result':'place'}),position:that.place.points[that.position]});};return that;};'use strict';Ox.Dialog=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({buttons:[],controlsBottom:[],controlsTop:[],closeButton:false,content:null,fixedCenter:false,fixedSize:false,fixedRatio:false,focus:true,height:200,keys:{},maxHeight:Infinity,maximizeButton:false,maxWidth:Infinity,minHeight:64,minWidth:128,removeOnClose:false,title:'',width:400}).options(options||{}).update({buttons:setButtons,content:setContent,height:function(){setMinAndMax();setCSS({height:self.options.height});},title:function(){self.$title.animate({opacity:0},50,function(){self.$title.html(self.options.title).animate({opacity:1},50);});},width:function(){setMinAndMax();setCSS({width:self.options.width});}}).addClass('OxDialog').bindEvent({key_enter:function(){keypress('enter');},key_escape:function(){keypress('escape');}}).hide().appendTo(Ox.Fullscreen.element?Ox.Fullscreen.element:Ox.$body);self.hasButtons=!!self.options.buttons.length;self.barsHeight=24+24*self.hasButtons;self.initialMaxHeight=self.options.maxHeight;self.initialMaxWidth=self.options.maxWidth;self.titleMargin=8+(self.options.closeButton?20:0)
+(self.options.maximizeButton?20:0);if(self.options.focus){self.$layer=Ox.Layer({type:'dialog'});}
self.$titlebar=Ox.Bar({size:24}).addClass('OxTitlebar').appendTo(that);if(self.options.closeButton){self.$closeButton=Ox.Button({title:'close',type:'image'}).css({top:'4px',left:'4px'}).bindEvent({click:function(){that.close();}}).appendTo(self.$titlebar);}
if(self.options.maximizeButton){self.$maximizeButton=Ox.Button({type:'image',values:['add','remove']}).css({top:'4px',left:'24px'}).bindEvent({click:maximize}).appendTo(self.$titlebar);}
self.$title=Ox.Element().addClass('OxTitle').css({marginLeft:self.titleMargin+'px',marginRight:self.titleMargin+'px'}).html(self.options.title).appendTo(self.$titlebar);setContent();if(self.hasButtons){self.$buttonsbar=Ox.Bar({size:24}).addClass('OxButtonsbar').appendTo(that);self.$buttonsLeft=$('
').addClass('OxButtonsLeft').appendTo(self.$buttonsbar.$element);self.$buttonsRight=$('
').addClass('OxButtonsRight').appendTo(self.$buttonsbar.$element);setButtons();}
if(!self.options.fixedCenter){self.$titlebar.css({cursor:'move'}).bindEvent({doubleclick:function(){!self.centered&¢er(true);},dragstart:dragstart,drag:drag,dragend:dragend});self.hasButtons&&self.$buttonsbar.css({cursor:'move'}).bindEvent({doubleclick:function(){!self.centered&¢er(true);},dragstart:dragstart,drag:drag,dragend:dragend});}
!self.options.fixedSize&&['TopLeft','Top','TopRight','Left','Right','BottomLeft','Bottom','BottomRight'].forEach(function(edge){Ox.Element().addClass('OxResize OxResize'+edge).bindEvent({doubleclick:function(){reset(true);},dragstart:resizestart,drag:resize,dragend:resizeend}).appendTo(that);});function center(animate){var ms=animate?100:0;self.centered&&decenter();that.animate({left:Math.round((window.innerWidth-self.options.width)*0.5)+'px',top:Math.round((window.innerHeight-self.options.height-self.barsHeight)*0.4)+'px',width:self.options.width+'px',height:self.options.height+self.barsHeight+'px'},ms,function(){that.css({left:0,top:0,right:0,bottom:Math.round((window.innerHeight-self.options.height-self.barsHeight)*0.2)+'px',margin:'auto'});self.centered=true;Ox.isFunction(animate)&&animate();});}
function decenter(){var offset=that.offset();if(self.centered){that.css({left:offset.left+'px',top:offset.top+'px',margin:0});self.centered=false;}}
function dragstart(event){var offset;if(!$(event.target).is('.OxButton')){Ox.$body.addClass('OxDragging');offset=that.offset();self.drag={left:offset.left,top:offset.top,x:event.clientX,y:event.clientY};decenter();}}
function drag(event){Ox.Log('Window',document.body.scrollTop,'...')
var left,top;if(!$(event.target).is('.OxButton')){left=Ox.limit(self.drag.left-self.drag.x+event.clientX,self.minLeft,self.maxLeft);top=Ox.limit(self.drag.top-self.drag.y+event.clientY,self.minTop,self.maxTop);setCSS({left:left,top:top});}}
function dragend(event){if(!$(event.target).is('.OxButton')){Ox.$body.removeClass('OxDragging');}}
function getButtonById(id){var ret=null;Ox.forEach(self.options.buttons,function(button){if(button.options&&button.options('id')==id){ret=button;return false;}});return ret;}
function keypress(key){var id=self.options.keys[key];Ox.Log('Window',id,getButtonById(id));id&&getButtonById(id).$element.trigger('click');}
function maximize(){var data,offset=that.offset();decenter();if(!self.maximized){self.originalLeft=offset.left;self.originalTop=offset.top;self.originalWidth=self.options.width;self.originalHeight=self.options.height;}
setCSS(self.maximized?{left:self.originalLeft,top:self.originalTop,width:self.originalWidth,height:self.originalHeight}:{left:Math.round((window.innerWidth-self.options.maxWidth)/2),top:Math.round((window.innerHeight-self.options.maxHeight-self.barsHeight)/2),width:self.options.maxWidth,height:self.options.maxHeight},true);self.maximized=!self.maximized;}
function reset(animate){var data,left,offset,top;if(!self.centered){offset=that.offset();left=Ox.limit(offset.left+Math.round((self.options.width-self.initialWidth)/2),self.minLeft,self.maxLeft);top=Ox.limit(offset.top+Math.round((self.options.height-self.initialHeight)/2),self.minTop,self.maxTop);}
setCSS(Ox.extend({width:self.initialWidth,height:self.initialHeight},self.centered?{}:{left:left,top:top}),animate);}
function resizestart(event){Ox.$body.addClass('OxDragging');var edge=event.target.className.slice(17).toLowerCase(),offset=that.offset();self.drag={edge:edge,height:self.options.height,isLeft:edge.indexOf('left')>-1,isTop:edge.indexOf('top')>-1,isRight:edge.indexOf('right')>-1,isBottom:edge.indexOf('bottom')>-1,left:offset.left,top:offset.top,width:self.options.width};decenter();if(self.maximized){self.$maximizeButton.toggle();self.maximized=false;}}
function resize(event){var horizontal,vertical,offset,ratio=self.drag.width/self.drag.height;if(!self.drag.fixedRatio&&event.shiftKey){self.drag.centerX=Math.round(self.drag.left+self.drag.width/2);self.drag.centerY=Math.round(self.drag.top+self.drag.height/2);}
self.drag.fixedCenter=self.options.fixedCenter||event.altKey;self.drag.fixedRatio=self.options.fixedRatio||event.shiftKey;horizontal=self.drag.edge=='left'||self.drag.edge=='right'||ratio>=1||!self.drag.fixedRatio;vertical=self.drag.edge=='top'||self.drag.edge=='bottom'||ratio<1||!self.drag.fixedRatio;if(self.drag.isLeft&&horizontal){self.options.width=Ox.limit(self.options.width+(self.drag.left-Math.min(event.clientX,self.maxLeft))*(self.drag.fixedCenter?2:1),self.options.minWidth,self.options.maxWidth);if(self.drag.fixedRatio){self.options.height=Ox.limit(Math.round(self.options.width/ratio),self.options.minHeight,self.options.maxHeight);self.options.width=Math.round(self.options.height*ratio);}
setCSS(Ox.extend({left:self.drag.left+(self.drag.width-self.options.width)/(self.drag.fixedCenter?2:1),width:self.options.width},self.drag.fixedRatio?{top:Math.max(Math.round(self.drag.edge=='topleft'?self.drag.top+self.drag.height-self.options.height:self.drag.edge=='bottomleft'?self.drag.top:self.drag.centerY-self.options.height/2),self.minTop),height:self.options.height}:{}));}
if(self.drag.isTop&&vertical){self.options.height=Ox.limit(self.options.height+(self.drag.top
-Ox.limit(event.clientY,self.minTop,self.maxTop))*(self.drag.fixedCenter?2:1),self.options.minHeight,self.options.maxHeight);if(self.drag.fixedRatio){self.options.width=Ox.limit(Math.round(self.options.height*ratio),self.options.minWidth,self.options.maxWidth);self.options.height=Math.round(self.options.width/ratio);}
setCSS(Ox.extend({top:Math.max(self.drag.top+(self.drag.height-self.options.height)/(self.drag.fixedCenter?2:1),self.minTop),height:self.options.height},(self.drag.fixedRatio)?{left:Math.round(self.drag.edge=='topleft'?self.drag.left+self.drag.width-self.options.width:self.drag.edge=='topright'?self.drag.left:self.drag.centerX-self.options.width/2),width:self.options.width}:{}));}
if(self.drag.isRight&&horizontal){self.options.width=Ox.limit(self.options.width+(Math.max(event.clientX,24)
-self.drag.left-self.drag.width)*(self.drag.fixedCenter?2:1),self.options.minWidth,self.options.maxWidth);if(self.drag.fixedRatio){self.options.height=Ox.limit(Math.round(self.options.width/ratio),self.options.minHeight,self.options.maxHeight);self.options.width=Math.round(self.options.height*ratio);}
setCSS(Ox.extend({width:self.options.width},self.drag.fixedCenter?{left:self.drag.left+(self.drag.width-self.options.width)/2}:{},self.drag.fixedRatio?{top:Math.max(Math.round(self.drag.edge=='topright'?self.drag.top+self.drag.height-self.options.height:self.drag.edge=='bottomright'?self.drag.top:self.drag.centerY-self.options.height/2),self.minTop),height:self.options.height}:{}));}
if(self.drag.isBottom&&vertical){self.options.height=Ox.limit(self.options.height+(Math.max(event.clientY,24)
-self.drag.top-self.drag.height-self.barsHeight)*(self.drag.fixedCenter?2:1),self.options.minHeight,self.options.maxHeight);if(self.drag.fixedRatio){self.options.width=Ox.limit(Math.round(self.options.height*ratio),self.options.minWidth,self.options.maxWidth);self.options.height=Math.round(self.options.width/ratio);}
setCSS(Ox.extend({height:self.options.height},self.drag.fixedCenter?{top:Math.max(self.drag.top+(self.drag.height-self.options.height)/2,self.minTop)}:{},self.drag.fixedRatio&&self.drag.edge=='bottom'?{left:Math.round(self.drag.edge=='bottomleft'?self.drag.left+self.drag.width-self.options.width:self.drag.edge=='bottomright'?self.drag.left:self.drag.centerX-self.options.width/2),width:self.options.width}:{}));}
offset=that.offset();self.drag.left=offset.left;self.drag.top=offset.top;self.drag.width=self.options.width;self.drag.height=self.options.height;self.drag.minLeft=24-self.options.width;self.drag.minTop=self.hasButtons?24-self.options.height-self.barsHeight:0;that.triggerEvent('resize',{width:self.options.width,height:self.options.height});}
function resizeend(){Ox.$body.removeClass('OxDragging');that.triggerEvent('resizeend',{width:self.options.width,height:self.options.height});}
function resizeWindow(){self.options.width=Math.min(self.options.width,window.innerWidth);self.options.height=Math.min(self.options.height,window.innerHeight-self.barsHeight);var offset=that.offset();setMinAndMax();if(self.centered){center();}else if(self.maximized){self.maximized=false;maximize();}else{setCSS({left:Math.min(offset.left,self.maxLeft),top:Math.min(offset.top,self.maxTop),width:self.options.width,height:self.options.height});}}
function setButtons(){var buttonsLeft,buttonsRight,index=Ox.indexOf(self.options.buttons,Ox.isEmpty);if(index>-1){buttonsLeft=self.options.buttons.slice(0,index);buttonsRight=self.options.buttons.slice(index+1);}else{buttonsLeft=[];buttonsRight=self.options.buttons;}
self.$buttonsLeft.empty();buttonsLeft.forEach(function($button){$button.addClass('OxLeft').appendTo(self.$buttonsLeft);});self.$buttonsRight.empty();buttonsRight.forEach(function($button){$button.addClass('OxRight').appendTo(self.$buttonsRight);});}
function setContent(){var animate=!!self.$content,isImage=!Ox.UI.isElement(self.options.content)&&self.options.content.is('img');if(animate){self.$content.animate({opacity:0},250,function(){$(this).remove();});self.options.content.css({opacity:0});}
self.$content=(isImage?self.options.content:Ox.Element()).addClass('OxContent').css(self.hasButtons?{bottom:'24px'}:{bottom:0,borderBottomLeftRadius:'8px',borderBottomRightRadius:'8px'}).appendTo(that);!isImage&&self.$content.append(self.options.content.css(self.hasButtons?{}:{borderBottomLeftRadius:'8px',borderBottomRightRadius:'8px'}));animate&&self.options.content.animate({opacity:1},250);}
function setCSS(css,animate){var ms=animate?100:0,offset=that.offset(),triggerEvent=self.isOpen&&((css.width&&css.width!=self.options.width)||(css.height&&css.height!=self.options.height));css=Ox.extend({left:offset.left,top:offset.top,width:self.options.width,height:self.options.height},css);that.animate({left:css.left+'px',top:css.top+'px',width:css.width+'px',height:css.height+self.barsHeight+'px'},ms,function(){self.options.width=css.width;self.options.height=css.height;self.minLeft=24-self.options.width;self.minTop=self.hasButtons?24-self.options.height-self.barsHeight:0;triggerEvent&&that.triggerEvent('resize',{width:self.options.width,height:self.options.height});Ox.isFunction(animate)&&animate();});}
function setMinAndMax(){var ratio,maxRatio,minRatio;self.maxLeft=window.innerWidth-24;self.maxTop=window.innerHeight-24;self.minLeft=24-self.options.width;self.minTop=self.hasButtons?24-self.options.height:0;self.options.maxHeight=Ox.limit(self.initialMaxHeight,64,window.innerHeight-self.barsHeight);self.options.maxWidth=Ox.limit(self.initialMaxWidth,128,window.innerWidth);if(self.options.fixedRatio){ratio=self.options.width/self.options.height;maxRatio=self.options.maxWidth/self.options.maxHeight;minRatio=self.options.minWidth/self.options.minHeight;if(maxRatio>ratio){self.options.maxWidth=Math.round(self.options.maxHeight*ratio);}else if(maxRatio
ratio){self.options.minWidth=Math.round(self.options.minHeight*ratio);}else if(minRatiowindow.innerHeight-height-16?self.y-16-height:self.y+16;that.css({left:left+'px',top:top+'px'});self.options.animate&&that.animate({opacity:1},250,function(){Ox.isFunction(last)&&last();});}
return that;};return that;};'use strict';Ox.Chart=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({color:[128,128,128],data:{},formatKey:null,keyAlign:'right',keyWidth:128,limit:0,rows:1,sort:{key:'value',operator:'-'},sortKey:null,title:'',width:512}).options(options||{}).update({width:function(){self.$chart.empty();renderChart();}}).addClass('OxChart');self.valueWidth=self.options.width-self.options.keyWidth;self.keys=Object.keys(self.options.data);if(Ox.isObject(self.options.data[self.keys[0]])){if(Ox.isUndefined(options.color)){self.options.color=[[192,64,64],[64,192,64],[64,64,192],[192,192,64],[64,192,192],[192,64,192],[192,128,64],[64,192,128],[128,64,192],[192,64,128],[128,192,64],[64,128,192]];}
self.subData={};}
self.sort={};self.totals={};Ox.forEach(self.options.data,function(value,key){self.totals[key]=self.subData?Ox.sum(value):value;if(self.subData){Object.keys(value).forEach(function(subKey){self.subData[subKey]=(self.subData[subKey]||0)+value[subKey];});}
self.sort[key]=key.replace(/(\d+)/g,function(number){return Ox.pad(parseInt(number,10),16);});});self.max=Ox.max(self.totals);self.sum=Ox.sum(self.totals);if(self.subData){Ox.forEach(self.subData,function(subValue,subKey){self.sort[subKey]=subKey.replace(/(\d+)/g,function(number){return Ox.pad(parseInt(number,10),16);});});self.subKeys=Object.keys(self.subData).sort(function(a,b){var aValue=self.subData[a],bValue=self.subData[b];return a===''?1:b===''?-1:self.sort[a]self.sort[b]?1:0;});}
self.items=self.keys.map(function(key){return{key:key,keySort:self.sort[key],value:self.options.data[key],valueSort:self.subData?self.totals[key]:self.options.data[key]};});self.sortBy=self.options.sort.key=='key'?[{key:'keySort',operator:self.options.sort.operator}]:[{key:'valueSort',operator:self.options.sort.operator},{key:'keySort',operator:'+'}]
if(self.options.limit){self.items=Ox.sortBy(self.items,self.sortBy).slice(0,self.options.limit);self.max=Ox.max(self.items.map(function(item){return self.subData?Ox.sum(item.value):item.value;}));}
self.max=self.max||1;if(self.options.rows==2){self.row=0;}
self.$title=Ox.Bar({size:16}).append($('').css({margin:'1px 0 0 4px'}).html(self.options.title)).appendTo(that);self.$chart=$('
').css({position:'absolute',top:'16px'}).append(renderChart()).appendTo(that);function getColumns(){return[{align:self.options.keyAlign,format:self.options.formatKey,id:'key',width:self.options.keyWidth,visible:true},{format:renderValue,id:'value',width:self.valueWidth,visible:true}];}
function getWidths(values){var max,maxKeys,total=Ox.sum(values),totalWidth=Math.ceil(total/self.max*self.valueWidth),widths={};Ox.forEach(values,function(value,key){widths[key]=Math.round(value/total*totalWidth);});while(Ox.sum(widths)!=totalWidth){max=Ox.max(widths);maxKeys=Object.keys(widths).filter(function(key){return widths[key]==max;});widths[maxKeys[0]]+=Ox.sum(widths)
',tooltip:Ox.formatNumber(value)
+' ('+Ox.formatPercent(value*self.options.rows,self.sum,2)+')'}).css({width:Math.ceil(value/self.max*self.valueWidth)+'px',height:'14px',borderRadius:'4px',marginLeft:'-4px'});colors[0]=Ox.isFunction(self.options.color)?self.options.color(data.key):self.options.color;}else{$element=$('').css({width:Math.ceil(self.totals[data.key]/self.max*self.valueWidth)+'px',height:'14px',marginLeft:'-4px'});len=Ox.len(value);widths=getWidths(value);self.subKeys.forEach(function(subKey,subKeyIndex){var i=$bars.length,subValue=value[subKey];if(subValue){$bars[i]=Ox.Element({element:'
',tooltip:Ox.formatNumber(self.totals[data.key])
+' ('+Ox.formatPercent(self.totals[data.key]*self.options.rows,self.sum,2)+')'}).css({float:'left',width:widths[subKey]+'px',height:'14px',borderTopLeftRadius:i==0?'4px':0,borderBottomLeftRadius:i==0?'4px':0,borderTopRightRadius:i==len-1?'4px':0,borderBottomRightRadius:i==len-1?'4px':0}).appendTo($element);colors[i]=subKey==''?[128,128,128]:Ox.isArray(self.options.color)?self.options.color[subKeyIndex%self.options.color.length]:Ox.isObject(self.options.color)?self.options.color[subKey]:self.options.color(subKey);}});}
$bars.forEach(function($bar,i){['moz','o','webkit'].forEach(function(browser){$bar.css({backgroundImage:'-'+browser
+'-linear-gradient(top, rgb('+colors[i].map(function(v){return Ox.limit(v+16,0,255);}).join(', ')+'), rgb('+colors[i].map(function(v){return Ox.limit(v-16,0,255);})+'))'});});});if(self.options.rows==2){self.row++;}
return $element;}
return that;};'use strict';Ox.ColumnList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({columns:[],custom:{},items:[],list:'table',query:{conditions:[],operator:'&'},resize:null,width:768}).options(options||{}).update({query:updateQuery,width:function(){self.columnWidths=getColumnWidths();self.$panel.size(0,self.columnWidths[0]);self.$panel.size(2,self.columnWidths[2]);self.$lists.forEach(function($list,i){$list.options({itemWidth:self.columnWidths[i]});});}}).addClass('OxColumnList');self.numberOfColumns=self.options.columns.length;self.columnWidths=getColumnWidths();self.flatItems=[];self.ids=[{},{},{}];self.options.items.forEach(function(item0){item0.items.forEach(function(item1){self.ids[1][item1.id]=[item0.id];item1.items.forEach(function(item2){self.ids[2][item2.id]=[item0.id,item1.id];self.flatItems.push(item2);});});});self.api=Ox.api(self.flatItems);self.$lists=self.options.columns.map(function(column,i){return Ox.CustomList({item:self.options.columns[i].item,itemHeight:self.options.columns[i].itemHeight,items:getItems(i),itemWidth:self.columnWidths[i],keys:self.options.columns[i].keys,max:self.options.columns[i].max,resize:self.options.resize,scrollbarVisible:true,selected:self.options.columns[i].selected,sort:self.options.columns[i].sort,unique:'id'}).bindEvent({key_left:function(){if(i>0){self.$lists[i-1].gainFocus();that.triggerEvent('select',{id:self.options.columns[i-1].id,ids:self.$lists[i-1].options('selected')});}},key_right:function(){var index,object,selected=self.$lists[i].options('selected');if(selected.length){if(i
-1){return false;}});items=items.concat(self.options.items[index[0]].items[index[1]].items);}});}
return items;}
function updateQuery(){if(self.options.query.conditions.length==0){self.items=self.options.items;}else{self.api({keys:['id','_ids'],query:self.options.query},function(result){var ids=[[],[],[]];result.data.items.forEach(function(item){ids[0].push(self.ids[2][item.id][0]);ids[1].push(self.ids[2][item.id][1]);ids[2].push(item.id);});self.items=self.options.items.filter(function(item0){return Ox.contains(ids[0],item0.id);});self.items.forEach(function(item0){item0.items=item0.items.filter(function(item1){return Ox.contains(ids[1],item1.id);});item0.items.forEach(function(item1){item1.items=item1.items.filter(function(item2){return Ox.contains(ids[2],item2.id);});});});});}
self.$lists.forEach(function($list,i){$list.options({items:i==0?self.items:[]});});}
that.sort=function(id,sort){var index=Ox.isNumber(id)?id:Ox.getIndexById(self.options.columns,id);self.$lists[index].options({sort:sort});self.options.columns[index].sort=sort;};return that;};'use strict';Ox.CustomList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({draggable:false,item:null,itemHeight:32,items:null,itemWidth:256,keys:[],max:-1,min:0,pageLength:100,query:{conditions:[],operator:'&'},resize:null,scrollbarVisible:false,selected:[],sort:[],sortable:false,sums:[],unique:''}).options(options||{}).update({items:function(){self.$list.options({items:self.options.items});},itemWidth:function(){var width=self.options.itemWidth-Ox.UI.SCROLLBAR_SIZE;if(self.options.resize){that.find('.OxItem').each(function(element){self.options.resize($(this),width);});}},query:function(){self.$list.options({query:self.options.query});},selected:function(){self.$list.options({selected:self.options.selected});that.triggerEvent('select',{ids:self.options.selected});},sort:function(){self.$list.options({sort:self.options.sort});}}).addClass('OxCustomList');self.$list=Ox.List({construct:function(data){return self.options.item(data,self.options.itemWidth-Ox.UI.SCROLLBAR_SIZE).addClass('OxTarget');},draggable:self.options.draggable,itemHeight:self.options.itemHeight,itemWidth:self.options.itemWidth
-self.options.scrollbarVisible*Ox.UI.SCROLLBAR_SIZE,items:self.options.items,keys:self.options.keys.concat(self.options.unique),max:self.options.max,min:self.options.min,orientation:'vertical',pageLength:self.options.pageLength,query:Ox.clone(self.options.query,true),selected:self.options.selected,sort:Ox.clone(self.options.sort,true),sortable:self.options.sortable,sums:self.options.sums,type:'text',unique:self.options.unique}).css({top:0,overflowY:(self.options.scrollbarVisible?'scroll':'hidden')}).bindEvent(function(data,event){if(event=='select'){self.options.selected=data.ids;}
that.triggerEvent(event,data);}).appendTo(that);that.api=self.$list.options('items');that.gainFocus=function(){self.$list.gainFocus();return that;};that.getPasteIndex=function(){return self.$list.getPasteIndex();};that.hasFocus=function(){return self.$list.hasFocus();};that.invertSelection=function(){self.$list.invertSelection();return that;};that.loseFocus=function(){self.$list.loseFocus();return that;};that.selectAll=function(){self.$list.selectAll();return that;};that.selectPosition=function(pos){self.$list.selectPosition(pos);return that;};that.selectSelected=function(offset){that.$list.selectSelected(offset);return that;};that.size=function(){self.$list.size();return that;};return that;};'use strict';Ox.IconItem=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({borderRadius:0,extra:null,find:'',iconHeight:128,iconWidth:128,imageHeight:128,imageWidth:128,itemHeight:192,itemWidth:128,id:'',info:'',title:'',url:''}).options(options||{});Ox.extend(self,{fontSize:self.options.itemWidth==64?6:9,infoIsObject:Ox.isObject(self.options.info),lineLength:self.options.itemWidth==64?15:23,lines:self.options.itemWidth==64?4:5,url:Ox.UI.PATH+'png/transparent.png'});self.title=formatText(self.options.title,self.lines-1-self.infoIsObject,self.lineLength);if(!self.infoIsObject){self.info=formatText(self.options.info,5-self.title.split(' ').length,self.lineLength);}else{self.title=$('').css({fontSize:self.fontSize+'px'}).html(self.title);self.info=$('
').append(self.options.info.css(Ox.extend(self.options.info.css('width')=='0px'?{width:Math.round(self.options.itemWidth/2)+'px'}:{},{padding:0,margin:'1px auto',fontSize:self.fontSize+'px',textShadow:'none'})));}
that.css({width:self.options.itemWidth+4+'px',height:self.options.itemHeight+ +4+'px'});that.$icon=$('
').addClass('OxIcon').css({top:(self.options.iconWidth==64?-64:-122)+'px',width:self.options.iconWidth+4+'px',height:self.options.iconHeight+4+'px'});that.$iconImage=$('
').addClass('OxLoading OxTarget').attr({src:self.url}).css({width:self.options.imageWidth+'px',height:self.options.imageHeight+'px',borderRadius:self.options.borderRadius+4+'px'}).mousedown(mousedown).mouseenter(mouseenter).mouseleave(mouseleave);self.options.url&&that.$iconImage.one('load',load);that.$textBox=$('
').addClass('OxText').css({top:self.options.iconHeight-(self.options.itemWidth==64?32:62)+'px',width:self.options.itemWidth+4+'px',height:(self.options.itemWidth==64?30:58)+'px'});that.$text=$('
').addClass('OxTarget').css({fontSize:self.fontSize+'px'}).mouseenter(mouseenter).mouseleave(mouseleave);if(!self.infoIsObject){that.$text.html((self.title?self.title+'
':'')
+'
'+self.info+' ');}else{that.$text.append(self.title).append(self.info);}
that.$reflection=$('
').addClass('OxReflection').css({top:self.options.iconHeight+(self.options.itemWidth==64?0:2)+'px',width:self.options.itemWidth+4+'px',height:self.options.itemHeight-self.options.iconHeight+'px'});that.$reflectionImage=$('
').addClass('OxLoading').attr({src:self.url}).css({width:self.options.imageWidth+'px',height:self.options.imageHeight+'px',paddingLeft:($.browser.mozilla&&self.options.imageWidth%2?1:0)+'px',borderRadius:self.options.borderRadius+'px'});that.$gradient=$('
').css({width:self.options.itemWidth+2+'px',height:self.options.itemWidth/2+'px'});that.append(that.$reflection.append(that.$reflectionImage).append(that.$gradient)).append(that.$textBox.append(that.$text)).append(that.$icon.append(that.$iconImage));if(self.options.extra){that.$extra=$('
').addClass('OxTarget').css({position:'absolute',left:0,right:0,bottom:0,width:self.options.imageWidth+'px',height:self.options.imageHeight+'px',border:'2px solid transparent',margin:'auto',cursor:'pointer',overflow:'hidden'})
that.$icon.append(that.$extra.append(self.options.extra));}
function formatText(text,maxLines,maxLength){text=Ox.isArray(text)?text.join(', '):text;var lines=Ox.wordwrap(text,maxLength,true).split('\n');if(lines.length>maxLines){lines[maxLines-1]=Ox.truncate(lines.slice(maxLines-1).join(''),'center',maxLength).replace('…','
… ');lines=lines.slice(0,maxLines);}
return Ox.highlight(lines.join('
'),self.options.find,'OxHighlight',true);}
function load(){that.$iconImage.attr({src:self.options.url}).one('load',function(){that.$iconImage.removeClass('OxLoading');that.$reflectionImage.attr({src:self.options.url}).removeClass('OxLoading');});}
function mousedown(e){}
function mouseenter(){that.addClass('OxHover');}
function mouseleave(){that.removeClass('OxHover');}
return that;};'use strict';Ox.IconList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({borderRadius:0,centered:false,defaultRatio:1,draggable:false,find:'',fixedRatio:false,id:'',item:null,itemConstructor:Ox.IconItem,items:null,keys:[],max:-1,min:0,orientation:'both',pageLength:100,query:{conditions:[],operator:'&'},selectAsYouType:'',selected:[],size:128,sort:[],sums:[],unique:''}).options(options||{}).update({items:function(){self.$list.options({items:self.options.items});},query:function(){self.$list.options({query:self.options.query});},selected:function(){self.$list.options({selected:self.options.selected});},sort:function(){updateKeys();self.$list.options({sort:self.options.sort});}});if(self.options.fixedRatio){self.options.defaultRatio=self.options.fixedRatio;}
if(Ox.isArray(self.options.items)){self.options.keys=Ox.unique(Ox.flatten(self.options.items.map(function(item){return Object.keys(item);})));}
self.iconWidth=self.options.size;self.iconHeight=self.options.fixedRatio>1?Math.round(self.options.size/self.options.fixedRatio):self.options.size;self.itemWidth=self.options.size;self.itemHeight=self.iconHeight+self.options.size*0.5;self.$list=Ox.List({centered:self.options.centered,construct:constructItem,draggable:self.options.draggable,id:self.options.id,itemHeight:self.itemHeight,items:self.options.items,itemWidth:self.itemWidth,keys:self.options.keys,max:self.options.max,min:self.options.min,orientation:self.options.orientation,pageLength:self.options.pageLength,query:self.options.query,selectAsYouType:self.options.selectAsYouType,selected:self.options.selected,sort:self.options.sort,sums:self.options.sums,type:'icon',unique:self.options.unique}).addClass('OxIconList Ox'+Ox.toTitleCase(self.options.orientation)).bindEvent(function(data,event){if(event=='select'){self.options.selected=data.ids;}
that.triggerEvent(event,data);});that.setElement(self.$list);updateKeys();function constructItem(data){var isEmpty=Ox.isEmpty(data);data=!isEmpty?self.options.item(data,self.options.sort,self.options.size):{width:Math.round(self.options.size*(self.options.defaultRatio>=1?1:self.options.defaultRatio)),height:Math.round(self.options.size/(self.options.defaultRatio<=1?1:self.options.defaultRatio))};return self.options.itemConstructor(Ox.extend(data,{borderRadius:self.options.borderRadius,find:self.options.find,iconHeight:self.iconHeight,iconWidth:self.iconWidth,imageHeight:data.height,imageWidth:data.width,itemHeight:self.itemHeight,itemWidth:self.itemWidth}));}
function updateKeys(){self.$list.options({keys:Ox.unique([self.options.sort[0].key].concat(self.options.keys))});}
that.closePreview=function(){self.$list.closePreview();return that;};that.gainFocus=function(){self.$list.gainFocus();return that;};that.getPasteIndex=function(){return self.$list.getPasteIndex();};that.hasFocus=function(){return self.$list.hasFocus();};that.invertSelection=function(){self.$list.invertSelection();return that;};that.loseFocus=function(){self.$list.loseFocus();return that;};that.openPreview=function(){self.$list.openPreview();return that;};that.reloadList=function(){self.$list.reloadList();return that;};that.scrollToSelection=function(){self.$list.scrollToSelection();return that;};that.selectAll=function(){self.$list.selectAll();return that;};that.selectPosition=function(pos){self.$list.selectPosition(pos);return that;};that.selectSelected=function(offset){self.$list.selectSelected(offset);return that;};that.size=function(){self.$list.size();return that;};that.sortList=function(key,operator){self.options.sort=[{key:key,operator:operator}];updateKeys();self.$list.sortList(key,operator);return that;};that.value=function(){var args=Ox.slice(arguments),id=args.shift(),sort=false;if(arguments.length==1){return self.$list.value(id);}else if(arguments.length==2&&Ox.isString(arguments[1])){return self.$list.value(id,arguments[1]);}else{Ox.forEach(Ox.makeObject(args),function(value,key){self.$list.value(id,key,value);if(key==self.unique){self.options.selected=self.options.selected.map(function(id_){return id_==id?value:id_});id=value;}
if(key==self.options.sort[0].key){sort=true;}});sort&&self.$list.sort();return that;}};return that;};'use strict';Ox.InfoList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({borderRadius:0,defaultRatio:1,draggable:false,id:'',item:null,items:null,keys:[],max:-1,min:0,query:{conditions:[],operator:'&'},selectAsYouType:'',selected:[],size:192,sort:[],sums:[],unique:''}).options(options||{}).update({items:function(){self.$list.options({items:self.options.items});},query:function(){self.$list.options({query:self.options.query});},selected:function(){self.$list.options({selected:self.options.selected});},sort:function(){updateKeys();self.$list.options({sort:self.options.sort});},width:function(){var width=getItemWidth();$('.OxInfoElement').each(function(){var $parent=$(this).parent(),id=parseInt(/OxId(.*?)$/.exec(this.className)[1],10);$parent.css({width:width-144});$parent.parent().css({width:width-144});$parent.parent().parent().css({width:width-8});Ox.$elements[id].options({width:width-152});});}});self.iconSize=Math.round(self.options.size*2/3);self.itemHeight=self.options.size;that.setElement(self.$list=Ox.List({construct:constructItem,draggable:self.options.draggable,id:self.options.id,itemHeight:self.itemHeight,items:self.options.items,itemWidth:getItemWidth(),keys:self.options.keys,max:self.options.max,min:self.options.min,orientation:'vertical',pageLength:10,query:self.options.query,selectAsYouType:self.options.selectAsYouType,selected:self.options.selected,sort:self.options.sort,sums:self.options.sums,type:'info',unique:self.options.unique}).addClass('OxInfoList').bindEvent(function(data,event){if(event=='select'){self.options.selected=data.ids;}
that.triggerEvent(event,data);}));updateKeys();function constructItem(data){var isEmpty=Ox.isEmpty(data),data=!isEmpty?self.options.item(data,self.options.sort,self.options.size):{icon:{width:Math.round(self.iconSize*(self.options.defaultRatio>=1?1:self.options.defaultRatio)),height:Math.round(self.iconSize/(self.options.defaultRatio<=1?1:self.options.defaultRatio))},info:{}},$icon=Ox.Element().css({float:'left',width:'132px',height:'192px',margin:'2px'}).append(Ox.IconItem(Ox.extend(data.icon,{borderRadius:self.options.borderRadius,iconHeight:self.iconSize,iconWidth:self.iconSize,imageHeight:data.icon.height,imageWidth:data.icon.width,itemHeight:self.itemHeight,itemWidth:128})).addClass('OxInfoIcon').css({position:'absolute'})),$info=Ox.Element().css({float:'left',width:getItemWidth()-144+'px',height:196+'px'}),$infobox=Ox.Element().css({position:'absolute',width:getItemWidth()-144+'px',height:196+'px',marginTop:'-2px',overflow:'hidden'}).appendTo($info),$item=Ox.Element().css({width:getItemWidth()-8+'px',height:196+'px',margin:'4px'}).append($icon).append($info);if(!isEmpty){var $element=data.info.element(Ox.extend(data.info.options,{width:getItemWidth()-152})).addClass('OxInfoElement');data.info.css&&$element.css(data.info.css);data.info.events&&$element.bindEvent(data.info.events);$element.addClass('OxId'+$element.oxid);$infobox.append($element);}
return $item;}
function getItemWidth(cached){if(!cached){self.cachedWidth=that.width()-Ox.UI.SCROLLBAR_SIZE;}else if(!self.cachedWidth||self.cachedWidthTime<+new Date()-5000){self.cachedWidth=that.width()-Ox.UI.SCROLLBAR_SIZE;self.cachedWidthTime=+new Date();}
return self.cachedWidth;}
function updateKeys(){self.$list.options({keys:Ox.unique([self.options.sort[0].key].concat(self.options.keys))});}
that.closePreview=function(){self.$list.closePreview();return that;};that.gainFocus=function(){self.$list.gainFocus();return that;};that.getPasteIndex=function(){return self.$list.getPasteIndex();};that.hasFocus=function(){return self.$list.hasFocus();};that.invertSelection=function(){self.$list.invertSelection();return that;};that.loseFocus=function(){self.$list.loseFocus();return that;};that.reloadList=function(stayAtPosition){self.$list.reloadList(stayAtPosition);return that;};that.scrollToSelection=function(){self.$list.scrollToSelection();return that;};that.selectAll=function(){self.$list.selectAll();return that;};that.selectPosition=function(pos){self.$list.selectPosition(pos);return that;};that.selectSelected=function(offset){self.$list.selectSelected(offset);return that;};that.size=function(){self.$list.size();return that;};that.sortList=function(key,operator){self.options.sort=[{key:key,operator:operator}];updateKeys();self.$list.sortList(key,operator);return that;};that.value=function(){var args=Ox.slice(arguments),id=args.shift();if(arguments.length==1){return self.$list.value(id);}else if(arguments.length==2&&Ox.isString(arguments[1])){return self.$list.value(id,arguments[1]);}else{Ox.forEach(Ox.makeObject(args),function(value,key){self.$list.value(id,key,value);});return that;}};return that;};'use strict';Ox.List=function(options,self){self=self||{};var that=Ox.Container({},self).defaults({_tree:false,centered:false,construct:null,disableHorizonzalScrolling:false,draggable:false,format:[],itemHeight:16,items:null,itemWidth:16,keys:[],max:-1,min:0,orientation:'vertical',pageLength:100,query:{conditions:[],operator:'&'},selected:[],sort:[],sortable:false,sums:[],type:'text',unique:''}).options(options||{}).update({draggable:updateDraggable,items:function(){if(!self.isAsync){updateItems();}else{if(Ox.isArray(self.options.items)){self.items=self.options.items;self.options.items=self.itemsAPI.update(self.items);}
updateQuery();}},query:function(){that.reloadList();},selected:function(){setSelected(self.options.selected);},sort:updateSort,sortable:updateSortable}).on({scroll:scroll});self.options.sort=self.options.sort.map(function(sort){return Ox.isString(sort)?{key:sort.replace(/^[\+\-]/,''),operator:sort[0]=='-'?'-':'+'}:sort;});if(Ox.isArray(self.options.items)&&!self.options._tree){self.items=self.options.items;self.options.items=Ox.api(self.items,{cache:true,map:self.options.map,sort:self.options.sort,sums:self.options.sums,unique:self.options.unique});self.itemsAPI=self.options.items;}
that.$content.bindEvent({mousedown:mousedown,singleclick:singleclick,doubleclick:doubleclick}).on({touchend:function(e){if(self.touchSelection.length&&self.options.selected[0]==self.touchSelection[0]){doubleclick(e);}else{self.touchSelection=Ox.clone(self.options.selected);}}});self.options.draggable&&updateDraggable();self.options.sortable&&updateSortable();self.options.orientation=='horizontal'&&that.$content.css({height:'1px'});Ox.extend(self,{$items:[],$pages:[],format:{},isAsync:!self.options._tree,itemMargin:self.options.type=='text'?0:8,keyboardEvents:{key_control_c:function(){copyItems();},key_control_shift_c:function(){copyItems(true);},key_control_e:editItems,key_control_n:function(){addItem('');},key_alt_control_n:function(){addItem('alt');},key_alt_control_shift_n:function(){addItem('alt_shift');},key_control_shift_n:function(){addItem('shift');},key_control_v:pasteItems,key_control_x:function(){cutItems();},key_control_shift_x:function(){cutItems(true);},key_delete:deleteItems,key_end:scrollToLast,key_enter:open,key_home:scrollToFirst,key_pagedown:scrollPageDown,key_pageup:scrollPageUp,key_section:preview,key_space:preview},listMargin:self.options.type=='text'?0:8,page:0,preview:false,requests:[],scrollTimeout:0,selected:[],touchSelection:[]});if(!self.isAsync){self.selected=self.options.items.map(function(item,i){return Ox.extend(item,{_index:i})}).filter(function(item){return Ox.contains(self.options.selected,item[self.options.unique]);}).map(function(item){return item['_index'];});}
self.options.max==-1&&Ox.extend(self.keyboardEvents,{key_alt_control_a:function(){that.invertSelection();},key_control_a:function(){that.selectAll();}});self.options.min==0&&Ox.extend(self.keyboardEvents,{key_control_shift_a:selectNone});self.keyboardEvents['key_'+(self.options.orientation=='vertical'?'up':'left')]=selectPrevious;self.keyboardEvents['key_'+(self.options.orientation=='vertical'?'down':'right')]=selectNext;if(self.options.max==-1){self.keyboardEvents['key_shift_'+(self.options.orientation=='vertical'?'up':'left')]=addPreviousToSelection;self.keyboardEvents['key_shift_'+(self.options.orientation=='vertical'?'down':'right')]=addNextToSelection;}
if(self.options.orientation=='vertical'){Ox.extend(self.keyboardEvents,{key_left:function(){triggerToggleEvent(false);},key_right:function(){triggerToggleEvent(true);}});}else if(self.options.orientation=='both'){Ox.extend(self.keyboardEvents,{key_down:selectBelow,key_up:selectAbove});if(self.options.max==-1){Ox.extend(self.keyboardEvents,{key_shift_down:addBelowToSelection,key_shift_up:addAboveToSelection});}
self.pageLengthByRowLength=[0,60,60,60,60,60,60,63,64,72,80,88,96,104,112,120,128,136,144,152,160,168,176,184,192];}
if(self.options.selectAsYouType){Ox.extend(self.keyboardEvents,{keys:selectAsYouType});}
that.bindEvent(self.keyboardEvents);!self.isAsync?updateItems():updateQuery();function addAboveToSelection(){var pos=getAbove();if(pos>-1){addToSelection(pos);scrollToPosition(pos);}}
function addAllToSelection(pos){var arr,i,len=self.$items.length;if(!isSelected(pos)){if(self.selected.length==0){addToSelection(pos);}else{arr=[pos];if(Ox.min(self.selected)
=0;i--){if(isSelected(i)){break;}
arr.push(i);}}
if(Ox.max(self.selected)>pos){for(i=pos+1;i-1){addToSelection(pos);scrollToPosition(pos);}}
function addItem(keys){that.triggerEvent('add',{keys:keys});}
function addNextToSelection(){var pos=getNext();if(pos>-1){addToSelection(pos);scrollToPosition(pos);}}
function addPreviousToSelection(){var pos=getPrevious();if(pos>-1){addToSelection(pos);scrollToPosition(pos);}}
function addToSelection(pos){Ox.makeArray(pos).reverse().forEach(function(pos){if(!isSelected(pos)){self.selected.unshift(pos);if(!Ox.isUndefined(self.$items[pos])){self.$items[pos].addClass('OxSelected');}}else{self.selected.splice(self.selected.indexOf(pos),1);self.selected.unshift(pos);}});triggerSelectEvent();}
function clear(){self.requests.forEach(function(request){Ox.Request.cancel(request);});Ox.extend(self,{$items:[],$pages:[],page:0,requests:[]});}
function constructEmptyPage(page){var i,$page=Ox.Element().addClass('OxPage').css(getPageCSS(page));Ox.loop(getPageLength(page),function(){Ox.ListItem({construct:self.options.construct}).appendTo($page);});return $page;}
function copyItems(add){self.options.selected.length&&that.triggerEvent('copy'+(add?'add':''),{ids:self.options.selected});}
function cutItems(add){self.options.selected.length&&that.triggerEvent('cut'+(add?'add':''),{ids:self.options.selected});}
function deleteItems(){self.options.selected.length&&that.triggerEvent('delete',{ids:self.options.selected});}
function deselect(pos){var triggerEvent=false;Ox.makeArray(pos).forEach(function(pos){if(isSelected(pos)){self.selected.splice(self.selected.indexOf(pos),1);!Ox.isUndefined(self.$items[pos])&&self.$items[pos].removeClass('OxSelected');triggerEvent=true;}});triggerEvent&&triggerSelectEvent();}
function doubleclick(data){open(isSpecialTarget(data));}
function dragstart(data){var $target=$(data.target),$parent=$target.parent();if(($target.is('.OxTarget')||$parent.is('.OxTarget')||$parent.parent().is('.OxTarget'))&&!$target.is('.OxSpecialTarget')){Ox.$body.addClass('OxDragging');self.drag={ids:self.options.selected};that.triggerEvent('draganddropstart',{event:data,ids:self.drag.ids});}}
function drag(data){self.drag&&that.triggerEvent('draganddrop',{event:data,ids:self.drag.ids});}
function dragpause(data){self.drag&&that.triggerEvent('draganddroppause',{event:data,ids:self.drag.ids});}
function dragenter(data){self.drag&&that.triggerEvent('draganddropenter',{event:data,ids:self.drag.ids});}
function dragleave(data){self.drag&&that.triggerEvent('draganddropleave',{event:data,ids:self.drag.ids});}
function dragend(data){if(self.drag){Ox.$body.removeClass('OxDragging');that.triggerEvent('draganddropend',{event:data,ids:self.drag.ids});delete self.drag;}}
function editItems(){}
function emptyFirstPage(){if(self.$pages[0]){if(self.options.type=='text'){self.$pages[0].find('.OxEmpty').each(function(){Ox.UI.getElement($(this)).remove();});}else if(self.options.orientation=='both'){that.$content.css({height:getListSize()+'px'});}}}
function fillFirstPage(){if(self.$pages[0]){if(self.options.type=='text'){var height=getHeight(),lastItemHeight=height%self.options.itemHeight||self.options.itemHeight,visibleItems=Math.ceil(height/self.options.itemHeight);if(self.listLength=self.$items.length){pos=-1;}}
return pos;}
function getHeight(){return that.height()-(!self.options.disableHorizontalScrolling&&that.$content.width()>that.width()?Ox.UI.SCROLLBAR_SIZE:0);}
function getListSize(){return Math.ceil(self.listLength/self.rowLength)*(self.options[self.options.orientation=='horizontal'?'itemWidth':'itemHeight']+self.itemMargin);}
function getNext(){var pos=-1;if(self.selected.length){pos=self.selected[0]+1;if(pos==self.$items.length){pos=-1;}}
return pos;}
function getPage(){return Math.max(Math.floor(self.options.orientation=='horizontal'?(that.scrollLeft()-self.listMargin/2)/self.pageWidth:(that.scrollTop()-self.listMargin/2)/self.pageHeight),0);}
function getPageByPosition(pos){return Math.floor(pos/self.options.pageLength);}
function getPageByScrollPosition(pos){return getPageByPosition(pos/(self.options.orientation=='vertical'?self.options.itemHeight:self.options.itemWidth));}
function getPageCSS(page){return self.options.orientation=='horizontal'?{left:(page*self.pageWidth+self.listMargin/2)+'px',top:(self.listMargin/2)+'px',width:(page-1){self.options.selected.push(id);self.selected.push(pos);}});if(self.selected.length){pos=Ox.min(self.selected);self.page=getPageByPosition(pos);}
if(!Ox.isEqual(self.options.selected,previousSelected)){that.triggerEvent('select',{ids:self.options.selected});}}else if(self.stayAtPosition){self.page=getPageByScrollPosition(self.stayAtPosition);}
that.$content.empty();loadPages(self.page,function(){scrollToPosition(pos,true);callback&&callback();});}
function getPrevious(){var pos=-1;if(self.selected.length){pos=self.selected[0]-1;}
return pos;}
function getRow(pos){return Math.floor(pos/self.rowLength);}
function getRowLength(){return self.options.orientation=='both'?Math.floor((getWidth()-self.listMargin)/(self.options.itemWidth+self.itemMargin)):1;}
function getScrollPosition(){return Math.floor(that.scrollTop()/(self.options.itemHeight+self.itemMargin))*self.rowLength;}
function getSelectedIds(callback){var ids=[],notFound=false;if(self.$items.length==0){callback(self.options.selected);}else{Ox.forEach(self.selected,function(pos){if(self.$items[pos]){ids.push(self.$items[pos].options('data')[self.options.unique]);}else{notFound=true;return false;}});if(notFound){self.options.items({keys:[self.options.unique],query:self.options.query,range:[0,self.listLength],sort:self.options.sort},function(result){var ids=[],rest=[],useRest=self.selected.length>self.listLength/2;result.data.items.forEach(function(item,i){if(isSelected(i)){ids.push(item[self.options.unique]);}else if(useRest){rest.push(item[self.options.unique]);}});useRest?callback(ids,rest):callback(ids);});}else{callback(ids);}}}
function getWidth(){return that.width()-(that.$content.height()>that.height()?Ox.UI.SCROLLBAR_SIZE:0);}
function isSelected(pos){return Ox.contains(self.selected,pos);}
function isSpecialTarget(e){var $element=$(e.target),$parent;while(!$element.is('.OxSpecialTarget')&&!$element.is('.OxPage')&&($parent=$element.parent()).length){$element=$parent;}
return $element.is('.OxSpecialTarget');}
function loadItems(){self.$pages[0].empty();self.$items=[];self.options.items.forEach(function(item,pos){var time0=+new Date();self.$items[pos]=Ox.ListItem({construct:self.options.construct,data:item,position:pos,unique:self.options.unique});isSelected(pos)&&self.$items[pos].addClass('OxSelected');self.$items[pos].appendTo(self.$pages[0]);});setTimeout(fillFirstPage,0);self.selected.length&&scrollToPosition(self.selected[0]);that.triggerEvent('init',{items:self.options.items.length});}
function loadPage(page,callback){if(page<0||page>=self.pages){!Ox.isUndefined(callback)&&callback();return;}
Ox.Log('List',that.oxid,'loadPage',page);var keys=Ox.unique(self.options.keys.concat(self.options.unique)),offset=page*self.pageLength,range=[offset,offset+getPageLength(page)];if(!Ox.isUndefined(self.$pages[page])){Ox.Log('List','fixme: unload should have made this undefined already');}
self.$pages[page]=constructEmptyPage(page);page==0&&fillFirstPage();self.$pages[page].appendTo(that.$content);self.requests.push(self.options.items({keys:keys,query:self.options.query,range:range,sort:self.options.sort},function(result){var $emptyPage=self.$pages[page];self.$pages[page]=Ox.Element().addClass('OxPage').css(getPageCSS(page));result.data.items.forEach(function(v,i){var pos=offset+i;self.$items[pos]=Ox.ListItem({construct:self.options.construct,data:v,position:pos,unique:self.options.unique});isSelected(pos)&&self.$items[pos].addClass('OxSelected');self.$items[pos].appendTo(self.$pages[page]);});page==0&&fillFirstPage();$emptyPage&&$emptyPage.remove&&$emptyPage.remove();self.$pages[page].appendTo(that.$content);!Ox.isUndefined(callback)&&callback();}));}
function loadPages(page,callback){Ox.Log('List','loadPages',page);var counter=0,fn=function(){if(++counter==3){!Ox.isUndefined(callback)&&callback();that.triggerEvent('load');}};loadPage(page,fn);loadPage(page-1,fn);loadPage(page+1,fn);}
function mousedown(data){var pos=findItemPosition(data);that.gainFocus();self.mousedownOnSelectedCell=false;if(pos>-1){if(data.metaKey){if(!isSelected(pos)&&(self.options.max==-1||self.options.max>self.selected.length)){addToSelection(pos);}else if(isSelected(pos)&&self.options.min8?1:0);}else if(position>self.drag.startPos){self.drag.stopPos=position-(offset<=8?1:0);}
if(self.drag.stopPos!=self.drag.startPos){moveItems(self.drag.startPos,self.drag.stopPos);self.drag.startPos=self.drag.stopPos;}}
function moveend(data){var ids=[];Ox.$body.removeClass('OxDragging');self.$items.forEach(function($item){$item.removeClass('OxDrag');ids.push($item.options('data')[self.options.unique]);});that.triggerEvent('move',{ids:ids});delete self.drag;}
function moveItems(startPos,stopPos){var pos=stopPos;while(self.$items[pos].is('.OxSelected')){pos=pos+(posself.$items.length-1){return;}}
self.drag.$items.forEach(function($item){$item.detach();});self.drag.$items.forEach(function($item,i){if(i==0){$item[posscroll+size){that.animate({scrollLeft:(positions[1]-size)+'px'},0);}}}else{positions[0]=(self.options.orientation=='vertical'?pos:getRow(pos))*itemHeight;positions[1]=positions[0]+itemHeight+(self.options.orientation=='vertical'?0:self.itemMargin);scroll=that.scrollTop();size=getHeight();if(positions[0]scroll+size){that.animate({scrollTop:(positions[1]-size)+'px'},0);}}}
function select(pos){if(!isSelected(pos)||self.selected.length>1){setSelected([pos]);triggerSelectEvent();self.options.centered&&scrollToPosition(pos);}}
function selectAbove(){var pos=getAbove();if(pos>-1){select(pos);scrollToPosition(pos);}}
function selectAsYouType(data){self.options.items({keys:[self.options.unique],query:{conditions:[self.options.query,{key:self.options.selectAsYouType,operator:'^',value:data.keys},],operator:'&'},range:[0,1],sort:[{key:self.options.selectAsYouType,operator:'+'}]},function(result){result.data.items.length&&that.options({selected:[result.data.items[0][self.options.unique]]});});}
function selectBelow(){var pos=getBelow();if(pos>-1){select(pos);scrollToPosition(pos);}}
function selectNext(){var pos=getNext();if(pos>-1){select(pos);scrollToPosition(pos);}else if(self.selected.length){that.triggerEvent('selectnext');}}
function selectNone(){deselect(Ox.clone(self.selected));}
function selectPrevious(){var pos=getPrevious();if(pos>-1){select(pos);scrollToPosition(pos);}else if(self.selected.length){that.triggerEvent('selectprevious');}}
function selectQuery(str){Ox.forEach(self.$items,function(v,i){if(Ox.toLatin(v.title).toUpperCase().indexOf(str)==0){select(i);scrollToPosition(i);return false;}});}
function setSelected(ids,callback){var counter=0;self.$items.forEach(function($item,pos){if(isSelected(pos)){if(!Ox.isUndefined(self.$items[pos])){self.$items[pos].removeClass('OxSelected');}}});self.selected=[];ids.forEach(function(id,i){var pos=Ox.isString(id)?getPositionById(id):id;if(pos>-1){select(pos,i);}else if(self.isAsync){self.options.items({positions:[id],query:self.options.query,sort:self.options.sort},function(result){pos=result.data.positions[id];select(pos,i);});}});function select(pos,i){self.selected.push(pos);if(!Ox.isUndefined(self.$items[pos])){self.$items[pos].addClass('OxSelected');}
i==0&&scrollToPosition(pos);++counter==ids.length&&callback&&callback();}}
function singleclick(data){var pos=findItemPosition(data),$cell,clickable,editable;if(pos>-1){if(!data.metaKey&&!data.shiftKey&&isSelected(pos)&&self.selected.length>1){select(pos);}else if(self.mousedownOnSelectedCell){$cell=findCell(data);if($cell){clickable=$cell.is('.OxClickable');editable=$cell.is('.OxEditable')&&!$cell.is('.OxEdit');if(clickable||editable){triggerClickEvent(clickable?'click':'edit',self.$items[pos],$cell);}}}}}
function toggleSelection(pos){if(!isSelected(pos)){addToSelection(pos);}else{deselect(pos);}}
function triggerClickEvent(event,$item,$cell){var key;if($cell){key=$cell.attr('class').split('OxColumn')[1].split(' ')[0];key=key[0].toLowerCase()+key.slice(1);}
that.triggerEvent(event,Ox.extend({id:$item.data('id')},key?{key:key}:{}));}
var triggerSelectEvent=Ox.debounce(function(){getSelectedIds(function(ids,rest){self.options.selected=ids;that.triggerEvent('select',Ox.extend({ids:ids},rest?{rest:rest}:{}));if(self.preview){if(ids.length){that.triggerEvent('openpreview',{ids:ids});}else{that.triggerEvent('closepreview');}}});},true);function triggerToggleEvent(expanded){that.triggerEvent('toggle',{expanded:expanded,ids:self.options.selected});}
function unloadPage(page){if(page<0||page>=self.pages){return;}
if(!Ox.isUndefined(self.$pages[page])){self.$pages[page].remove();delete self.$pages[page];}}
function unloadPages(page){unloadPage(page);unloadPage(page-1);unloadPage(page+1)}
function updateDraggable(){that.$content[self.options.draggable?'bindEvent':'unbindEvent']({dragstart:dragstart,drag:drag,dragpause:dragpause,dragenter:dragenter,dragleave:dragleave,dragend:dragend});}
function updateItems(){clear();that.$content.empty();self.$pages=[];self.$pages[0]=Ox.Element().addClass('OxPage').css({left:self.listMargin/2+'px',top:self.listMargin/2+'px'}).appendTo(that.$content);self.listLength=self.options.items.length;loadItems();}
function updatePages(pos,scroll){clear();self.pageLength=self.pageLengthByRowLength[self.rowLength]
Ox.extend(self,{listSize:getListSize(),pages:Math.ceil(self.listLength/self.pageLength),pageWidth:(self.options.itemWidth+self.itemMargin)*self.rowLength,pageHeight:getPageHeight()});that.$content.css({height:self.listSize+'px'});self.page=getPageByPosition(pos);that.$content.empty();loadPages(self.page,function(){scrollTo(scroll);});}
function updatePositions(){self.$items.forEach(function($item,pos){$item.options({position:pos});});}
function updateQuery(callback){var data;self.requests.push(data=self.options.items({query:self.options.query},function(result){var keys={};setTimeout(function(){clear();that.triggerEvent('init',Ox.extend(result.data,data&&data.query?{query:data.query}:{}));self.rowLength=getRowLength();self.pageLength=self.options.orientation=='both'?self.pageLengthByRowLength[self.rowLength]:self.options.pageLength;Ox.extend(self,{listLength:result.data.items,pages:Math.max(Math.ceil(result.data.items/self.pageLength),1),pageWidth:self.options.orientation=='vertical'?0:(self.options.itemWidth+self.itemMargin)*(self.options.orientation=='horizontal'?self.pageLength:self.rowLength),pageHeight:self.options.orientation=='horizontal'?0:Math.ceil(self.pageLength*(self.options.itemHeight+self.itemMargin)/self.rowLength)});self.listSize=getListSize();that.$content.css(self.options.orientation=='horizontal'?'width':'height',self.listSize+'px');getPositions(callback);});}));}
function updateSelected(){getSelectedIds(function(oldIds){var newIds=[];Ox.forEach(self.options.items,function(item){if(Ox.contains(oldIds,item.id)){newIds.push(item.id);}
if(newIds.length==oldIds.length){return false;}});setSelected(newIds);});}
function updateSort(){var length=self.options.sort.length,operator=[],sort=[];if(!self.isAsync){getSelectedIds(function(selectedIds){self.options.sort.forEach(function(v,i){operator.push(v.operator);sort.push({});self.options.items.forEach(function(item){sort[i][item.id]=v.map?v.map(item[v.key],item):item[v.key]});});self.options.items.sort(function(a,b){var aValue,bValue,index=0,ret=0;while(ret==0&&indexbValue){ret=operator[index]=='+'?1:-1;}else{index++;}}
return ret;});if(selectedIds.length){self.selected=[];self.options.items.forEach(function(item,i){if(Ox.contains(selectedIds,item.id)){self.selected.push(i);}});}
loadItems();});}else{clear();getPositions();}}
function updateSortable(){that.$content[self.options.sortable?'bindEvent':'unbindEvent']({dragstart:movestart,drag:move,dragend:moveend});}
that.addItems=function(pos,items){if(arguments.length==1){items=pos;pos=self.listLength;}
var $items=[],length=items.length;self.selected.forEach(function(v,i){if(v>=pos){self.selected[i]+=length;}});items.forEach(function(item,i){var $item;$items.push($item=Ox.ListItem({construct:self.options.construct,data:item,position:pos+i,unique:self.options.unique}));if(i==0){if(pos==0){$item.insertBefore(self.$items[0]);}else{$item.insertAfter(self.$items[pos-1]);}}else{$item.insertAfter($items[i-1]);}});self.options.items.splice.apply(self.options.items,[pos,0].concat(items));self.$items.splice.apply(self.$items,[pos,0].concat($items));self.listLength=self.options.items.length;updatePositions();emptyFirstPage();fillFirstPage();};that.closePreview=function(){self.preview=false;that.triggerEvent('closepreview');return that;};that.clearCache=function(){self.$pages=[];return that;};that.getPasteIndex=function(){return self.selected.length?Ox.max(self.selected)+1:self.items.length;};that.invertSelection=function(){var arr=Ox.range(self.listLength).filter(function(pos){return!isSelected(pos);});setSelected(arr);triggerSelectEvent();return that;};that.openPreview=function(){self.preview=true;that.triggerEvent('openpreview',{ids:self.options.selected});return that;};that.reloadList=function(stayAtPosition){var scrollTop=that.scrollTop();if(!self.isAsync){loadItems();scrollList();}else{updateQuery(scrollList);}
function scrollList(){stayAtPosition&&that.scrollTop(scrollTop);}
return that;};that.reloadPages=function(){var page,scrollLeft,scrollTop;if(!self.isAsync){scrollLeft=that.scrollLeft();scrollTop=that.scrollTop();loadItems();that.scrollLeft(scrollLeft).scrollTop(scrollTop);}else{page=self.page;clear();self.page=page
that.$content.empty();loadPages(self.page);}
return that;};that.removeItems=function(pos,length){Ox.Log('List','removeItems',pos,length)
if(Ox.isUndefined(length)){pos.forEach(function(id){var p=getPositionById(id);that.removeItems(p,1);});}else{Ox.range(pos,pos+length).forEach(function(i){isSelected(i)&&deselect(i);self.$items[i].remove();});self.options.items.splice(pos,length);self.$items.splice(pos,length);self.selected.forEach(function(v,i){if(v>=pos+length){self.selected[i]-=length;}});self.listLength=self.options.items.length;updatePositions();}
emptyFirstPage();fillFirstPage();};that.scrollToSelection=function(){self.selected.length&&scrollToPosition(self.selected[0]);return that;};that.selectAll=function(){addToSelection(Ox.range(self.listLength));return that;};that.selectPosition=function(pos){select(pos);return that;};that.selectSelected=function(offset){var pos,positions;if(self.selected.length>1){positions=Ox.sort(Ox.clone(self.selected));pos=positions[Ox.mod(positions.indexOf(self.selected[0])+offset,positions.length)];addToSelection(pos);scrollToPosition(pos);}
return that;};that.size=function(){if(self.options.orientation=='both'){var rowLength=getRowLength(),pageLength=self.pageLengthByRowLength[rowLength],pos=getScrollPosition(),scroll=that.scrollTop()/self.listSize;if(pageLength!=self.pageLength){self.pageLength=pageLength;self.rowLength=rowLength;updatePages(pos,scroll);}else if(rowLength!=self.rowLength){self.rowLength=rowLength;self.pageWidth=(self.options.itemWidth+self.itemMargin)*self.rowLength;self.listSize=getListSize();self.pageHeight=getPageHeight();self.$pages.forEach(function($page,i){!Ox.isUndefined($page)&&$page.css({width:self.pageWidth+'px',top:(i*self.pageHeight+self.listMargin/2)+'px'});});that.$content.css({height:self.listSize+'px'});scrollTo(scroll);}
emptyFirstPage();fillFirstPage();}else if(self.options.type=='text'){emptyFirstPage();fillFirstPage();}
return that;};that.sort=function(){updateSort();};that.sortList=function(key,operator,map){if(key!=self.options.sort[0].key||operator!=self.options.sort[0].operator){self.options.sort[0]={key:key,operator:operator,map:map};updateSort();that.triggerEvent('sort',self.options.sort[0]);}
return that;};that.value=function(){var args=Ox.slice(arguments),id=args.shift(),pos=Ox.isNumber(id)?id:getPositionById(id),$item=self.$items[pos],data=$item?$item.options('data'):{},updateItems=false;if(arguments.length==1){return data;}else if(arguments.length==2&&Ox.isString(arguments[1])){return data[arguments[1]];}else if($item){Ox.forEach(Ox.makeObject(args),function(value,key){if(key==self.options.unique){self.options.selected=self.options.selected.map(function(id_){return id_==data[key]?value:id_});}
if(!self.isAsync){self.options.items[pos][key]=value;}else if(self.items){self.items[Ox.getIndex(self.items,self.options.unique,id)][key]=value;updateItems=true;}
data[key]=value;});$item.options({data:data});if(updateItems){self.options.items.update(self.items);}
return that;}};return that;};'use strict';Ox.ListItem=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({construct:null,data:{},draggable:false,position:0,unique:''}).options(options||{}).update({data:function(){if(!that.find('.OxEdit').length){constructItem(true);}},position:function(){that.data({position:self.options.position});}});constructItem();function constructItem(update){var $element=self.options.construct(self.options.data).addClass('OxItem').data({id:self.options.data[self.options.unique],position:self.options.position});if(update){that.hasClass('OxSelected')&&$element.addClass('OxSelected');}
that.setElement($element);}
return that;};'use strict';Ox.SortList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({items:[],scrollbarVisible:false}).options(options||{}).update({items:function(){self.items=getItems();self.$list.reloadList();that.triggerEvent('sort',{ids:self.items.map(function(item){return item.id;})});}});self.items=getItems();self.$list=Ox.TableList({columns:[{id:'title',visible:true}],items:self.items,max:1,scrollbarVisible:self.options.scrollbarVisible,sort:[{key:'position',operator:'+'}],sortable:true,unique:'id'}).bindEvent({move:function(data){self.options.items.sort(function(a,b){return data.ids.indexOf(a.id)-data.ids.indexOf(b.id);});that.triggerEvent('sort',data);}});function getItems(){return self.options.items.map(function(item,position){return{id:item.id,title:item.title,position:position};});}
that.setElement(self.$list);return that;};'use strict';Ox.TableList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({clearButton:false,clearButtonTooltip:'',columns:[],columnsMovable:false,columnsRemovable:false,columnsResizable:false,columnsVisible:false,columnWidth:[40,800],disableHorizontalScrolling:false,draggable:false,droppable:false,id:'',items:null,keys:[],max:-1,min:0,pageLength:100,query:{conditions:[],operator:'&'},scrollbarVisible:false,selected:[],sort:[],sortable:false,sums:[],unique:''}).options(options||{}).update({disableHorizontalScrolling:function(){self.options.disableHorizontalScrolling?disableHorizontalScrolling():enableHorizontalScrolling();},draggable:function(){that.$body.options({sortable:self.options.draggable});},items:function(){that.$body.options({items:self.options.items});},paste:function(){that.$body.options({paste:self.options.paste});},query:function(){that.$body.options({query:self.options.query});},selected:function(){that.$body.options({selected:self.options.selected});updateClearButton();},sort:function(){updateColumn();that.$body.options({sort:self.options.sort});},sortable:function(){that.$body.options({sortable:self.options.sortable});}}).addClass('OxTableList');self.options.columns.forEach(function(column){if(Ox.isUndefined(column.align)){column.align='left';}
if(Ox.isUndefined(column.clickable)){column.clickable=false;}
if(Ox.isUndefined(column.editable)){column.editable=false;}
if(Ox.isUndefined(column.unique)){column.unique=false;}
if(Ox.isUndefined(column.visible)){column.visible=false;}
if(column.unique&&!self.options.unique){self.options.unique=column.id;}});if(Ox.isEmpty(self.options.sort)){self.options.sort=[{key:self.options.unique,operator:Ox.getObjectById(self.options.columns,self.options.unique).operator}];}else{self.options.sort=self.options.sort.map(function(sort){return Ox.isString(sort)?{key:sort.replace(/^[\+\-]/,''),operator:sort[0]=='-'?'-':'+'}:sort;});}
Ox.extend(self,{columnPositions:[],defaultColumnWidths:self.options.columns.map(function(column){return column.defaultWidth||column.width;}),hasItemsArray:Ox.isArray(self.options.items),itemHeight:16,page:0,pageLength:100,scrollLeft:0,selectedColumn:getColumnIndexById(self.options.sort[0].key),visibleColumns:self.options.columns.filter(function(column){return column.visible;})});self.options.columns.forEach(function(column){if(!Ox.isUndefined(column.position)){self.visibleColumns[column.position]=column;}});Ox.extend(self,{columnWidths:self.visibleColumns.map(function(column){return column.width;}),pageHeight:self.options.pageLength*self.itemHeight});self.format={};self.map={};self.options.columns.forEach(function(column){if(column.format){self.format[column.id]=column.format;}
if(column.sort){self.map[column.id]=column.sort;}});if(self.options.columnsVisible){that.$bar=Ox.Bar({orientation:'horizontal',size:16}).appendTo(that);that.$head=Ox.Container().addClass('OxHead').css({right:self.options.scrollbarVisible?Math.max(Ox.UI.SCROLLBAR_SIZE,8)+'px':0}).appendTo(that.$bar);that.$head.$content.addClass('OxTitles');constructHead();if(self.options.columnsRemovable){that.$select=Ox.Select({id:self.options.id+'SelectColumns',items:self.options.columns.filter(function(column){return column.addable!==false;}).map(function(column){return{disabled:column.removable===false,id:column.id,title:column.title};}),max:-1,min:1,type:'image',value:Ox.filter(self.options.columns,function(column){return column.visible;}).map(function(column){return column.id;})}).css(Ox.UI.SCROLLBAR_SIZE==16?{right:0,width:'14px'}:{right:'-1px',width:'8px',}).bindEvent('change',changeColumns).appendTo(that.$bar);Ox.UI.SCROLLBAR_SIZE<16&&$(that.$select.find('input')[0]).css({marginRight:'-3px',marginTop:'1px',width:'8px',height:'8px'});}else if(self.options.clearButton){self.$clearButton=Ox.Element({element:' ',tooltip:self.options.clearButtonTooltip}).addClass('OxClear').attr({src:Ox.UI.getImageURL('symbolClose')}).css(Ox.UI.SCROLLBAR_SIZE==16?{paddingLeft:'4px',paddingRight:'2px',marginRight:0}:{paddingRight:'1px',marginRight:'-2px'})
[self.options.selected.length?'show':'hide']().bindEvent({anyclick:function(){self.$clearButton.hide();self.options.selected=[];that.$body.options({selected:self.options.selected});that.triggerEvent('select',{ids:[]});}}).appendTo(that.$bar);}}
that.$body=Ox.List({construct:constructItem,disableHorizontalScrolling:self.options.disableHorizontalScrolling,draggable:self.options.draggable,id:self.options.id,itemHeight:16,items:self.options.items,itemWidth:getItemWidth(),format:self.format,keys:Ox.unique((self.hasItemsArray?self.options.columns:self.visibleColumns).map(function(column){return column.id;}).concat(self.options.unique).concat(self.options.keys)),map:self.map,max:self.options.max,min:self.options.min,orientation:'vertical',pageLength:self.options.pageLength,paste:self.options.paste,query:self.options.query,selectAsYouType:self.options.selectAsYouType,selected:self.options.selected,sort:self.options.sort,sortable:self.options.sortable,sums:self.options.sums,type:'text',unique:self.options.unique}).addClass('OxBody').css({top:(self.options.columnsVisible?16:0)+'px',overflowY:(self.options.scrollbarVisible?'scroll':'hidden')}).on({scroll:function(){var scrollLeft=$(this).scrollLeft();if(scrollLeft!=self.scrollLeft){self.scrollLeft=scrollLeft;that.$head&&that.$head.scrollLeft(scrollLeft);}}}).bindEvent(function(data,event){if(event=='cancel'){Ox.Log('List','cancel edit',data);}else if(event=='edit'){that.editCell(data.id,data.key);}else if(event=='select'){self.options.selected=data.ids;updateClearButton();}
that.triggerEvent(event,data);}).appendTo(that);that.$body.$content.css({width:getItemWidth()+'px'});self.options.disableHorizontalScrolling?disableHorizontalScrolling():enableHorizontalScrolling();function addColumn(id){var column,ids,index=0;Ox.forEach(self.options.columns,function(v){if(v.visible){index++;}else if(v.id==id){column=v;return false;}});column.visible=true;self.visibleColumns.splice(index,0,column);self.columnWidths.splice(index,0,column.width);that.$head.$content.empty();constructHead();!self.hasItemsArray&&that.$body.options({keys:self.visibleColumns.map(function(column){return column.id;}).concat(self.options.keys)});that.$body.reloadPages();}
function changeColumns(data){var add,ids=[];Ox.forEach(data.value,function(id){var index=getColumnIndexById(id);if(!self.options.columns[index].visible){addColumn(id);add=true;return false;}
ids.push(id);});if(!add){Ox.forEach(self.visibleColumns,function(column){if(ids.indexOf(column.id)==-1){removeColumn(column.id);return false;}});}
triggerColumnChangeEvent();}
function clickColumn(id){Ox.Log('List','clickColumn',id);var i=getColumnIndexById(id),isSelected=self.options.sort[0].key==self.options.columns[i].id;self.options.sort=[{key:self.options.columns[i].id,operator:isSelected?(self.options.sort[0].operator=='+'?'-':'+'):self.options.columns[i].operator}];updateColumn();setTimeout(function(){that.$body.options({sort:self.options.sort});that.gainFocus().triggerEvent('sort',{key:self.options.sort[0].key,operator:self.options.sort[0].operator});},10);}
function constructHead(){var pos;self.$heads=[];self.$titles=[];self.$titleImages=[];self.$orderImages=[];self.visibleColumns.forEach(function(column,i){var $resize;self.$heads[i]=Ox.Element().addClass('OxHeadCell '+getColumnClassName(column.id)).css({width:self.columnWidths[i]-5+'px'}).appendTo(that.$head.$content);if(column.operator){self.$heads[i].bindEvent({anyclick:function(){clickColumn(column.id);}});}
if(self.options.columnsMovable){self.$heads[i].bindEvent({dragstart:function(data){dragstartColumn(column.id,data);},drag:function(data){dragColumn(column.id,data);},dragpause:function(data){dragpauseColumn(column.id,data);},dragend:function(data){dragendColumn(column.id,data);}});}
self.$titles[i]=Ox.Element().addClass('OxTitle').css({width:self.columnWidths[i]-9+'px',textAlign:column.align}).appendTo(self.$heads[i]);if(column.titleImage){self.$titleImages[i]=$(' ').attr({src:Ox.UI.getImageURL('symbol'+Ox.toTitleCase(column.titleImage))}).appendTo(self.$titles[i]);}else{self.$titles[i].html(column.title);}
if(column.operator){self.$orderImages[i]=$(' ').attr({src:Ox.UI.getImageURL('symbol'+(column.operator=='+'?'Up':'Down'),'selected')}).addClass('OxOrder').css({marginTop:(column.operator=='+'?3:2)+'px'}).click(function(){$(this).parent().trigger('click');}).appendTo(self.$heads[i]);}
$resize=Ox.Element().addClass('OxResize').appendTo(that.$head.$content);$('').appendTo($resize);$('
').addClass('OxCenter').appendTo($resize);$('
').appendTo($resize);if(self.options.columnsResizable&&column.resizable!==false){$resize.addClass('OxResizable').bindEvent({doubleclick:function(data){resetColumn(column.id,data);},dragstart:function(data){dragstartResize(column.id,data);},drag:function(data){dragResize(column.id,data);},dragend:function(data){dragendResize(column.id,data);}});}});that.$head.$content.css({width:(Ox.sum(self.columnWidths)+2)+'px'});pos=getColumnPositionById(self.options.columns[self.selectedColumn].id);if(pos>-1){toggleSelected(self.options.columns[self.selectedColumn].id);self.$titles[pos].css({width:(self.options.columns[self.selectedColumn].width-25)+'px'});}}
function constructItem(data){var $item=$('
').addClass('OxTarget').css({width:getItemWidth(true)+'px'});self.visibleColumns.forEach(function(v,i){var clickable=Ox.isBoolean(v.clickable)?v.clickable:v.clickable(data),editable=Ox.isBoolean(v.editable)?v.editable:v.editable(data),value=v.id in data?formatValue(v.id,data[v.id],data):'',$cell;if(v.tooltip){$cell=Ox.Element({tooltip:function(){return self.options.selected.indexOf(data[self.options.unique])>-1?(Ox.isString(v.tooltip)?v.tooltip:v.tooltip(data)):'';}});}else if(self.options.droppable){$cell=Ox.Element();}else{$cell=$('
');}
$cell.addClass('OxCell '+getColumnClassName(v.id)
+(clickable?' OxClickable':'')
+(editable?' OxEditable':'')).css({width:(self.columnWidths[i]-(self.options.columnsVisible?9:8))+'px',borderRightWidth:(self.options.columnsVisible?1:0)+'px',textAlign:v.align})
[Ox.isString(value)?'html':'append'](value).appendTo($item);});return $item;}
function disableHorizontalScrolling(){that.$body.options({disableHorizontalScrolling:true}).css({overflowX:'hidden'});that.unbindEvent('key_left').unbindEvent('key_right');}
function dragstartColumn(id,e){Ox.$body.addClass('OxDragging');self.drag={columnOffsets:getColumnOffsets(),listOffset:that.offset().left-that.$body.scrollLeft(),startPos:getColumnPositionById(id)}
self.drag.stopPos=self.drag.startPos;$('.'+getColumnClassName(id)).css({opacity:0.5});self.drag.startPos>0&&self.$heads[self.drag.startPos].prev().children().eq(2).css({opacity:0.5});self.$heads[self.drag.startPos].next().children().eq(0).css({opacity:0.5});self.$heads[self.drag.startPos].addClass('OxDrag').css({cursor:'ew-resize'});}
function dragColumn(id,e){var listLeft=that.offset().left,listRight=listLeft+that.width(),pos=self.drag.stopPos;Ox.forEach(self.drag.columnOffsets,function(offset,i){var x=self.drag.listOffset+offset+self.columnWidths[i]/2;if(i
self.drag.startPos&&e.clientX>x){self.drag.stopPos=i;}});if(self.drag.stopPos!=pos){moveColumn(id,self.drag.stopPos);self.drag.columnOffsets=getColumnOffsets();self.drag.startPos=self.drag.stopPos;var left=self.drag.columnOffsets[self.drag.startPos],right=left+self.columnWidths[self.drag.startPos];if(leftthat.width()){that.$body.scrollLeft(leftlistRight-16){if(!self.scrollInterval){self.scrollInterval=setInterval(function(){that.$body.scrollLeft(that.$body.scrollLeft()+(e.clientX-1){that.find('.OxResize .OxSelected').removeClass('OxSelected');pos>0&&self.$heads[pos].prev().children().eq(2).addClass('OxSelected');self.$heads[pos].next().children().eq(0).addClass('OxSelected');if(pos==stopPos){pos>0&&self.$heads[pos].prev().children().eq(2).css({opacity:0.5});self.$heads[pos].next().children().eq(0).css({opacity:0.5});}}}
function removeColumn(id){var index=getColumnIndexById(id),itemWidth,position=getColumnPositionById(id),selector='.'+getColumnClassName(id),$column=$('.OxHeadCell '+selector),$order=$column.next(),$resize=$order.next();self.options.columns[index].visible=false;self.visibleColumns.splice(position,1);self.columnWidths.splice(position,1);that.$head.$content.empty();constructHead();itemWidth=getItemWidth();that.$body.find('.OxItem').each(function(){var $this=$(this);$this.children(selector).remove();$this.css({width:itemWidth+'px'});});that.$body.$content.css({width:itemWidth+'px'});!self.hasItemsArray&&that.$body.options({keys:self.visibleColumns.map(function(column){return column.id;}).concat(self.options.keys)});}
function resetColumn(id){var width=self.defaultColumnWidths[getColumnIndexById(id)];resizeColumn(id,width);that.triggerEvent('columnresize',{id:id,width:width});}
function resizeColumn(id,width){var i=getColumnIndexById(id),pos=getColumnPositionById(id);self.options.columns[i].width=width;self.columnWidths[pos]=width;if(self.options.columnsVisible){that.$head.$content.css({width:(Ox.sum(self.columnWidths)+2)+'px'});self.$heads[pos].css({width:width-5+'px'});self.$titles[pos].css({width:width-9-(i==self.selectedColumn?16:0)+'px'});}
that.find('.OxCell.'+getColumnClassName(self.options.columns[i].id)).css({width:width-(self.options.columnsVisible?9:8)+'px'});setWidth();}
function setWidth(){var width=getItemWidth();that.$body.find('.OxItem').css({width:width+'px'});that.$body.$content.css({width:width+'px'});}
function toggleSelected(id){var isSelected,pos=getColumnPositionById(id);if(pos>-1){updateOrder(id);pos>0&&self.$heads[pos].prev().children().eq(2).toggleClass('OxSelected');self.$heads[pos].toggleClass('OxSelected');self.$heads[pos].next().children().eq(0).toggleClass('OxSelected');isSelected=self.$heads[pos].hasClass('OxSelected');self.$titles[pos].css({width:self.$titles[pos].width()
+(isSelected?-16:16)
+'px'});if(self.visibleColumns[pos].titleImage){self.$titleImages[pos].attr({src:Ox.UI.getImageURL('symbol'+Ox.toTitleCase(self.visibleColumns[pos].titleImage),isSelected?'selected':'')});}}}
function triggerColumnChangeEvent(){that.triggerEvent('columnchange',{ids:self.visibleColumns.map(function(column){return column.id;})});}
function updateClearButton(){if(self.options.clearButton){self.$clearButton[self.options.selected.length?'show':'hide']();}}
function updateColumn(){var columnId=self.options.columns[self.selectedColumn].id,isSelected=columnId==self.options.sort[0].key;if(self.options.columnsVisible){if(isSelected){updateOrder(columnId);}else{toggleSelected(columnId);self.selectedColumn=getColumnIndexById(self.options.sort[0].key);toggleSelected(self.options.columns[self.selectedColumn].id);}}}
function updateImages(){that.$body.find('img').each(function(i,element){var $element=$(element),data=Ox.UI.getImageData($element.attr('src'));if(data&&data.color=='selected'){$element.attr({src:Ox.UI.getImageURL(data.name,'default')});}});that.$body.find('.OxSelected img').each(function(i,element){var $element=$(element),data=Ox.UI.getImageData($element.attr('src'));if(data&&data.color=='default'){$element.attr({src:Ox.UI.getImageURL(data.name,'selected')});}});}
function updateOrder(id){var operator=self.options.sort[0].operator,pos=getColumnPositionById(id);if(pos>-1){self.$orderImages[pos].attr({src:Ox.UI.getImageURL('symbol'+(operator=='+'?'Up':'Down'),'selected')}).css({marginTop:(operator=='+'?3:2)+'px'});}}
that.addColumn=function(id){addColumn(id);};that.addItems=function(items){that.$body.addItems(items);};that.api=that.$body.options('items');that.closePreview=function(){that.$body.closePreview();return that;};that.editCell=function(id,key,select){Ox.Log('List','editCell',id,key)
var $item=getItem(id),$cell=getCell(id,key),$input,html=$cell.html(),clickableCells=$item.find('.OxClickable').removeClass('OxClickable'),editableCells=$item.find('.OxEditable').removeClass('OxEditable'),index=getColumnIndexById(key),column=self.options.columns[index],width=column.width-self.options.columnsVisible;$cell.empty().addClass('OxEdit').css({width:width+'px'});$input=Ox.Input({autovalidate:column.input?column.input.autovalidate:null,style:'square',textAlign:column.align||'left',value:column.unformat?column.unformat(html):html,width:width-2}).css({padding:'0 1px'}).on({mousedown:function(e){e.stopPropagation();}}).bindEvent({blur:submit,cancel:submit,submit:submit}).appendTo($cell);setTimeout(function(){$input.focusInput(select);});function submit(){var value=$input.value();$input.remove();$cell.removeClass('OxEdit').css({width:(width-8)+'px'}).html(value);setTimeout(function(){clickableCells.addClass('OxClickable');editableCells.addClass('OxEditable');},250);that.triggerEvent('submit',{id:id,key:key,value:value});}};that.gainFocus=function(){that.$body.gainFocus();return that;};that.getColumnWidth=function(id){var pos=getColumnPositionById(id);return self.columnWidths[pos];};that.getPasteIndex=function(){return that.$body.getPasteIndex();};that.getVisibleColumns=function(){return self.visibleColumns.map(function(column){return column.id;});};that.hasFocus=function(){return that.$body.hasFocus();};that.invertSelection=function(){that.$body.invertSelection();return that;};that.loseFocus=function(){that.$body.loseFocus();return that;};that.openPreview=function(){that.$body.openPreview();return that;};that.reloadList=function(stayAtPosition){that.$body.reloadList(stayAtPosition);return that;};that.removeColumn=function(id){removeColumn(id);return that;};that.selectAll=function(){that.$body.selectAll();return that;};that.selectPosition=function(pos){that.$body.selectPosition(pos);return that;};that.selectSelected=function(offset){that.$body.selectSelected(offset);return that;};that.setColumnTitle=function(id,title){var index=getColumnIndexById(id);self.options.columns[index].title=title;if(self.options.columns[index].visible){self.$titles[getColumnPositionById(id)].html(title);}
return that;};that.setColumnWidth=that.resizeColumn=function(id,width){resizeColumn(id,width);return that;};that.setVisibleColumns=function(ids){Ox.forEach(ids,function(id){var index=getColumnIndexById(id);if(!self.options.columns[index].visible){addColumn(id);}});Ox.forEach(self.visibleColumns,function(column){if(ids.indexOf(column.id)==-1){removeColumn(column.id);}});triggerColumnChangeEvent();return that;};that.size=function(){setWidth();that.$body.size();return that;};that.sortList=function(key,operator){Ox.Log('List','$$$$ DEPRECATED $$$$')
var isSelected=key==self.options.sort[0].key;self.options.sort=[{key:key,operator:operator,map:self.options.columns[self.selectedColumn].sort}];if(self.options.columnsVisible){if(isSelected){updateOrder(self.options.columns[self.selectedColumn].id);}else{toggleSelected(self.options.columns[self.selectedColumn].id);self.selectedColumn=getColumnIndexById(key);toggleSelected(self.options.columns[self.selectedColumn].id);}}
setTimeout(function(){that.$body.options({sort:self.options.sort});},10);return that;};that.value=function(){var $cell,args=Ox.slice(arguments),id=args.shift(),sort=false;if(arguments.length==1){return that.$body.value(id);}else if(arguments.length==2&&Ox.isString(arguments[1])){return that.$body.value(id,arguments[1]);}else{that.$body.value(id,Ox.makeObject(args));Ox.forEach(Ox.makeObject(args),function(value,key){var changed=false;if(key==self.options.unique){self.options.selected=self.options.selected.map(function(id_){return id_==id?value:id_});id=value;}
$cell=getItem(id)&&getCell(id,key);if($cell&&!$cell.is('.OxEdit')){var value=formatValue(key,value,that.$body.value(id));if(value!=$cell.html()){$cell.html(value);changed=true;}}
if(changed&&!self.options.sortable&&key==self.options.sort[0].key){sort=true;}});sort&&that.$body.sort();return that;}};return that;};'use strict';Ox.TreeList=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({data:null,expanded:false,icon:null,items:[],max:1,min:0,selected:[],width:'auto'}).options(options||{}).update({data:function(){self.options.items=getItems();self.$list.options({items:parseItems()});},selected:function(){selectItem({ids:self.options.selected});self.$list.scrollToSelection();},width:function(){}});if(self.options.data){self.options.items=getItems();}
that.setElement(self.$list=Ox.List({_tree:true,construct:constructItem,itemHeight:16,items:parseItems(),itemWidth:self.options.width,keys:['expanded','id','items','level','title'],max:self.options.max,min:self.options.min,unique:'id'}).addClass('OxTableList OxTreeList').css({width:self.options.width+'px',overflowY:'scroll'}).bindEvent(function(data,event){if(event=='anyclick'){clickItem(data);}else if(event=='toggle'){toggleItems(data);}
that.triggerEvent(event,data);}));self.options.selected.length&&selectItem({ids:self.options.selected});function clickItem(e){var $target=$(e.target),$item,id,item;if($target.is('.OxToggle')){$item=$target.parent().parent();id=$item.data('id');item=getItemById(id);toggleItem(item,!item.expanded);}}
function constructItem(data){var $item=$('').css({width:self.options.width=='auto'?'100%':self.options.width-Ox.UI.SCROLLBAR_SIZE+'px'}),$cell=$('
').addClass('OxCell').css({width:'8px'}),$icon=data.id?getIcon(data.id,data.expanded||(data.items?false:null)):null,padding=data.level*16-8;if(data.level){$('
').addClass('OxCell OxTarget').css({width:padding+'px'}).appendTo($item);}
$cell.appendTo($item);$icon&&$icon.addClass(data.items?'OxToggle':'OxTarget').appendTo($cell);$('
').addClass('OxCell OxTarget').css({width:self.options.width-padding-32-Ox.UI.SCROLLBAR_SIZE+'px'}).html(data.title||'').appendTo($item);return $item;}
function getIcon(id,expanded){var isFunction=Ox.isFunction(self.options.icon),$icon=isFunction?self.options.icon(id,expanded):null;if(!$icon){if(expanded===null){if(!$icon&&self.options.icon&&!isFunction){$icon=$('
').attr({src:self.options.icon});}}else{$icon=$('
').attr({src:Ox.UI.getImageURL('symbol'+(expanded?'Down':'Right'))});}}
return $icon;}
function getItemById(id,items,level){var ret=null;items=items||self.options.items;level=level||0;Ox.forEach(items,function(item){if(item.id==id){ret=Ox.extend(item,{level:level});return false;}
if(item.items){ret=getItemById(id,item.items,level+1);if(ret){return false;}}});return ret;}
function getItems(){var items=[];Ox.sort(Object.keys(self.options.data)).forEach(function(key){items.push(parseData(key,self.options.data[key]));});return items;}
function getParent(id,items){var ret;Ox.forEach(items,function(item){if(item.items){if(Ox.getObjectById(item.items,id)){ret=item.id;}else{ret=getParent(id,item.items);}
if(ret){return false;}}});return ret;}
function parseData(key,value){var ret={id:Ox.uid().toString(),title:Ox.encodeHTMLEntities(key.toString())+': '},type=Ox.typeOf(value);if(type=='array'||type=='object'){ret.expanded=self.options.expanded;ret.title+=Ox.toTitleCase(type)
+'
['+Ox.len(value)+'] ';ret.items=type=='array'?value.map(function(v,i){return parseData(i,v);}):Ox.sort(Object.keys(value)).map(function(k){return parseData(k,value[k]);});}else{ret.title+=(type=='function'?value.toString().split('{')[0]:Ox.encodeHTMLEntities(JSON.stringify(value)).replace(/(^"|"$)/g,'
" '));}
return ret;}
function parseItems(items,level){var ret=[];items=items||self.options.items;level=level||0;items.forEach(function(item,i){if(item.items&&self.options.expanded){item.expanded=true;}
var item_=Ox.extend({level:level},item,item.items?{items:item.expanded?parseItems(item.items,level+1):[]}:{});ret.push(item_);if(item.items){ret=ret.concat(item_.items);}});return ret;}
function selectItem(data){var id=data.ids[0],parent=id,parents=[];while(parent=getParent(parent,self.options.items)){parents.push(parent);}
parents=parents.reverse();toggleItems({expanded:true,ids:parents});self.$list.options({selected:data.ids})}
function toggleItem(item,expanded){var $img,pos;item.expanded=expanded;that.find('.OxItem').each(function(){var $item=$(this);if($item.data('id')==item.id){$img=$item.find('.OxToggle');pos=$item.data('position');return false;}});$img.attr({src:getIcon(item.id,expanded).attr('src')});if(expanded){self.$list.addItems(pos+1,parseItems(item.items,item.level+1));}else{self.$list.removeItems(pos+1,parseItems(item.items,item.level+1).length);}}
function toggleItems(data){data.ids.forEach(function(id,i){var item=getItemById(id);if(item.items&&data.expanded!=!!item.expanded){toggleItem(item,data.expanded);}});}
that.gainFocus=function(){self.$list.gainFocus();return that;};that.hasFocus=function(){return self.$list.hasFocus();};that.loseFocus=function(){self.$list.loseFocus();return that;};return that;};'use strict';Ox.MainMenu=function(options,self){self=self||{};var that=Ox.Bar({},self).defaults({extras:[],menus:[],size:'medium'}).options(options||{}).addClass('OxMainMenu Ox'+Ox.toTitleCase(self.options.size)).on({click:click,mousemove:mousemove});self.focused=false;self.selected=-1;that.menus=[];that.titles=[];that.layer=$('
').addClass('OxLayer');self.options.menus.forEach(function(menu,position){addMenu(menu,position);});if(self.options.extras.length){that.extras=$('
').addClass('OxExtras').appendTo(that);self.options.extras.forEach(function(extra){extra&&extra.appendTo(that.extras);});}
function addMenu(menu,position){that.titles[position]=$('
').addClass('OxTitle').html(menu.title).data({position:position});if(position==0){if(that.titles.length==1){that.titles[position].appendTo(that);}else{that.titles[position].insertBefore(that.titles[1]);}}else{that.titles[position].insertAfter(that.titles[position-1])}
that.menus[position]=Ox.Menu(Ox.extend(menu,{element:that.titles[position],mainmenu:that,size:self.options.size})).bindEvent({hide:onHideMenu});}
function click(event){var $element=getElement(event),position=typeof $element.data('position')!='undefined'?$element.data('position'):-1;clickTitle(position);}
function clickTitle(position){var selected=self.selected;if(self.selected>-1){that.menus[self.selected].hideMenu();}
if(position>-1){if(position!=selected){self.focused=true;self.selected=position;that.titles[self.selected].addClass('OxSelected');that.menus[self.selected].showMenu();}}}
function getElement(event){var $element=$(event.target);return $element.is('img')?$element.parent():$element;}
function mousemove(event){var $element=getElement(event),focused,position=typeof $element.data('position')!='undefined'?$element.data('position'):-1;if(self.focused&&position!=self.selected){if(position>-1){clickTitle(position);}else{focused=self.focused;that.menus[self.selected].hideMenu();self.focused=focused;}}}
function onHideMenu(){if(self.selected>-1){that.titles[self.selected].removeClass('OxSelected');self.selected=-1;}
self.focused=false;}
function removeMenu(position){that.titles[position].remove();that.menus[position].remove();}
that.addMenuAfter=function(id){};that.addMenuBefore=function(id){};that.checkItem=function(id){var ids=id.split('_'),item=that.getItem(id);if(item){if(item.options('group')){item.options('menu').checkItem(ids[ids.length-1]);}else{item.options({checked:true});}}
return that;};that.disableItem=function(id){var item=that.getItem(id);item&&item.options({disabled:true});return that;};that.enableItem=function(id){var item=that.getItem(id);item&&item.options({disabled:false});return that;};that.getItem=function(id){var ids=id.split('_'),item;if(ids.length==1){Ox.forEach(that.menus,function(menu){item=menu.getItem(id);if(item){return false;}});}else{item=that.getMenu(ids.shift()).getItem(ids.join('_'));}
Ox.Log('Menu','getItem',id,item);return item;};that.getMenu=function(id){var ids=id.split('_'),menu;if(ids.length==1){Ox.forEach(that.menus,function(v){if(v.options('id')==id){menu=v;return false;}});}else{menu=that.getMenu(ids.shift()).getSubmenu(ids.join('_'));}
return menu;};that.highlightMenu=function(id){var position=Ox.getIndexById(self.options.menus,id);self.highlightTimeout&&clearTimeout(self.highlightTimeout);that.titles[position].addClass('OxHighlight');self.highlightTimeout=setTimeout(function(){that.titles[position].removeClass('OxHighlight');delete self.highlightTimeout;},500);};that.isSelected=function(){return self.selected>-1;};that.removeMenu=function(){};that.replaceMenu=function(id,menu){var position=Ox.getIndexById(self.options.menus,id);self.options.menus[position]=menu;removeMenu(position);addMenu(menu,position);};that.selectNextMenu=function(){if(self.selected
').addClass('OxTop').appendTo(that);that.$scrollbars.up=renderScrollbar('up').appendTo(that);that.$container=$('').addClass('OxContainer').appendTo(that);that.$content=$('
').addClass('OxContent').appendTo(that.$container);renderItems(self.options.items);that.$scrollbars.down=renderScrollbar('down').appendTo(that);that.$bottom=$('').addClass('OxBottom').appendTo(that);function clickItem(position,files){var item=that.items[position],group=item.options('group'),menu=self.options.mainmenu||self.options.parent||that,offset,toggled;that.hideMenu();if(!item.options('items').length){if(self.options.parent){self.options.parent.hideMenu(true).triggerEvent('click',Ox.extend({id:item.options('id'),title:parseTitle(item.options('title')[0])},files?{files:files}:{}));}
if(item.options('checked')!==null){if(group){offset=self.optionGroupOffset[group];toggled=self.optionGroup[group].toggle(position-offset);if(toggled.length){toggled.forEach(function(pos){that.items[pos+offset].toggleChecked();});menu.triggerEvent('change',{id:item.options('group'),checked:self.optionGroup[group].checked().map(function(pos){return{id:that.items[pos+offset].options('id'),title:Ox.isString(that.items[pos+offset].options('title')[0])?parseTitle(that.items[pos+offset].options('title')[0]):''};})});}}else{item.toggleChecked();menu.triggerEvent('change',{checked:item.options('checked'),id:item.options('id'),title:Ox.isString(item.options('title')[0])?parseTitle(item.options('title')[0]):''});}}else{if(!item.options('file')||files){menu.triggerEvent('click',Ox.extend({id:item.options('id'),title:parseTitle(item.options('title')[0])},files?{files:files}:{}));}}
if(item.options('title').length==2){item.toggleTitle();}}}
function clickLayer(){that.hideMenu();}
function clickSelectedItem(){if(self.options.selected>-1){clickItem(self.options.selected);}}
function getElement(id){return $('#'+Ox.toCamelCase(options.id+'/'+id));}
function getItemPositionById(id){var position;Ox.forEach(that.items,function(item,i){if(item.options('id')==id){position=i;return false;}});return position;}
function hideMenu(){that.hideMenu();}
function isFirstEnabledItem(){var ret=true;Ox.forEach(that.items,function(item,i){if(i
self.options.selected&&!item.options('disabled')){ret=false;return false;}});return ret;}
function mouseenter(){that.gainFocus();}
function mouseleave(){if(self.options.selected>-1&&!that.items[self.options.selected].options('items').length){selectItem(-1);}}
function mousemove(event){var item,position,$target=$(event.target),$parent=$target.parent(),$grandparent=$parent.parent();if($parent.is('.OxCell')){$target=$parent;$parent=$target.parent();}else if($grandparent.is('.OxCell')){$target=$grandparent;$parent=$target.parent();}
if($target.is('.OxCell')){position=$parent.data('position');item=that.items[position];if(position!=self.options.selected){if(!item.options('disabled')){selectItem(position);}else{mouseleave();}}}else{mouseleave();}}
function mouseup(event){var item,position,$target=$(event.target),$parent=$target.parent();if($parent.is('.OxCell')){$target=$parent;$parent=$target.parent();}
if($target.is('.OxCell')){position=$parent.data('position');item=that.items[position];if(!item.options('disabled')){clickItem(position);}else{that.hideMenu();}}else{that.hideMenu();}}
function mousewheel(e,delta,deltaX,deltaY){var $scrollbar;if(deltaY&&!$(e.target).is('.OxScrollbar')){$scrollbar=that.$scrollbars[deltaY<0?'down':'up'];Ox.loop(0,Math.abs(deltaY),function(){if($scrollbar.is(':visible')){$scrollbar.trigger('mouseenter').trigger('mouseleave');}});}}
function parseTitle(title){return Ox.decodeHTMLEntities(Ox.stripTags(title));}
function renderItems(items){var offset=0;that.$content.empty();scrollMenuUp();self.optionGroup={};self.optionGroupOffset={};items.forEach(function(item,i){if(item.group&&item.items){items[i]=item.items.map(function(v){return Ox.extend(v,{group:item.group});});self.optionGroup[item.group]=new Ox.OptionGroup(items[i].filter(function(v){return'id'in v;}),'min'in item?item.min:1,'max'in item?item.max:1);self.optionGroupOffset[item.group]=offset;offset+=items[i].length;}else if('id'in item){offset+=1;}});items=Ox.flatten(items);that.items=[];items.forEach(function(item){var position;if('id'in item){position=that.items.length;that.items.push(Ox.MenuItem(Ox.extend(Ox.clone(item),{maxWidth:self.options.maxWidth,menu:that,position:position})).data('position',position).appendTo(that.$content));if(item.items){that.submenus[item.id]=Ox.Menu({edge:'right',element:that.items[position],id:Ox.toCamelCase(self.options.id+'/'+item.id),items:item.items,mainmenu:self.options.mainmenu,offset:{left:0,top:-4},parent:that,size:self.options.size});}}else{that.$content.append(renderSpace());that.$content.append(renderLine());that.$content.append(renderSpace());}});if(!that.is(':hidden')){that.hideMenu();that.showMenu();}}
function renderLine(){return $('').append($('').addClass('OxLine').attr({colspan:5}));}
function renderScrollbar(direction){var interval,speed=direction=='up'?-1:1;return $('
',{'class':'OxScrollbar Ox'+Ox.toTitleCase(direction),html:Ox.SYMBOLS['triangle_'+direction],mousedown:function(){self.scrollSpeed=2;return false;},mouseenter:function(){self.scrollSpeed=1;var $otherScrollbar=that.$scrollbars[direction=='up'?'down':'up'];$(this).addClass('OxSelected');if($otherScrollbar.is(':hidden')){$otherScrollbar.show();that.$container.height(that.$container.height()-self.itemHeight);if(direction=='down'){that.$content.css({top:-self.itemHeight+'px'});}}
scrollMenu(speed);interval=setInterval(function(){scrollMenu(speed);},100);},mouseleave:function(){self.scrollSpeed=1;$(this).removeClass('OxSelected');clearInterval(interval);},mouseup:function(){self.scrollSpeed=1;return false;}});}
function renderSpace(){return $(' ').append($('').addClass('OxSpace').attr({colspan:5}));}
function scrollMenu(speed){var containerHeight=that.$container.height(),contentHeight=that.$content.height(),top=parseInt(that.$content.css('top'),10)||0,min=containerHeight-contentHeight+self.itemHeight,max=0;top+=speed*self.scrollSpeed*-self.itemHeight;if(top<=min){top=min;that.$scrollbars.down.hide().trigger('mouseleave');that.$container.height(containerHeight+self.itemHeight);that.items[that.items.length-1].trigger('mouseover');}else if(top>=max-self.itemHeight){top=max;that.$scrollbars.up.hide().trigger('mouseleave');that.$container.height(containerHeight+self.itemHeight);that.items[0].trigger('mouseover');}
that.$content.css({top:top+'px'});}
function scrollMenuUp(){if(that.$scrollbars.up.is(':visible')){that.$content.css({top:'0px'});that.$scrollbars.up.hide();if(that.$scrollbars.down.is(':hidden')){that.$scrollbars.down.show();}else{that.$container.height(that.$container.height()+self.itemHeight);}}}
function selectItem(position){var item;if(self.options.selected>-1){item=that.items[self.options.selected];if(item){item.removeClass('OxSelected');}}
if(position>-1){item=that.items[position];Ox.forEach(that.submenus,function(submenu,id){if(!submenu.is(':hidden')){submenu.hideMenu();return false;}});item.options('items').length&&that.submenus[item.options('id')].showMenu();item.addClass('OxSelected');that.triggerEvent('select',{id:item.options('id'),title:Ox.isString(item.options('title')[0])?parseTitle(item.options('title')[0]):''});}
self.options.selected=position;}
function selectNextItem(){var offset,selected=self.options.selected;if(!isLastEnabledItem()){if(selected==-1){scrollMenuUp();}else{that.items[selected].removeClass('OxSelected');}
do{selected++;}while(that.items[selected].options('disabled'))
selectItem(selected);offset=that.items[selected].offset().top+self.itemHeight-that.$container.offset().top-that.$container.height();if(offset>0){if(that.$scrollbars.up.is(':hidden')){that.$scrollbars.up.show();that.$container.height(that.$container.height()-self.itemHeight);offset+=self.itemHeight;}
if(selected==that.items.length-1){that.$scrollbars.down.hide();that.$container.height(that.$container.height()+self.itemHeight);}else{that.$content.css({top:((parseInt(that.$content.css('top'),10)||0)-offset)+'px'});}}}}
function selectPreviousItem(){var offset,selected=self.options.selected;if(selected>-1){if(!isFirstEnabledItem()){that.items[selected].removeClass('OxSelected');do{selected--;}while(that.items[selected].options('disabled'))
selectItem(selected);}
offset=that.items[selected].offset().top-that.$container.offset().top;if(offset<0){if(that.$scrollbars.down.is(':hidden')){that.$scrollbars.down.show();that.$container.height(that.$container.height()-self.itemHeight);}
if(selected==0){that.$scrollbars.up.hide();that.$container.height(that.$container.height()+self.itemHeight);}
that.$content.css({top:((parseInt(that.$content.css('top'),10)||0)-offset)+'px'});}}}
function selectSubmenu(){if(self.options.selected>-1){var submenu=that.submenus[that.items[self.options.selected].options('id')];if(submenu&&submenu.hasEnabledItems()){submenu.gainFocus();submenu.selectFirstItem();}else if(self.options.mainmenu){self.options.mainmenu.selectNextMenu();}}else if(self.options.mainmenu){self.options.mainmenu.selectNextMenu();}}
function selectSupermenu(){if(self.options.parent){self.options.selected>-1&&that.items[self.options.selected].trigger('mouseleave');scrollMenuUp();self.options.parent.gainFocus();}else if(self.options.mainmenu){self.options.mainmenu.selectPreviousMenu();}}
function setCSS(){var offset=self.options.element.offset(),width=self.options.element.outerWidth(),height=self.options.element.outerHeight(),menuWidth=that.width(),windowWidth=Ox.$window.width(),windowHeight=Ox.$window.height(),left=offset.left+self.options.offset.left+(self.options.edge=='bottom'?0:width),top=offset.top+self.options.offset.top+(self.options.edge=='bottom'?height:0),menuHeight=that.$content.outerHeight(),menuMaxHeight=Math.floor(Ox.$window.height()-top-16);if(self.options.edge=='bottom'&&left+menuWidth>windowWidth){left=offset.left+width-menuWidth;that.is('.OxRight')&&that.removeClass('OxRight')&&that.addClass('OxLeft');}
if(self.options.parent){if(menuHeight>menuMaxHeight){top=Ox.limit(top-menuHeight+menuMaxHeight,self.options.parent.offset().top,top);menuMaxHeight=Math.floor(windowHeight-top-16);}}
that.css({left:left+'px',top:top+'px'});if(menuHeight>menuMaxHeight){that.$container.height(menuMaxHeight-self.itemHeight-8);that.$scrollbars.down.show();}else{that.$container.height(menuHeight);}}
that.addItem=function(item,position){};that.addItemAfter=function(item,id){};that.addItemBefore=function(item,id){};that.checkItem=function(id,checked){Ox.Log('Menu','checkItem id',id)
var group,ids=Ox.isEmpty(that.submenus)?[id]:id.split('_'),item,offset,position,toggled;checked=Ox.isUndefined(checked)?true:checked;if(ids.length==1){item=that.getItem(id);group=item.options('group');if(group){offset=self.optionGroupOffset[group];position=getItemPositionById(id);if(item.options('checked')!=checked){toggled=self.optionGroup[item.options('group')].toggle(position-offset);if(toggled.length){toggled.forEach(function(pos){that.items[pos+offset].toggleChecked();});}}}else{item.options({checked:checked});}}else{that.submenus[ids.shift()].checkItem(ids.join('_'),checked);}
return that;};that.clickItem=function(position,files){clickItem(position,files);return that;};that.getItem=function(id){var ids=Ox.isEmpty(that.submenus)?[id]:id.split('_'),item;if(ids.length==1){Ox.forEach(that.items,function(v){if(v.options('id')==id){item=v;return false;}});if(!item){Ox.forEach(that.submenus,function(submenu){item=submenu.getItem(id);if(item){return false;}});}}else{item=that.submenus[ids.shift()].getItem(ids.join('_'));}
return item;};that.getSubmenu=function(id){var ids=id.split('_'),submenu;if(ids.length==1){submenu=that.submenus[id];}else{submenu=that.submenus[ids.shift()].getSubmenu(ids.join('_'));}
return submenu;}
that.hasEnabledItems=function(){var ret=false;Ox.forEach(that.items,function(item){if(!item.options('disabled')){ret=true;return false;}});return ret;};that.hideMenu=function(hideParent){if(that.is(':hidden')){return;}
Ox.forEach(that.submenus,function(submenu){if(submenu.is(':visible')){submenu.hideMenu();return false;}});selectItem(-1);scrollMenuUp();that.$scrollbars.up.is(':visible')&&that.$scrollbars.up.hide();that.$scrollbars.down.is(':visible')&&that.$scrollbars.down.hide();if(self.options.parent){self.options.parent.options({selected:-1});hideParent&&self.options.parent.hideMenu(true);}
that.$layer&&that.$layer.hide();that.hide().loseFocus().triggerEvent('hide');return that;};that.removeElement=function(){Ox.forEach(that.submenus,function(submenu){submenu.remove();});return Ox.Element.prototype.removeElement.apply(that,arguments);};that.removeItem=function(){};that.selectFirstItem=function(){selectNextItem();return that;};that.setItemKeyboard=function(id,keyboard){var item=that.getItem(id);item&&item.options({keyboard:keyboard});return that;};that.setItemTitle=function(id,title){var item=that.getItem(id);item&&item.options({title:title});return that;};that.showMenu=function(){if(!that.is(':hidden')){return;}
that.appendTo(Ox.Fullscreen.element?Ox.Fullscreen.element:Ox.$body);that.css({position:'fixed',left:'-1000px',top:'-1000px'}).show();setCSS();if(!self.options.parent){that.gainFocus();that.$layer=Ox.Layer({type:'menu'}).css({top:self.options.mainmenu?'20px':0}).on({mouseup:clickLayer}).show();}
return that;};that.toggleMenu=function(){return that.is(':hidden')?that.showMenu():that.hideMenu();};that.uncheckItem=function(id){that.checkItem(id,false);return that;};that.updatePosition=function(){setCSS();return that;};return that;};'use strict';Ox.MenuButton=function(options,self){self=self||{};var that=Ox.Element({tooltip:options.tooltip||''},self).defaults({disabled:false,id:'',items:[],maxWidth:0,overlap:'none',style:'rounded',title:'',type:'text',width:'auto'}).options(options||{}).update({items:function(){self.$menu.options({items:self.options.items});},title:function(){if(self.options.type=='text'){self.$title.html(self.options.title);}else{self.$button.options({title:self.options.title});}},width:function(){that.css({width:self.options.width-2+'px'});self.$title.css({width:self.options.width-24+'px'});}}).addClass('OxSelect Ox'+Ox.toTitleCase(self.options.style)+(self.options.overlap!='none'?' OxOverlap'+Ox.toTitleCase(self.options.overlap):'')).css(self.options.width=='auto'?{}:{width:self.options.width-2+'px'}).bindEvent({anyclick:function(e){showMenu($(e.target).is('.OxButton')?'button':null);},});if(self.options.type=='text'){self.$title=Ox.$('').addClass('OxTitle').css({width:self.options.width-24+'px'}).html(self.options.title).appendTo(that);}
self.$button=Ox.Button({id:self.options.id+'Button',selectable:true,overlap:self.options.overlap,style:'symbol',title:self.options.type=='text'||!self.options.title?'select':self.options.title,type:'image'}).appendTo(that);self.$menu=Ox.Menu({edge:'bottom',element:self.$title||self.$button,id:self.options.id+'Menu',items:self.options.items,maxWidth:self.options.maxWidth}).bindEvent({change:changeMenu,click:clickMenu,hide:hideMenu});self.options.type=='image'&&self.$menu.addClass('OxRight');function clickMenu(data){that.triggerEvent('click',data);}
function changeMenu(data){that.triggerEvent('change',data);}
function hideMenu(data){that.loseFocus();that.removeClass('OxSelected');self.$button.options({value:false});that.triggerEvent('hide');}
function showMenu(from){that.gainFocus();that.addClass('OxSelected');from!='button'&&self.$button.options({value:true});that.$tooltip&&that.$tooltip.hide();self.$menu.showMenu();that.triggerEvent('show');}
that.checkItem=function(id){self.$menu.checkItem(id);return that;};that.disableItem=function(id){self.$menu.getItem(id).options({disabled:true});return that;};that.enableItem=function(id){self.$menu.getItem(id).options({disabled:false});return that;};that.removeElement=function(){self.$menu.remove();return Ox.Element.prototype.removeElement.apply(that,arguments);};that.setItemTitle=function(id,title){self.$menu.setItemTitle(id,title);return that;};that.uncheckItem=function(id){self.$menu.uncheckItem(id);return that;};return that;};'use strict';Ox.MenuItem=function(options,self){self=self||{};var that=Ox.Element('
',self).defaults({bind:[],checked:null,disabled:false,file:null,group:'',icon:'',id:'',items:[],keyboard:'',maxWidth:0,menu:null,position:0,title:[],type:''}).options(Ox.extend(Ox.clone(options),{keyboard:parseKeyboard(options.keyboard||self.defaults.keyboard),title:Ox.makeArray(options.title||self.defaults.title)})).update({checked:function(){that.$status.html(self.options.checked?Ox.SYMBOLS.check:'')},disabled:function(){that[self.options.disabled?'addClass':'removeClass']('OxDisabled');},keyboard:function(){self.options.keyboard=parseKeyboard(self.options.keyboard);that.$modifiers.html(formatModifiers());that.$key.html(formatKey());},title:function(){self.options.title=Ox.makeArray(self.options.title);that.$title.html(self.options.title[0]);}}).addClass('OxItem'+(self.options.disabled?' OxDisabled':'')).data('group',self.options.group);if(self.options.group&&self.options.checked===null){self.options.checked=false;}
if(self.options.file){self.$input=$(' ').attr(Ox.extend({type:'file'},self.options.file.multiple?{multiple:true}:{})).on({change:function(event){var filelist=this.files
var files=[];Ox.loop(filelist.length,function(i){files.push(filelist.item(i));});self.options.menu.clickItem(self.options.position,files);}})}
that.append(that.$status=Ox.$('').addClass('OxCell OxStatus').html(self.options.checked?Ox.SYMBOLS.check:'')).append(that.$icon=$(' ').addClass('OxCell OxIcon').append(self.options.icon?Ox.$(' ').attr({src:self.options.icon}):null)).append(that.$title=$(' ').addClass('OxCell OxTitle').css(self.options.maxWidth?{maxWidth:self.options.maxWidth-46,textOverflow:'ellipsis',overflow:'hidden'}:{}).html(Ox.isString(self.options.title[0])?self.options.title[0]:Ox.$('').html(self.options.title[0]).html()).on({click:self.options.file?function(event){!self.options.disabled&&self.$input.click()
event.preventDefault()
event.stopPropagation()}:null})).append(that.$modifiers=Ox.$('
').addClass('OxCell OxModifiers').html(formatModifiers())).append(that.$key=Ox.$(' ').addClass('OxCell Ox'+(self.options.items.length?'Submenu':'Key')).html(self.options.items.length?Ox.SYMBOLS.triangle_right:formatKey()));function formatKey(){return Ox.SYMBOLS[self.options.keyboard.key]||self.options.keyboard.key.toUpperCase();}
function formatModifiers(){return self.options.keyboard.modifiers.map(function(modifier){return Ox.SYMBOLS[modifier];}).join('');}
function parseKeyboard(str){var modifiers=str.split(' '),key=modifiers.pop();return{modifiers:modifiers,key:key};}
that.toggle=function(){};that.toggleChecked=function(){that.options({checked:!self.options.checked});return that;};that.toggleDisabled=function(){};that.toggleTitle=function(){that.options({title:Ox.clone(self.options.title).reverse()});return that;};return that;};'use strict';Ox.Bar=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({orientation:'horizontal',size:16}).options(options||{}).addClass('OxBar Ox'+Ox.toTitleCase(self.options.orientation));self.dimensions=Ox.UI.DIMENSIONS[self.options.orientation];that.css(self.dimensions[0],'100%').css(self.dimensions[1],self.options.size+'px');return that;};'use strict';Ox.Progressbar=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({cancelled:false,paused:false,progress:0,style:'default',showCancelButton:false,showPauseButton:false,showPercent:false,showRestartButton:false,showTime:false,showTooltips:false,width:256}).options(options||{}).update({cancelled:toggleCancelled,paused:togglePaused,progress:function(){self.indeterminate=self.options.progress==-1;if(self.options.progress!=-1){self.options.progress=Ox.limit(self.options.progress,0,1);}
!self.options.paused&&!self.options.cancelled&&setProgress(true);}}).addClass('OxProgressbar'+(self.options.style!='default'?' Ox'+Ox.toTitleCase(self.options.style):'')).css({width:self.options.width-2+'px'});self.indeterminate=self.options.progress==-1;self.trackWidth=self.options.width
-self.options.showPercent*36
-self.options.showTime*60
-self.options.showPauseButton*16
-self.options.showCancelButton*16;self.$track=$('').addClass('OxTrack').css({width:self.trackWidth-2+'px'}).appendTo(that);self.$progress=$('
').addClass('OxProgress').appendTo(self.$track);if(self.options.showPercent){self.$percent=$('
').addClass('OxText').css({width:'36px'}).appendTo(that);}
if(self.options.showTime){self.$time=$('
').addClass('OxText').css({width:'60px'}).appendTo(that);}
if(self.options.showPauseButton){self.$pauseButton=Ox.Button({style:'symbol',tooltip:self.options.showTooltips?[Ox._('Pause'),Ox._('Resume')]:'',type:'image',value:!self.options.paused?'pause':'redo',values:['pause','redo']}).bindEvent({click:togglePaused}).appendTo(that);}
if(self.options.showCancelButton){self.$cancelButton=Ox.Button(Ox.extend({style:'symbol',type:'image'},self.options.showRestartButton?{tooltip:self.options.showTooltips?[Ox._('Cancel'),Ox._('Restart')]:'',value:'close',values:['close','redo']}:{title:'close',tooltip:self.options.showTooltips?Ox._('Cancel'):''})).bindEvent({click:toggleCancelled}).appendTo(that);}
setProgress();!self.options.paused&&resume();function cancel(){self.options.cancelled=true;if(self.options.paused){self.options.paused=false;self.$pauseButton&&self.$pauseButton.toggle();}
stop();that.triggerEvent('cancel');}
function complete(){self.complete=true;stop();self.paused=false;that.triggerEvent('complete');}
function pause(){self.pauseTime=+new Date();self.$progress.removeClass('OxAnimate');($.browser.mozilla||$.browser.opera)&&clearInterval(self.interval);self.$time&&self.$time.html(self.options.cancelled?Ox._('Cancelled'):Ox._('Paused'));}
function restart(){self.options.cancelled=false;if(!self.indeterminate){self.options.progress=0;}
delete self.startTime;self.$pauseButton&&self.$pauseButton.options({disabled:false});setProgress();resume();that.triggerEvent('restart');}
function resume(){self.startTime=!self.startTime?+new Date():self.startTime+ +new Date()-self.pauseTime;self.$progress.addClass('OxAnimate');if($.browser.mozilla||$.browser.opera){self.offset=0;self.interval=setInterval(function(){self.$progress.css({backgroundPosition:--self.offset+'px 0, 0 0'})},1000/32);}
self.$time&&self.$time.html(self.options.progress?Ox.formatDuration(that.status().remaining):Ox._('unknown'));}
function setProgress(animate){self.$percent&&self.$percent.html(Math.floor(self.options.progress*100)+'%');self.$time&&self.$time.html(self.options.progress?Ox.formatDuration(that.status().remaining):Ox._('unknown'));self.$progress.stop().animate({width:Math.round(14+Math.abs(self.options.progress)*(self.trackWidth-16))+'px'},animate?250:0,function(){self.options.progress==1&&complete();});}
function stop(){pause();self.$time&&self.$time.html(self.options.cancelled?Ox._('Cancelled'):Ox._('Complete'));if(self.$pauseButton&&(self.options.cancelled||self.complete)){self.$pauseButton.options({disabled:true});}
if(self.$cancelButton&&(self.complete||!self.options.showRestartButton)){self.$cancelButton.options({disabled:true});}}
function toggleCancelled(e){if(e){self.options.cancelled=!self.options.cancelled;}else if(self.$cancelButton){self.$cancelButton.toggle();}
self.options.cancelled?cancel():restart();that.triggerEvent(self.options.cancelled?'cancel':'restart');}
function togglePaused(e){if(e){self.options.paused=!self.options.paused;}else if(self.$pauseButton){self.$pauseButton.toggle();}
self.options.paused?pause():resume();that.triggerEvent(self.options.paused?'pause':'resume');}
that.status=function(){var elapsed=+new Date()-self.startTime,remaining=elapsed/self.options.progress*(1-self.options.progress);return{elapsed:Math.floor(elapsed/1000),remaining:self.options.progress?Math.ceil(remaining/1000):Infinity};};return that;};'use strict';Ox.Resizebar=function(options,self){self=self||{};var that=Ox.Element({},self).defaults({collapsed:false,collapsible:false,defaultSize:null,edge:'left',orientation:'horizontal',resettable:false,resizable:false,resize:[],size:0,tooltip:false}).options(options||{}).update({collapsed:function(){that.css({cursor:getCursor()});self.$tooltip&&self.$tooltip.options({title:getTooltipTitle()});}}).addClass('OxResizebar Ox'+Ox.toTitleCase(self.options.orientation)).bindEvent(Ox.extend({dragstart:onDragstart,drag:onDrag,dragpause:onDragpause,dragend:onDragend},self.options.resettable?{doubleclick:reset,singleclick:toggle}:{anyclick:toggle})).append(Ox.$('
').addClass('OxSpace')).append(Ox.$('
').addClass('OxLine')).append(Ox.$('
').addClass('OxSpace'));if(Ox.isString(self.options.tooltip)){self.$tooltip=Ox.Tooltip({title:getTooltipTitle()});that.on({mouseenter:self.$tooltip.show,mouseleave:self.$tooltip.hide});}
self.clientXY=self.options.orientation=='horizontal'?'clientY':'clientX';self.dimensions=Ox.UI.DIMENSIONS[self.options.orientation];self.edges=Ox.UI.EDGES[self.options.orientation];self.isLeftOrTop=self.options.edge=='left'||self.options.edge=='top';that.css({cursor:getCursor()});function getCursor(){var cursor='';if(self.options.collapsed){cursor=self.options.orientation=='horizontal'?(self.isLeftOrTop?'s':'n'):(self.isLeftOrTop?'e':'w');}else{if(self.options.resizable){cursor=self.options.orientation=='horizontal'?'ns':'ew';}else if(self.options.collapsible){cursor=self.options.orientation=='horizontal'?(self.isLeftOrTop?'n':'s'):(self.isLeftOrTop?'w':'e');}}
return cursor+'-resize';}
function getTooltipTitle(){var title='';if(self.options.collapsed){title=Ox._('Click to show');}else{if(self.options.resizable){title=Ox._('Drag to resize');}
if(self.options.collapsible){title=title?Ox._('{0}{1} click to hide',[title,self.options.resettable?',':' or']):Ox._('Click to hide');}
if(self.options.resettable){title+=' or doubleclick to reset'}}
if(title&&self.options.tooltip){title+=' '+self.options.tooltip;}
return title;}
function onDragstart(data){if(self.options.resizable&&!self.options.collapsed){Ox.$body.addClass('OxDragging');self.drag={startPos:data[self.clientXY],startSize:self.options.size}}
that.triggerEvent('resizestart',{size:self.options.size});}
function onDrag(data){if(self.options.resizable&&!self.options.collapsed){var delta=data[self.clientXY]-self.drag.startPos,size=self.options.size;self.options.size=Ox.limit(self.drag.startSize+delta*(self.isLeftOrTop?1:-1),self.options.resize[0],self.options.resize[self.options.resize.length-1]);Ox.forEach(self.options.resize,function(value){if(self.options.size>=value-8&&self.options.size<=value+8){self.options.size=value;return false;}});if(self.options.size!=size){that.css(self.edges[self.isLeftOrTop?2:3],self.options.size+'px').triggerEvent('resize',{size:self.options.size});}}}
function onDragpause(){if(self.options.resizable&&!self.options.collapsed){if(self.options.size!=self.drag.startSize){that.triggerEvent('resizepause',{size:self.options.size});}}}
function onDragend(){if(self.options.resizable&&!self.options.collapsed){Ox.$body.removeClass('OxDragging');if(self.options.size!=self.drag.startSize){that.triggerEvent('resizeend',{size:self.options.size});}}}
function reset(){if(self.options.resizable&&!self.options.collapsed){that.triggerEvent('reset');}}
function toggle(){if(self.options.collapsible){self.options.collapsed=!self.options.collapsed;that.css({cursor:getCursor()});self.$tooltip&&self.$tooltip.hide(function(){self.$tooltip.options({title:getTooltipTitle()});});that.triggerEvent('toggle',{collapsed:self.options.collapsed});}}
return that;};'use strict';Ox.Tabbar=function(options,self){self=self||{};var that=Ox.Bar({size:20},self).defaults({selected:0,tabs:[]}).options(options||{}).addClass('OxTabbar');Ox.ButtonGroup({buttons:self.options.tabs,group:true,selectable:true,selected:self.options.selected,size:'medium',style:'tab'}).appendTo(that);return that;};