//MooTools, <http://mootools.net>, My Object Oriented (JavaScript) Tools. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

var MooTools={version:"1.2dev",build:""};var Native=function(J){J=J||{};var F=J.afterImplement||function(){};var G=J.generics;G=(G!==false);var H=J.legacy;
var E=J.initialize;var B=J.protect;var A=J.name;var C=E||H;C.constructor=Native;C.$family={name:"native"};if(H&&E){C.prototype=H.prototype;}C.prototype.constructor=C;
if(A){var D=A.toLowerCase();C.prototype.$family={name:D};Native.typize(C,D);}var I=function(M,K,N,L){if(!B||L||!M.prototype[K]){M.prototype[K]=N;}if(G){Native.genericize(M,K,B);
}F.call(M,K,N);return M;};C.implement=function(L,K,N){if(typeof L=="string"){return I(this,L,K,N);}for(var M in L){I(this,M,L[M],K);}return this;};C.alias=function(M,K,N){if(typeof M=="string"){M=this.prototype[M];
if(M){I(this,K,M,N);}}else{for(var L in M){this.alias(L,M[L],K);}}return this;};return C;};Native.implement=function(D,C){for(var B=0,A=D.length;B<A;B++){D[B].implement(C);
}};Native.genericize=function(B,C,A){if((!A||!B[C])&&typeof B.prototype[C]=="function"){B[C]=function(){var D=Array.prototype.slice.call(arguments);return B.prototype[C].apply(D.shift(),D);
};}};Native.typize=function(A,B){if(!A.type){A.type=function(C){return($type(C)===B);};}};Native.alias=function(E,B,A,F){for(var D=0,C=E.length;D<C;D++){E[D].alias(B,A,F);
}};(function(B){for(var A in B){Native.typize(B[A],A);}})({"boolean":Boolean,"native":Native,object:Object});(function(B){for(var A in B){new Native({name:A,initialize:B[A],protect:true});
}})({String:String,Function:Function,Number:Number,Array:Array,RegExp:RegExp,Date:Date});(function(B,A){for(var C=A.length;C--;C){Native.genericize(B,A[C],true);
}return arguments.callee;})(Array,["pop","push","reverse","shift","sort","splice","unshift","concat","join","slice","toString","valueOf","indexOf","lastIndexOf"])(String,["charAt","charCodeAt","concat","indexOf","lastIndexOf","match","replace","search","slice","split","substr","substring","toLowerCase","toUpperCase","valueOf"]);
function $chk(A){return !!(A||A===0);}function $clear(A){clearTimeout(A);clearInterval(A);return null;}function $defined(A){return(A!=undefined);}function $empty(){}function $arguments(A){return function(){return arguments[A];
};}function $lambda(A){return(typeof A=="function")?A:function(){return A;};}function $extend(C,A){for(var B in (A||{})){C[B]=A[B];}return C;}function $unlink(C){var B;
switch($type(C)){case"object":B={};for(var E in C){B[E]=$unlink(C[E]);}break;case"hash":B=$unlink(C.getClean());break;case"array":B=[];for(var D=0,A=C.length;
D<A;D++){B[D]=$unlink(C[D]);}break;default:return C;}return B;}function $merge(){var E={};for(var D=0,A=arguments.length;D<A;D++){var B=arguments[D];if($type(B)!="object"){continue;
}for(var C in B){var G=B[C],F=E[C];E[C]=(F&&$type(G)=="object"&&$type(F)=="object")?$merge(F,G):$unlink(G);}}return E;}function $pick(){for(var B=0,A=arguments.length;
B<A;B++){if(arguments[B]!=undefined){return arguments[B];}}return null;}function $random(B,A){return Math.floor(Math.random()*(A-B+1)+B);}function $splat(B){var A=$type(B);
return(A)?((A!="array"&&A!="arguments")?[B]:B):[];}var $time=Date.now||function(){return new Date().getTime();};function $try(){for(var B=0,A=arguments.length;
B<A;B++){try{return arguments[B]();}catch(C){}}return null;}function $type(A){if(A==undefined){return false;}if(A.$family){return(A.$family.name=="number"&&!isFinite(A))?false:A.$family.name;
}if(A.nodeName){switch(A.nodeType){case 1:return"element";case 3:return(/\S/).test(A.nodeValue)?"textnode":"whitespace";}}else{if(typeof A.length=="number"){if(A.callee){return"arguments";
}else{if(A.item){return"collection";}}}}return typeof A;}var Hash=new Native({name:"Hash",initialize:function(A){if($type(A)=="hash"){A=$unlink(A.getClean());
}for(var B in A){this[B]=A[B];}return this;}});Hash.implement({getLength:function(){var B=0;for(var A in this){if(this.hasOwnProperty(A)){B++;}}return B;
},forEach:function(B,C){for(var A in this){if(this.hasOwnProperty(A)){B.call(C,this[A],A,this);}}},getClean:function(){var B={};for(var A in this){if(this.hasOwnProperty(A)){B[A]=this[A];
}}return B;}});Hash.alias("forEach","each");function $H(A){return new Hash(A);}Array.implement({forEach:function(C,D){for(var B=0,A=this.length;B<A;B++){C.call(D,this[B],B,this);
}}});Array.alias("forEach","each");function $A(C){if(C.item){var D=[];for(var B=0,A=C.length;B<A;B++){D[B]=C[B];}return D;}return Array.prototype.slice.call(C);
}function $each(C,B,D){var A=$type(C);((A=="arguments"||A=="collection"||A=="array")?Array:Hash).each(C,B,D);}var Browser=new Hash({Engine:{name:"unknown",version:""},Platform:{name:(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase()},Features:{xpath:!!(document.evaluate),air:!!(window.runtime)},Plugins:{}});
if(window.opera){Browser.Engine={name:"presto",version:(document.getElementsByClassName)?950:925};}else{if(window.ActiveXObject){Browser.Engine={name:"trident",version:(window.XMLHttpRequest)?5:4};
}else{if(!navigator.taintEnabled){Browser.Engine={name:"webkit",version:(Browser.Features.xpath)?420:419};}else{if(document.getBoxObjectFor!=null){Browser.Engine={name:"gecko",version:(document.getElementsByClassName)?19:18};
}}}}Browser.Engine[Browser.Engine.name]=Browser.Engine[Browser.Engine.name+Browser.Engine.version]=true;if(window.orientation!=undefined){Browser.Platform.name="ipod";
}Browser.Platform[Browser.Platform.name]=true;Browser.Request=function(){return $try(function(){return new XMLHttpRequest();},function(){return new ActiveXObject("MSXML2.XMLHTTP");
});};Browser.Features.xhr=!!(Browser.Request());Browser.Plugins.Flash=(function(){var A=($try(function(){return navigator.plugins["Shockwave Flash"].description;
},function(){return new ActiveXObject("ShockwaveFlash.ShockwaveFlash").GetVariable("$version");})||"0 r0").match(/\d+/g);return{version:parseInt(A[0]||0+"."+A[1]||0),build:parseInt(A[2]||0)};
})();function $exec(B){if(!B){return B;}if(window.execScript){window.execScript(B);}else{var A=document.createElement("script");A.setAttribute("type","text/javascript");
A.text=B;document.head.appendChild(A);document.head.removeChild(A);}return B;}Native.UID=1;var $uid=(Browser.Engine.trident)?function(A){return(A.uid||(A.uid=[Native.UID++]))[0];
}:function(A){return A.uid||(A.uid=Native.UID++);};var Window=new Native({name:"Window",legacy:(Browser.Engine.trident)?null:window.Window,initialize:function(A){$uid(A);
if(!A.Element){A.Element=$empty;if(Browser.Engine.webkit){A.document.createElement("iframe");}A.Element.prototype=(Browser.Engine.webkit)?window["[[DOMElement.prototype]]"]:{};
}return $extend(A,Window.Prototype);},afterImplement:function(B,A){window[B]=Window.Prototype[B]=A;}});Window.Prototype={$family:{name:"window"}};new Window(window);
var Document=new Native({name:"Document",legacy:(Browser.Engine.trident)?null:window.Document,initialize:function(A){$uid(A);A.head=A.getElementsByTagName("head")[0];
A.html=A.getElementsByTagName("html")[0];A.window=A.defaultView||A.parentWindow;if(Browser.Engine.trident4){$try(function(){A.execCommand("BackgroundImageCache",false,true);
});}return $extend(A,Document.Prototype);},afterImplement:function(B,A){document[B]=Document.Prototype[B]=A;}});Document.Prototype={$family:{name:"document"}};
new Document(document);Array.implement({every:function(C,D){for(var B=0,A=this.length;B<A;B++){if(!C.call(D,this[B],B,this)){return false;}}return true;
},filter:function(D,E){var C=[];for(var B=0,A=this.length;B<A;B++){if(D.call(E,this[B],B,this)){C.push(this[B]);}}return C;},clean:function(){return this.filter($defined);
},indexOf:function(C,D){var A=this.length;for(var B=(D<0)?Math.max(0,A+D):D||0;B<A;B++){if(this[B]===C){return B;}}return -1;},map:function(D,E){var C=[];
for(var B=0,A=this.length;B<A;B++){C[B]=D.call(E,this[B],B,this);}return C;},some:function(C,D){for(var B=0,A=this.length;B<A;B++){if(C.call(D,this[B],B,this)){return true;
}}return false;},associate:function(C){var D={},B=Math.min(this.length,C.length);for(var A=0;A<B;A++){D[C[A]]=this[A];}return D;},link:function(C){var A={};
for(var E=0,B=this.length;E<B;E++){for(var D in C){if(C[D](this[E])){A[D]=this[E];delete C[D];break;}}}return A;},contains:function(A,B){return this.indexOf(A,B)!=-1;
},extend:function(C){for(var B=0,A=C.length;B<A;B++){this.push(C[B]);}return this;},getLast:function(){return(this.length)?this[this.length-1]:null;},getRandom:function(){return(this.length)?this[$random(0,this.length-1)]:null;
},include:function(A){if(!this.contains(A)){this.push(A);}return this;},combine:function(C){for(var B=0,A=C.length;B<A;B++){this.include(C[B]);}return this;
},erase:function(B){for(var A=this.length;A--;A){if(this[A]===B){this.splice(A,1);}}return this;},empty:function(){this.length=0;return this;},flatten:function(){var D=[];
for(var B=0,A=this.length;B<A;B++){var C=$type(this[B]);if(!C){continue;}D=D.concat((C=="array"||C=="collection"||C=="arguments")?Array.flatten(this[B]):this[B]);
}return D;},hexToRgb:function(B){if(this.length!=3){return null;}var A=this.map(function(C){if(C.length==1){C+=C;}return C.toInt(16);});return(B)?A:"rgb("+A+")";
},rgbToHex:function(D){if(this.length<3){return null;}if(this.length==4&&this[3]==0&&!D){return"transparent";}var B=[];for(var A=0;A<3;A++){var C=(this[A]-0).toString(16);
B.push((C.length==1)?"0"+C:C);}return(D)?B:"#"+B.join("");}});Function.implement({extend:function(A){for(var B in A){this[B]=A[B];}return this;},create:function(B){var A=this;
B=B||{};return function(D){var C=B.arguments;C=(C!=undefined)?$splat(C):Array.slice(arguments,(B.event)?1:0);if(B.event){C=[D||window.event].extend(C);
}var E=function(){return A.apply(B.bind||null,C);};if(B.delay){return setTimeout(E,B.delay);}if(B.periodical){return setInterval(E,B.periodical);}if(B.attempt){return $try(E);
}return E();};},pass:function(A,B){return this.create({arguments:A,bind:B});},attempt:function(A,B){return this.create({arguments:A,bind:B,attempt:true})();
},bind:function(B,A){return this.create({bind:B,arguments:A});},bindWithEvent:function(B,A){return this.create({bind:B,event:true,arguments:A});},delay:function(B,C,A){return this.create({delay:B,bind:C,arguments:A})();
},periodical:function(A,C,B){return this.create({periodical:A,bind:C,arguments:B})();},run:function(A,B){return this.apply(B,$splat(A));}});Number.implement({limit:function(B,A){return Math.min(A,Math.max(B,this));
},round:function(A){A=Math.pow(10,A||0);return Math.round(this*A)/A;},times:function(B,C){for(var A=0;A<this;A++){B.call(C,A,this);}},toFloat:function(){return parseFloat(this);
},toInt:function(A){return parseInt(this,A||10);}});Number.alias("times","each");(function(B){var A={};B.each(function(C){if(!Number[C]){A[C]=function(){return Math[C].apply(null,[this].concat($A(arguments)));
};}});Number.implement(A);})(["abs","acos","asin","atan","atan2","ceil","cos","exp","floor","log","max","min","pow","sin","sqrt","tan"]);String.implement({test:function(A,B){return((typeof A=="string")?new RegExp(A,B):A).test(this);
},contains:function(A,B){return(B)?(B+this+B).indexOf(B+A+B)>-1:this.indexOf(A)>-1;},trim:function(){return this.replace(/^\s+|\s+$/g,"");},clean:function(){return this.replace(/\s+/g," ").trim();
},camelCase:function(){return this.replace(/-\D/g,function(A){return A.charAt(1).toUpperCase();});},hyphenate:function(){return this.replace(/[A-Z]/g,function(A){return("-"+A.charAt(0).toLowerCase());
});},capitalize:function(){return this.replace(/\b[a-z]/g,function(A){return A.toUpperCase();});},escapeRegExp:function(){return this.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1");
},toInt:function(A){return parseInt(this,A||10);},toFloat:function(){return parseFloat(this);},hexToRgb:function(B){var A=this.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return(A)?A.slice(1).hexToRgb(B):null;},rgbToHex:function(B){var A=this.match(/\d{1,3}/g);return(A)?A.rgbToHex(B):null;},stripScripts:function(B){var A="";
var C=this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi,function(){A+=arguments[1]+"\n";return"";});if(B===true){$exec(A);}else{if($type(B)=="function"){B(A,C);
}}return C;},substitute:function(A,B){return this.replace(B||(/\\?\{([^}]+)\}/g),function(D,C){if(D.charAt(0)=="\\"){return D.slice(1);}return(A[C]!=undefined)?A[C]:"";
});}});Hash.implement({has:Object.prototype.hasOwnProperty,keyOf:function(B){for(var A in this){if(this.hasOwnProperty(A)&&this[A]===B){return A;}}return null;
},hasValue:function(A){return(Hash.keyOf(this,A)!==null);},extend:function(A){Hash.each(A,function(C,B){Hash.set(this,B,C);},this);return this;},combine:function(A){Hash.each(A,function(C,B){Hash.include(this,B,C);
},this);return this;},erase:function(A){if(this.hasOwnProperty(A)){delete this[A];}return this;},get:function(A){return(this.hasOwnProperty(A))?this[A]:null;
},set:function(A,B){if(!this[A]||this.hasOwnProperty(A)){this[A]=B;}return this;},empty:function(){Hash.each(this,function(B,A){delete this[A];},this);
return this;},include:function(B,C){var A=this[B];if(A==undefined){this[B]=C;}return this;},map:function(B,C){var A=new Hash;Hash.each(this,function(E,D){A.set(D,B.call(C,E,D,this));
},this);return A;},filter:function(B,C){var A=new Hash;Hash.each(this,function(E,D){if(B.call(C,E,D,this)){A.set(D,E);}},this);return A;},every:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&!B.call(C,this[A],A)){return false;
}}return true;},some:function(B,C){for(var A in this){if(this.hasOwnProperty(A)&&B.call(C,this[A],A)){return true;}}return false;},getKeys:function(){var A=[];
Hash.each(this,function(C,B){A.push(B);});return A;},getValues:function(){var A=[];Hash.each(this,function(B){A.push(B);});return A;},toQueryString:function(A){var B=[];
Hash.each(this,function(F,E){if(A){E=A+"["+E+"]";}var D;switch($type(F)){case"object":D=Hash.toQueryString(F,E);break;case"array":var C={};F.each(function(H,G){C[G]=H;
});D=Hash.toQueryString(C,E);break;default:D=E+"="+encodeURIComponent(F);}if(F!=undefined){B.push(D);}});return B.join("&");}});Hash.alias({keyOf:"indexOf",hasValue:"contains"});
var Event=new Native({name:"Event",initialize:function(A,F){F=F||window;var K=F.document;A=A||F.event;if(A.$extended){return A;}this.$extended=true;var J=A.type;
var G=A.target||A.srcElement;while(G&&G.nodeType==3){G=G.parentNode;}if(J.test(/key/)){var B=A.which||A.keyCode;var M=Event.Keys.keyOf(B);if(J=="keydown"){var D=B-111;
if(D>0&&D<13){M="f"+D;}}M=M||String.fromCharCode(B).toLowerCase();}else{if(J.match(/(click|mouse|menu)/i)){K=(!K.compatMode||K.compatMode=="CSS1Compat")?K.html:K.body;
var I={x:A.pageX||A.clientX+K.scrollLeft,y:A.pageY||A.clientY+K.scrollTop};var C={x:(A.pageX)?A.pageX-F.pageXOffset:A.clientX,y:(A.pageY)?A.pageY-F.pageYOffset:A.clientY};
if(J.match(/DOMMouseScroll|mousewheel/)){var H=(A.wheelDelta)?A.wheelDelta/120:-(A.detail||0)/3;}var E=(A.which==3)||(A.button==2);var L=null;if(J.match(/over|out/)){switch(J){case"mouseover":L=A.relatedTarget||A.fromElement;
break;case"mouseout":L=A.relatedTarget||A.toElement;}if(!(function(){while(L&&L.nodeType==3){L=L.parentNode;}return true;}).create({attempt:Browser.Engine.gecko})()){L=false;
}}}}return $extend(this,{event:A,type:J,page:I,client:C,rightClick:E,wheel:H,relatedTarget:L,target:G,code:B,key:M,shift:A.shiftKey,control:A.ctrlKey,alt:A.altKey,meta:A.metaKey});
}});Event.Keys=new Hash({enter:13,up:38,down:40,left:37,right:39,esc:27,space:32,backspace:8,tab:9,"delete":46});Event.implement({stop:function(){return this.stopPropagation().preventDefault();
},stopPropagation:function(){if(this.event.stopPropagation){this.event.stopPropagation();}else{this.event.cancelBubble=true;}return this;},preventDefault:function(){if(this.event.preventDefault){this.event.preventDefault();
}else{this.event.returnValue=false;}return this;}});var Class=new Native({name:"Class",initialize:function(B){B=B||{};var A=function(E){for(var D in this){this[D]=$unlink(this[D]);
}for(var F in Class.Mutators){if(!this[F]){continue;}Class.Mutators[F](this,this[F]);delete this[F];}this.constructor=A;if(E===$empty){return this;}var C=(this.initialize)?this.initialize.apply(this,arguments):this;
if(this.options&&this.options.initialize){this.options.initialize.call(this);}return C;};$extend(A,this);A.constructor=Class;A.prototype=B;return A;}});
Class.implement({implement:function(){Class.Mutators.Implements(this.prototype,Array.slice(arguments));return this;}});Class.Mutators={Implements:function(A,B){$splat(B).each(function(C){$extend(A,($type(C)=="class")?new C($empty):C);
});},Extends:function(self,klass){var instance=new klass($empty);delete instance.parent;delete instance.parentOf;for(var key in instance){var current=self[key],previous=instance[key];
if(current==undefined){self[key]=previous;continue;}var ctype=$type(current),ptype=$type(previous);if(ctype!=ptype){continue;}switch(ctype){case"function":if(!arguments.callee.caller){self[key]=eval("("+String(current).replace(/\bthis\.parent\(\s*(\))?/g,function(full,close){return"arguments.callee._parent_.call(this"+(close||", ");
})+")");}self[key]._parent_=previous;break;case"object":self[key]=$merge(previous,current);}}self.parent=function(){return arguments.callee.caller._parent_.apply(this,arguments);
};self.parentOf=function(descendant){return descendant._parent_.apply(this,Array.slice(arguments,1));};}};var Chain=new Class({chain:function(){this.$chain=(this.$chain||[]).extend(arguments);
return this;},callChain:function(){return(this.$chain&&this.$chain.length)?this.$chain.shift().apply(this,arguments):false;},clearChain:function(){if(this.$chain){this.$chain.empty();
}return this;}});var Events=new Class({addEvent:function(C,B,A){C=Events.removeOn(C);if(B!=$empty){this.$events=this.$events||{};this.$events[C]=this.$events[C]||[];
this.$events[C].include(B);if(A){B.internal=true;}}return this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);}return this;},fireEvent:function(C,B,A){C=Events.removeOn(C);
if(!this.$events||!this.$events[C]){return this;}this.$events[C].each(function(D){D.create({bind:this,delay:A,"arguments":B})();},this);return this;},removeEvent:function(B,A){B=Events.removeOn(B);
if(!this.$events||!this.$events[B]){return this;}if(!A.internal){this.$events[B].erase(A);}return this;},removeEvents:function(C){for(var D in this.$events){if(C&&C!=D){continue;
}var B=this.$events[D];for(var A=B.length;A--;A){this.removeEvent(D,B[A]);}}return this;}});Events.removeOn=function(A){return A.replace(/^on([A-Z])/,function(B,C){return C.toLowerCase();
});};var Options=new Class({setOptions:function(){this.options=$merge.run([this.options].extend(arguments));if(!this.addEvent){return this;}for(var A in this.options){if($type(this.options[A])!="function"||!(/^on[A-Z]/).test(A)){continue;
}this.addEvent(A,this.options[A]);delete this.options[A];}return this;}});Document.implement({newElement:function(A,B){if(Browser.Engine.trident&&B){["name","type","checked"].each(function(C){if(!B[C]){return ;
}A+=" "+C+'="'+B[C]+'"';if(C!="checked"){delete B[C];}});A="<"+A+">";}return $.element(this.createElement(A)).set(B);},newTextNode:function(A){return this.createTextNode(A);
},getDocument:function(){return this;},getWindow:function(){return this.defaultView||this.parentWindow;},purge:function(){var C=this.getElementsByTagName("*");
for(var B=0,A=C.length;B<A;B++){Browser.freeMem(C[B]);}}});var Element=new Native({name:"Element",legacy:window.Element,initialize:function(A,B){var C=Element.Constructors.get(A);
if(C){return C(B);}if(typeof A=="string"){return document.newElement(A,B);}return $(A).set(B);},afterImplement:function(A,B){if(!Array[A]){Elements.implement(A,Elements.multi(A));
}Element.Prototype[A]=B;}});Element.Prototype={$family:{name:"element"}};Element.Constructors=new Hash;var IFrame=new Native({name:"IFrame",generics:false,initialize:function(){var E=Array.link(arguments,{properties:Object.type,iframe:$defined});
var C=E.properties||{};var B=$(E.iframe)||false;var D=C.onload||$empty;delete C.onload;C.id=C.name=$pick(C.id,C.name,B.id,B.name,"IFrame_"+$time());B=new Element(B||"iframe",C);
var A=function(){var F=$try(function(){return B.contentWindow.location.host;});if(F&&F==window.location.host){var H=new Window(B.contentWindow);var G=new Document(B.contentWindow.document);
$extend(H.Element.prototype,Element.Prototype);}D.call(B.contentWindow,B.contentWindow.document);};(!window.frames[C.id])?B.addListener("load",A):A();return B;
}});var Elements=new Native({initialize:function(F,B){B=$extend({ddup:true,cash:true},B);F=F||[];if(B.ddup||B.cash){var G={},E=[];for(var C=0,A=F.length;
C<A;C++){var D=$.element(F[C],!B.cash);if(B.ddup){if(G[D.uid]){continue;}G[D.uid]=true;}E.push(D);}F=E;}return(B.cash)?$extend(F,this):F;}});Elements.implement({filter:function(A,B){if(!A){return this;
}return new Elements(Array.filter(this,(typeof A=="string")?function(C){return C.match(A);}:A,B));}});Elements.multi=function(A){return function(){var B=[];
var F=true;for(var D=0,C=this.length;D<C;D++){var E=this[D][A].apply(this[D],arguments);B.push(E);if(F){F=($type(E)=="element");}}return(F)?new Elements(B):B;
};};Window.implement({$:function(B,C){if(B&&B.$family&&B.uid){return B;}var A=$type(B);return($[A])?$[A](B,C,this.document):null;},$$:function(A){if(arguments.length==1&&typeof A=="string"){return this.document.getElements(A);
}var F=[];var C=Array.flatten(arguments);for(var D=0,B=C.length;D<B;D++){var E=C[D];switch($type(E)){case"element":E=[E];break;case"string":E=this.document.getElements(E,true);
break;default:E=false;}if(E){F.extend(E);}}return new Elements(F);},getDocument:function(){return this.document;},getWindow:function(){return this;}});
$.string=function(C,B,A){C=A.getElementById(C);return(C)?$.element(C,B):null;};$.element=function(A,D){$uid(A);if(!D&&!A.$family&&!(/^object|embed$/i).test(A.tagName)){var B=Element.Prototype;
for(var C in B){A[C]=B[C];}}return A;};$.object=function(B,C,A){if(B.toElement){return $.element(B.toElement(A),C);}return null;};$.textnode=$.whitespace=$.window=$.document=$arguments(0);
Native.implement([Element,Document],{getElement:function(A,B){return $(this.getElements(A,true)[0]||null,B);},getElements:function(A,D){A=A.split(",");
var C=[];var B=(A.length>1);A.each(function(E){var F=this.getElementsByTagName(E.trim());(B)?C.extend(F):C=F;},this);return new Elements(C,{ddup:B,cash:!D});
}});Element.Storage={get:function(A){return(this[A]||(this[A]={}));}};Element.Inserters=new Hash({before:function(B,A){if(A.parentNode){A.parentNode.insertBefore(B,A);
}},after:function(B,A){if(!A.parentNode){return ;}var C=A.nextSibling;(C)?A.parentNode.insertBefore(B,C):A.parentNode.appendChild(B);},bottom:function(B,A){A.appendChild(B);
},top:function(B,A){var C=A.firstChild;(C)?A.insertBefore(B,C):A.appendChild(B);}});Element.Inserters.inside=Element.Inserters.bottom;Element.Inserters.each(function(C,B){var A=B.capitalize();
Element.implement("inject"+A,function(D){C(this,$(D,true));return this;});Element.implement("grab"+A,function(D){C($(D,true),this);return this;});});Element.implement({getDocument:function(){return this.ownerDocument;
},getWindow:function(){return this.ownerDocument.getWindow();},getElementById:function(D,C){var B=this.ownerDocument.getElementById(D);if(!B){return null;
}for(var A=B.parentNode;A!=this;A=A.parentNode){if(!A){return null;}}return $.element(B,C);},set:function(D,B){switch($type(D)){case"object":for(var C in D){this.set(C,D[C]);
}break;case"string":var A=Element.Properties.get(D);(A&&A.set)?A.set.apply(this,Array.slice(arguments,1)):this.setProperty(D,B);}return this;},get:function(B){var A=Element.Properties.get(B);
return(A&&A.get)?A.get.apply(this,Array.slice(arguments,1)):this.getProperty(B);},erase:function(B){var A=Element.Properties.get(B);(A&&A.erase)?A.erase.apply(this,Array.slice(arguments,1)):this.removeProperty(B);
return this;},match:function(A){return(!A||Element.get(this,"tag")==A);},inject:function(B,A){Element.Inserters.get(A||"bottom")(this,$(B,true));return this;
},wraps:function(B,A){B=$(B,true);return this.replaces(B).grab(B,A);},grab:function(B,A){Element.Inserters.get(A||"bottom")($(B,true),this);return this;
},appendText:function(B,A){return this.grab(this.getDocument().newTextNode(B),A);},adopt:function(){Array.flatten(arguments).each(function(A){A=$(A,true);
if(A){this.appendChild(A);}},this);return this;},dispose:function(){return(this.parentNode)?this.parentNode.removeChild(this):this;},clone:function(D,C){switch($type(this)){case"element":var H={};
for(var G=0,E=this.attributes.length;G<E;G++){var B=this.attributes[G],L=B.nodeName.toLowerCase();if(Browser.Engine.trident&&(/input/i).test(this.tagName)&&(/width|height/).test(L)){continue;
}var K=(L=="style"&&this.style)?this.style.cssText:B.nodeValue;if(!$chk(K)||L=="uid"||(L=="id"&&!C)){continue;}if(K!="inherit"&&["string","number"].contains($type(K))){H[L]=K;
}}var J=new Element(this.nodeName.toLowerCase(),H);if(D!==false){for(var I=0,F=this.childNodes.length;I<F;I++){var A=Element.clone(this.childNodes[I],true,C);
if(A){J.grab(A);}}}return J;case"textnode":return document.newTextNode(this.nodeValue);}return null;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this,A);
return this;},hasClass:function(A){return this.className.contains(A," ");},addClass:function(A){if(!this.hasClass(A)){this.className=(this.className+" "+A).clean();
}return this;},removeClass:function(A){this.className=this.className.replace(new RegExp("(^|\\s)"+A+"(?:\\s|$)"),"$1").clean();return this;},toggleClass:function(A){return this.hasClass(A)?this.removeClass(A):this.addClass(A);
},getComputedStyle:function(B){if(this.currentStyle){return this.currentStyle[B.camelCase()];}var A=this.getWindow().getComputedStyle(this,null);return(A)?A.getPropertyValue([B.hyphenate()]):null;
},empty:function(){$A(this.childNodes).each(function(A){Browser.freeMem(A);Element.empty(A);Element.dispose(A);},this);return this;},destroy:function(){Browser.freeMem(this.empty().dispose());
return null;},getSelected:function(){return new Elements($A(this.options).filter(function(A){return A.selected;}));},toQueryString:function(){var A=[];
this.getElements("input, select, textarea").each(function(B){if(!B.name||B.disabled){return ;}var C=(B.tagName.toLowerCase()=="select")?Element.getSelected(B).map(function(D){return D.value;
}):((B.type=="radio"||B.type=="checkbox")&&!B.checked)?null:B.value;$splat(C).each(function(D){if(D){A.push(B.name+"="+encodeURIComponent(D));}});});return A.join("&");
},getProperty:function(C){var B=Element.Attributes,A=B.Props[C];var D=(A)?this[A]:this.getAttribute(C,2);return(B.Bools[C])?!!D:(A)?D:D||null;},getProperties:function(){var A=$A(arguments);
return A.map(function(B){return this.getProperty(B);},this).associate(A);},setProperty:function(D,E){var C=Element.Attributes,B=C.Props[D],A=$defined(E);
if(B&&C.Bools[D]){E=(E||!A)?true:false;}else{if(!A){return this.removeProperty(D);}}(B)?this[B]=E:this.setAttribute(D,E);return this;},setProperties:function(A){for(var B in A){this.setProperty(B,A[B]);
}return this;},removeProperty:function(D){var C=Element.Attributes,B=C.Props[D],A=(B&&C.Bools[D]);(B)?this[B]=(A)?false:"":this.removeAttribute(D);return this;
},removeProperties:function(){Array.each(arguments,this.removeProperty,this);return this;}});(function(){var A=function(D,B,I,C,F,H){var E=D[I||B];var G=[];
while(E){if(E.nodeType==1&&(!C||Element.match(E,C))){G.push(E);if(!F){break;}}E=E[B];}return(F)?new Elements(G,{ddup:false,cash:!H}):$(G[0],H);};Element.implement({getPrevious:function(B,C){return A(this,"previousSibling",null,B,false,C);
},getAllPrevious:function(B,C){return A(this,"previousSibling",null,B,true,C);},getNext:function(B,C){return A(this,"nextSibling",null,B,false,C);},getAllNext:function(B,C){return A(this,"nextSibling",null,B,true,C);
},getFirst:function(B,C){return A(this,"nextSibling","firstChild",B,false,C);},getLast:function(B,C){return A(this,"previousSibling","lastChild",B,false,C);
},getParent:function(B,C){return A(this,"parentNode",null,B,false,C);},getParents:function(B,C){return A(this,"parentNode",null,B,true,C);},getChildren:function(B,C){return A(this,"nextSibling","firstChild",B,true,C);
},hasChild:function(B){B=$(B,true);return(!!B&&$A(this.getElementsByTagName(B.tagName)).contains(B));}});})();Element.Properties=new Hash;Element.Properties.style={set:function(A){this.style.cssText=A;
},get:function(){return this.style.cssText;},erase:function(){this.style.cssText="";}};Element.Properties.tag={get:function(){return this.tagName.toLowerCase();
}};Element.Properties.href={get:function(){return(!this.href)?null:this.href.replace(new RegExp("^"+document.location.protocol+"//"+document.location.host),"");
}};Element.Properties.html={set:function(){return this.innerHTML=Array.flatten(arguments).join("");}};Native.implement([Element,Window,Document],{addListener:function(B,A){if(this.addEventListener){this.addEventListener(B,A,false);
}else{this.attachEvent("on"+B,A);}return this;},removeListener:function(B,A){if(this.removeEventListener){this.removeEventListener(B,A,false);}else{this.detachEvent("on"+B,A);
}return this;},retrieve:function(B,A){var D=Element.Storage.get(this.uid);var C=D[B];if($defined(A)&&!$defined(C)){C=D[B]=A;}return $pick(C);},store:function(B,A){var C=Element.Storage.get(this.uid);
C[B]=A;return this;},eliminate:function(A){var B=Element.Storage.get(this.uid);delete B[A];return this;}});Element.Attributes=new Hash({Props:{html:"innerHTML","class":"className","for":"htmlFor",text:(Browser.Engine.trident)?"innerText":"textContent"},Bools:["compact","nowrap","ismap","declare","noshade","checked","disabled","readonly","multiple","selected","noresize","defer"],Camels:["value","accessKey","cellPadding","cellSpacing","colSpan","frameBorder","maxLength","readOnly","rowSpan","tabIndex","useMap"]});
Browser.freeMem=function(A){if(!A){return ;}if(Browser.Engine.trident&&(/object/i).test(A.tagName)){for(var B in A){if(typeof A[B]=="function"){A[B]=$empty;
}}Element.dispose(A);}if(A.uid&&A.removeEvents){A.removeEvents();}};(function(B){var C=B.Bools,A=B.Camels;B.Bools=C=C.associate(C);Hash.extend(Hash.combine(B.Props,C),A.associate(A.map(function(D){return D.toLowerCase();
})));B.erase("Camels");})(Element.Attributes);window.addListener("unload",function(){window.removeListener("unload",arguments.callee);document.purge();
if(Browser.Engine.trident){CollectGarbage();}});Element.Properties.events={set:function(A){this.addEvents(A);}};Native.implement([Element,Window,Document],{addEvent:function(E,G){var H=this.retrieve("events",{});
H[E]=H[E]||{keys:[],values:[]};if(H[E].keys.contains(G)){return this;}H[E].keys.push(G);var F=E,A=Element.Events.get(E),C=G,I=this;if(A){if(A.onAdd){A.onAdd.call(this,G);
}if(A.condition){C=function(J){if(A.condition.call(this,J)){return G.call(this,J);}return false;};}F=A.base||F;}var D=function(){return G.call(I);};var B=Element.NativeEvents[F]||0;
if(B){if(B==2){D=function(J){J=new Event(J,I.getWindow());if(C.call(I,J)===false){J.stop();}};}this.addListener(F,D);}H[E].values.push(D);return this;},removeEvent:function(D,C){var B=this.retrieve("events");
if(!B||!B[D]){return this;}var G=B[D].keys.indexOf(C);if(G==-1){return this;}var A=B[D].keys.splice(G,1)[0];var F=B[D].values.splice(G,1)[0];var E=Element.Events.get(D);
if(E){if(E.onRemove){E.onRemove.call(this,C);}D=E.base||D;}return(Element.NativeEvents[D])?this.removeListener(D,F):this;},addEvents:function(A){for(var B in A){this.addEvent(B,A[B]);
}return this;},removeEvents:function(B){var A=this.retrieve("events");if(!A){return this;}if(!B){for(var C in A){this.removeEvents(C);}A=null;}else{if(A[B]){while(A[B].keys[0]){this.removeEvent(B,A[B].keys[0]);
}A[B]=null;}}return this;},fireEvent:function(D,B,A){var C=this.retrieve("events");if(!C||!C[D]){return this;}C[D].keys.each(function(E){E.create({bind:this,delay:A,"arguments":B})();
},this);return this;},cloneEvents:function(D,A){D=$(D);var C=D.retrieve("events");if(!C){return this;}if(!A){for(var B in C){this.cloneEvents(D,B);}}else{if(C[A]){C[A].keys.each(function(E){this.addEvent(A,E);
},this);}}return this;}});Element.NativeEvents={click:2,dblclick:2,mouseup:2,mousedown:2,contextmenu:2,mousewheel:2,DOMMouseScroll:2,mouseover:2,mouseout:2,mousemove:2,selectstart:2,selectend:2,keydown:2,keypress:2,keyup:2,focus:2,blur:2,change:2,reset:2,select:2,submit:2,load:1,unload:1,beforeunload:2,resize:1,move:1,DOMContentLoaded:1,readystatechange:1,error:1,abort:1,scroll:1};
(function(){var A=function(B){var C=B.relatedTarget;if(C==undefined){return true;}if(C===false){return false;}return($type(this)!="document"&&C!=this&&C.prefix!="xul"&&!this.hasChild(C));
};Element.Events=new Hash({mouseenter:{base:"mouseover",condition:A},mouseleave:{base:"mouseout",condition:A},mousewheel:{base:(Browser.Engine.gecko)?"DOMMouseScroll":"mousewheel"}});
})();Element.Properties.styles={set:function(A){this.setStyles(A);}};Element.Properties.opacity={set:function(A,B){if(!B){if(A==0){if(this.style.visibility!="hidden"){this.style.visibility="hidden";
}}else{if(this.style.visibility!="visible"){this.style.visibility="visible";}}}if(!this.currentStyle||!this.currentStyle.hasLayout){this.style.zoom=1;}if(Browser.Engine.trident){this.style.filter=(A==1)?"":"alpha(opacity="+A*100+")";
}this.style.opacity=A;this.store("opacity",A);},get:function(){return this.retrieve("opacity",1);}};Element.implement({setOpacity:function(A){return this.set("opacity",A,true);
},getOpacity:function(){return this.get("opacity");},setStyle:function(B,A){switch(B){case"opacity":return this.set("opacity",parseFloat(A));case"float":B=(Browser.Engine.trident)?"styleFloat":"cssFloat";
}B=B.camelCase();if($type(A)!="string"){var C=(Element.Styles.get(B)||"@").split(" ");A=$splat(A).map(function(E,D){if(!C[D]){return"";}return($type(E)=="number")?C[D].replace("@",Math.round(E)):E;
}).join(" ");}else{if(A==String(Number(A))){A=Math.round(A);}}this.style[B]=A;return this;},getStyle:function(G){switch(G){case"opacity":return this.get("opacity");
case"float":G=(Browser.Engine.trident)?"styleFloat":"cssFloat";}G=G.camelCase();var A=this.style[G];if(!$chk(A)){A=[];for(var F in Element.ShortStyles){if(G!=F){continue;
}for(var E in Element.ShortStyles[F]){A.push(this.getStyle(E));}return A.join(" ");}A=this.getComputedStyle(G);}if(A){A=String(A);var C=A.match(/rgba?\([\d\s,]+\)/);
if(C){A=A.replace(C[0],C[0].rgbToHex());}}if(Browser.Engine.presto||(Browser.Engine.trident&&!$chk(parseInt(A)))){if(G.test(/^(height|width)$/)){var B=(G=="width")?["left","right"]:["top","bottom"],D=0;
B.each(function(H){D+=this.getStyle("border-"+H+"-width").toInt()+this.getStyle("padding-"+H).toInt();},this);return this["offset"+G.capitalize()]-D+"px";
}if(Browser.Engine.presto&&String(A).test("px")){return A;}if(G.test(/(border(.+)Width|margin|padding)/)){return"0px";}}return A;},setStyles:function(B){for(var A in B){this.setStyle(A,B[A]);
}return this;},getStyles:function(){var A={};Array.each(arguments,function(B){A[B]=this.getStyle(B);},this);return A;}});Element.Styles=new Hash({left:"@px",top:"@px",bottom:"@px",right:"@px",width:"@px",height:"@px",maxWidth:"@px",maxHeight:"@px",minWidth:"@px",minHeight:"@px",backgroundColor:"rgb(@, @, @)",backgroundPosition:"@px @px",color:"rgb(@, @, @)",fontSize:"@px",letterSpacing:"@px",lineHeight:"@px",clip:"rect(@px @px @px @px)",margin:"@px @px @px @px",padding:"@px @px @px @px",border:"@px @ rgb(@, @, @) @px @ rgb(@, @, @) @px @ rgb(@, @, @)",borderWidth:"@px @px @px @px",borderStyle:"@ @ @ @",borderColor:"rgb(@, @, @) rgb(@, @, @) rgb(@, @, @) rgb(@, @, @)",zIndex:"@",zoom:"@",fontWeight:"@",textIndent:"@px",opacity:"@"});
Element.ShortStyles={margin:{},padding:{},border:{},borderWidth:{},borderStyle:{},borderColor:{}};["Top","Right","Bottom","Left"].each(function(G){var F=Element.ShortStyles;
var B=Element.Styles;["margin","padding"].each(function(H){var I=H+G;F[H][I]=B[I]="@px";});var E="border"+G;F.border[E]=B[E]="@px @ rgb(@, @, @)";var D=E+"Width",A=E+"Style",C=E+"Color";
F[E]={};F.borderWidth[D]=F[E][D]=B[D]="@px";F.borderStyle[A]=F[E][A]=B[A]="@";F.borderColor[C]=F[E][C]=B[C]="rgb(@, @, @)";});(function(){Element.implement({scrollTo:function(H,I){if(B(this)){this.getWindow().scrollTo(H,I);
}else{this.scrollLeft=H;this.scrollTop=I;}return this;},getSize:function(){if(B(this)){return this.getWindow().getSize();}return{x:this.offsetWidth,y:this.offsetHeight};
},getScrollSize:function(){if(B(this)){return this.getWindow().getScrollSize();}return{x:this.scrollWidth,y:this.scrollHeight};},getScroll:function(){if(B(this)){return this.getWindow().getScroll();
}return{x:this.scrollLeft,y:this.scrollTop};},getScrolls:function(){var I=this,H={x:0,y:0};while(I&&!B(I)){H.x+=I.scrollLeft;H.y+=I.scrollTop;I=I.parentNode;
}return H;},getOffsetParent:function(){var H=this;if(B(H)){return null;}if(!Browser.Engine.trident){return H.offsetParent;}while((H=H.parentNode)&&!B(H)){if(D(H,"position")!="static"){return H;
}}return null;},getOffsets:function(){var I=this,H={x:0,y:0};if(B(this)){return H;}while(I&&!B(I)){H.x+=I.offsetLeft;H.y+=I.offsetTop;if(Browser.Engine.gecko){if(!F(I)){H.x+=C(I);
H.y+=G(I);}var J=I.parentNode;if(J&&D(J,"overflow")!="visible"){H.x+=C(J);H.y+=G(J);}}else{if(I!=this&&(Browser.Engine.trident||Browser.Engine.webkit)){H.x+=C(I);
H.y+=G(I);}}I=I.offsetParent;if(Browser.Engine.trident){while(I&&!I.currentStyle.hasLayout){I=I.offsetParent;}}}if(Browser.Engine.gecko&&!F(this)){H.x-=C(this);
H.y-=G(this);}return H;},getPosition:function(K){if(B(this)){return{x:0,y:0};}var L=this.getOffsets(),I=this.getScrolls();var H={x:L.x-I.x,y:L.y-I.y};var J=(K&&(K=$(K)))?K.getPosition():{x:0,y:0};
return{x:H.x-J.x,y:H.y-J.y};},getCoordinates:function(J){if(B(this)){return this.getWindow().getCoordinates();}var H=this.getPosition(J),I=this.getSize();
var K={left:H.x,top:H.y,width:I.x,height:I.y};K.right=K.left+K.width;K.bottom=K.top+K.height;return K;},computePosition:function(H){return{left:H.x-E(this,"margin-left"),top:H.y-E(this,"margin-top")};
},position:function(H){return this.setStyles(this.computePosition(H));}});Native.implement([Document,Window],{getSize:function(){var I=this.getWindow();
if(Browser.Engine.presto||Browser.Engine.webkit){return{x:I.innerWidth,y:I.innerHeight};}var H=A(this);return{x:H.clientWidth,y:H.clientHeight};},getScroll:function(){var I=this.getWindow();
var H=A(this);return{x:I.pageXOffset||H.scrollLeft,y:I.pageYOffset||H.scrollTop};},getScrollSize:function(){var I=A(this);var H=this.getSize();return{x:Math.max(I.scrollWidth,H.x),y:Math.max(I.scrollHeight,H.y)};
},getPosition:function(){return{x:0,y:0};},getCoordinates:function(){var H=this.getSize();return{top:0,left:0,bottom:H.y,right:H.x,height:H.y,width:H.x};
}});var D=Element.getComputedStyle;function E(H,I){return D(H,I).toInt()||0;}function F(H){return D(H,"-moz-box-sizing")=="border-box";}function G(H){return E(H,"border-top-width");
}function C(H){return E(H,"border-left-width");}function B(H){return(/^(?:body|html)$/i).test(H.tagName);}function A(H){var I=H.getDocument();return(!I.compatMode||I.compatMode=="CSS1Compat")?I.html:I.body;
}})();Native.implement([Window,Document,Element],{getHeight:function(){return this.getSize().y;},getWidth:function(){return this.getSize().x;},getScrollTop:function(){return this.getScroll().y;
},getScrollLeft:function(){return this.getScroll().x;},getScrollHeight:function(){return this.getScrollSize().y;},getScrollWidth:function(){return this.getScrollSize().x;
},getTop:function(){return this.getPosition().y;},getLeft:function(){return this.getPosition().x;}});Native.implement([Document,Element],{getElements:function(H,G){H=H.split(",");
var C,E={};for(var D=0,B=H.length;D<B;D++){var A=H[D],F=Selectors.Utils.search(this,A,E);if(D!=0&&F.item){F=$A(F);}C=(D==0)?F:(C.item)?$A(C).concat(F):C.concat(F);
}return new Elements(C,{ddup:(H.length>1),cash:!G});}});Element.implement({match:function(B){if(!B){return true;}var D=Selectors.Utils.parseTagAndID(B);
var A=D[0],E=D[1];if(!Selectors.Filters.byID(this,E)||!Selectors.Filters.byTag(this,A)){return false;}var C=Selectors.Utils.parseSelector(B);return(C)?Selectors.Utils.filter(this,C,{}):true;
}});var Selectors={Cache:{nth:{},parsed:{}}};Selectors.RegExps={id:(/#([\w-]+)/),tag:(/^(\w+|\*)/),quick:(/^(\w+|\*)$/),splitter:(/\s*([+>~\s])\s*([a-zA-Z#.*:\[])/g),combined:(/\.([\w-]+)|\[(\w+)(?:([!*^$~|]?=)["']?(.*?)["']?)?\]|:([\w-]+)(?:\(["']?(.*?)?["']?\)|$)/g)};
Selectors.Utils={chk:function(B,C){if(!C){return true;}var A=$uid(B);if(!C[A]){return C[A]=true;}return false;},parseNthArgument:function(F){if(Selectors.Cache.nth[F]){return Selectors.Cache.nth[F];
}var C=F.match(/^([+-]?\d*)?([a-z]+)?([+-]?\d*)?$/);if(!C){return false;}var E=parseInt(C[1]);var B=(E||E===0)?E:1;var D=C[2]||false;var A=parseInt(C[3])||0;
if(B!=0){A--;while(A<1){A+=B;}while(A>=B){A-=B;}}else{B=A;D="index";}switch(D){case"n":C={a:B,b:A,special:"n"};break;case"odd":C={a:2,b:0,special:"n"};
break;case"even":C={a:2,b:1,special:"n"};break;case"first":C={a:0,special:"index"};break;case"last":C={special:"last-child"};break;case"only":C={special:"only-child"};
break;default:C={a:(B-1),special:"index"};}return Selectors.Cache.nth[F]=C;},parseSelector:function(E){if(Selectors.Cache.parsed[E]){return Selectors.Cache.parsed[E];
}var D,H={classes:[],pseudos:[],attributes:[]};while((D=Selectors.RegExps.combined.exec(E))){var I=D[1],G=D[2],F=D[3],B=D[4],C=D[5],J=D[6];if(I){H.classes.push(I);
}else{if(C){var A=Selectors.Pseudo.get(C);if(A){H.pseudos.push({parser:A,argument:J});}else{H.attributes.push({name:C,operator:"=",value:J});}}else{if(G){H.attributes.push({name:G,operator:F,value:B});
}}}}if(!H.classes.length){delete H.classes;}if(!H.attributes.length){delete H.attributes;}if(!H.pseudos.length){delete H.pseudos;}if(!H.classes&&!H.attributes&&!H.pseudos){H=null;
}return Selectors.Cache.parsed[E]=H;},parseTagAndID:function(B){var A=B.match(Selectors.RegExps.tag);var C=B.match(Selectors.RegExps.id);return[(A)?A[1]:"*",(C)?C[1]:false];
},filter:function(F,C,E){var D;if(C.classes){for(D=C.classes.length;D--;D){var G=C.classes[D];if(!Selectors.Filters.byClass(F,G)){return false;}}}if(C.attributes){for(D=C.attributes.length;
D--;D){var B=C.attributes[D];if(!Selectors.Filters.byAttribute(F,B.name,B.operator,B.value)){return false;}}}if(C.pseudos){for(D=C.pseudos.length;D--;D){var A=C.pseudos[D];
if(!Selectors.Filters.byPseudo(F,A.parser,A.argument,E)){return false;}}}return true;},getByTagAndID:function(B,A,D){if(D){var C=(B.getElementById)?B.getElementById(D,true):Element.getElementById(B,D,true);
return(C&&Selectors.Filters.byTag(C,A))?[C]:[];}else{return B.getElementsByTagName(A);}},search:function(J,I,O){var B=[];var C=I.trim().replace(Selectors.RegExps.splitter,function(Z,Y,X){B.push(Y);
return":)"+X;}).split(":)");var K,F,E,V;for(var U=0,Q=C.length;U<Q;U++){var T=C[U];if(U==0&&Selectors.RegExps.quick.test(T)){K=J.getElementsByTagName(T);
continue;}var A=B[U-1];var L=Selectors.Utils.parseTagAndID(T);var W=L[0],M=L[1];if(U==0){K=Selectors.Utils.getByTagAndID(J,W,M);}else{var D={},H=[];for(var S=0,R=K.length;
S<R;S++){H=Selectors.Getters[A](H,K[S],W,M,D);}K=H;}var G=Selectors.Utils.parseSelector(T);if(G){E=[];for(var P=0,N=K.length;P<N;P++){V=K[P];if(Selectors.Utils.filter(V,G,O)){E.push(V);
}}K=E;}}return K;}};Selectors.Getters={" ":function(H,G,I,A,E){var D=Selectors.Utils.getByTagAndID(G,I,A);for(var C=0,B=D.length;C<B;C++){var F=D[C];if(Selectors.Utils.chk(F,E)){H.push(F);
}}return H;},">":function(H,G,I,A,F){var C=Selectors.Utils.getByTagAndID(G,I,A);for(var E=0,D=C.length;E<D;E++){var B=C[E];if(B.parentNode==G&&Selectors.Utils.chk(B,F)){H.push(B);
}}return H;},"+":function(C,B,A,E,D){while((B=B.nextSibling)){if(B.nodeType==1){if(Selectors.Utils.chk(B,D)&&Selectors.Filters.byTag(B,A)&&Selectors.Filters.byID(B,E)){C.push(B);
}break;}}return C;},"~":function(C,B,A,E,D){while((B=B.nextSibling)){if(B.nodeType==1){if(!Selectors.Utils.chk(B,D)){break;}if(Selectors.Filters.byTag(B,A)&&Selectors.Filters.byID(B,E)){C.push(B);
}}}return C;}};Selectors.Filters={byTag:function(B,A){return(A=="*"||(B.tagName&&B.tagName.toLowerCase()==A));},byID:function(A,B){return(!B||(A.id&&A.id==B));
},byClass:function(B,A){return(B.className&&B.className.contains(A," "));},byPseudo:function(A,D,C,B){return D.call(A,C,B);},byAttribute:function(C,D,B,E){var A=Element.prototype.getProperty.call(C,D);
if(!A){return false;}if(!B||E==undefined){return true;}switch(B){case"=":return(A==E);case"*=":return(A.contains(E));case"^=":return(A.substr(0,E.length)==E);
case"$=":return(A.substr(A.length-E.length)==E);case"!=":return(A!=E);case"~=":return A.contains(E," ");case"|=":return A.contains(E,"-");}return false;
}};Selectors.Pseudo=new Hash({empty:function(){return !(this.innerText||this.textContent||"").length;},not:function(A){return !Element.match(this,A);},contains:function(A){return(this.innerText||this.textContent||"").contains(A);
},"first-child":function(){return Selectors.Pseudo.index.call(this,0);},"last-child":function(){var A=this;while((A=A.nextSibling)){if(A.nodeType==1){return false;
}}return true;},"only-child":function(){var B=this;while((B=B.previousSibling)){if(B.nodeType==1){return false;}}var A=this;while((A=A.nextSibling)){if(A.nodeType==1){return false;
}}return true;},"nth-child":function(G,E){G=(G==undefined)?"n":G;var C=Selectors.Utils.parseNthArgument(G);if(C.special!="n"){return Selectors.Pseudo[C.special].call(this,C.a,E);
}var F=0;E.positions=E.positions||{};var D=$uid(this);if(!E.positions[D]){var B=this;while((B=B.previousSibling)){if(B.nodeType!=1){continue;}F++;var A=E.positions[$uid(B)];
if(A!=undefined){F=A+F;break;}}E.positions[D]=F;}return(E.positions[D]%C.a==C.b);},index:function(A){var B=this,C=0;while((B=B.previousSibling)){if(B.nodeType==1&&++C>A){return false;
}}return(C==A);},even:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n+1",A);},odd:function(B,A){return Selectors.Pseudo["nth-child"].call(this,"2n",A);
}});Element.Events.domready={onAdd:function(A){if(Browser.loaded){A.call(this);}}};(function(){var B=function(){if(Browser.loaded){return ;}Browser.loaded=true;
window.fireEvent("domready");document.fireEvent("domready");};switch(Browser.Engine.name){case"webkit":(function(){(["loaded","complete"].contains(document.readyState))?B():arguments.callee.delay(50);
})();break;case"trident":var A=document.createElement("div");(function(){($try(function(){A.doScroll("left");return $(A).inject(document.body).set("html","temp").dispose();
}))?B():arguments.callee.delay(50);})();break;default:window.addEvent("load",B);document.addEvent("DOMContentLoaded",B);}})();var JSON=new Hash({encode:function(B){switch($type(B)){case"string":return'"'+B.replace(/[\x00-\x1f\\"]/g,JSON.$replaceChars)+'"';
case"array":return"["+String(B.map(JSON.encode).filter($defined))+"]";case"object":case"hash":var A=[];Hash.each(B,function(E,D){var C=JSON.encode(E);if(C){A.push(JSON.encode(D)+":"+C);
}});return"{"+A+"}";case"number":case"boolean":return String(B);case false:return"null";}return null;},$specialChars:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},$replaceChars:function(A){return JSON.$specialChars[A]||"\\u00"+Math.floor(A.charCodeAt()/16).toString(16)+(A.charCodeAt()%16).toString(16);
},decode:function(string,secure){if($type(string)!="string"||!string.length){return null;}if(secure&&!(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(string.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""))){return null;
}return eval("("+string+")");}});Native.implement([Hash,Array,String,Number],{toJSON:function(){return JSON.encode(this);}});var Cookie=new Class({Implements:Options,options:{path:false,domain:false,duration:false,secure:false,document:document},initialize:function(B,A){this.key=B;
this.setOptions(A);},write:function(B){B=encodeURIComponent(B);if(this.options.domain){B+="; domain="+this.options.domain;}if(this.options.path){B+="; path="+this.options.path;
}if(this.options.duration){var A=new Date();A.setTime(A.getTime()+this.options.duration*24*60*60*1000);B+="; expires="+A.toGMTString();}if(this.options.secure){B+="; secure";
}this.options.document.cookie=this.key+"="+B;return this;},read:function(){var A=this.options.document.cookie.match("(?:^|;)\\s*"+this.key.escapeRegExp()+"=([^;]*)");
return(A)?decodeURIComponent(A[1]):null;},dispose:function(){new Cookie(this.key,$merge(this.options,{duration:-1})).write("");return this;}});Cookie.write=function(B,C,A){return new Cookie(B,A).write(C);
};Cookie.read=function(A){return new Cookie(A).read();};Cookie.dispose=function(B,A){return new Cookie(B,A).dispose();};var Swiff=new Class({Implements:[Options],options:{id:null,height:1,width:1,container:null,properties:{},params:{quality:"high",allowScriptAccess:"always",wMode:"transparent",swLiveConnect:true},callBacks:{},vars:{}},toElement:function(){return this.object;
},initialize:function(L,M){this.instance="Swiff_"+$time();this.setOptions(M);M=this.options;var B=this.id=M.id||this.instance;var A=$(M.container);Swiff.CallBacks[this.instance]={};
var E=M.params,G=M.vars,F=M.callBacks;var H=$extend({height:M.height,width:M.width},M.properties);var K=this;for(var D in F){Swiff.CallBacks[this.instance][D]=(function(N){return function(){return N.apply(K.object,arguments);
};})(F[D]);G[D]="Swiff.CallBacks."+this.instance+"."+D;}E.flashVars=Hash.toQueryString(G);if(Browser.Engine.trident){H.classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000";
E.movie=L;}else{H.type="application/x-shockwave-flash";H.data=L;}var J='<object id="'+B+'"';for(var I in H){J+=" "+I+'="'+H[I]+'"';}J+=">";for(var C in E){if(E[C]){J+='<param name="'+C+'" value="'+E[C]+'" />';
}}J+="</object>";this.object=((A)?A.empty():new Element("div")).set("html",J).firstChild;},replaces:function(A){A=$(A,true);A.parentNode.replaceChild(this.toElement(),A);
return this;},inject:function(A){$(A,true).appendChild(this.toElement());return this;},remote:function(){return Swiff.remote.apply(Swiff,[this.toElement()].extend(arguments));
}});Swiff.CallBacks={};Swiff.remote=function(obj,fn){var rs=obj.CallFunction('<invoke name="'+fn+'" returntype="javascript">'+__flash__argumentsToXML(arguments,2)+"</invoke>");
return eval(rs);};var Fx=new Class({Implements:[Chain,Events,Options],options:{fps:50,unit:false,duration:500,link:"ignore",transition:function(A){return -(Math.cos(Math.PI*A)-1)/2;
}},initialize:function(A){this.subject=this.subject||this;this.setOptions(A);this.options.duration=Fx.Durations[this.options.duration]||this.options.duration.toInt();
var B=this.options.wait;if(B===false){this.options.link="cancel";}},step:function(){var A=$time();if(A<this.time+this.options.duration){var B=this.options.transition((A-this.time)/this.options.duration);
this.set(this.compute(this.from,this.to,B));}else{this.set(this.compute(this.from,this.to,1));this.complete();}},set:function(A){return A;},compute:function(C,B,A){return Fx.compute(C,B,A);
},check:function(A){if(!this.timer){return true;}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));
return false;}return false;},start:function(B,A){if(!this.check(arguments.callee,B,A)){return this;}this.from=B;this.to=A;this.time=0;this.startTimer();
this.onStart();return this;},complete:function(){if(this.stopTimer()){this.onComplete();}return this;},cancel:function(){if(this.stopTimer()){this.onCancel();
}return this;},onStart:function(){this.fireEvent("start",this.subject);},onComplete:function(){this.fireEvent("complete",this.subject);if(!this.callChain()){this.fireEvent("chainComplete",this.subject);
}},onCancel:function(){this.fireEvent("cancel",this.subject).clearChain();},pause:function(){this.stopTimer();return this;},resume:function(){this.startTimer();
return this;},stopTimer:function(){if(!this.timer){return false;}this.time=$time()-this.time;this.timer=$clear(this.timer);return true;},startTimer:function(){if(this.timer){return false;
}this.time=$time()-this.time;this.timer=this.step.periodical(Math.round(1000/this.options.fps),this);return true;}});Fx.compute=function(C,B,A){return(B-C)*A+C;
};Fx.Durations={"short":250,normal:500,"long":1000};Fx.CSS=new Class({Extends:Fx,prepare:function(D,E,B){B=$splat(B);var C=B[1];if(!$chk(C)){B[1]=B[0];
B[0]=D.getStyle(E);}var A=B.map(this.parse);return{from:A[0],to:A[1]};},parse:function(A){A=$lambda(A)();A=(typeof A=="string")?A.split(" "):$splat(A);
return A.map(function(C){C=String(C);var B=false;Fx.CSS.Parsers.each(function(F,E){if(B){return ;}var D=F.parse(C);if($chk(D)){B={value:D,parser:F};}});
B=B||{value:C,parser:Fx.CSS.Parsers.String};return B;});},compute:function(D,C,B){var A=[];(Math.min(D.length,C.length)).times(function(E){A.push({value:D[E].parser.compute(D[E].value,C[E].value,B),parser:D[E].parser});
});A.$family={name:"fx:css:value"};return A;},serve:function(C,B){if($type(C)!="fx:css:value"){C=this.parse(C);}var A=[];C.each(function(D){A=A.concat(D.parser.serve(D.value,B));
});return A;},render:function(A,D,C,B){A.setStyle(D,this.serve(C,B));},search:function(A){if(Fx.CSS.Cache[A]){return Fx.CSS.Cache[A];}var B={};Array.each(document.styleSheets,function(E,D){var C=E.href;
if(C&&C.contains("://")&&!C.contains(document.domain)){return ;}var F=E.rules||E.cssRules;Array.each(F,function(I,G){if(!I.style){return ;}var H=(I.selectorText)?I.selectorText.replace(/^\w+/,function(J){return J.toLowerCase();
}):null;if(!H||!H.test("^"+A+"$")){return ;}Element.Styles.each(function(K,J){if(!I.style[J]||Element.ShortStyles[J]){return ;}K=String(I.style[J]);B[J]=(K.test(/^rgb/))?K.rgbToHex():K;
});});});return Fx.CSS.Cache[A]=B;}});Fx.CSS.Cache={};Fx.CSS.Parsers=new Hash({Color:{parse:function(A){if(A.match(/^#[0-9a-f]{3,6}$/i)){return A.hexToRgb(true);
}return((A=A.match(/(\d+),\s*(\d+),\s*(\d+)/)))?[A[1],A[2],A[3]]:false;},compute:function(C,B,A){return C.map(function(E,D){return Math.round(Fx.compute(C[D],B[D],A));
});},serve:function(A){return A.map(Number);}},Number:{parse:parseFloat,compute:Fx.compute,serve:function(B,A){return(A)?B+A:B;}},String:{parse:$lambda(false),compute:$arguments(1),serve:$arguments(0)}});
Fx.Tween=new Class({Extends:Fx.CSS,initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);},set:function(B,A){if(arguments.length==1){A=B;
B=this.property||this.options.property;}this.render(this.element,B,A,this.options.unit);return this;},start:function(C,E,D){if(!this.check(arguments.callee,C,E,D)){return this;
}var B=Array.flatten(arguments);this.property=this.options.property||B.shift();var A=this.prepare(this.element,this.property,B);return this.parent(A.from,A.to);
}});Element.Properties.tween={set:function(A){var B=this.retrieve("tween");if(B){B.cancel();}return this.eliminate("tween").store("tween:options",$extend({link:"cancel"},A));
},get:function(A){if(A||!this.retrieve("tween")){if(A||!this.retrieve("tween:options")){this.set("tween",A);}this.store("tween",new Fx.Tween(this,this.retrieve("tween:options")));
}return this.retrieve("tween");}};Element.implement({tween:function(A,C,B){this.get("tween").start(arguments);return this;},fade:function(C){var E=this.get("tween"),D="opacity",A;
C=$pick(C,"toggle");switch(C){case"in":E.start(D,1);break;case"out":E.start(D,0);break;case"show":E.set(D,1);break;case"hide":E.set(D,0);break;case"toggle":var B=this.retrieve("fade:flag",this.get("opacity")==1);
E.start(D,(B)?0:1);this.store("fade:flag",!B);A=true;break;default:E.start(D,arguments);}if(!A){this.eliminate("fade:flag");}return this;},highlight:function(C,A){if(!A){A=this.retrieve("highlight:original",this.getStyle("background-color"));
A=(A=="transparent")?"#fff":A;}var B=this.get("tween");B.start("background-color",C||"#ffff88",A).chain(function(){this.setStyle("background-color",this.retrieve("highlight:original"));
B.callChain();}.bind(this));return this;}});Fx.Morph=new Class({Extends:Fx.CSS,initialize:function(B,A){this.element=this.subject=$(B);this.parent(A);},set:function(A){if(typeof A=="string"){A=this.search(A);
}for(var B in A){this.render(this.element,B,A[B],this.options.unit);}return this;},compute:function(E,D,C){var A={};for(var B in E){A[B]=this.parent(E[B],D[B],C);
}return A;},start:function(B){if(!this.check(arguments.callee,B)){return this;}if(typeof B=="string"){B=this.search(B);}var E={},D={};for(var C in B){var A=this.prepare(this.element,C,B[C]);
E[C]=A.from;D[C]=A.to;}return this.parent(E,D);}});Element.Properties.morph={set:function(A){var B=this.retrieve("morph");if(B){B.cancel();}return this.eliminate("morph").store("morph:options",$extend({link:"cancel"},A));
},get:function(A){if(A||!this.retrieve("morph")){if(A||!this.retrieve("morph:options")){this.set("morph",A);}this.store("morph",new Fx.Morph(this,this.retrieve("morph:options")));
}return this.retrieve("morph");}};Element.implement({morph:function(A){this.get("morph").start(A);return this;}});(function(){var A=Fx.prototype.initialize;
Fx.prototype.initialize=function(B){A.call(this,B);var C=this.options.transition;if(typeof C=="string"&&(C=C.split(":"))){var D=Fx.Transitions;D=D[C[0]]||D[C[0].capitalize()];
if(C[1]){D=D["ease"+C[1].capitalize()+(C[2]?C[2].capitalize():"")];}this.options.transition=D;}};})();Fx.Transition=function(B,A){A=$splat(A);return $extend(B,{easeIn:function(C){return B(C,A);
},easeOut:function(C){return 1-B(1-C,A);},easeInOut:function(C){return(C<=0.5)?B(2*C,A)/2:(2-B(2*(1-C),A))/2;}});};Fx.Transitions=new Hash({linear:$arguments(0)});
Fx.Transitions.extend=function(A){for(var B in A){Fx.Transitions[B]=new Fx.Transition(A[B]);}};Fx.Transitions.extend({Pow:function(B,A){return Math.pow(B,A[0]||6);
},Expo:function(A){return Math.pow(2,8*(A-1));},Circ:function(A){return 1-Math.sin(Math.acos(A));},Sine:function(A){return 1-Math.sin((1-A)*Math.PI/2);
},Back:function(B,A){A=A[0]||1.618;return Math.pow(B,2)*((A+1)*B-A);},Bounce:function(D){var C;for(var B=0,A=1;1;B+=A,A/=2){if(D>=(7-4*B)/11){C=-Math.pow((11-6*B-11*D)/4,2)+A*A;
break;}}return C;},Elastic:function(B,A){return Math.pow(2,10*--B)*Math.cos(20*B*Math.PI*(A[0]||1)/3);}});["Quad","Cubic","Quart","Quint"].each(function(B,A){Fx.Transitions[B]=new Fx.Transition(function(C){return Math.pow(C,[A+2]);
});});var Request=new Class({Implements:[Chain,Events,Options],options:{url:"",data:"",headers:{"X-Requested-With":"XMLHttpRequest",Accept:"text/javascript, text/html, application/xml, text/xml, */*"},async:true,format:false,method:"post",link:"ignore",isSuccess:null,emulation:true,urlEncoded:true,encoding:"utf-8",evalScripts:false,evalResponse:false},initialize:function(A){this.xhr=new Browser.Request();
this.setOptions(A);this.options.isSuccess=this.options.isSuccess||this.isSuccess;this.headers=new Hash(this.options.headers);},onStateChange:function(){if(this.xhr.readyState!=4||!this.running){return ;
}this.running=false;this.status=0;$try(function(){this.status=this.xhr.status;}.bind(this));if(this.options.isSuccess.call(this,this.status)){this.response={text:this.xhr.responseText,xml:this.xhr.responseXML};
this.success(this.response.text,this.response.xml);}else{this.response={text:null,xml:null};this.failure();}this.xhr.onreadystatechange=$empty;},isSuccess:function(){return((this.status>=200)&&(this.status<300));
},processScripts:function(A){if(this.options.evalResponse||(/(ecma|java)script/).test(this.getHeader("Content-type"))){return $exec(A);}return A.stripScripts(this.options.evalScripts);
},success:function(B,A){this.onSuccess(this.processScripts(B),A);},onSuccess:function(){this.fireEvent("complete",arguments).fireEvent("success",arguments).callChain();
},failure:function(){this.onFailure();},onFailure:function(){this.fireEvent("complete").fireEvent("failure",this.xhr);},setHeader:function(A,B){this.headers.set(A,B);
return this;},getHeader:function(A){return $try(function(){return this.xhr.getResponseHeader(A);}.bind(this));},check:function(A){if(!this.running){return true;
}switch(this.options.link){case"cancel":this.cancel();return true;case"chain":this.chain(A.bind(this,Array.slice(arguments,1)));return false;}return false;
},send:function(I){if(!this.check(arguments.callee,I)){return this;}this.running=true;var G=$type(I);if(G=="string"||G=="element"){I={data:I};}var D=this.options;
I=$extend({data:D.data,url:D.url,method:D.method},I);var E=I.data,B=I.url,A=I.method;switch($type(E)){case"element":E=$(E).toQueryString();break;case"object":case"hash":E=Hash.toQueryString(E);
}if(this.options.format){var H="format="+this.options.format;E=(E)?H+"&"+E:H;}if(this.options.emulation&&["put","delete"].contains(A)){var F="_method="+A;
E=(E)?F+"&"+E:F;A="post";}if(this.options.urlEncoded&&A=="post"){var C=(this.options.encoding)?"; charset="+this.options.encoding:"";this.headers.set("Content-type","application/x-www-form-urlencoded"+C);
}if(E&&A=="get"){B=B+(B.contains("?")?"&":"?")+E;E=null;}this.xhr.open(A.toUpperCase(),B,this.options.async);this.xhr.onreadystatechange=this.onStateChange.bind(this);
this.headers.each(function(K,J){if(!$try(function(){this.xhr.setRequestHeader(J,K);return true;}.bind(this))){this.fireEvent("exception",[J,K]);}},this);
this.fireEvent("request");this.xhr.send(E);if(!this.options.async){this.onStateChange();}return this;},cancel:function(){if(!this.running){return this;
}this.running=false;this.xhr.abort();this.xhr.onreadystatechange=$empty;this.xhr=new Browser.Request();this.fireEvent("cancel");return this;}});(function(){var A={};
["get","post","put","delete","GET","POST","PUT","DELETE"].each(function(B){A[B]=function(){var C=Array.link(arguments,{url:String.type,data:$defined});
return this.send($extend(C,{method:B.toLowerCase()}));};});Request.implement(A);})();Element.Properties.send={set:function(A){var B=this.retrieve("send");
if(B){B.cancel();}return this.eliminate("send").store("send:options",$extend({data:this,link:"cancel",method:this.get("method")||"post",url:this.get("action")},A));
},get:function(A){if(A||!this.retrieve("send")){if(A||!this.retrieve("send:options")){this.set("send",A);}this.store("send",new Request(this.retrieve("send:options")));
}return this.retrieve("send");}};Element.implement({send:function(A){var B=this.get("send");B.send({data:this,url:A||B.options.url});return this;}});Request.HTML=new Class({Extends:Request,options:{update:false,evalScripts:true,filter:false},processHTML:function(C){var B=C.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
C=(B)?B[1]:C;var A=new Element("div");return $try(function(){var D="<root>"+C+"</root>",G;if(Browser.Engine.trident){G=new ActiveXObject("Microsoft.XMLDOM");
G.async=false;G.loadXML(D);}else{G=new DOMParser().parseFromString(D,"text/xml");}D=G.getElementsByTagName("root")[0];for(var F=0,E=D.childNodes.length;
F<E;F++){var H=Element.clone(D.childNodes[F],true,true);if(H){A.grab(H);}}return A;})||A.set("html",C);},success:function(D){var C=this.options,B=this.response;
B.html=D.stripScripts(function(E){B.javascript=E;});var A=this.processHTML(B.html);B.tree=A.childNodes;B.elements=A.getElements("*");if(C.filter){B.tree=B.elements.filter(C.filter);
}if(C.update){$(C.update).empty().adopt(B.tree);}if(C.evalScripts){$exec(B.javascript);}this.onSuccess(B.tree,B.elements,B.html,B.javascript);}});Element.Properties.load={set:function(A){var B=this.retrieve("load");
if(B){send.cancel();}return this.eliminate("load").store("load:options",$extend({data:this,link:"cancel",update:this,method:"get"},A));},get:function(A){if(A||!this.retrieve("load")){if(A||!this.retrieve("load:options")){this.set("load",A);
}this.store("load",new Request.HTML(this.retrieve("load:options")));}return this.retrieve("load");}};Element.implement({load:function(){this.get("load").send(Array.link(arguments,{data:Object.type,url:String.type}));
return this;}});Request.JSON=new Class({Extends:Request,options:{secure:true},initialize:function(A){this.parent(A);this.headers.extend({Accept:"application/json","X-Request":"JSON"});
},success:function(A){this.response.json=JSON.decode(A,this.options.secure);this.onSuccess(this.response.json,A);}});//MooTools More, <http://mootools.net/more>. Copyright (c) 2006-2008 Valerio Proietti, <http://mad4milk.net>, MIT Style License.

Fx.Slide=new Class({Extends:Fx,options:{mode:"vertical"},initialize:function(B,A){this.addEvent("complete",function(){this.open=(this.wrapper["offset"+this.layout.capitalize()]!=0);
if(this.open&&Browser.Engine.webkit419){this.element.dispose().inject(this.wrapper);}},true);this.element=this.subject=$(B);this.parent(A);var C=this.element.retrieve("wrapper");
this.wrapper=C||new Element("div",{styles:$extend(this.element.getStyles("margin","position"),{overflow:"hidden"})}).wraps(this.element);this.element.store("wrapper",this.wrapper).setStyle("margin",0);
this.now=[];this.open=true;},vertical:function(){this.margin="margin-top";this.layout="height";this.offset=this.element.offsetHeight;},horizontal:function(){this.margin="margin-left";
this.layout="width";this.offset=this.element.offsetWidth;},set:function(A){this.element.setStyle(this.margin,A[0]);this.wrapper.setStyle(this.layout,A[1]);
return this;},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B[F]=Fx.compute(E[F],D[F],C);});return B;},start:function(B,E){if(!this.check(arguments.callee,B,E)){return this;
}this[E||this.options.mode]();var D=this.element.getStyle(this.margin).toInt();var C=this.wrapper.getStyle(this.layout).toInt();var A=[[D,C],[0,this.offset]];
var G=[[D,C],[-this.offset,0]];var F;switch(B){case"in":F=A;break;case"out":F=G;break;case"toggle":F=(this.wrapper["offset"+this.layout.capitalize()]==0)?A:G;
}return this.parent(F[0],F[1]);},slideIn:function(A){return this.start("in",A);},slideOut:function(A){return this.start("out",A);},hide:function(A){this[A||this.options.mode]();
this.open=false;return this.set([-this.offset,0]);},show:function(A){this[A||this.options.mode]();this.open=true;return this.set([0,this.offset]);},toggle:function(A){return this.start("toggle",A);
}});Element.Properties.slide={set:function(B){var A=this.retrieve("slide");if(A){A.cancel();}return this.eliminate("slide").store("slide:options",$extend({link:"cancel"},B));
},get:function(A){if(A||!this.retrieve("slide")){if(A||!this.retrieve("slide:options")){this.set("slide",A);}this.store("slide",new Fx.Slide(this,this.retrieve("slide:options")));
}return this.retrieve("slide");}};Element.implement({slide:function(D,E){D=D||"toggle";var B=this.get("slide"),A;switch(D){case"hide":B.hide(E);break;case"show":B.show(E);
break;case"toggle":var C=this.retrieve("slide:flag",B.open);B[(C)?"slideOut":"slideIn"](E);this.store("slide:flag",!C);A=true;break;default:B.start(D,E);
}if(!A){this.eliminate("slide:flag");}return this;}});Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(B,A){this.element=this.subject=$(B);
this.parent(A);var D=this.cancel.bind(this,false);if($type(this.element)!="element"){this.element=$(this.element.getDocument().body);}var C=this.element;
if(this.options.wheelStops){this.addEvent("start",function(){C.addEvent("mousewheel",D);},true);this.addEvent("complete",function(){C.removeEvent("mousewheel",D);
},true);}},set:function(){var A=Array.flatten(arguments);this.element.scrollTo(A[0],A[1]);},compute:function(E,D,C){var B=[];var A=2;A.times(function(F){B.push(Fx.compute(E[F],D[F],C));
});return B;},start:function(C,H){if(!this.check(arguments.callee,C,H)){return this;}var E=this.element.getSize(),F=this.element.getScrollSize();var B=this.element.getScroll(),D={x:C,y:H};
for(var G in D){var A=F[G]-E[G];if($chk(D[G])){D[G]=($type(D[G])=="number")?D[G].limit(0,A):A;}else{D[G]=B[G];}D[G]+=this.options.offset[G];}return this.parent([B.x,B.y],[D.x,D.y]);
},toTop:function(){return this.start(false,0);},toLeft:function(){return this.start(0,false);},toRight:function(){return this.start("right",false);},toBottom:function(){return this.start(false,"bottom");
},toElement:function(B){var A=$(B).getPosition(this.element);return this.start(A.x,A.y);}});Fx.Elements=new Class({Extends:Fx.CSS,initialize:function(B,A){this.elements=this.subject=$$(B);
this.parent(A);},compute:function(G,H,I){var C={};for(var D in G){var A=G[D],E=H[D],F=C[D]={};for(var B in A){F[B]=this.parent(A[B],E[B],I);}}return C;
},set:function(B){for(var C in B){var A=B[C];for(var D in A){this.render(this.elements[C],D,A[D],this.options.unit);}}return this;},start:function(C){if(!this.check(arguments.callee,C)){return this;
}var H={},I={};for(var D in C){var F=C[D],A=H[D]={},G=I[D]={};for(var B in F){var E=this.prepare(this.elements[D],B,F[B]);A[B]=E.from;G[B]=E.to;}}return this.parent(H,I);
}});var Drag=new Class({Implements:[Events,Options],options:{snap:6,unit:"px",grid:false,style:true,limit:false,handle:false,invert:false,preventDefault:false,modifiers:{x:"left",y:"top"}},initialize:function(){var B=Array.link(arguments,{options:Object.type,element:$defined});
this.element=$(B.element);this.document=this.element.getDocument();this.setOptions(B.options||{});var A=$type(this.options.handle);this.handles=(A=="array"||A=="collection")?$$(this.options.handle):$(this.options.handle)||this.element;
this.mouse={now:{},pos:{}};this.value={start:{},now:{}};this.selection=(Browser.Engine.trident)?"selectstart":"mousedown";this.bound={start:this.start.bind(this),check:this.check.bind(this),drag:this.drag.bind(this),stop:this.stop.bind(this),cancel:this.cancel.bind(this),eventStop:$lambda(false)};
this.attach();},attach:function(){this.handles.addEvent("mousedown",this.bound.start);return this;},detach:function(){this.handles.removeEvent("mousedown",this.bound.start);
return this;},start:function(C){if(this.options.preventDefault){C.preventDefault();}this.fireEvent("beforeStart",this.element);this.mouse.start=C.page;
var A=this.options.limit;this.limit={x:[],y:[]};for(var D in this.options.modifiers){if(!this.options.modifiers[D]){continue;}if(this.options.style){this.value.now[D]=this.element.getStyle(this.options.modifiers[D]).toInt();
}else{this.value.now[D]=this.element[this.options.modifiers[D]];}if(this.options.invert){this.value.now[D]*=-1;}this.mouse.pos[D]=C.page[D]-this.value.now[D];
if(A&&A[D]){for(var B=2;B--;B){if($chk(A[D][B])){this.limit[D][B]=$lambda(A[D][B])();}}}}if($type(this.options.grid)=="number"){this.options.grid={x:this.options.grid,y:this.options.grid};
}this.document.addEvents({mousemove:this.bound.check,mouseup:this.bound.cancel});this.document.addEvent(this.selection,this.bound.eventStop);},check:function(A){if(this.options.preventDefault){A.preventDefault();
}var B=Math.round(Math.sqrt(Math.pow(A.page.x-this.mouse.start.x,2)+Math.pow(A.page.y-this.mouse.start.y,2)));if(B>this.options.snap){this.cancel();this.document.addEvents({mousemove:this.bound.drag,mouseup:this.bound.stop});
this.fireEvent("start",this.element).fireEvent("snap",this.element);}},drag:function(A){if(this.options.preventDefault){A.preventDefault();}this.mouse.now=A.page;
for(var B in this.options.modifiers){if(!this.options.modifiers[B]){continue;}this.value.now[B]=this.mouse.now[B]-this.mouse.pos[B];if(this.options.invert){this.value.now[B]*=-1;
}if(this.options.limit&&this.limit[B]){if($chk(this.limit[B][1])&&(this.value.now[B]>this.limit[B][1])){this.value.now[B]=this.limit[B][1];}else{if($chk(this.limit[B][0])&&(this.value.now[B]<this.limit[B][0])){this.value.now[B]=this.limit[B][0];
}}}if(this.options.grid[B]){this.value.now[B]-=(this.value.now[B]%this.options.grid[B]);}if(this.options.style){this.element.setStyle(this.options.modifiers[B],this.value.now[B]+this.options.unit);
}else{this.element[this.options.modifiers[B]]=this.value.now[B];}}this.fireEvent("drag",this.element);},cancel:function(A){this.document.removeEvent("mousemove",this.bound.check);
this.document.removeEvent("mouseup",this.bound.cancel);if(A){this.document.removeEvent(this.selection,this.bound.eventStop);this.fireEvent("cancel",this.element);
}},stop:function(A){this.document.removeEvent(this.selection,this.bound.eventStop);this.document.removeEvent("mousemove",this.bound.drag);this.document.removeEvent("mouseup",this.bound.stop);
if(A){this.fireEvent("complete",this.element);}}});Element.implement({makeResizable:function(A){return new Drag(this,$merge({modifiers:{x:"width",y:"height"}},A));
}});Drag.Move=new Class({Extends:Drag,options:{droppables:[],container:false},initialize:function(C,B){this.parent(C,B);this.droppables=$$(this.options.droppables);
this.container=$(this.options.container);if(this.container&&$type(this.container)!="element"){this.container=$(this.container.getDocument().body);}C=this.element;
var D=C.getStyle("position");var A=(D!="static")?D:"absolute";if(C.getStyle("left")=="auto"||C.getStyle("top")=="auto"){C.position(C.getPosition(C.offsetParent));
}C.setStyle("position",A);this.addEvent("start",function(){this.checkDroppables();},true);},start:function(B){if(this.container){var D=this.element,J=this.container,E=J.getCoordinates(D.offsetParent),F={},A={};
["top","right","bottom","left"].each(function(K){F[K]=J.getStyle("padding-"+K).toInt();A[K]=D.getStyle("margin-"+K).toInt();},this);var C=D.offsetWidth+A.left+A.right,I=D.offsetHeight+A.top+A.bottom;
var H=[E.left+F.left,E.right-F.right-C];var G=[E.top+F.top,E.bottom-F.bottom-I];this.options.limit={x:H,y:G};}this.parent(B);},checkAgainst:function(B){B=B.getCoordinates();
var A=this.mouse.now;return(A.x>B.left&&A.x<B.right&&A.y<B.bottom&&A.y>B.top);},checkDroppables:function(){var A=this.droppables.filter(this.checkAgainst,this).getLast();
if(this.overed!=A){if(this.overed){this.fireEvent("leave",[this.element,this.overed]);}if(A){this.overed=A;this.fireEvent("enter",[this.element,A]);}else{this.overed=null;
}}},drag:function(A){this.parent(A);if(this.droppables.length){this.checkDroppables();}},stop:function(A){this.checkDroppables();this.fireEvent("drop",[this.element,this.overed]);
this.overed=null;return this.parent(A);}});Element.implement({makeDraggable:function(A){return new Drag.Move(this,A);}});Hash.Cookie=new Class({Extends:Cookie,options:{autoSave:true},initialize:function(B,A){this.parent(B,A);
this.load();},save:function(){var A=JSON.encode(this.hash);if(!A||A.length>4096){return false;}if(A=="{}"){this.dispose();}else{this.write(A);}return true;
},load:function(){this.hash=new Hash(JSON.decode(this.read(),true));return this;}});Hash.Cookie.implement((function(){var A={};Hash.each(Hash.prototype,function(C,B){A[B]=function(){var D=C.apply(this.hash,arguments);
if(this.options.autoSave){this.save();}return D;};});return A;})());var Color=new Native({initialize:function(B,C){if(arguments.length>=3){C="rgb";B=Array.slice(arguments,0,3);
}else{if(typeof B=="string"){if(B.match(/rgb/)){B=B.rgbToHex().hexToRgb(true);}else{if(B.match(/hsb/)){B=B.hsbToRgb();}else{B=B.hexToRgb(true);}}}}C=C||"rgb";
switch(C){case"hsb":var A=B;B=B.hsbToRgb();B.hsb=A;break;case"hex":B=B.hexToRgb(true);break;}B.rgb=B.slice(0,3);B.hsb=B.hsb||B.rgbToHsb();B.hex=B.rgbToHex();
return $extend(B,this);}});Color.implement({mix:function(){var A=Array.slice(arguments);var C=($type(A.getLast())=="number")?A.pop():50;var B=this.slice();
A.each(function(D){D=new Color(D);for(var E=0;E<3;E++){B[E]=Math.round((B[E]/100*(100-C))+(D[E]/100*C));}});return new Color(B,"rgb");},invert:function(){return new Color(this.map(function(A){return 255-A;
}));},setHue:function(A){return new Color([A,this.hsb[1],this.hsb[2]],"hsb");},setSaturation:function(A){return new Color([this.hsb[0],A,this.hsb[2]],"hsb");
},setBrightness:function(A){return new Color([this.hsb[0],this.hsb[1],A],"hsb");}});function $RGB(C,B,A){return new Color([C,B,A],"rgb");}function $HSB(C,B,A){return new Color([C,B,A],"hsb");
}function $HEX(A){return new Color(A,"hex");}Array.implement({rgbToHsb:function(){var B=this[0],C=this[1],J=this[2];var G,F,H;var I=Math.max(B,C,J),E=Math.min(B,C,J);
var K=I-E;H=I/255;F=(I!=0)?K/I:0;if(F==0){G=0;}else{var D=(I-B)/K;var A=(I-C)/K;var L=(I-J)/K;if(B==I){G=L-A;}else{if(C==I){G=2+D-L;}else{G=4+A-D;}}G/=6;
if(G<0){G++;}}return[Math.round(G*360),Math.round(F*100),Math.round(H*100)];},hsbToRgb:function(){var C=Math.round(this[2]/100*255);if(this[1]==0){return[C,C,C];
}else{var A=this[0]%360;var E=A%60;var F=Math.round((this[2]*(100-this[1]))/10000*255);var D=Math.round((this[2]*(6000-this[1]*E))/600000*255);var B=Math.round((this[2]*(6000-this[1]*(60-E)))/600000*255);
switch(Math.floor(A/60)){case 0:return[C,B,F];case 1:return[D,C,F];case 2:return[F,C,B];case 3:return[F,D,C];case 4:return[B,F,C];case 5:return[C,F,D];
}}return false;}});String.implement({rgbToHsb:function(){var A=this.match(/\d{1,3}/g);return(A)?hsb.rgbToHsb():null;},hsbToRgb:function(){var A=this.match(/\d{1,3}/g);
return(A)?A.hsbToRgb():null;}});var Group=new Class({initialize:function(){this.instances=Array.flatten(arguments);this.events={};this.checker={};},addEvent:function(B,A){this.checker[B]=this.checker[B]||{};
this.events[B]=this.events[B]||[];if(this.events[B].contains(A)){return false;}else{this.events[B].push(A);}this.instances.each(function(C,D){C.addEvent(B,this.check.bind(this,[B,C,D]));
},this);return this;},check:function(C,A,B){this.checker[C][B]=true;var D=this.instances.every(function(F,E){return this.checker[C][E]||false;},this);if(!D){return ;
}this.checker[C]={};this.events[C].each(function(E){E.call(this,this.instances,A);},this);}});var Asset=new Hash({javascript:function(F,D){D=$extend({onload:$empty,document:document,check:$lambda(true)},D);
var B=new Element("script",{src:F,type:"text/javascript"});var E=D.onload.bind(B),A=D.check,G=D.document;delete D.onload;delete D.check;delete D.document;
B.addEvents({load:E,readystatechange:function(){if(["loaded","complete"].contains(this.readyState)){E();}}}).setProperties(D);if(Browser.Engine.webkit419){var C=(function(){if(!$try(A)){return ;
}$clear(C);E();}).periodical(50);}return B.inject(G.head);},css:function(B,A){return new Element("link",$merge({rel:"stylesheet",media:"screen",type:"text/css",href:B},A)).inject(document.head);
},image:function(C,B){B=$merge({onload:$empty,onabort:$empty,onerror:$empty},B);var D=new Image();var A=$(D)||new Element("img");["load","abort","error"].each(function(E){var F="on"+E;
var G=B[F];delete B[F];D[F]=function(){if(!D){return ;}if(!A.parentNode){A.width=D.width;A.height=D.height;}D=D.onload=D.onabort=D.onerror=null;G.delay(1,A,A);
A.fireEvent(E,A,1);};});D.src=A.src=C;if(D&&D.complete){D.onload.delay(1);}return A.setProperties(B);},images:function(D,C){C=$merge({onComplete:$empty,onProgress:$empty},C);
if(!D.push){D=[D];}var A=[];var B=0;D.each(function(F){var E=new Asset.image(F,{onload:function(){C.onProgress.call(this,B,D.indexOf(F));B++;if(B==D.length){C.onComplete();
}}});A.push(E);});return new Elements(A);}});var Sortables=new Class({Implements:[Events,Options],options:{snap:4,opacity:1,clone:false,revert:false,handle:false,constrain:false},initialize:function(A,B){this.setOptions(B);
this.elements=[];this.lists=[];this.idle=true;this.addLists($$($(A)||A));if(!this.options.clone){this.options.revert=false;}if(this.options.revert){this.effect=new Fx.Morph(null,$merge({duration:250,link:"cancel"},this.options.revert));
}},attach:function(){this.addLists(this.lists);return this;},detach:function(){this.lists=this.removeLists(this.lists);return this;},addItems:function(){Array.flatten(arguments).each(function(A){this.elements.push(A);
var B=A.retrieve("sortables:start",this.start.bindWithEvent(this,A));(this.options.handle?A.getElement(this.options.handle)||A:A).addEvent("mousedown",B);
},this);return this;},addLists:function(){Array.flatten(arguments).each(function(A){this.lists.push(A);this.addItems(A.getChildren());},this);return this;
},removeItems:function(){var A=[];Array.flatten(arguments).each(function(B){A.push(B);this.elements.erase(B);var C=B.retrieve("sortables:start");(this.options.handle?B.getElement(this.options.handle)||B:B).removeEvent("mousedown",C);
},this);return $$(A);},removeLists:function(){var A=[];Array.flatten(arguments).each(function(B){A.push(B);this.lists.erase(B);this.removeItems(B.getChildren());
},this);return $$(A);},getClone:function(B,A){if(!this.options.clone){return new Element("div").inject(document.body);}if($type(this.options.clone)=="function"){return this.options.clone.call(this,B,A,this.list);
}return A.clone(true).setStyles({margin:"0px",position:"absolute",visibility:"hidden",width:A.getStyle("width")}).inject(this.list).position(A.getPosition(A.getOffsetParent()));
},getDroppables:function(){var A=this.list.getChildren();if(!this.options.constrain){A=this.lists.concat(A).erase(this.list);}return A.erase(this.clone).erase(this.element);
},insert:function(C,B){var A="inside";if(this.lists.contains(B)){this.list=B;this.drag.droppables=this.getDroppables();}else{A=this.element.getAllPrevious().contains(B)?"before":"after";
}this.element.inject(B,A);this.fireEvent("sort",[this.element,this.clone]);},start:function(B,A){if(!this.idle){return ;}this.idle=false;this.element=A;
this.opacity=A.get("opacity");this.list=A.getParent();this.clone=this.getClone(B,A);this.drag=new Drag.Move(this.clone,{snap:this.options.snap,container:this.options.constrain&&this.element.getParent(),droppables:this.getDroppables(),onSnap:function(){B.stop();
this.clone.setStyle("visibility","visible");this.element.set("opacity",this.options.opacity||0);this.fireEvent("start",[this.element,this.clone]);}.bind(this),onEnter:this.insert.bind(this),onCancel:this.reset.bind(this),onComplete:this.end.bind(this)});
this.clone.inject(this.element,"before");this.drag.start(B);},end:function(){this.drag.detach();this.element.set("opacity",this.opacity);if(this.effect){var A=this.element.getStyles("width","height");
var B=this.clone.computePosition(this.element.getPosition(this.clone.offsetParent));this.effect.element=this.clone;this.effect.start({top:B.top,left:B.left,width:A.width,height:A.height,opacity:0.25}).chain(this.reset.bind(this));
}else{this.reset();}},reset:function(){this.idle=true;this.clone.destroy();this.fireEvent("complete",this.element);},serialize:function(){var C=Array.link(arguments,{modifier:Function.type,index:$defined});
var B=this.lists.map(function(D){return D.getChildren().map(C.modifier||function(E){return E.get("id");},this);},this);var A=C.index;if(this.lists.length==1){A=0;
}return $chk(A)&&A>=0&&A<this.lists.length?B[A]:B;}});var Tips=new Class({Implements:[Events,Options],options:{onShow:function(A){A.setStyle("visibility","visible");
},onHide:function(A){A.setStyle("visibility","hidden");},showDelay:100,hideDelay:100,className:null,offsets:{x:16,y:16},fixed:false},initialize:function(){var C=Array.link(arguments,{options:Object.type,elements:$defined});
this.setOptions(C.options||null);this.tip=new Element("div").inject(document.body);if(this.options.className){this.tip.addClass(this.options.className);
}var B=new Element("div",{"class":"tip-top"}).inject(this.tip);this.container=new Element("div",{"class":"tip"}).inject(this.tip);var A=new Element("div",{"class":"tip-bottom"}).inject(this.tip);
this.tip.setStyles({position:"absolute",top:0,left:0,visibility:"hidden"});if(C.elements){this.attach(C.elements);}},attach:function(A){$$(A).each(function(D){var G=D.retrieve("tip:title",D.get("title"));
var F=D.retrieve("tip:text",D.get("rel")||D.get("href"));var E=D.retrieve("tip:enter",this.elementEnter.bindWithEvent(this,D));var C=D.retrieve("tip:leave",this.elementLeave.bindWithEvent(this,D));
D.addEvents({mouseenter:E,mouseleave:C});if(!this.options.fixed){var B=D.retrieve("tip:move",this.elementMove.bindWithEvent(this,D));D.addEvent("mousemove",B);
}D.store("tip:native",D.get("title"));D.erase("title");},this);return this;},detach:function(A){$$(A).each(function(C){C.removeEvent("mouseenter",C.retrieve("tip:enter")||$empty);
C.removeEvent("mouseleave",C.retrieve("tip:leave")||$empty);C.removeEvent("mousemove",C.retrieve("tip:move")||$empty);C.eliminate("tip:enter").eliminate("tip:leave").eliminate("tip:move");
var B=C.retrieve("tip:native");if(B){C.set("title",B);}});return this;},elementEnter:function(B,A){$A(this.container.childNodes).each(Element.dispose);
var D=A.retrieve("tip:title");if(D){this.titleElement=new Element("div",{"class":"tip-title"}).inject(this.container);this.fill(this.titleElement,D);}var C=A.retrieve("tip:text");
if(C){this.textElement=new Element("div",{"class":"tip-text"}).inject(this.container);this.fill(this.textElement,C);}this.timer=$clear(this.timer);this.timer=this.show.delay(this.options.showDelay,this);
this.position((!this.options.fixed)?B:{page:A.getPosition()});},elementLeave:function(A){$clear(this.timer);this.timer=this.hide.delay(this.options.hideDelay,this);
},elementMove:function(A){this.position(A);},position:function(D){var B=window.getSize(),A=window.getScroll();var E={x:this.tip.offsetWidth,y:this.tip.offsetHeight};
var C={x:"left",y:"top"};for(var F in C){var G=D.page[F]+this.options.offsets[F];if((G+E[F]-A[F])>B[F]){G=D.page[F]-this.options.offsets[F]-E[F];}this.tip.setStyle(C[F],G);
}},fill:function(A,B){(typeof B=="string")?A.set("html",B):A.adopt(B);},show:function(){this.fireEvent("show",this.tip);},hide:function(){this.fireEvent("hide",this.tip);
}});var SmoothScroll=new Class({Extends:Fx.Scroll,initialize:function(B,C){C=C||document;var E=C.getDocument(),D=C.getWindow();this.parent(E,B);this.links=(this.options.links)?$$(this.options.links):$$(E.links);
var A=D.location.href.match(/^[^#]*/)[0]+"#";this.links.each(function(G){if(G.href.indexOf(A)!=0){return ;}var F=G.href.substr(A.length);if(F&&$(F)){this.useLink(G,F);
}},this);if(!Browser.Engine.webkit419){this.addEvent("complete",function(){D.location.hash=this.anchor;},true);}},useLink:function(B,A){B.addEvent("click",function(C){this.anchor=A;
this.toElement(A);C.stop();}.bind(this));}});var Slider=new Class({Implements:[Events,Options],options:{onTick:function(A){if(this.options.snap){A=this.toPosition(this.step);
}this.knob.setStyle(this.property,A);},snap:false,offset:0,range:false,wheel:false,steps:100,mode:"horizontal"},initialize:function(E,A,D){this.setOptions(D);
this.element=$(E);this.knob=$(A);this.previousChange=this.previousEnd=this.step=-1;this.element.addEvent("mousedown",this.clickedElement.bind(this));if(this.options.wheel){this.element.addEvent("mousewheel",this.scrolledElement.bindWithEvent(this));
}var F,B={},C={x:false,y:false};switch(this.options.mode){case"vertical":this.axis="y";this.property="top";F="offsetHeight";break;case"horizontal":this.axis="x";
this.property="left";F="offsetWidth";}this.half=this.knob[F]/2;this.full=this.element[F]-this.knob[F]+(this.options.offset*2);this.min=$chk(this.options.range[0])?this.options.range[0]:0;
this.max=$chk(this.options.range[1])?this.options.range[1]:this.options.steps;this.range=this.max-this.min;this.steps=this.options.steps||this.full;this.stepSize=Math.abs(this.range)/this.steps;
this.stepWidth=this.stepSize*this.full/Math.abs(this.range);this.knob.setStyle("position","relative").setStyle(this.property,-this.options.offset);C[this.axis]=this.property;
B[this.axis]=[-this.options.offset,this.full-this.options.offset];this.drag=new Drag(this.knob,{snap:0,limit:B,modifiers:C,onDrag:this.draggedKnob.bind(this),onStart:this.draggedKnob.bind(this),onComplete:function(){this.draggedKnob();
this.end();}.bind(this)});if(this.options.snap){this.drag.options.grid=Math.ceil(this.stepWidth);this.drag.options.limit[this.axis][1]=this.full;}},set:function(A){if(!((this.range>0)^(A<this.min))){A=this.min;
}if(!((this.range>0)^(A>this.max))){A=this.max;}this.step=Math.round(A);this.checkStep();this.end();this.fireEvent("tick",this.toPosition(this.step));return this;
},clickedElement:function(C){var B=this.range<0?-1:1;var A=C.page[this.axis]-this.element.getPosition()[this.axis]-this.half;A=A.limit(-this.options.offset,this.full-this.options.offset);
this.step=Math.round(this.min+B*this.toStep(A));this.checkStep();this.end();this.fireEvent("tick",A);},scrolledElement:function(A){var B=(this.options.mode=="horizontal")?(A.wheel<0):(A.wheel>0);
this.set(B?this.step-this.stepSize:this.step+this.stepSize);A.stop();},draggedKnob:function(){var B=this.range<0?-1:1;var A=this.drag.value.now[this.axis];
A=A.limit(-this.options.offset,this.full-this.options.offset);this.step=Math.round(this.min+B*this.toStep(A));this.checkStep();},checkStep:function(){if(this.previousChange!=this.step){this.previousChange=this.step;
this.fireEvent("change",this.step);}},end:function(){if(this.previousEnd!==this.step){this.previousEnd=this.step;this.fireEvent("complete",this.step+"");
}},toStep:function(A){var B=(A+this.options.offset)*this.stepSize/this.full*this.steps;return this.options.steps?Math.round(B-=B%this.stepSize):B;},toPosition:function(A){return(this.full*Math.abs(this.min-A))/(this.steps*this.stepSize)-this.options.offset;
}});var Scroller=new Class({Implements:[Events,Options],options:{area:20,velocity:1,onChange:function(A,B){this.element.scrollTo(A,B);}},initialize:function(B,A){this.setOptions(A);
this.element=$(B);this.listener=($type(this.element)!="element")?$(this.element.getDocument().body):this.element;this.timer=null;this.coord=this.getCoords.bind(this);
},start:function(){this.listener.addEvent("mousemove",this.coord);},stop:function(){this.listener.removeEvent("mousemove",this.coord);this.timer=$clear(this.timer);
},getCoords:function(A){this.page=(this.listener.get("tag")=="body")?A.client:A.page;if(!this.timer){this.timer=this.scroll.periodical(50,this);}},scroll:function(){var B=this.element.getSize(),A=this.element.getScroll(),E=this.element.getPosition(),D={x:0,y:0};
for(var C in this.page){if(this.page[C]<(this.options.area+E[C])&&A[C]!=0){D[C]=(this.page[C]-this.options.area-E[C])*this.options.velocity;}else{if(this.page[C]+this.options.area>(B[C]+E[C])&&B[C]+B[C]!=A[C]){D[C]=(this.page[C]-B[C]+this.options.area-E[C])*this.options.velocity;
}}}if(D.y||D.x){this.fireEvent("change",[A.x+D.x,A.y+D.y]);}}});var Accordion=new Class({Extends:Fx.Elements,options:{display:0,show:false,height:true,width:false,opacity:true,fixedHeight:false,fixedWidth:false,wait:false,alwaysHide:false},initialize:function(){var C=Array.link(arguments,{container:Element.type,options:Object.type,togglers:$defined,elements:$defined});
this.parent(C.elements,C.options);this.togglers=$$(C.togglers);this.container=$(C.container);this.previous=-1;if(this.options.alwaysHide){this.options.wait=true;
}if($chk(this.options.show)){this.options.display=false;this.previous=this.options.show;}if(this.options.start){this.options.display=false;this.options.show=false;
}this.effects={};if(this.options.opacity){this.effects.opacity="fullOpacity";}if(this.options.width){this.effects.width=this.options.fixedWidth?"fullWidth":"offsetWidth";
}if(this.options.height){this.effects.height=this.options.fixedHeight?"fullHeight":"scrollHeight";}for(var B=0,A=this.togglers.length;B<A;B++){this.addSection(this.togglers[B],this.elements[B]);
}this.elements.each(function(E,D){if(this.options.show===D){this.fireEvent("active",[this.togglers[D],E]);}else{for(var F in this.effects){E.setStyle(F,0);
}}},this);if($chk(this.options.display)){this.display(this.options.display);}},addSection:function(E,C,G){E=$(E);C=$(C);var F=this.togglers.contains(E);
var B=this.togglers.length;this.togglers.include(E);this.elements.include(C);if(B&&(!F||G)){G=$pick(G,B-1);E.inject(this.togglers[G],"before");C.inject(E,"after");
}else{if(this.container&&!F){E.inject(this.container);C.inject(this.container);}}var A=this.togglers.indexOf(E);E.addEvent("click",this.display.bind(this,A));
if(this.options.height){C.setStyles({"padding-top":0,"border-top":"none","padding-bottom":0,"border-bottom":"none"});}if(this.options.width){C.setStyles({"padding-left":0,"border-left":"none","padding-right":0,"border-right":"none"});
}C.fullOpacity=1;if(this.options.fixedWidth){C.fullWidth=this.options.fixedWidth;}if(this.options.fixedHeight){C.fullHeight=this.options.fixedHeight;}C.setStyle("overflow","hidden");
if(!F){for(var D in this.effects){C.setStyle(D,0);}}return this;},display:function(A){A=($type(A)=="element")?this.elements.indexOf(A):A;if((this.timer&&this.options.wait)||(A===this.previous&&!this.options.alwaysHide)){return this;
}this.previous=A;var B={};this.elements.each(function(E,D){B[D]={};var C=(D!=A)||(this.options.alwaysHide&&(E.offsetHeight>0));this.fireEvent(C?"background":"active",[this.togglers[D],E]);
for(var F in this.effects){B[D][F]=C?0:E[this.effects[F]];}},this);return this.start(B);}});/**
 * Roar - Notifications
 *
 * Inspired by Growl
 *
 * @version		1.0.1
 *
 * @license		MIT-style license
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	Author
 */

var Roar = new Class({

	Implements: [Options, Events, Chain],

	options: {
		duration: 5000,
		position: 'upperLeft',
		container: null,
		bodyFx: null,
		itemFx: null,
		margin: {x: 10, y: 10},
		offset: 10,
		className: 'roar',
		onShow: $empty,
		onHide: $empty,
		onRender: $empty
	},

	initialize: function(options) {
		this.setOptions(options);
		this.items = [];
		this.container = $(this.options.container) || document;
	},

	alert: function(title, message, options) {
		var params = Array.link(arguments, {title: String.type, message: String.type, options: Object.type});
		var items = [new Element('h3', {'html': $pick(params.title, '')})];
		if (params.message) items.push(new Element('p', {'html': params.message}));
		return this.inject(items, params.options);
	},

	inject: function(elements, options) {
		if (!this.body) this.render();
		options = options || {};

		var offset = [-this.options.offset, 0];
		var last = this.items.getLast();
		if (last) {
			offset[0] = last.retrieve('roar:offset');
			offset[1] = offset[0] + last.offsetHeight + this.options.offset;
		}
		var to = {'opacity': 1};
		to[this.align.y] = offset;

		var item = new Element('div', {
			'class': this.options.className,
			'opacity': 0
		}).adopt(
			new Element('div', {
				'class': 'roar-bg',
				'opacity': 0.7
			}),
			elements
		);

		item.setStyle(this.align.x, 0).store('roar:offset', offset[1]).set('morph', $merge({
			unit: 'px',
			link: 'cancel',
			onStart: Chain.prototype.clearChain,
			transition: Fx.Transitions.Back.easeOut
		}, this.options.itemFx));

		var remove = this.remove.create({
			bind: this,
			arguments: [item],
			delay: 10
		});
		this.items.push(item.addEvent('click', remove));

		if (this.options.duration) {
			var over = false;
			var trigger = (function() {
				trigger = null;
				if (!over) remove();
			}).delay(this.options.duration);
			item.addEvents({
				mouseover: function() {
					over = true;
				},
				mouseout: function() {
					over = false;
					if (!trigger) remove();
				}
			});
		}
		item.inject(this.body).morph(to);
		return this.fireEvent('onShow', [item, this.items.length]);
	},

	remove: function(item) {
		var index = this.items.indexOf(item);
		if (index == -1) return this;
		this.items.splice(index, 1);
		item.removeEvents();
		var to = {opacity: 0};
		to[this.align.y] = item.getStyle(this.align.y).toInt() - item.offsetHeight - this.options.offset;
		item.morph(to).get('morph').chain(item.destroy.bind(item));
		return this.fireEvent('onHide', [item, this.items.length]).callChain(item);
	},

	empty: function() {
		while (this.items.length) this.remove(this.items[0]);
		return this;
	},

	render: function() {
		this.position = this.options.position;
		if ($type(this.position) == 'string') {
			var position = {x: 'center', y: 'center'};
			this.align = {x: 'left', y: 'top'};
			if ((/left|west/i).test(this.position)) position.x = 'left';
			else if ((/right|east/i).test(this.position)) this.align.x = position.x = 'right';
			if ((/upper|top|north/i).test(this.position)) position.y = 'top';
			else if ((/bottom|lower|south/i).test(this.position)) this.align.y = position.y = 'bottom';
			this.position = position;
		}
		this.body = new Element('div', {'class': 'roar-body'}).inject(document.body);
		if (Browser.Engine.trident4) this.body.addClass('roar-body-ugly');
		this.moveTo = this.body.setStyles.bind(this.body);
		this.reposition();
		if (this.options.bodyFx) {
			var morph = new Fx.Morph(this.body, $merge({
				unit: 'px',
				chain: 'cancel',
				transition: Fx.Transitions.Circ.easeOut
			}, this.options.bodyFx));
			this.moveTo = morph.start.bind(morph);
		}
		var repos = this.reposition.bind(this);
		window.addEvents({
			scroll: repos,
			resize: repos
		});
		this.fireEvent('onRender', this.body);
	},

	reposition: function() {
		var max = document.getCoordinates(), scroll = document.getScroll(), margin = this.options.margin;
		max.left += scroll.x;
		max.right += scroll.x;
		max.top += scroll.y;
		max.bottom += scroll.y;
		var rel = ($type(this.container) == 'element') ? this.container.getCoordinates() : max;
		this.moveTo({
			left: (this.position.x == 'right')
				? (Math.min(rel.right, max.right) - margin.x)
				: (Math.max(rel.left, max.left) + margin.x),
			top: (this.position.y == 'bottom')
				? (Math.min(rel.bottom, max.bottom) - margin.y)
				: (Math.max(rel.top, max.top) + margin.y)
		});
	}

});/*
Script: mootree.js
	My Object Oriented Tree
	- Developed by Rasmus Schultz, <http://www.mindplay.dk>
	- Tested with MooTools release 1.2, under Firefox 2, Opera 9 and Internet Explorer 6 and 7.
	
License:
	MIT-style license.

Credits:
	Inspired by:
	- WebFX xTree, <http://webfx.eae.net/dhtml/xtree/>
	- Destroydrop dTree, <http://www.destroydrop.com/javascripts/tree/>
	
Changes:
	
	rev.12:
	- load() only worked once on the same node, fixed.
	- the script would sometimes try to get 'R' from the server, fixed.
	- the 'load' attribute is now supported in XML files (see example_5.html).
	
	rev.13:
	- enable() and disable() added - the adopt() and load() methods use these to improve performance by minimizing the number of visual updates.
	
	rev.14:
	- toggle() was using enable() and disable() which actually caused it to do extra work - fixed.
	
	rev.15:
	- adopt() now picks up 'href', 'target', 'title' and 'name' attributes of the a-tag, and stores them in the data object.
	- adopt() now picks up additional constructor arguments from embedded comments, e.g. icons, colors, etc.
	- documentation now generates properly with NaturalDocs, <http://www.naturaldocs.org/>
	
	rev.16:
	- onClick events added to MooTreeControl and MooTreeNode
	- nodes can now have id's - <MooTreeControl.get> method can be used to find a node with a given id
	
	rev.17:
	- changed icon rendering to use innerHTML, making the control faster (and code size slightly smaller).
	
	rev.18:
	- migrated to MooTools 1.2 (previous versions no longer supported)
	
*/

var MooTreeIcon = ['I','L','Lminus','Lplus','Rminus','Rplus','T','Tminus','Tplus','_closed','_doc','_open','minus','plus'];

/*
Class: MooTreeControl
	This class implements a tree control.

Properties:
	root - returns the root <MooTreeNode> object.
	selected - returns the currently selected <MooTreeNode> object, or null if nothing is currently selected.

Events:
	onExpand - called when a node is expanded or collapsed: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:expanded or false:collapsed.
	onSelect - called when a node is selected or deselected: function(node, state) - where node is the <MooTreeNode> object that fired the event, and state is a boolean meaning true:selected or false:deselected.
	onClick - called when a node is clicked: function(node) - where node is the <MooTreeNode> object that fired the event.

Parameters:
	The constructor takes two object parameters: config and options.
	The first, config, contains global settings for the tree control - you can use the configuration options listed below.
	The second, options, should contain options for the <MooTreeNode> constructor - please refer to the options listed in the <MooTreeNode> documentation.

Config:
	div - a string representing the div Element inside which to build the tree control.
	mode - optional string, defaults to 'files' - specifies default icon behavior. In 'files' mode, empty nodes have a document icon - whereas, in 'folders' mode, all nodes are displayed as folders (a'la explorer).
	grid - boolean, defaults to false. If set to true, a grid is drawn to outline the structure of the tree.
	
	theme - string, optional, defaults to 'mootree.gif' - specifies the 'theme' GIF to use.
	
	loader - optional, an options object for the <MooTreeNode> constructor - defaults to {icon:'mootree_loader.gif', text:'Loading...', color:'a0a0a0'}
	
	onExpand - optional function (see Events above)
	onSelect - optional function (see Events above)

*/

var MooTreeControl = new Class({
	
	initialize: function(config, options) {
		
		options.control = this;               // make sure our new MooTreeNode knows who it's owner control is
		options.div = config.div;             // tells the root node which div to insert itself into
		this.root = new MooTreeNode(options); // create the root node of this tree control
		
		this.index = new Object();            // used by the get() method
		
		this.enabled = true;                  // enable visual updates of the control
		
		this.theme = config.theme || '/include/omf/omtree/mootree.gif';
		
		this.loader = config.loader || {icon:'/include/omf/omtree/icons/mootree_loader.gif', text:'Loading...', color:'#a0a0a0'};
		
		this.selected = null;                 // set the currently selected node to nothing
		this.mode = config.mode;              // mode can be "folders" or "files", and affects the default icons
		this.grid = config.grid;              // grid can be turned on (true) or off (false)
		
		this.onExpand = config.onExpand || new Function(); // called when any node in the tree is expanded/collapsed
		this.onSelect = config.onSelect || new Function(); // called when any node in the tree is selected/deselected
		this.onClick = config.onClick || new Function(); // called when any node in the tree is clicked
		
		this.root.update(true);
		
	},
	
	/*
	Property: insert
		Creates a new node under the root node of this tree.
	
	Parameters:
		options - an object containing the same options available to the <MooTreeNode> constructor.
		
	Returns:
		A new <MooTreeNode> instance.
	*/
	
	insert: function(options) {
		options.control = this;
		return this.root.insert(options);
	},
	
	/*
	Property: select
		Sets the currently selected node.
		This is called by <MooTreeNode> when a node is selected (e.g. by clicking it's title with the mouse).
	
	Parameters:
		node - the <MooTreeNode> object to select.
	*/
	
	select: function(node) {
		this.onClick(node); node.onClick(); // fire click events
		if (this.selected === node) return; // already selected
		if (this.selected) {
			// deselect previously selected node:
			this.selected.select(false);
			this.onSelect(this.selected, false);
		}
		// select new node:
		this.selected = node;
		node.select(true);
		this.onSelect(node, true);
	},
	
	/*
	Property: expand
		Expands the entire tree, recursively.
	*/
	
	expand: function() {
		this.root.toggle(true, true);
	},

	/*
	Property: collapse
		Collapses the entire tree, recursively.
	*/

	collapse: function() {
		this.root.toggle(true, false);
	},
	
	/*
	Property: get
		Retrieves the node with the given id - or null, if no node with the given id exists.
	
	Parameters:
		id - a string, the id of the node you wish to retrieve.
	
	Note:
		Node id can be assigned via the <MooTreeNode> constructor, e.g. using the <MooTreeNode.insert> method.
	*/
	
	get: function(id) {
		return this.index[id] || null;
	},
	
	/*
	Property: adopt
		Adopts a structure of nested ul/li/a elements as tree nodes, then removes the original elements.
	
	Parameters:
		id - a string representing the ul element to be adopted, or an element reference.
		parentNode - optional, a <MooTreeNode> object under which to import the specified ul element. Defaults to the root node of the parent control.
	
	Note:
		The ul/li structure must be properly nested, and each li-element must contain one a-element, e.g.:
		
		><ul id="mytree">
		>  <li><a href="test.html">Item One</a></li>
		>  <li><a href="test.html">Item Two</a>
		>    <ul>
		>      <li><a href="test.html">Item Two Point One</a></li>
		>      <li><a href="test.html">Item Two Point Two</a></li>
		>    </ul>
		>  </li>
		>  <li><a href="test.html"><!-- icon:_doc; color:#ff0000 -->Item Three</a></li>
		></ul>
		
		The "href", "target", "title" and "name" attributes of the a-tags are picked up and stored in the
		data property of the node.
		
		CSS-style comments inside a-tags are parsed, and treated as arguments for <MooTreeNode> constructor,
		e.g. "icon", "openicon", "color", etc.
	*/
	
	adopt: function(id, parentNode) {
		if (parentNode === undefined) parentNode = this.root;
		this.disable();
		this._adopt(id, parentNode);
		parentNode.update(true);
		$(id).destroy();
		this.enable();
	},
	
	_adopt: function(id, parentNode) {
		/* adopts a structure of ul/li elements into this tree */
		e = $(id);
		var i=0, c = e.getChildren();
		for (i=0; i<c.length; i++) {
			if (c[i].nodeName == 'LI') {
				var con={text:''}, comment='', node=null, subul=null;
				var n=0, z=0, se=null, s = c[i].getChildren();
				for (n=0; n<s.length; n++) {
					switch (s[n].nodeName) {
						case 'A':
							for (z=0; z<s[n].childNodes.length; z++) {
								se = s[n].childNodes[z];
								switch (se.nodeName) {
									case '#text': con.text += se.nodeValue; break;
									case '#comment': comment += se.nodeValue; break;
								}
							}
							con.data = s[n].getProperties('href','target','title','name');
						break;
						case 'UL':
							subul = s[n];
						break;
					}
				}
				if (con.label != '') {
					con.data.url = con.data['href']; // (for backwards compatibility)
					if (comment != '') {
						var bits = comment.split(';');
						for (z=0; z<bits.length; z++) {
							var pcs = bits[z].trim().split(':');
							if (pcs.length == 2) con[pcs[0].trim()] = pcs[1].trim();
						}
					}
					node = parentNode.insert(con);
					if (subul) this._adopt(subul, node);
				}
			}
		}
	},
		
	/*
	Property: disable
		Call this to temporarily disable visual updates -- if you need to insert/remove many nodes
		at a time, many visual updates would normally occur. By temporarily disabling the control,
		these visual updates will be skipped.
		
		When you're done making changes, call <MooTreeControl.enable> to turn on visual updates
		again, and automatically repaint all nodes that were changed.
	*/
	
	disable: function() {
		this.enabled = false;
	},
	
	/*
	Property: enable
		Enables visual updates again after a call to <MooTreeControl.disable>
	*/

	enable: function() {
		this.enabled = true;
		this.root.update(true, true);
	}
	
});

/*
Class: MooTreeNode
	This class implements the functionality of a single node in a <MooTreeControl>.

Note:
	You should not manually create objects of this class -- rather, you should use
	<MooTreeControl.insert> to create nodes in the root of the tree, and then use
	the similar function <MooTreeNode.insert> to create subnodes.
	
	Both insert methods have a similar syntax, and both return the newly created
	<MooTreeNode> object.

Parameters:
	options - an object. See options below.

Options:
	text - this is the displayed text of the node, and as such as is the only required parameter.
	id - string, optional - if specified, must be a unique node identifier. Nodes with id can be retrieved using the <MooTreeControl.get> method.
	color - string, optional - if specified, must be a six-digit hexadecimal RGB color code.
	
	open - boolean value, defaults to false. Use true if you want the node open from the start.
	
	icon - use this to customize the icon of the node. The following predefined values may be used: '_open', '_closed' and '_doc'. Alternatively, specify the URL of a GIF or PNG image to use - this should be exactly 18x18 pixels in size. If you have a strip of images, you can specify an image number (e.g. 'my_icons.gif#4' for icon number 4).
	openicon - use this to customize the icon of the node when it's open.
	
	data - an object containing whatever data you wish to associate with this node (such as an url and/or an id, etc.)

Events:
	onExpand - called when the node is expanded or collapsed: function(state) - where state is a boolean meaning true:expanded or false:collapsed.
	onSelect - called when the node is selected or deselected: function(state) - where state is a boolean meaning true:selected or false:deselected.
	onClick - called when the node is clicked (no arguments).
*/

var MooTreeNode = new Class({
	
	initialize: function(options) {
		
		this.options = options;
		this.text = options.text;       // the text displayed by this node
		this.id = options.id || null;   // the node's unique id
		this.nodes = new Array();       // subnodes nested beneath this node (MooTreeNode objects)
		this.parent = null;             // this node's parent node (another MooTreeNode object)
		this.last = true;               // a flag telling whether this node is the last (bottom) node of it's parent
		this.control = options.control; // owner control of this node's tree
		this.selected = false || options.selected;          // a flag telling whether this node is the currently selected node in it's tree
		
		this.color = options.color || null; // text color of this node
		
		this.data = options.data || {}; // optional object containing whatever data you wish to associate with the node (typically an url or an id)
		
		this.onExpand = options.onExpand || new Function(); // called when the individual node is expanded/collapsed
		this.onSelect = options.onSelect || new Function(); // called when the individual node is selected/deselected
		this.onClick = options.onClick || new Function(); // called when the individual node is clicked
		
		this.onCheckboxClick = options.onCheckboxClick || new Function();
		
		this.open = options.open ? true : false; // flag: node open or closed?
		
		this.icon = options.icon;
		this.openicon = options.openicon || this.icon;
		this.buttons = options.buttons;
		this.labelFunction = options.labelFunction;
		
		// add the node to the control's node index:
		if (this.id) this.control.index[this.id] = this;
		
		// create the necessary divs:
		this.div = {
			main: new Element('div').addClass('mooTree_node'),
			indent: new Element('div'),
			gadget: new Element('div'),
			icon: new Element('div'),
			text: new Element('div').addClass('mooTree_text'),							
			sub: new Element('div')
		}
		
		if (document.all)
		this.div.checkbox = new Element('input', {style:"float:left;margin:1px 4px 0 0;", type:"checkbox" });
		else
		this.div.checkbox = new Element('input', {style:"float:left;margin:4px 4px 0 0;", type:"checkbox" });	
			
		this.div.checkbox.addEvent('click', this.checkBoxClick.bind(this));
		this.div.checkbox.addEvent('dblclick', this.checkBoxClick.bind(this));
				
		// put the other divs under the main div:
		this.div.main.adopt(this.div.indent);
		this.div.main.adopt(this.div.gadget);
		this.div.main.adopt(this.div.checkbox);
		//this.div.checkbox2 = new omniCheckbox(this.div.main,{style:"float:left;margin:5px 4px 0 0;display:none" }),
		this.div.checkbox2 = new Element('div',{style:"width:10px;height:10px;border:1px solid #aaa;float:left;margin:5px 4px 0 0;display:none" }),
		this.div.main.adopt(this.div.checkbox2);
		
		//alert(this.div.checkbox2.checked);
		this.div.checkbox2.checked = true;
		
		this.div.main.adopt(this.div.icon);		
		this.div.main.adopt(this.div.text);
		
		

		// put the main and sub divs in the specified parent div:
		$(options.div).adopt(this.div.main);
		$(options.div).adopt(this.div.sub);
		
		// attach event handler to gadget:
		this.div.gadget._node = this;
		this.div.gadget.onclick = this.div.gadget.ondblclick = function() {
			this._node.toggle();
		}
		
		// attach event handler to icon/text:
		this.div.icon._node = this.div.text._node = this;
		this.div.icon.onclick = this.div.icon.ondblclick = this.div.text.onclick = this.div.text.ondblclick = function() {
			this._node.control.select(this._node);
		}
		
	},
	
	/*
	Property: insert
		Creates a new node, nested inside this one.
	
	Parameters:
		options - an object containing the same options available to the <MooTreeNode> constructor.

	Returns:
		A new <MooTreeNode> instance.
	*/
	
	insert: function(options) {
		
		// set the parent div and create the node:
		options.div = this.div.sub;
		options.control = this.control;
		var node = new MooTreeNode(options);
		
		// set the new node's parent:
		node.parent = this;
		
		// mark this node's last node as no longer being the last, then add the new last node:
		var n = this.nodes;
		if (n.length) n[n.length-1].last = false;
		n.push(node);
		
		// repaint the new node:
		node.update();
		
		// repaint the new node's parent (this node):
		if (n.length == 1) this.update();
		
		// recursively repaint the new node's previous sibling node:
		if (n.length > 1) n[n.length-2].update(true);
		
		return node;
		
	},
	
	/*
	Property: remove
		Removes this node, and all of it's child nodes. If you want to remove all the childnodes without removing the node itself, use <MooTreeNode.clear>
	*/
	
	remove: function() {		
		var p = this.parent;
		this._remove();
		p.update(true);
	},
	
	_remove: function() {
		
		// recursively remove this node's subnodes:
		var n = this.nodes;
		while (n.length) n[n.length-1]._remove();
		
		// remove the node id from the control's index:
		delete this.control.index[this.id];

		//remove ref to node, ie leak
		this.div.gadget._node = null;
		this.div.icon._node = null;
		this.div.text._node = null;
		
		// remove this node's divs:
		this.div.main.destroy();
		this.div.sub.destroy();
		
		if (this.parent) {
			
			// remove this node from the parent's collection of nodes:
			var p = this.parent.nodes;
			p.erase(this);
			
			// in case we removed the parent's last node, flag it's current last node as being the last:
			if (p.length) p[p.length-1].last = true;
			
		}
		
	},
	
	/*
	Property: clear
		Removes all child nodes under this node, without removing the node itself.
		To remove all nodes including this one, use <MooTreeNode.remove>
	*/
	
	clear: function() {
		this.control.disable();
		while (this.nodes.length) this.nodes[this.nodes.length-1].remove();
		this.control.enable();
	},

	/*
	Property: update
		Update the tree node's visual appearance.
	
	Parameters:
		recursive - boolean, defaults to false. If true, recursively updates all nodes beneath this one.
		invalidated - boolean, defaults to false. If true, updates only nodes that have been invalidated while the control has been disabled.
	*/
	
	optionsClick: function(evt){
		console.log(43);
	},
	
	mouseOverNode: function(evt) {
		this.div.main.addClass('mooTree_over');
		
		var el = new Element('div', {html:''});
		el.addEvent('click', this.optionsClick.bind(this));
		el.addClass('settings');
		
		el.inject(this.div.main);
	},
	
	mouseOutNode: function(evt) {
		this.div.main.removeClass('mooTree_over');
		
		var el = this.div.main.getElement('.settings');
		if (el)
			el.dispose();
	},
	
	checkrecursive: function(node, check) {
		// ako nema djece prekini
		if (!node.nodes)
			return;
		
		node.nodes.forEach( function(n) {
			n.div.checkbox.checked = check;
			
			this.checkrecursive(n, check);
		}.bind(this));
	},
	
	getChecked:function(node,onlynodes) {
		if (!node) node = this;
		var list = new Array();
		node.nodes.forEach( function(n) {
			if (n.div.checkbox.checked && ((!n.categorytext && !onlynodes) || (n.categorytext && onlynodes)))
			{				
				list.push(n.id);
				//console.log(n);
			}			
			list = list.concat(this.getChecked(n,onlynodes));
		}.bind(this));
		
		return list;
	},
	
	setChecked:function(node,list) {
		if (!node) node = this;
		node.nodes.forEach( function(n) {
			if ((!list || list["c"+n.id]) && n.nodes.length == 0)
				n.div.checkbox.checked = true;
			//console.log(list);
			this.setChecked(n,list);
		}.bind(this));
	},
	
	setNodeCheck:function(node,nid,stat) {
		if (!nid) 
		{
			this.div.checkbox.checked = stat;
			return;
		}
		
		if (!node) node = this;
		
		node.nodes.forEach( function(n) {
			if (nid == n.id)
				n.div.checkbox.checked = stat;
			else
				this.setNodeCheck(n,stat);
		}.bind(this));
	},
	
	checkBoxClick: function(evt) {
		evt.cancelBubble = true;				
		this.checkrecursive(this, this.div.checkbox.checked);			
		this.onCheckboxClick(this);
	},
	
	update: function(recursive, invalidated) {
		
		var draw = true;
		
		if (!this.control.enabled) {
			// control is currently disabled, so we don't do any visual updates
			this.invalidated = true;
			draw = false;
		}
		
		if (invalidated) {
			if (!this.invalidated) {
				draw = false; // this one is still valid, don't draw
			} else {
				this.invalidated = false; // we're drawing this item now
			}
		}
		
		if (draw) {
			
			var x;
			
			// make selected, or not:
			this.div.main.className = 'mooTree_node' + (this.selected ? ' mooTree_selected' : '');
			
			// update indentations:
			var p = this, i = '';
			while (p.parent) {
				p = p.parent;
				i = this.getImg(p.last || !this.control.grid ? '' : 'I') + i;
			}
			this.div.indent.innerHTML = i;
			
			//this.div.main.addEvent("mouseenter", this.mouseOverNode.bind(this));
			//this.div.main.addEvent("mouseleave", this.mouseOutNode.bind(this));
			
			// update the text:
			if (this.labelFunction){
				this.labelFunction(this);				
			}else{
				x = this.div.text;
				x.empty();
				x.appendText(this.text);				
				if (this.color) x.style.color = this.color;
			}
			
			//if (this.text == 'Podloga')	x.setStyle('height', 50);
			
			// update the icon:
			var iconhtml = "";
			
			var icon = this.nodes.length ? ( this.open ? (this.openicon || this.icon || '_open') : (this.icon || '_closed') ) : ( this.icon || (this.control.mode == 'folders' ? '_closed' : '_doc') );

			if (icon != '_doc' || !this.buttons)
				iconhtml += this.getImg( icon );

			if (this.buttons)
			{
				for(var i=0; i<this.buttons.length; i++)
				{
					iconhtml += this.getCustomImg( this.buttons[i].icon, this.buttons[i].tooltip, this.buttons[i].text, 'cursor:pointer' );			
				}
			}
			
			this.div.icon.innerHTML = iconhtml;
			
			// update the plus/minus gadget:
			this.div.gadget.innerHTML = this.getImg( ( this.control.grid ? ( this.control.root == this ? (this.nodes.length ? 'R' : '') : (this.last?'L':'T') ) : '') + (this.nodes.length ? (this.open?'minus':'plus') : '') );
			
			// show/hide subnodes:
			this.div.sub.style.display = this.open ? 'block' : 'none';
		
		}
		
		// if recursively updating, update all child nodes:
		if (recursive) this.nodes.forEach( function(node) {
			node.update(true, invalidated);
		});
		
	},
	
	/*
	Property: getImg
		Creates a new image, in the form of HTML for a DIV element with appropriate style.
		You should not need to manually call this method. (though if for some reason you want to, you can)
	
	Parameters:
		name - the name of new image to create, defined by <MooTreeIcon> or located in an external file.
	
	Returns:
		The HTML for a new div Element.
	*/
	
	getCustomImg: function(name, title, text,addstyle) {
		var html = '<div class="mooTree_img"';
		
		if (title != null) {
			html += ' title="'+title+'"';
		}
		if (!text) text = "";
		text = "";
		
		//html += ' onclick="console.log(32);"'; //event.cancelBubble = true;
		if (!addstyle) addstyle = "";
		
	
		if (text)
			addstyle += ";width:auto;padding-left:18px;padding-top:3px;font-size:9px";
	
   	
		html += ' style="background-image:url(' + name + ');'+addstyle+'"';
		html += ">"+text+"</div>";
		
			/*	
		html += ' style="'+addstyle+'"';		
		html += "><img src=\""+name+"\" />"+text+"</div>";
	*/
		return html;
	},
	
	getImg: function(name) {
		
		var html = '<div class="mooTree_img"';
		
		if (name != '' && name != '_doc') {
			var img = this.control.theme;
			var i = MooTreeIcon.indexOf(name);
			if (i == -1) {
				// custom (external) icon:
				var x = name.split('#');
				img = x[0];
				i = (x.length == 2 ? parseInt(x[1])-1 : 0);
			}
			html += ' style="background-image:url(' + img + '); background-position:-' + (i*18) + 'px 2px;"';
		}
		
		html += "></div>";
		
		return html;
		
	},
	
	/*
	Property: toggle
		By default (with no arguments) this function toggles the node between expanded/collapsed.
		Can also be used to recursively expand/collapse all or part of the tree.
	
	Parameters:
		recursive - boolean, defaults to false. With recursive set to true, all child nodes are recursively toggle to this node's new state.
		state - boolean. If undefined, the node's state is toggled. If true or false, the node can be explicitly opened or closed.
	*/
	
	toggle: function(recursive, state) {
		
		this.open = (state === undefined ? !this.open : state);
		this.update();

		this.onExpand(this.open);
		this.control.onExpand(this, this.open);

		if (recursive) this.nodes.forEach( function(node) {
			node.toggle(true, this.open);
		}, this);
		
	},
	
	/*
	Property: select
		Called by <MooTreeControl> when the selection changes.
		You should not manually call this method - to set the selection, use the <MooTreeControl.select> method.
	*/
	
	select: function(state) {
		if (!this.id || this.id < 0) return;
		this.selected = state;
		this.update();
		this.onSelect(state);
	},
	
	/*
	Property: load
		Asynchronously load an XML structure into a node of this tree.
	
	Parameters:
		url - string, required, specifies the URL from which to load the XML document.
		vars - query string, optional.
	*/
	
	load: function(url, vars) {
	
		if (this.loading) return; // if this node is already loading, return
		this.loading = true;      // flag this node as loading
		
		this.toggle(false, true); // expand the node to make the loader visible
		
		this.clear();

		this.insert(this.control.loader);
		
		var f = function() {
			new Request({
				method: 'GET',
				url: url,
				onSuccess: this._loaded.bind(this),
				onFailure: this._load_err.bind(this)
			}).send(url, vars || '');
		}.bind(this).delay(20);
		
		//window.setTimeout(f.bind(this), 20); // allowing a small delay for the browser to draw the loader-icon.
		
	},
	
	_loaded: function(text, xml) {
		// called on success - import nodes from the root element:
		this.control.disable();
		this.clear();
		this._import(xml.documentElement);
		this.control.enable();
		this.loading = false;
	},
	
	_import: function(e) {
		// import childnodes from an xml element:
		var n = e.childNodes;
		for (var i=0; i<n.length; i++) if (n[i].tagName == 'node') {
			var opt = {data:{}};
			var a = n[i].attributes;
			for (var t=0; t<a.length; t++) {
				switch (a[t].name) {
					case 'text':
					case 'id':
					case 'icon':
					case 'openicon':
					case 'color':
					case 'open':
						opt[a[t].name] = a[t].value;
						break;
					default:
						opt.data[a[t].name] = a[t].value;
				}
			}
			var node = this.insert(opt);
			if (node.data.load) {
				node.open = false; // can't have a dynamically loading node that's already open!
				node.insert(this.control.loader);
				node.onExpand = function(state) {
					this.load(this.data.load);
					this.onExpand = new Function();
				}
			}
			// recursively import subnodes of this node:
			if (n[i].childNodes.length) node._import(n[i]);
		}
	},
	
	_load_err: function(req) {
		window.alert('Error loading: ' + this.text);
	}
	
});
/*
Author: Marko
Depends: mootree.js 1.2
Projects: GeoTrag

Part of Omnia framework

*/

var fleetTree = new Class({
	Extends: MooTreeControl,

	initialize: function(config) {
		
		config.mode = 'files';
		config.grid = false;
		config.theme = '';
				
		this.parent(config, config);
		
		this.categoryicon = config.categoryicon || '/include/omf/omtree/icons/folder.png';
		this.loadericon = config.loadericon || '/include/omf/omtree/icons/load.gif';
		
		this.disable(); // this stops visual updates while we're building the tree...
		
		// dino
		this.catNodes = new Array();
		
		if (!config.catNodes)
		{
			this.categoryActiveText = 'U kretanju';
			this.categoryStandText = 'Stoje';
			this.categoryInactiveText = 'Neaktivni';
		
			this.catNodes["active"] = this.insert({text:this.categoryActiveText+' (0)', id:-1, icon: this.categoryicon, onCheckboxClick:config.onCheckboxClick});
			this.catNodes["stand"] = this.insert({text:this.categoryStandText+' (0)', id:-2, icon: this.categoryicon, onCheckboxClick:config.onCheckboxClick});
			this.catNodes["inactive"] = this.insert({text:this.categoryInactiveText+' (0)', id:-3, icon: this.categoryicon, onCheckboxClick:config.onCheckboxClick});
			
			this.catNodes["active"].categorytext = this.categoryActiveText;
			this.catNodes["stand"].categorytext = this.categoryStandText;
			this.catNodes["inactive"].categorytext = this.categoryInactiveText;
		}
		else
		{
			for (var i = 0; i < config.catNodes.length; i++)
			{
				var n = config.catNodes[i];
				this.catNodes[n.id] = this.insert({text:n.text+' (0)', id:n.id, icon: this.categoryicon, onCheckboxClick:config.onCheckboxClick});
				this.catNodes[n.id].categorytext = n.text;
			}
		}
		
		/*
		this.nodeActive = this.insert({text:this.categoryActiveText+' (0)', id:-1, icon: this.categoryicon});
		this.nodeStand = this.insert({text:this.categoryStandText+' (0)', id:-2, icon: this.categoryicon});
		this.nodeInactive = this.insert({text:this.categoryInactiveText+' (0)', id:-3, icon: this.categoryicon});
		
		this.nodeActive.categorytext = this.categoryActiveText;
		this.nodeStand.categorytext = this.categoryStandText;
		this.nodeInactive.categorytext = this.categoryInactiveText;
		*/
		
		this.enable();
	},
	
	// API
	insert: function(options) {
		// dino
		if (cat = this.catNodes[options.category])
		{
			//alert(cat.text+" "+cat.categorytext);
			var newnode =cat.insert(options);
			cat.div.text.innerHTML = cat.text = cat.categorytext+' ('+cat.nodes.length+')';
			cat.update(false, true);
		}
		
		/*
		switch(options.category){
			case 'active':
				var newnode = this.nodeActive.insert(options);
				this.nodeActive.div.text.innerHTML = this.nodeActive.text = this.categoryActiveText+' ('+this.nodeActive.nodes.length+')';
				this.nodeActive.update(false, true);
				break;
			case 'stand':
				var newnode = this.nodeStand.insert(options);
				this.nodeStand.div.text.innerHTML = this.nodeStand.text = this.categoryStandText+' ('+this.nodeStand.nodes.length+')';
				this.nodeStand.update(false, true);
				break;
			case 'inactive':
				var newnode = this.nodeInactive.insert(options);
				this.nodeInactive.div.text.innerHTML = this.nodeInactive.text = this.categoryInactiveText+' ('+this.nodeInactive.nodes.length+')';
				this.nodeInactive.update(false, true);
				break;
		}
		*/
	
		if (newnode)
		{
			newnode.category = options.category;
			return newnode;
		}
		else 
			return this.parent(options);
	},
	
	// API
	findById: function(parent, id) {
	
		for(var i=0; i<parent.nodes.length; i++ ){
			var node = parent.nodes[i];
			
			if (node.id == id)
			{
				return node;
			}
			
			// search in node's children
			var r = this.findById(node, id);
			
			if (r) return r;
		}
	},
	
	// API
	change: function(options) {
		
		var node = this.findById(this.root, options.id);
		
		// moze biti promjena statusa ili promjena kategorije
		//console.log(options.category || node.category);
		
		// ako mijenja kategoriju onda ga zbrise i napravi
		if (options.category && node.category != options.category){
			// zbrisi starog i napravi novog sa istim prop.
			this.disable();
			
			var nodeoptions = {
					text: options.text || node.text, 
					buttons: options.buttons || node.buttons, 
					id: node.id, 
					data: options.data || node.data, 
					category: options.category || node.category
			};
			
			this.remove(node.id);
			
			this.insert(nodeoptions);
			
			this.enable();
		}else{
			
			node.text = options.text || node.text; 
			node.buttons = options.buttons || node.buttons; 
			node.data = options.data || node.data; 
			
			node.update();
		}
		
	},
	
	// API
	clear: function(options) {
		
		var node = this.getCategoryNode(options.category);
		
		if (node){
		
			node.div.text.innerHTML = node.text = node.categorytext+' (0)';
			if (options.showloader)
				node.icon = this.loadericon;
			node.clear();
			
			//this.enable();
		}
	},
	
	// API
	remove: function(node) {
				
		//var node = this.findById(this.root, id);
		
		if (node){
			var parentnode = node.parent;
			node.remove();
			parentnode.div.text.innerHTML = parentnode.text = parentnode.categorytext+' ('+parentnode.nodes.length+')';
			parentnode.update(false, true);
		}
	},
	
	sortFunction: function(a, b)
	{
		//console.log(a);console.log(b);console.log(' ');

		if ( eval('a.'+this.sortfield) >= eval('b.'+this.sortfield)){
			a.div.main.inject(b.div.main, 'after');
			
			return 1;
		}else{
			a.div.main.inject(b.div.main, 'before');
			
			return -1;
		}
	},
	
	getCategoryNode: function(category) {
		var node = this.root;
		
		// dino
		return this.catNodes[category];
		/*
		switch(category){
			case 'active':
				node = this.nodeActive;
				
				break;
			case 'stand':
				node = this.nodeStand;

				break;
			case 'inactive':
				node = this.nodeInactive;

				break;
		}
		
		return node;*/
	},
	
	// API
	sort: function(options) {
		var node = this.getCategoryNode(options.category);

		this.sortfield = options.field;
		node.nodes.sort(this.sortFunction.bind(this));

	},
	
	getCheckedList: function(onlynodes) {
		var c = this.root.getChecked(null,onlynodes);
		return c;
	},
	
	setCheckedList: function(list) {
		return this.root.setChecked(null,list);
	},
	
	setNodeCheck: function(nid,stat) {
		return this.root.setNodeCheck(null,nid,stat);
	},
	
	changeCheckBoxColor: function(id,color) {
		this.root.changeCheckBoxColor(id,color);		
	}
	
	
});

// Author: Dino Ravnić
// Web: http://www.omnisdata.com
// Email: dino@omnisdata.com
// Company: Omnisdata Ltd.
// Licence: Creative Commons Attribution 3.0 Unported License, http://creativecommons.org/licenses/by/3.0/
//			If you copy, distribute or transmit the source code please retain the above copyright notice, author name and project URL. 
// Required: Mootools 1.2
// Version: OmniGrid 1.2.3
// ****************************************************************************

var omniCheckbox = new Class({
	Implements: [Events,Options],					  
	
	initialize: function(container, options){
		//console.log("ch init");
		/*
		this.setOptions(this.getOptions(), options);
		this.container = $(container);
		
		if (!this.container)
			return;
			
		this.draw();
		
		this.reset();
		
		this.loadData();
		*/
		this.elem = new Element('a', options);
		this.elem.addClass("omnicheckbox");
		//el.setStyle("float","left");			
		container.adopt(this.elem);								
	},
	
	_check:function()
	{
		if (this._checked)
			this.elem.setStyle("backgroundColor","red");
		else
			this.elem.setStyle("backgroundColor","white");	
	},
	
	_checked:false,		
	
	setColor:function(color)
	{
		this.elem.setStyle("backgroundColor",color);		
	},
	
	checked:{
		set:function(value)
		{
			this._checked = value;
			this._check();
		},
		
		get:function()
		{
			return this._checked;
		}
	}

});


/*************************************************************/

var OmniForm = new Class({

	prefix:null,
	currentData:null,
	currentSelValue:null,
	url:null,
	confirmBeforeChange:null,
	
	initialize: function(options) {
		//console.log("init"+config+" "+options);
		this.prefix = options.prefix;
		this.url = options.url;
		this.controlField = options.controlField;
		this.confirmBeforeChange = options.confirmBeforeChange;
	},
	
	getItemValue:function(i)
	{
		if (i.selectedIndex >= 0)
			return i.options[i.selectedIndex].value;
		
		return i.value;
	},
	
	setItemValue:function(item,val)
	{
		i = $(this.prefix+item);
		
		if (i.selectedIndex >= 0)
		{
			for (k = 0; k < i.options.length; k++)
			{
				if (i.options[k].value == val)
				{
					i.selectedIndex = k;
				  return val;
				}
			}
			i.selectedIndex = 0;
			return 0;
		}
			
		i.value = val;
		return val;
	},
	
	checkItemsForChange:function(p)
	{
		if (!p) p = this.currentData;
		
		for (var i in p)
		{
			if (i != this.controlField && this.getItemValue($(this.prefix+i)) != p[i]) return 1; 			
		}
		return 0;
	},
	
	createNew:function()
	{
		var newid = -1;
		if (this.currentData)
		{
			if (this.checkItemsForChange())
			{
				if (this.confirmBeforeChange && confirm(this.confirmBeforeChange))
				{
					this.store(true);
				}
			}
			this.clearItems();
			this.currentData[this.controlField] = newid;
		}		
		this.currentSelValue = newid;
	},
	
	changeContent:function(refresh)
	{
	
		if (refresh)
		{		
			var p = this.currentData;
			for (var i in p)
				this.setItemValue(i,p[i]);
				
			return;
		}
		
		o = $(this.prefix+this.controlField);
		var i = this.getItemValue(o);
		
		if (this.currentSelValue == i) return;
		
		this.createNew();
		
		this.currentSelValue = i;
		if (o.selectedIndex >= 0)
		this.curSelectOption = o.options[o.selectedIndex];

		this.load();
	},
	
	getItemValues:function(p)
	{
		if (!p) p = this.currentData;
		
		var arr = new Object();
		for (var i in p)
		{
			arr[this.prefix+i] = this.getItemValue($(this.prefix+i));
		}
			
		return arr;
	},
	
	clearItems:function(p)
	{
		if (!p) p = this.currentData;
		
		for (var i in p)
		if (i != this.controlField)
			p[i] = this.setItemValue(i,"");
	},
	
	load:function()
	{
		var jsonRequest = new Request.JSON({url: this.url, onComplete: function(d)
		{	        	
			if (!d || d.length == 0) 
			{
				this.omform.clearItems();
				return;
			}
			
			var p = d[0];
			this.omform.currentData = p;
			
			for (var i in p)
				this.omform.setItemValue(i,p[i]);						
				
		}});
		jsonRequest.omform = this;
		var f = this.prefix+this.controlField;
		var o = {'action':'load'};
		o[f] = this.getItemValue($(f));
		jsonRequest.get(o);
	},
	
	store:function(use_last_control_value,obj)
	{
		
		var arr = this.getItemValues();
		
		arr.action = "store";
		if (use_last_control_value)
		arr[this.prefix+this.controlField] = this.currentSelValue;
		console.log(arr);
		var jsonRequest = new Request({url: this.url, data:arr, onComplete: function(rez)
		{	      
			var rez = rez.split("|");
			//console.log(rez);
			if (rez[0] != "ok") 
			{
				alert("Greška kod spremanja!");
				return;
			}
			if (rez[1] && this.curSelectOption)
			{
				if (this.curSelectOption)
				this.curSelectOption.value = rez[1]*1;					
			}
			
			var p = this.omform.currentData;
			if (!p) 
			{
				alert("x");
				p = new Object();
			}
			for (var i in p)
				p[i] = this.omform.getItemValue($(this.omform.prefix+i));
			this.omform.currentData = p;
			
			if (this.obj)
			this.obj.innerHTML = this.objName;
						
			//console.log(p);						       
		}});
		jsonRequest.curSelectOption = this.curSelectOption;
		jsonRequest.omform = this;
		if (obj)
		{
		jsonRequest.obj = obj;
		jsonRequest.objName = obj.innerHTML;
		 obj.innerHTML = "Spremam...";
		}
		jsonRequest.send();
		
	},
	
	remove:function()
	{
		var jsonRequest = new Request({url: this.url, onComplete: function(rez)
		{	      
			 o = $(this.omform.prefix+this.omform.controlField);
			 if (o.selectedIndex >= 0)
			 o.remove(o.selectedIndex);
			
			 this.omform.changeContent();
		}});
		var f = this.prefix+this.controlField;
		var o = {'action':'delete'};
		o[f] = this.getItemValue($(f));
		jsonRequest.omform = this;
		jsonRequest.get(o);				
	}
});

		/*
---
 
name: Mif.Tree
description: Mif.Tree base Class
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: 
  - Core:1.2.4/*
  - More/Fx.Scroll
provides: Mif.Tree
 
...
*/

if(!Mif) var Mif = {};
if(!Mif.ids) Mif.ids = {};
if(!Mif.id) Mif.id = function(id){
	return Mif.ids[id];
}

Mif.Tree = new Class({
	
	version: '1.2.6.1',

	Implements: [new Events, new Options],
		
	options:{
		types: {},
		forest: false,
		animateScroll: true,
		height: 18,
		expandTo: true
	},
	
	initialize: function(options){
		this.setOptions(options);
		$extend(this, {
			types: this.options.types,
			forest: this.options.forest,
			animateScroll: this.options.animateScroll,
			dfltType: this.options.dfltType,
			height: this.options.height,
			container: $(options.container),
			UID: ++Mif.Tree.UID,
			key: {},
			expanded: []
		});
		this.defaults = {
			name: '',
			cls: '',
			openIcon: 'mif-tree-empty-icon',
			closeIcon: 'mif-tree-empty-icon',
			loadable: false,
			hidden: false
		};
		this.dfltState = {
			open: false
		};
		this.$index = [];
		this.updateOpenState();
		if(this.options.expandTo) this.initExpandTo();
		this.DOMidPrefix='mif-tree-';
		this.wrapper = new Element('div').addClass('mif-tree-wrapper').injectInside(this.container);
		this.events();
		this.initScroll();
		this.initSelection();
		this.initHover();
		this.addEvent('drawChildren', function(parent){
			var nodes = parent._toggle||[];
			for(var i = 0, l = nodes.length; i < l; i++){
				nodes[i].drawToggle();
			}
			parent._toggle = [];
		});
		var id = this.options.id;
		this.id = id;
		if(id != null) Mif.ids[id] = this;
		if (MooTools.version >= '1.2.2' && this.options.initialize) this.options.initialize.call(this);
	},
	
	bound: function(){
		Array.each(arguments, function(name){
			this.bound[name] = this[name].bind(this);
		}, this);
	},
	
	events: function(){
		this.bound('mouse', 'mouseleave', 'mousedown', 'preventDefault', 'toggleClick', 'toggleDblclick', 'focus', 'blurOnClick', 'keyDown', 'keyUp');
		
		this.wrapper.addEvents({
			mousemove: this.bound.mouse,
			mouseover: this.bound.mouse,
			mouseout: this.bound.mouse,
			mouseleave: this.bound.mouseleave,
			mousedown: this.bound.mousedown,
			click: this.bound.toggleClick,
			dblclick: this.bound.toggleDblclick,
			selectstart: this.bound.preventDefault
		});
		
		this.container.addEvent('click', this.bound.focus);
		document.addEvent('click', this.bound.blurOnClick);
		
		document.addEvents({
			keydown: this.bound.keyDown,
			keyup: this.bound.keyUp
		});
    },
    
	blurOnClick: function(event){
		var target = event.target;
		while(target){
			if(target == this.container) return;
			target = target.parentNode;
		}
		this.blur();
	},
    
	focus: function(){
		if(Mif.Focus && Mif.Focus == this) return this;
		if(Mif.Focus) Mif.Focus.blur();
		Mif.Focus = this;
		this.focused = true;
		this.container.addClass('mif-tree-focused');
		return this.fireEvent('focus');
	},
    
	blur: function(){
		Mif.Focus = null;
		if(!this.focused) return this;
		this.focused = false;
		this.container.removeClass('mif-tree-focused');
		return this.fireEvent('blur');
	},
	
	$getIndex: function(){//return array of visible nodes.
		this.$index = [];
		var node = this.forest ? this.root.getFirst() : this.root;
		var previous = node;
		while(node){
			if(!(previous.hidden && previous.contains(node))){
				if(!node.hidden) this.$index.push(node);
				previous = node;
			}
			node = node._getNextVisible();
		}
	},
	
	preventDefault: function(event){
		event.preventDefault();
	},
	
	mousedown: function(event){
		if(event.rightClick) return;
		event.preventDefault();
		this.fireEvent('mousedown');
	},
	
	mouseleave: function(){
		this.mouse.coords = {x: null,y: null};
		this.mouse.target = false;
		this.mouse.node = false;
		if(this.hover) this.hover();
	},
	
	mouse: function(event){
		this.mouse.coords = this.getCoords(event);
		var target = this.getTarget(event);
		this.mouse.target = target.target;
		this.mouse.node	= target.node;
	},
	
	getTarget: function(event){
		var target = event.target, node;
		while(!/mif-tree/.test(target.className)){
			target = target.parentNode;
		}
		var test = target.className.match(/mif-tree-(gadjet)-[^n]|mif-tree-(icon)|mif-tree-(name)|mif-tree-(checkbox)/);
		if(!test){
			var y = this.mouse.coords.y;
			if(y == -1||!this.$index) {
				node = false;
			}else{
				node = this.$index[((y)/this.height).toInt()];
			}
			return {
				node: node,
				target: 'node'
			};
		}
		for(var i = 5; i > 0; i--){
			if(test[i]){
				var type = test[i];
				break;
			}
		}
		return {
			node: Mif.Tree.Nodes[target.getAttribute('uid')],
			target: type
		};
	},
	
	getCoords: function(event){
		var position = this.wrapper.getPosition();
		var x = event.page.x - position.x;
		var y = event.page.y - position.y;
		var wrapper = this.wrapper;
		if((y-wrapper.scrollTop > wrapper.clientHeight)||(x - wrapper.scrollLeft > wrapper.clientWidth)){//scroll line
			y = -1;
		};
		return {x: x, y: y};
	},
	
	keyDown: function(event){
		this.key = event;
		this.key.state = 'down';
		if(this.focused) this.fireEvent('keydown', [event]);
	},
	
	keyUp: function(event){
		this.key = {};
		this.key.state = 'up';
		if(this.focused) this.fireEvent('keyup', [event]);
	},
	
	toggleDblclick: function(event){
		var target = this.mouse.target;
		if(!(target == 'name' || target == 'icon')) return;
		this.mouse.node.toggle();
	},
	
	toggleClick: function(event){
		if(this.mouse.target != 'gadjet') return;
		this.mouse.node.toggle();
	},
	
	initScroll: function(){
		this.scroll = new Fx.Scroll(this.wrapper, {link: 'cancel'});
	},
	
	scrollTo: function(node){
		var position = node.getVisiblePosition();
		var top = position*this.height;
		var up = (top < this.wrapper.scrollTop);
		var down = (top > (this.wrapper.scrollTop + this.wrapper.clientHeight - this.height));
		if(position == -1 || ( !up && !down ) ) {
			this.scroll.fireEvent('complete');
			return false;
		}
		if(this.animateScroll){
			this.scroll.start(this.wrapper.scrollLeft, top - (down ? this.wrapper.clientHeight - this.height : this.height));
		}else{
			this.scroll.set(this.wrapper.scrollLeft, top - (down ? this.wrapper.clientHeight - this.height : this.height));
			this.scroll.fireEvent('complete');
		}
	},
	
	updateOpenState: function(){
		this.addEvents({
			'drawChildren': function(parent){
				var children = parent.children;
				for(var i = 0, l = children.length; i < l; i++){
					children[i].updateOpenState();
				}
			},
			'drawRoot': function(){
				this.root.updateOpenState();
			}
		});
	},
	
	expandTo: function(node){
		if (!node) return this;
		var path = [];
		while( !node.isRoot() && !(this.forest && node.getParent().isRoot()) ){
			node = node.getParent();
			if(!node) break;
			path.unshift(node);
		};
		path.each(function(el){
			el.toggle(true)
		});
		return this;
	},
	
	initExpandTo: function(){
		this.addEvent('loadChildren', function(parent){
			if(!parent) return;
			var children = parent.children;
			for( var i = children.length; i--; ){
				var child = children[i];
				if(child.expandTo) this.expanded.push(child);
			}
		});
		function expand(){
			this.expanded.each(function(node){
				this.expandTo(node);
			}, this);
			this.expanded = [];
		};
		this.addEvents({
			'load': expand.bind(this),
			'loadNode': expand.bind(this)
		});
	}
	
});
Mif.Tree.UID = 0;

Array.implement({
	
	inject: function(added, current, where){//inject added after or before current;
		var pos = this.indexOf(current) + (where == 'before' ? 0 : 1);
		for(var i = this.length-1; i >= pos; i--){
			this[i + 1] = this[i];
		}
		this[pos] = added;
		return this;
	}
	
});


/*
---
 
name: Mif.Tree.Node
description: Mif.Tree.Node
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Node
 
...
*/

Mif.Tree.Node = new Class({

	Implements: [Events],
	
	initialize: function(structure, options) {
		$extend(this, structure);
		this.children = [];
		this.type = options.type || this.tree.dfltType;
		this.property = options.property || {};
		this.data = options.data;
		this.state = $extend($unlink(this.tree.dfltState), options.state);
		this.$calculate();
		this.UID = Mif.Tree.Node.UID++;
		Mif.Tree.Nodes[this.UID] = this;
		var id = this.id;
		if(id != null) Mif.ids[id] = this;
		this.tree.fireEvent('nodeCreate', [this]);
		this._property = ['id', 'name', 'cls', 'openIcon', 'closeIcon', 'openIconUrl', 'closeIconUrl', 'hidden'];
	},
	
	$calculate: function(){
		$extend(this, $unlink(this.tree.defaults));
		this.type = $splat(this.type);
		this.type.each(function(type){
			var props = this.tree.types[type];
			if(props) $extend(this, props);
		}, this);
		$extend(this, this.property);
		return this;
	},
	
	getDOM: function(what){
		var node = $(this.tree.DOMidPrefix+this.UID);
		if(what == 'node') return node;
		var wrapper = node.getFirst();
		if(what == 'wrapper') return wrapper;
		if(what == 'children') return wrapper.getNext();
		return wrapper.getElement('.mif-tree-'+what);
	},
	
	getGadjetType: function(){
		return (this.loadable && !this.isLoaded()) ? 'plus' : (this.hasVisibleChildren() ? (this.isOpen() ? 'minus' : 'plus') : 'none');
	},
	
	toggle: function(state) {
		if(this.state.open == state || this.$loading || this.$toggling) return this;
		var parent = this.getParent();
		function toggle(type){
			this.state.open = !this.state.open;
			if(type == 'drawed'){
				this.drawToggle();
			}else{
				parent._toggle = (parent._toggle||[])[this.state.open ? 'include' : 'erase'](this)
			}
			this.fireEvent('toggle', [this.state.open]);
			this.tree.fireEvent('toggle', [this, this.state.open]);
			return this;
		}
		if(parent && !parent.$draw){
			return toggle.apply(this, []);
		}
		if(this.loadable && !this.state.loaded) {
            if(!this.load_event){
                this.load_event = true;
                this.addEvent('load',function(){
                    this.toggle();
                }.bind(this));
            }
            return this.load();
        }
		if(!this.hasChildren()) return this;
		return toggle.apply(this, ['drawed']);
	},
	
	drawToggle: function(){
		this.tree.$getIndex();
		Mif.Tree.Draw.update(this);
	},
	
	recursive: function(fn, args){
		args=$splat(args);
		if(fn.apply(this, args) !== false){
			this.children.each(function(node){
				if(node.recursive(fn, args) === false){
					return false;
				}
			});
		}
		return this;
	},
	
	isOpen: function(){
		return this.state.open;
	},
	
	isLoaded: function(){
		return this.state.loaded;
	},
	
	isLast: function(){
		if(this.parentNode == null || this.parentNode.children.getLast() == this) return true;
		return false;
	},
	
	isFirst: function(){
		if(this.parentNode == null || this.parentNode.children[0] == this) return true;
		return false;
	},
	
	isRoot: function(){
		return this.parentNode == null ? true : false;
	},
	
	getChildren: function(){
		return this.children;
	},
	
	hasChildren: function(){
		return this.children.length ? true : false;
	},
	
	index: function(){
		if( this.isRoot() ) return 0;
		return this.parentNode.children.indexOf(this);
	},
	
	getNext: function(){
		if(this.isLast()) return null;
		return this.parentNode.children[this.index()+1];
	},
	
	getPrevious: function(){
		if( this.isFirst() ) return null;
		return this.parentNode.children[this.index()-1];
	},
	
	getFirst: function(){
		if(!this.hasChildren()) return null;
		return this.children[0];
	},
	
	getLast: function(){
		if(!this.hasChildren()) return null;
		return this.children.getLast();		
	},
	
	getParent: function(){
		return this.parentNode;
	},
	
	_getNextVisible: function(){
		var current=this;
		if(current.isRoot()){
			if(!current.isOpen() || !current.hasChildren(true)) return false;
			return current.getFirst(true);
		}else{
			if(current.isOpen() && current.getFirst(true)){
				return current.getFirst(true);
			}else{
				var parent = current;
				do{
					current = parent.getNext(true);
					if(current) return current;
				}while( parent = parent.parentNode );
				return false;
			}
		}
	},
	
	getPreviousVisible: function(){
		var index = this.tree.$index.indexOf(this);
		return index == 0 ? null : this.tree.$index[index-1];
	},
	
	getNextVisible: function(){
		var index = this.tree.$index.indexOf(this);
		return index < this.tree.$index.length-1 ? this.tree.$index[index+1] : null;
	},
	
	getVisiblePosition: function(){
		return this.tree.$index.indexOf(this);
	},
	
	hasVisibleChildren: function(){
		if(!this.hasChildren()) return false;
		if(this.isOpen()){
			var next = this.getNextVisible();
			if(!next) return false;
			if(next.parentNode != this) return false;
			return true;
		}else{
			var child = this.getFirst();
			while(child){
				if(!child.hidden) return true;
				child = child.getNext();
			}
			return false;
		}
	},
	
	isLastVisible: function(){
		var next = this.getNext();
		while(next){
			if(!next.hidden) return false;
			next = next.getNext();
		};
		return true;
	},
		
	contains: function(node){
		while(node){
			if(node == this) return true;
			node = node.parentNode;
		};
		return false;
	},

	addType: function(type){
		return this.processType(type, 'add');
	},

	removeType: function(type){
		return this.processType(type, 'remove');
	},
	
	setType: function(type){
		return this.processType(type, 'set');
	},
	
	processType: function(type, action){
		switch(action){
			case 'add': this.type.include(type); break;
			case 'remove': this.type.erase(type); break;
			case 'set': this.type = type; break;
		}
		var current = {};
		this._property.each(function(p){
			current[p] = this[p];
		}, this);
		this.$calculate();
		this._property.each(function(p){
			this.updateProperty(p, current[p], this[p]);
		}, this);
		return this;
	},
	
	set: function(obj){
		this.tree.fireEvent('beforeSet', [this, obj]);
		var property = obj.property||obj||{};
		for(var p in property){
			var nv = property[p];
			var cv = this[p];
			this.updateProperty(p, cv, nv);
			this[p] = this.property[p] = nv;
		}
		this.tree.fireEvent('set', [this, obj]);
		return this;
	},
	
	updateProperty: function(p, cv, nv){
		if(nv == cv) return this;
		if(p == 'id'){
			delete Mif.ids[cv];
			if(nv) Mif.ids[nv]=this;
			return this;
		}
		if(!Mif.Tree.Draw.isUpdatable(this)) return this;
		switch(p){
			case 'name':
				this.getDOM('name').set('html', nv);
				return this;
			case 'cls':
				this.getDOM('wrapper').removeClass(cv).addClass(nv);
				return this;
			case 'openIcon':
			case 'closeIcon':
				this.getDOM('icon').removeClass(cv).addClass(nv);
				return this;
			case 'openIconUrl':
			case 'closeIconUrl':
				var icon = this.getDOM('icon');
				icon.setStyle('background-image', 'none');
				if(nv) icon.setStyle('background-image', 'url('+nv+')');
				return this;
			case 'hidden':
				this.getDOM('node').setStyle('display', nv ? 'none' : 'block');
				var _previous = this.getPreviousVisible();
				var _next = this.getNextVisible();
				var parent = this.getParent();
				this[p] = this.property[p]=nv;
				this.tree.$getIndex();
				var previous = this.getPreviousVisible();
				var next = this.getNextVisible();
				[_previous, _next, previous, next, parent, this].each(function(node){
					Mif.Tree.Draw.update(node);
				});
				return this;
		}
	},
	
	updateOpenState: function(){
		if(this.state.open){
			this.state.open = false;
			this.toggle();
		}
	}
	
});

Mif.Tree.Node.UID = 0;
Mif.Tree.Nodes = {};

/*
---
 
name: Mif.Tree.Draw
description: convert javascript tree object to html
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Draw
 
...
*/

Mif.Tree.Draw = {

	getHTML: function(node,html){
		var prefix = node.tree.DOMidPrefix;
		if($defined(node.state.checked)){
			if(!node.hasCheckbox) node.state.checked='nochecked';
			var checkbox = '<span class="mif-tree-checkbox mif-tree-node-'+node.state.checked+'" uid="'+node.UID+'">'+Mif.Tree.Draw.zeroSpace+'</span>';
		}else{
			var checkbox = '';
		}
		html = html||[];
		var color = "";
		var extraname = "";
		if (node.data && node.data.text_right)
		{
			extraname = node.data.text_right;
		}
		if (node.data && node.data.color)
		{
			color = '<span class="mif-tree-color"><div class="mif-tree-color-inside" style="'+node.data.color+'"></div></span>';
		}
		html.push(
		'<div class="mif-tree-node ',(node.isLast() ? 'mif-tree-node-last' : ''),'"'+(node.hidden ? ' style="display:none"' : '')+' id="',prefix,node.UID,'">',
			'<span class="mif-tree-node-wrapper ',node.cls,(node.state.selected ? ' mif-tree-node-selected' : ''),'" uid="',node.UID,'">',
				'<span class="mif-tree-gadjet mif-tree-gadjet-',node.getGadjetType(),'" uid="',node.UID,'">',Mif.Tree.Draw.zeroSpace,'</span>',
				checkbox,			
				color,	
				'<span class="mif-tree-icon ',(node.closeIconUrl?'" style="background-image: url('+node.closeIconUrl+')" ': node.closeIcon+'"'),' uid="',node.UID,'">',Mif.Tree.Draw.zeroSpace,'</span>',
				
				'<span class="mif-tree-name" uid="',node.UID,'">',node.name,'</span>',
				'<span class="mif-tree-name-small">',extraname,'</span>',
			'</span>',
			'<div class="mif-tree-children" style="display:none"></div>',
		'</div>'
		);
		return html;
	},
	
	children: function(parent, container){
		parent.open = true;
		parent.$draw = true;
		var html = [];
		var children = parent.children;
		for(var i = 0, l = children.length; i < l; i++){
			this.getHTML(children[i], html);
		}
		container = container || parent.getDOM('children');
		container.set('html', html.join(''));
		parent.tree.fireEvent('drawChildren',[parent]);
	},
	
	root: function(tree){
		var domRoot = this.node(tree.root);
		domRoot.inject(tree.wrapper);
		tree.$draw = true;
		tree.fireEvent('drawRoot');
	},
	
	forestRoot: function(tree){
		var container = new Element('div').addClass('mif-tree-children-root').injectInside(tree.wrapper);
		Mif.Tree.Draw.children(tree.root, container);
	},
	
	node: function(node){
		return new Element('div').set('html', this.getHTML(node).join('')).getFirst();
	},
	
	isUpdatable: function(node){
		if(
			(!node||!node.tree) ||
			(node.getParent() && !node.getParent().$draw) || 
			(node.isRoot() && (!node.tree.$draw||node.tree.forest)) 
		) return false;
		return true;
	},
	
	update: function(node){
		if(!this.isUpdatable(node)) return;
		if(!node.hasChildren()) node.state.open=false;
		node.getDOM('gadjet').className = 'mif-tree-gadjet mif-tree-gadjet-'+node.getGadjetType();
		if (node.closeIconUrl) {
			node.getDOM('icon').setStyle('background-image', 'url('+(node.isOpen() ? node.openIconUrl : node.closeIconUrl)+')');
		} else {
			node.getDOM('icon').className='mif-tree-icon '+node[node.isOpen() ? 'openIcon' : 'closeIcon'];
		}
		node.getDOM('node')[(node.isLastVisible() ?'add' : 'remove')+'Class']('mif-tree-node-last');
		if(node.$loading) return;
		var children = node.getDOM('children');
		if(node.isOpen()){
			if(!node.$draw) Mif.Tree.Draw.children(node);
			children.style.display = 'block';
		}else{
			children.style.display = 'none';
		}
		node.tree.fireEvent('updateNode', node);
		return node;
	},
	
	inject: function(node, element){
		if(!this.isUpdatable(node)) return;
		element = element || node.getDOM('node') || this.node(node);
		var previous = node.getPrevious();
		if(previous){
			element.injectAfter(previous.getDOM('node'));
			return;
		}
		var container;
		if(node.tree.forest && node.parentNode.isRoot()){
			container = node.tree.wrapper.getElement('.mif-tree-children-root');
		}else if(node.tree.root == node){
			container = node.tree.wrapper;
		}else{
			container = node.parentNode.getDOM('children');
		}
		element.inject(container, 'top');
	}
	
};

Mif.Tree.Draw.zeroSpace = Browser.Engine.trident ? '&shy;' : (Browser.Engine.webkit ? '&#8203' : '');



/*
---
 
name: Mif.Tree.Selection
description: tree nodes selection
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Selection
 
...
*/

Mif.Tree.implement({
	
	initSelection: function(){
		this.defaults.selectClass = '';
		this.wrapper.addEvent('mousedown', this.attachSelect.bindWithEvent(this));
	},
	
	attachSelect: function(event){
		if(!['icon', 'name', 'node'].contains(this.mouse.target)) return;
		var node = this.mouse.node;
		if(!node) return;
		this.select(node);
	},
	
	select: function(node) {
		if(!node) return this;
		var current = this.selected;
		if (current == node) return this;
		if (current) {
			current.select(false);
			this.fireEvent('unSelect', [current]).fireEvent('selectChange', [current, false]);
		}
		this.selected = node;
		node.select(true);
		this.fireEvent('select', [node]).fireEvent('selectChange', [node, true]);
		return this;
	},
	
	unselect: function(){
		var current = this.selected;
		if(!current) return this;
		this.selected = false;
		current.select(false);
		this.fireEvent('unSelect', [current]).fireEvent('selectChange', [current, false]);
		return this;
	},
	
	getSelected: function(){
		return this.selected;
	},
	
	isSelected: function(node){
		return node.isSelected();
	}
	
});

Mif.Tree.Node.implement({
		
	select: function(state) {
		this.state.selected = state;
		if(!Mif.Tree.Draw.isUpdatable(this)) return;
		var wrapper=this.getDOM('wrapper');
		wrapper[(state ? 'add' : 'remove')+'Class'](this.selectClass||'mif-tree-node-selected');
	},
	
	isSelected: function(){
		return this.state.selected;
	}
	
});


/*
---
 
name: Mif.Tree.Hover
description: hover(mouseover/mouseout) events/effects
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Hover
 
...
*/

Mif.Tree.implement({
	
	initHover: function(){
		this.defaults.hoverClass = '';
		this.wrapper.addEvent('mousemove', this.hover.bind(this));
		this.wrapper.addEvent('mouseout', this.hover.bind(this));
		this.defaultHoverState = {
			gadjet: false,
			checkbox: false,
			icon: false,
			name: false,
			node: false
		};
		this.hoverState = $unlink(this.defaultHoverState);
	},
	
	hover: function(){
		var cnode = this.mouse.node;
		var ctarget = this.mouse.target;
		$each(this.hoverState, function(node, target, state){
			if(node == cnode && (target == 'node'||target==ctarget)) return;
			if(node) {
				Mif.Tree.Hover.out(node, target);
				state[target] = false;
				this.fireEvent('hover', [node, target, 'out']);
			}
			if(cnode && (target == 'node'||target == ctarget)) {
				Mif.Tree.Hover.over(cnode, target);
				state[target] = cnode;
				this.fireEvent('hover', [cnode, target, 'over']);
			}else{
				state[target] = false;
			}
		}, this);
	},
	
	updateHover: function(){
		this.hoverState = $unlink(this.defaultHoverState);
		this.hover();
	}
	
});

Mif.Tree.Hover = {
	
	over: function(node, target){
		var wrapper = node.getDOM('wrapper');
		wrapper.addClass((node.hoverClass||'mif-tree-hover')+'-'+target);
		if(node.state.selected) wrapper.addClass((node.hoverClass||'mif-tree-hover')+'-selected-'+target);
	},
	
	out: function(node, target){
		var wrapper = node.getDOM('wrapper');
		wrapper.removeClass((node.hoverClass||'mif-tree-hover')+'-'+target).removeClass((node.hoverClass||'mif-tree-hover')+'-selected-'+target);
	}
	
};


/*
---
 
name: Mif.Tree.Load
description: load tree from json
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Load
 
...
*/

Mif.Tree.Load = {
		
	children: function(children, parent, tree){
		for( var i = children.length; i--; ){
			var child = children[i];
			var subChildren = child.children;
			var node = new Mif.Tree.Node({
				tree: tree,
				parentNode: parent||undefined
			}, child);
			if( tree.forest || parent != undefined){
				parent.children.unshift(node);
			}else{
				tree.root = node;
			}
			if(subChildren && subChildren.length){
				arguments.callee(subChildren, node, tree);
			}
		}
		if(parent) parent.state.loaded = true;
		tree.fireEvent('loadChildren', parent);
	}
	
};

Mif.Tree.implement({

	load: function(options){
		var tree = this;
		this.loadOptions = this.loadOptions||$lambda({});
		function success(json){
			if(tree.forest){
				tree.root = new Mif.Tree.Node({
					tree: tree,
					parentNode: null
				}, {});
				var parent = tree.root;
			}else{
				var parent = null;
			}
			Mif.Tree.Load.children(json, parent, tree);
			Mif.Tree.Draw[tree.forest ? 'forestRoot' : 'root'](tree);
			tree.$getIndex();
			tree.fireEvent('load');
			return tree;
		}
		options = $extend($extend({
			isSuccess: $lambda(true),
			secure: true,
			onSuccess: success,
			method: 'get'
		}, this.loadOptions()), options);
		if(options.json) return success(options.json);
		new Request.JSON(options).send();
		return this;
	}
	
});

Mif.Tree.Node.implement({
	
	load: function(options){
		this.$loading = true;
		options = options||{};
		this.addType('loader');
		var self = this;
		function success(json){
			Mif.Tree.Load.children(json, self, self.tree);
			delete self.$loading;
			self.state.loaded = true;
			self.removeType('loader');
			Mif.Tree.Draw.update(self);
			self.fireEvent('load');
			self.tree.fireEvent('loadNode', self);
			return self;
		}
		options=$extend($extend($extend({
			isSuccess: $lambda(true),
			secure: true,
			onSuccess: success,
			method: 'get'
		}, this.tree.loadOptions(this)), this.loadOptions), options);
		if(options.json) return success(options.json);
		new Request.JSON(options).send();
		return this;
	}
	
});

/*
---
 
name: Mif.Tree.KeyNav
description: Mif.Tree.KeyNav
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.KeyNav
 
...
*/

Mif.Tree.KeyNav=new Class({
	
	initialize: function(tree){
		this.tree=tree;
		this.bound={
			action: this.action.bind(this),
			attach: this.attach.bind(this),
			detach: this.detach.bind(this)
		}
		tree.addEvents({
			'focus': this.bound.attach,
			'blur': this.bound.detach
		});
	},
	
	attach: function(){
		var event=Browser.Engine.trident||Browser.Engine.webkit ? 'keydown' : 'keypress';
		document.addEvent(event, this.bound.action);
	},
	
	detach: function(){
		var event=Browser.Engine.trident||Browser.Engine.webkit ? 'keydown' : 'keypress';
		document.removeEvent(event, this.bound.action);
	},
	
	action: function(event){
		if(!['down','left','right','up', 'pgup', 'pgdown', 'end', 'home'].contains(event.key)) return;
		var tree=this.tree;
		if(!tree.selected){
			tree.select(tree.forest ? tree.root.getFirst() : tree.root);
		}else{
			var current=tree.selected;
			switch (event.key){
				case 'down': this.goForward(current);event.stop();break;  
				case 'up': this.goBack(current);event.stop();break;   
				case 'left': this.goLeft(current);event.stop();break;
				case 'right': this.goRight(current);event.stop();break;
				case 'home': this.goStart(current);event.stop();break;
				case 'end': this.goEnd(current);event.stop();break;
				case 'pgup': this.goPageUp(current);event.stop();break;
				case 'pgdown': this.goPageDown(current);event.stop();break;
			}
		}
		tree.scrollTo(tree.selected);
	},

	goForward: function(current){
		var forward=current.getNextVisible();
		if( forward ) this.tree.select(forward)
	},
	
	goBack: function(current){
		var back=current.getPreviousVisible();
		if (back) this.tree.select(back);
	},
	
	goLeft: function(current){
		if(current.isRoot()){
			if(current.isOpen()){
				current.toggle();
			}else{
				return false;
			}
		}else{
			if( current.hasChildren(true) && current.isOpen() ){
				current.toggle();
			}else{
				if(current.tree.forest && current.getParent().isRoot()) return false;
				return this.tree.select(current.getParent());
			}
		}
	},
	
	goRight: function(current){
		if(!current.hasChildren(true)&&!current.loadable){
			return false;
		}else if(!current.isOpen()){
			return current.toggle();
		}else{
			return this.tree.select(current.getFirst(true));
		}
	},
	
	goStart: function(){
		this.tree.select(this.tree.$index[0]);
	},
	
	goEnd: function(){
		this.tree.select(this.tree.$index.getLast());
	},
	
	goPageDown: function(current){
		var tree=this.tree;
		var count=(tree.container.clientHeight/tree.height).toInt()-1;
		var newIndex=Math.min(tree.$index.indexOf(current)+count, tree.$index.length-1);
		tree.select(tree.$index[newIndex]);
	},
	
	goPageUp: function(current){
		var tree=this.tree;
		var count=(tree.container.clientHeight/tree.height).toInt()-1;
		var newIndex=Math.max(tree.$index.indexOf(current)-count, 0);
		tree.select(tree.$index[newIndex]);
	}
	
});

Event.Keys.extend({
	'pgdown': 34,
	'pgup': 33,
	'home': 36,
	'end': 35
});


/*
---

name: Mif.Tree.Sort
description: Mif.Tree.Sort
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Sort

...
*/

Mif.Tree.implement({
	
	initSortable: function(sortFunction){
		this.sortable=true;
		this.sortFunction=sortFunction||function(node1, node2){
			if(node1.name>node2.name){
				return 1;
			}else if(node1.name<node2.name){
				return -1;
			}else{
				return 0;
			}
		};
		this.addEvent('loadChildren', function(parent){
			if(parent) parent.sort();
		});
		this.addEvent('structureChange', function(from, to, where, type){
			from.sort();
		});
		return this;
	}
	
});


Mif.Tree.Node.implement({

	sort: function(sortFunction){
		this.children.sort(sortFunction||this.tree.sortFunction);
		return this;
	}
	
});


/*
---
 
name: Mif.Tree.Transform
description: implement move/copy/del/add actions
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Transform
 
...
*/

Mif.Tree.Node.implement({
	
	inject: function(node, where, element){//element - internal property
		where=where||'inside';
		var parent=this.parentNode;
		function getPreviousVisible(node){
			var previous=node;
			while(previous){
				previous=previous.getPrevious();
				if(!previous) return null;
				if(!previous.hidden) return previous;
			}
		}
		var previousVisible=getPreviousVisible(this);
		var type=element ? 'copy' : 'move';
		switch(where){
			case 'after':
			case 'before':
				if( node['get'+(where=='after' ? 'Next' : 'Previous')]()==this ) return false;
				if(this.parentNode) {
					this.parentNode.children.erase(this);
				}
				this.parentNode=node.parentNode;
				this.parentNode.children.inject(this, node, where);
				break;
			case 'inside':
				if( node.tree && node.getLast()==this ) return false;
				if(this.parentNode) {
					this.parentNode.children.erase(this);
				}
				if(node.tree){
					if(!node.hasChildren()){
						node.$draw=true;
						node.state.open=true;
					}
					node.children.push(this);
					this.parentNode=node;
				}else{
					node.root=this;
					this.parentNode=null;
					node.fireEvent('drawRoot');
				}
				break;
		}		
		var tree=node.tree||node;
		if(this==this.tree.root){
			this.tree.root=false;
		}
		if(this.tree!=tree){
			var oldTree=this.tree;
			this.recursive(function(){
				this.tree=tree;
			});
		};
		tree.fireEvent('structureChange', [this, node, where, type]);
		tree.$getIndex();
		if(oldTree)	oldTree.$getIndex();
		Mif.Tree.Draw.inject(this, element);
		[node, this, parent, previousVisible, getPreviousVisible(this)].each(function(node){
			Mif.Tree.Draw.update(node);
		});
		return this;
	},
	
	copy: function(node, where){
		if (this.copyDenied) return;
		function copy(structure){
			var node=structure.node;
			var tree=structure.tree;
			var options=$unlink({
				property: node.property,
				type: node.type,
				state: node.state,
				data: node.data
			});
			options.state.open=false;
			var nodeCopy = new Mif.Tree.Node({
				parentNode: structure.parentNode,
				children: [],
				tree: tree
			}, options);
			node.children.each(function(child){
				var childCopy=copy({
					node: child,
					parentNode: nodeCopy,
					tree: tree
				});
				nodeCopy.children.push(childCopy);
			});
			return nodeCopy;
		};
		
		var nodeCopy=copy({
			node: this,
			parentNode: null,
			tree: node.tree
		});
		return nodeCopy.inject(node, where, Mif.Tree.Draw.node(nodeCopy));
	},
	
	remove: function(){
		if (this.removeDenied) return;
		this.tree.fireEvent('remove', [this]);
		var parent=this.parentNode, previousVisible=this.getPreviousVisible();
		if(parent) {	
			parent.children.erase(this);
		}else if(!this.tree.forest){
			this.tree.root=null;
		}
		this.tree.selected=false;
		this.getDOM('node').destroy();
		this.tree.$getIndex();
		Mif.Tree.Draw.update(parent);
		Mif.Tree.Draw.update(previousVisible);
		this.recursive(function(){
			if(this.id) delete Mif.ids[this.id];
		});
		this.tree.mouse.node=false;
		this.tree.updateHover();
	}
	
});


Mif.Tree.implement({

	move: function(from, to, where){
		if(from.inject(to, where)){
			this.fireEvent('move', [from, to, where]);
		}
		return this;
	},
	
	copy: function(from, to, where){
		var copy=from.copy(to, where);
		if(copy){
			this.fireEvent('copy', [from, to, where, copy]);
		}
		return this;
	},
	
	remove: function(node){
		node.remove();
		return this;
	},
	
	add: function(node, current, where){
		if(!(node instanceof Mif.Tree.Node)){
			node=new Mif.Tree.Node({
				parentNode: null,
				tree: this
			}, node);
		};
		node.inject(current, where, Mif.Tree.Draw.node(node));
		this.fireEvent('add', [node, current, where]);
		return this;
	}
	
});


/*
---
 
name: Mif.Tree.Checkbox
description: Mif.Tree.Checkbox
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.Checkbox
 
...
*/

Mif.Tree.implement({

	initCheckbox: function(type){
		this.checkboxType=type||'simple';
		this.dfltState.checked='unchecked';
		this.defaults.hasCheckbox=true;
		this.wrapper.addEvent('click',this.checkboxClick.bind(this));
		if(this.checkboxType=='simple') return;
		this.addEvent('loadChildren', function(node){
			if(!node) return;
			if(node.state.checked=='checked'){
				node.recursive(function(){
					this.state.checked='checked';
				});
			}else{
				node.getFirst().setParentCheckbox(1)
			}
		});

	},
	
	checkboxClick: function(event){		

		if(this.mouse.target!='checkbox') {return;}
		
		if (this.mouse.node.checking) {
			this.mouse.node.checking = 0;
			return;
		}
		this.mouse.node.checking = 1;
		
		this.mouse.node['switch']();
	},
	
	getChecked: function(includePartially){
		var checked=[];
		this.root.recursive(function(){
			var condition = includePartially ? this.state.checked!=='unchecked' : this.state.checked=='checked';
			if(this.hasCheckbox && condition) checked.push(this);
		});
		return checked;
	}

});

Mif.Tree.Node.implement({

	'switch' : function(state){
		if(this.state.checked==state||!this.hasCheckbox) return;
		var type=this.tree.checkboxType;
		var checked=(this.state.checked=='checked') ? 'unchecked' : 'checked';
		if(type=='simple'){
			this.setCheckboxState(checked);
			this.tree.fireEvent(checked=='checked' ? 'check' : 'unCheck', this);
			this.tree.fireEvent('switch', [this, (checked=='checked' ? true : false)]);
			return this;
		};
		this.recursive(function(){
			this.setCheckboxState(checked);
		});
		this.setParentCheckbox();
		this.tree.fireEvent(checked=='checked' ? 'check' : 'unCheck', this);
		this.tree.fireEvent('switch', [this, (checked=='checked' ? true : false)]);
		return this;
	},
	
	setCheckboxState: function(state){
		if(!this.hasCheckbox) return;
		var oldState=this.state.checked;
		this.state.checked=state;
		if((!this.parentNode&&this.tree.$draw) || (this.parentNode && this.parentNode.$draw)){
			this.getDOM('checkbox').removeClass('mif-tree-node-'+oldState).addClass('mif-tree-node-'+state);
		}
	},
	
	setParentCheckbox: function(s){
		if(!this.hasCheckbox || !this.parentNode || (this.tree.forest && !this.parentNode.parentNode)) return;
		var parent=this.parentNode;
		var state='';
		var children=parent.children;
		for(var i=children.length; i--; i>0){
			var child=children[i];
			if(!child.hasCheckbox) continue;
			var childState=child.state.checked;
			if(childState=='partially'){
				state='partially';
				break;
			}else if(childState=='checked'){
				if(state=='unchecked'){
					state='partially';
					break;
				}
				state='checked';
			}else{
				if(state=='checked'){
					state='partially';
					break;
				}else{
					state='unchecked';
				}
			}
		}
		if(parent.state.checked==state ||(s && state=='partially' && parent.state.checked=='checked')){return;};
		parent.setCheckboxState(state);
		parent.setParentCheckbox(s);
	}

});


/*
---
 
name: Mif.Tree.CookieStorage
description: Mif.Tree.Node
license: MIT-Style License (http://mifjs.net/license.txt)
copyright: Anton Samoylov (http://mifjs.net)
authors: Anton Samoylov (http://mifjs.net)
requires: Mif.Tree
provides: Mif.Tree.CookieStorage
 
...
*/

Mif.Tree.CookieStorage = new Class({

	Implements: [Options],
	
	options:{
		store: function(node){
			return node.property.id;
		},
		retrieve: function(value){
			return Mif.id(value);
		},
		event: 'toggle',
		action: 'toggle'
	},

	initialize: function(tree, options){
		this.setOptions(options);
		this.tree = tree;
		this.cookie = new Cookie('mif.tree:' + this.options.event + tree.id||'');
		this.nodes = [];
		this.initSave();
	},
	
	write: function(){
		this.cookie.write(JSON.encode(this.nodes));
	},
	
	read: function(){
		return JSON.decode(this.cookie.read()) || [];
	},
	
	restore: function(data){
		if(!data){
			this.restored = this.restored || this.read();
		}
		var restored = data || this.restored;
		for(var i = 0, l = restored.length; i < l; i++){
			var stored = restored[i];
			var node = this.options.retrieve(stored);
			if(node){
				node[this.options.action](true);
				restored.erase(stored);
				l--;
			}
		}
		return restored;
	},
	
	initSave: function(){
		this.tree.addEvent(this.options.event, function(node, state){
			var value = this.options.store(node);
			if(state){
				this.nodes.include(value);
			}else{
				this.nodes.erase(value);
			}
			this.write();
		}.bind(this));
	}

});


/**
 * @author Marko
 */

var omRanges = new Class(
{		
	Implements: [Events, Options],

	options: function(){
		return {
			input1Validation:{},
			inputButton:false,
			headerFunction:null,
			renderFunction:null,
			serializeFunction:null,
			deserializeFunction:null
		};
	},
	
	data:[],
	
	initialize: function(container, options){
		this.setOptions(options);

		this.container = $(container);
		this.container.addClass('omranges');
		
		this.reset();

		this.addRange({});
	
	},
	
	reset: function(afterli)
	{
		if (this.options.headerFunction)
			this.options.headerFunction(this.container, this.options);
		
		// Validation
		this.valia = [];
		
		this.ul = new Element('ul');
		
		this.messspan = new Element('span');
		this.messspan.addClass('vl_message');

		this.ul.inject(this.container);
		this.messspan.inject(this.container);
	},

	addRange: function(values, afterli)
	{ 
		var li = new Element('li');
	
		var licount = this.ul.getElements("li").length;
		
		if (this.options.renderFunction) {
			this.options.renderFunction(li, values, this);
		}else {
			this.input1 = new Element('input', {
				type: 'text'
			});
			this.input1.addClass('firstinput');
			
			if (this.options.input1Validation) {
				var input1Val = new LiveValidation(this.input1, {
					onInvalid: this.onInvalid.bind(this),
					onValid: this.onValid.bind(this)
				});
				
				for (var n = 0; n < this.options.input1Validation.length; n++) {
					//alert(this.ul.getElements("li").length);
					//alert(this.options.input1Validation[n].options.notFirst);
					if (!(licount == 0 && this.options.input1Validation[n].options.notFirst)) 
						input1Val.add(this.options.input1Validation[n].func, this.options.input1Validation[n].options);
				}
				
				this.valia.push(input1Val);
			}
			
			
			this.input2 = new Element('input', {
				type: 'text'
			});
			this.input2.addClass('secondinput');
			
			
			if (this.options.input2Validation) {
				var input2Val = new LiveValidation(this.input2, {
					onInvalid: this.onInvalid.bind(this),
					onValid: this.onValid.bind(this)
				});
				
				for (var n = 0; n < this.options.input2Validation.length; n++) {
					if (!(licount == 0 && this.options.input1Validation[n].options.notFirst)) 
						input2Val.add(this.options.input2Validation[n].func, this.options.input2Validation[n].options);
				}
				
				this.valia.push(input2Val);
			}
			
			if (this.options.inputButton) {
				this.inputval = new Element('a', {
					href: 'javascript:;',
					text: 'Change',
					style: 'margin-right:10px;'
				});
				this.inputval.addEvent('click', this.changeRange.bind(this, li));
			}
			else {
				this.inputval = new Element('input', {
					type: 'text'
				});
				this.inputval.addClass('valinput');
				
				if (this.options.input3Validation) {
					var input3Val = new LiveValidation(this.inputval, {
						onInvalid: this.onInvalid.bind(this),
						onValid: this.onValid.bind(this)
					});
					
					for (var n = 0; n < this.options.input3Validation.length; n++) {
						if (!(licount == 0 && this.options.input1Validation[n].options.notFirst)) 
							input3Val.add(this.options.input3Validation[n].func, this.options.input3Validation[n].options);
					}
					
					this.valia.push(input3Val);
				}
			}
			
			// ako su zadane inic. vrijednosti
			if (values) {
				if (values.value1) 
					this.input1.value = values.value1;
				
				if (values.value2) 
					this.input2.value = values.value2;
				
				if (values.value3 && !this.options.inputButton) 
					this.inputval.value = values.value3;
			}
			
			this.input1.inject(li);
			this.input2.inject(li);
			this.inputval.inject(li);
		}
		
		
		var addEl = new Element('div', {
			title: 'Add new range'
		});
		addEl.addClass("addBt");
		addEl.addEvent('click', this.newRangeClick.bind(this, li));
		
		var deleteEl = new Element('div', {
			title: 'Delete range'
		});
		deleteEl.addClass("deleteBt");
		deleteEl.addEvent('click', this.deleteRange.bind(this, li));
		
		deleteEl.inject(li);
		addEl.inject(li);
		
		
		if (afterli) {
			var liIndex = this.getIndexByLi(afterli);
			
			if (liIndex >= 0) {
				// ubaci novi element
				this.data.splice(liIndex+1, 0, values);
				li.inject(afterli, 'after');
			}
		}
		else {
			li.inject(this.ul);
			this.data.push(values);
		}
		
		return li;
	},
	
	newRangeClick: function(afterli)
	{
		var newli = this.addRange({}, afterli);

		// ne radi
		this.fireEvent('newrange', newli);
	},
	
	addRanges: function(values)
	{
		for (var n = 0; n < values.length; n++)
		{
			this.addRange( values[n] );
		}
	},
	
	changeRange: function(li)
	{
		
	},
	
	deleteRange: function(li)
	{
		var ali = this.ul.getChildren('li');
		
		if (ali.length > 1) {
			// prvo mora naci index toga elementa da ukloni i element u data arrayu
			var liIndex = this.getIndexByLi(li);
			
			if (liIndex >= 0) {
				this.data.splice(liIndex, 1);
				
				var childs = li.getChildren();
				for (var i=0; i<childs.length; i++)
				{
					for (var j=0; j < this.valia.length; j++)
					{
						
						if (this.valia[j].element == childs[i] )
							this.valia.splice(j, 1);
					}
				}
				
				li.destroy();
			}
		}
	},
	
	getIndexByLi: function(li)
	{
		var lis = this.ul.getElements("li");
			
		for (var l = 0; l < lis.length; l++) {
			if (lis[l] == li) {
				return l;
			}
		}
			
		return -1;
	},
	
	setData: function(index, obj)
	{
		if (index >= this.data.length)
			return;
			
		this.data[index] = obj;
	},
	
	getData: function(index)
	{
		//alert(index +' '+ this.data.length);
		if (index >= this.data.length)
			return null;
			
		return this.data[index];
	},
	
	count: function(index)
	{
		return this.ul.getElements("li").length;
	},
	
	getElement: function(index)
	{
		var lis = this.ul.getElements("li");
		
		if (index<0 || index >= lis.length)
			return null;
			
		return lis[index];
	},
	
	serialize: function()
	{
		if (!this.options.serializeFunction)
			return;
			
		this.elements = this.ul.getElements('li');
		
		var ret = [];
		
		this.elements.each( (function(el,i){
								//ret.push({v1:i1.value, v2:i2.value, v3:i3.value});
								ret.push( this.options.serializeFunction(el, i) );
							}).bind(this)
		);
		
		return ret.join(';');
	},
	
	deserialize: function(data)
	{
		if (!data || !this.options.deserializeFunction)
			return;
		
		this.removeAll();
		
		var d1 = data.split(";");
			
		for (var i=0; i<d1.length; i++)
		{
			this.addRange( this.options.deserializeFunction(d1[i]) ); 
		}
	},
	
	removeAll: function()
	{
		this.ul.empty();
		this.data = [];
		
		// Validation
		this.valia = [];
		
		this.messspan.set('text', '');
		//this.addRange();
	},
	
	onInvalid: function(valObj, mess)
	{
		if (valObj)
			valObj.addFieldClass();
		
		this.messspan.set('text', mess);
	},
	
	onValid: function(valObj, mess)
	{
		if (valObj)
			valObj.addFieldClass();
		
		this.messspan.set('text', '');
	},
	
	validate: function()
	{
		return LiveValidation.massValidate(this.valia);
	}
	
	
}
)
// Author: Marko Šantić
// Web: http://www.omnisdata.com/omnigrid
// Email: marko@omnisdata.com
// Company: Omnisdata Ltd.
// Licence: Creative Commons Attribution 3.0 Unported License, http://creativecommons.org/licenses/by/3.0/
//			If you copy, distribute or transmit the source code please retain the above copyright notice, author name and project URL. 
// Required: Mootools 1.2
// Version: OmniGrid 1.2.5
// ****************************************************************************

var omniGrid = new Class({
	Implements: [Events,Options],
				  
	getOptions: function(){
		return {
			alternaterows: true,	
			showHeader:true,
			sortHeader:false,
			resizeColumns:true,
			selectable:true,
			serverSort:true,
			sortOn: null,
			sortBy: 'ASC',
			filterHide: true,
			filterHideCls: 'hide',
			filterSelectedCls: 'filter',
			multipleSelection:true,
			editable:false,
			editondblclick:false,
			// accordion
			accordion:false,
			accordionRenderer:null,
			autoSectionToggle:true, // if true just one section can be open/visible
			showtoggleicon:true,
			openAccordionOnDblClick:false,
			// pagination
			url:null,
			pagination:false,
			page:1,
			perPageOptions: [10, 20, 50, 100, 200],
			perPage:10,
			// dataProvider
			dataProvider:null
		};
	},
	
	initialize: function(container, options){
		this.setOptions(this.getOptions(), options);
		this.container = $(container);
		
		if (!this.container)
			return;
			
		this.draw();
		
		this.reset();
		
		this.loadData();
	},
	
	// API	
	reset: function(){
		
		this.renderData();
		
		this.refreshDelayID = null;
		this.dragging = false;
		this.selected = new Array();
		
		if (this.options.accordion)	
			this.elements = this.ulBody.getElements('li:nth-child(2n+1)') // all li el. except accordian sections
		else
			this.elements = this.ulBody.getElements('li');

		this.filtered = false;
		this.lastsection = null;
		
		if (this.options.alternaterows)	this.altRow();		

		this.elements.each(function(el,i){
			
			el.addEvent('click', this.onRowClick.bind(this));
			el.addEvent('dblclick', this.onRowDblClick.bind(this));		
			el.addEvent('mouseover', this.onRowMouseOver.bind(this) );
			el.addEvent('mouseout',  this.onRowMouseOut.bind(this) );
			
		}, this);

		// ******************************************************************
		// **************************** Setup header ************************
		// ******************************************************************
		this.container.getElements('.th').each(function(el,i){
			//alert(el.dataType);
			var dataType = el.retrieve('dataType');
			if(dataType){

				el.getdate = function(str){
					// inner util function to convert 2-digit years to 4
					function fixYear(yr) {
						yr = +yr;
						if (yr<50) { yr += 2000; }
						else if (yr<100) { yr += 1900; }
						return yr;
					};
					var ret;
					//
					if (str.length>12){
						strtime = str.substring(str.lastIndexOf(' ')+1);
						strtime = strtime.substring(0,2)+strtime.substr(-2)
					}else{
						strtime = '0000';
					}
					//
					// YYYY-MM-DD
					if (ret=str.match(/(\d{2,4})-(\d{1,2})-(\d{1,2})/)) {
						return (fixYear(ret[1])*10000) + (ret[2]*100) + (+ret[3]) + strtime;
					}
					// DD/MM/YY[YY] or DD-MM-YY[YY]
					if (ret=str.match(/(\d{1,2})[\/-](\d{1,2})[\/-](\d{2,4})/)) {
						return (fixYear(ret[3])*10000) + (ret[2]*100) + (+ret[1]) + strtime;
					}
					return 999999990000; // So non-parsed dates will be last, not first
				};
				
				//
				el.findData = function(elem){
					var child = elem.getFirst();
					if(child){
						return el.findData(child);
					}else{
						return elem.innerHTML.trim();
					}
				};
				
				//
				el.compare = function(a, b){
					// a i b su LI elementi

					var var1 = a.getChildren()[i].innerHTML.trim();
					var var2 = b.getChildren()[i].innerHTML.trim();
					
					//console.log(el.sortBy);
					
					//var1 = a.getChildren()[i].firstChild.data;
					//var2 = b.getChildren()[i].firstChild.data;
					
					if(dataType == 'number'){
						var1 = parseFloat(var1);
						var2 = parseFloat(var2);
						
						if(el.sortBy == 'ASC'){
							return var1-var2;
						}else{
							return var2-var1;
						}
						
					}else if(dataType == 'string'){
						var1 = var1.toUpperCase();
						var2 = var2.toUpperCase();
						
						if(var1==var2){return 0};
						if(el.sortBy == 'ASC'){
							if(var1<var2){return -1};
						}else{
							if(var1>var2){return -1};
						}
						return 1;
						
					}else if(dataType == 'date'){
						var1 = parseFloat(el.getdate(var1));
						var2 = parseFloat(el.getdate(var2));
						
						if(el.sortBy == 'ASC'){
							return var1-var2;
						}else{
							return var2-var1;
						}
						
					}else if(dataType == 'currency'){
						var1 = parseFloat(var1.substr(1).replace(',',''));
						var2 = parseFloat(var2.substr(1).replace(',',''));
						
						if(el.sortBy == 'ASC'){
							return var1-var2;
						}else{
							return var2-var1;
						}
						
					}
					
				}

			}
		}, this);
	},
	
	// API	
	// pretvara zadanu columnu u inline edit mode
	// options = {
	//		dataIndex:Number - column name || columnIndex:Number - column index 
	//}
	edit: function(options){
		
		var sels = this.getSelectedIndices();

		if ( !sels || sels.length==0 || !this.options.editable ) return;
		
		this.finishEditing(); // ako je negde otvoren
		
		var li = this.elements[ sels[0] ];
		
		// nadi index u columnModel
		var c = options.columnIndex ? options.columnIndex : 0; // ako ne nade ili nije definiran pretpostavi 1.
		var colmod;
		if (options.dataIndex)
		{
			for (; c < this.options.columnModel.length; c++) 
			{
				colmod = this.options.columnModel[c];
				
				if (colmod.hidden) continue;
				//console.log(colmod.dataIndex+" "+options.dataIndex);
				if ( colmod.dataIndex == options.dataIndex ) break;
			}
		}
		
		if (c == this.options.columnModel.length) return; // znaci da nije nasao columnu
		
		colmod = this.options.columnModel[c];

		if (!colmod.editable) return;
		
		var td = li.getElements('div.td')[c];
		var data = this.options.data[ sels[0] ];
		
		
		var width = td.getStyle('width').toInt()-5;
		var height = 15;
		var html = data[colmod.dataIndex];
		
		td.innerHTML = "";
		
		var input = new Element('input', {style:"width: "+width+"px; height: "+height+"px;", maxlength:254, value: html} );
		input.addClass('inline');
		input.addEvent("keyup", this.finishEditing.bind(this) );
		input.addEvent("blur", this.finishEditing.bind(this) );
		input.inject(td);
		input.focus();
		
		//td.innerHTML = " onkeypress=\"return fieldEnter(this,event,' actual.id ')\" onfocus=\"highLight(this);\" onblur=\"noLight(this); return fieldBlur(this,' actual.id ');\" />";
		//td.innerHTML = '';
		
		this.inlineEditSafe = {row:sels[0], columnModel: colmod, td:td, input:input, oldvalue: html};
		
		this.inlineeditmode = true; // radi chromea jer poziva keyup i blur event skoro paralelno !?
		
		return this.inlineEditSafe;
		
		// global click za finish editing --> ne treba jer ima onblur event
		//(Browser.Engine.trident ? document : window).addEvent("click", this.finishEditing.bind(this) );
	},
	
	finishEditing: function(evt)
	{
		if (!this.inlineeditmode) return;
		
		if ( evt && evt.type == "keyup" && evt.key != 'enter' && evt.key != 'esc' ) return;
		
		//if (evt) console.log(evt.type+" "+this.inlineEditSafe.oldvalue+" "+this.editmode);

		this.inlineeditmode = false;  // radi chromea
		
		var row = this.inlineEditSafe.row;
		var data = this.options.data[ row ];
		var colmod = this.inlineEditSafe.columnModel;
		var td = this.inlineEditSafe.td;
		
		//alert(this.inlineEditSafe);
		// ako nije potvrdio sa ENTER vrati na staro
		data[colmod.dataIndex] = ( evt && evt.type == "keyup" && evt.key == 'enter') ? this.inlineEditSafe.input.value : this.inlineEditSafe.oldvalue;
		
		td.innerHTML = colmod.labelFunction ? colmod.labelFunction(data, row) : data[colmod.dataIndex];
		
		if (td.innerHTML.length == 0) td.innerHTML = "&nbsp;"; // bitno jer inace ne bi drugi put reagirao na dbl click
		
		// opali event samo za key=ENTER i ako je je napravljena promjena 
		if ( evt && evt.type == "keyup" && evt.key == 'enter' && this.inlineEditSafe.oldvalue != td.innerHTML )
		{
			// opali event za van
			this.inlineEditSafe.target = this; // ovo je mozda lose jer poslije brisem varijablu
			
			this.fireEvent("editcomplete", this.inlineEditSafe);
		}
		
		this.inlineEditSafe = null;
	},

	
	toggle: function(el){
		if ( el.getStyle('display') == 'block' )
		{
			el.setStyle('display', 'none');
		}else{
			el.setStyle('display', 'block');
		}
	},
	
	// API
	getSection: function(row){
		return this.ulBody.getElement('.section-'+row);
	},
	
	getLiParent: function (target){
		// ! ako se koristi labelFunction onda neki html elem. moze hvatati event, detektiraj pravi li
		target = $(target);

		while ( target && !target.hasClass('td') ){
			target = target.getParent();
		}
		
		if (target)
			return target.getParent();
	},
	
	onRowMouseOver: function (evt){
		var li = this.getLiParent(evt.target);
		if (!li) return;
		
		if (!this.dragging)
			li.addClass('over');
			
		this.fireEvent("mouseover", {target:this, row:li.retrieve('row'), element:li });
	},
	
	onRowMouseOut: function (evt){
		var li = this.getLiParent(evt.target);
		if (!li) return;
		
		if (!this.dragging)
			li.removeClass('over');
			
		this.fireEvent("mouseout", {target:this, row:li.retrieve('row'), element:li });
	},
	
	onRowClick: function (evt){
	
		var li = this.getLiParent(evt.target);
		
		if (!li) return;
		
		
		if (this.options.selectable)
		{
			var currentindex = li.retrieve('row');
			var selectedNum = this.selected.length;
			var dontselect = false;
			
			if ( (!evt.control && !evt.shift) || !this.options.multipleSelection )
			{
				// ocisti stari selection
				this.elements.each(function(el, i){ el.removeClass('selected') }, this);
				
				//for (var i=0; i<this.selected.length; i++) this.elements[ this.selected[i] ].removeClass('selected');
				
				this.selected = new Array();
			}
		
			if ( evt.control )
			{
				for (var i=0; i<selectedNum; i++)
				{
					if ( currentindex == this.selected[i] ) // ako je vec selektiran unselectaj ga
					{
						this.elements[ currentindex ].removeClass('selected');
						this.selected.splice(i, 1 );
						dontselect = true;
					}
				}
			}
		
			if ( evt.shift && this.options.multipleSelection )
			{
				var si = 0;
				if (this.selected.length>0)
					si = this.selected[selectedNum-1]; // uzmi zadnjeg
					
				var endindex = currentindex;
				
				startindex = Math.min(si, endindex);
				endindex = Math.max(si, endindex);
				
				//if ( !evt.control ) this.unselectAll(); // ako ne drzi shift+ctrl ocisti select
				for (var i=startindex; i<=endindex; i++)
				{
					this.elements[i].addClass('selected');
					this.selected.push( Number(i) );
				}
			}
					
			if (!dontselect)
			{
				li.addClass('selected');
				this.selected.push( Number(li.retrieve('row')) );
			}
			
			this.unique(this.selected, true); // izbaci sve duplikate iz selection arr.
		}
		
		if (this.options.accordion && !this.options.openAccordionOnDblClick)
		{
			this.accordianOpen(li);
		}
		
		this.fireEvent("click", {indices:this.selected, target:this, row:li.retrieve('row'), element:li });
	},
	
	accordianOpen: function(li)
	{
		var section = this.getSection(li.retrieve('row'));
	
		if (this.options.autoSectionToggle)
		{
			
			if (this.lastsection)
				if (this.lastsection != section)
				{
					this.lastsection.setStyle('display', 'none');
					this.lastsection.getPrevious().getElement('.toggleicon').setStyle('background-position', '0 0');
				}
			
			if (!this.options.accordionRenderer)
			{
				section.setStyle('display', 'block');
			}
		}
		
		if (this.options.accordionRenderer)
		{
			this.toggle( section );
		}
		
		
		if (this.options.showtoggleicon)
		{
			li.getElement('.toggleicon').setStyle('background-position', section.getStyle('display') == 'block' ? '-16px 0' : '0 0');
		}
		
		
		this.lastsection = section;
	},

	
	onRowDblClick: function (evt){
		
		var li = this.getLiParent(evt.target);
		if (!li) return;
		
		var t = evt.target;
		if ( this.options.editable && this.options.editondblclick && t.hasClass('td') )
		{
			var childs = li.getChildren();
			for(var i=0; i<childs.length; i++)
			{
				if (childs[i] == t) break;
			}
			
			var obj = this.edit({columnIndex:i});
			
			if (obj) obj.input.selectRange(0, obj.input.value.length);
		}
	
		if (this.options.accordion && this.options.openAccordionOnDblClick)
		{
			this.accordianOpen(li);
		}
		
		this.fireEvent("dblclick", {row:li.retrieve('row'), target:this, element:li});
	},
	
	onLoadData: function (data)
	{
		//this.hideLoader(); //u setData() jer mu nekad dosta treba da nacrta
			
		this.setData(data);
		
		// API
		this.fireEvent("loaddata", {target:this});
	},
		
	unique: function(a, asNumber)
	{
		function om_sort_number(a, b)
		{
			return a - b;
		}
		
		var sf =  asNumber ? om_sort_number : function(){};
		
		a.sort( sf );
		
		for (var i = 1; i < a.length; i++)
		{
			if (a[i-1] == a[i])
			{
				a.splice(i, 1);
				i--;
			}
		}
		
		return a;
	},
	
	// API
	loadData: function (url)
	{
		if (!this.options.url && !this.options.dataProvider)
			return;
		
		var param = {};
		
		// ************* pagination *************************
		if (this.options.pagination)
			param = {page:this.options.page, perpage:this.options.perPage};
		
		// ************* server sorting *********************
		if (this.options.serverSort){
			param.sorton = this.options.sortOn;
			param.sortby = this.options.sortBy;
		}
		
		this.showLoader();
		
		if (this.options.dataProvider)
		{
			// load data throw external class
			this.options.dataProvider.loadData(param);
		}else{
			var url = (url != null) ? url : this.options.url;
			var request = new Request.JSON({url:url, data:param});

			request.addEvent("complete", this.onLoadData.bind(this) ) ;

			request.get();
		}
	},
	
	// API
	refresh: function(){
		this.loadData();
	},
		
	// API
	setData: function(data, cm){
		
		if (!data) return;
		
		this.options.data = data.data;
		
		// ako nije zadana columnModel napravi ga sam
		if (!this.options.columnModel) this.setAutoColumnModel();
		
		if (this.options.pagination)
		{
			this.options.page =  data.page*1;
			this.options.total =  data.total;
			this.options.maxpage = Math.ceil(this.options.total/this.options.perPage);
			
			this.container.getElement('div.pDiv input').value = data.page;
			var to = (data.page*this.options.perPage) > data.total ? data.total : (data.page*this.options.perPage);
			this.container.getElement('div.pDiv .pPageStat').set('html', ((data.page-1)*this.options.perPage+1)+'..'+to+' / '+data.total);
			this.container.getElement('div.pDiv .pcontrol span').set('html', this.options.maxpage);
		}
			

		if (cm) {
			// first check is new columnModel different from active one
			if (this.options.columnModel != cm) {
				this.options.columnModel = cm;
				// if we change columnModel then we must redraw entire component
				this.draw();
			}
		}
		
		this.reset();
		
		this.hideLoader(); // kad je zavrsio sa loadanjem i crtanjem tek onda makni loader
	},
	
	// API
	getData: function(){
		return this.options.data;
	},
	
	// API
	getDataByRow: function(row){
		if (row >=0 && row<this.options.data.length)
			return this.options.data[row];
	},
	
	// API
	setDataByRow: function(row, data){
		if (row >=0 && row<this.options.data.length)
		{	
			this.options.data[row] = data;
			
			this.reset();
		}
	},
	
	// API
	addRow: function(data, row){
		if (row >=0)
		{	
			// ako podataci nisu inic. napravi novi array
			if (!this.options.data)
				this.options.data = [];

			this.options.data.splice(row, 0, data);

			this.reset();
		}
	},
	
	// API
	deleteRow: function(row){
		if (row >=0 && row<this.options.data.length)
		{	
			this.options.data.splice(row, 1);
			this.reset();
		}
	},
	
	isHidden: function(i){
		return this.elements[i].hasClass( this.options.filterHideCls );
	},
	
	hideWhiteOverflow: function(i){
		if ( this.container.getElement('.gBlock') )
			this.container.getElement('.gBlock').dispose();
		
		var pReload = this.container.getElement('div.pDiv .pReload');
		if (pReload)
			pReload.removeClass('loading'); 
	},
	
	showWhiteOverflow: function(i){
		// ************* white overflow & loader ************
		if ( this.container.getElement('.gBlock') )
			this.container.getElement('.gBlock').dispose();
			
		var gBlock = new Element('div', {style:'top: 0px; left: 0px; background: white none repeat scroll 0% 0%;  -moz-background-clip: -moz-initial; -moz-background-origin: -moz-initial; -moz-background-inline-policy: -moz-initial; position: absolute; z-index: 999; opacity: 0.5; filter: alpha(opacity=50'} ) ;
		var bDiv = this.container.getElement('.bDiv');
		
		var top = 1;
		top += this.container.getElement('.tDiv') ? this.container.getElement('.tDiv').getSize().y : 0;
		top += this.container.getElement('.hDiv') ? this.container.getElement('.hDiv').getSize().y : 0;
		
		// height: (bDiv && bDiv.getSize().y ? bDiv.getSize().y:this.options.height)
		gBlock.setStyles({width:this.options.width, height: this.options.height-1, top:0});
		gBlock.addClass('gBlock');
		
		this.container.appendChild(gBlock);
		
		var pReload = this.container.getElement('div.pDiv .pReload');
		if (pReload)
			pReload.addClass('loading');
	},
		
	
	showLoader: function(){
		if (this.loader)
			return;
		
		this.showWhiteOverflow(); // ovako bi cak mogao maknuti u sve staviti unutar showLoadera
		
		this.loader = new Element('div');
		
		this.loader.addClass('elementloader');
		this.loader.inject(this.container);
		
		// pozicioniranje loadera
		/*var gBlock = this.container.getElement('.gBlock');
		var sizeGBlock = gBlock.getSize();

		var top = 0;
		top += this.container.getElement('.tDiv') ? this.container.getElement('.tDiv').getSize().y : 0;
		top += this.container.getElement('.hDiv') ? this.container.getElement('.hDiv').getSize().y : 0;

		this.loader.setStyles({top:top+sizeGBlock.y/2-16, left: sizeGBlock.x/2});
		*/
		
		this.loader.setStyles({top:this.options.height/2-16, left:  this.options.width/2});
	},
	
	hideLoader: function(){
		if (!this.loader)
			return;
		
		this.hideWhiteOverflow();
		this.loader.dispose();
		this.loader = null;
		
	},
	
	// API
	selectAll: function(){

		this.elements.each(function(el, i){ 
			this.selected.push(el.retrieve('row'));
			el.addClass('selected'); 
		}, this);
	},
	
	// API
	unselectAll: function(){
		this.elements.each(function(el, i){ 
			el.removeClass('selected'); 
		}, this);
		
		this.selected = [];
	},
	
	// API
	getSelectedIndices: function(){
		return this.selected;
	},
	
	// API
	setSelectedIndices: function(arr){
		this.selected = arr;
		
		for (var i = 0; i < arr.length; i++) 
		{
			var li = this.elements[arr[i]];
			//el.addClass('selected');
			// simulate user click
			this.onRowClick({target:li.getFirst(), control:false}); 
		}

	},

	// mislim da je visak
	onMouseOver: function(obj){
		//alert(3);
		obj.columnModel.onMouseOver(obj.element, obj.data);
	},
	
	// API
	removeHeader: function(){
		var obj = this.container.getElement('.hDiv');
		
		if (obj) obj.empty();	//obj.set('html', '&nbsp;');
			
		this.options.columnModel = null;
	},	
	
	// API
	removeAll: function(){
		if (this.ulBody)
			this.ulBody.empty();
		
		this.selected = new Array();
		
		//this.options.data = null;
	},	
	
	// API
	setColumnModel: function(cmu){
		if ( !cmu )
			return;
				
		this.options.columnModel = cmu;	
		
		this.draw();
	},
	
	// API
	setColumnProperty: function(columnName, property, value){
	
		var cmu = this.options.columnModel;
		
		if ( !cmu || !columnName || !property  ) return;
		
		columnName = columnName.toLowerCase();
		
		for (var i=0; i<cmu.length; i++)
		{
			if ( cmu[i].dataIndex.toLowerCase() == columnName )
			{
				cmu[i][property] = value;
				
				return;
			}
		}
	},
	
	// Automatsko odredivanje column modela ako nije zadan
	setAutoColumnModel: function(){
		if ( !this.options.data )
			return;
			
		var rowCount = this.options.data.length;
		
		if ( !(rowCount>0) )
			return;
			
		this.options.columnModel = [];
		
		// uzmi schemu od prvog podatka
		for ( var cn in this.options.data[0] )
		{
			var dataType = typeof(this.options.data[0][cn]) == "number" ? "number" : "string";
			
			this.options.columnModel.push({header:cn, dataIndex:cn, dataType: dataType, editable:true});
		}
		
		this.draw();
	},
	
	// API
	setSize: function(w, h){
		
		// Width
		this.options.width = w ? w : this.options.width;
		
		this.container.setStyle('width', this.options.width);
		
		var width = this.options.width-2;
		if (this.options.buttons) this.container.getElement('.tDiv').setStyle('width', width);
		
		var hDiv = this.container.getElement('.hDiv');
		if (this.options.showHeader && hDiv) hDiv.setStyle('width', width);
		
		var bodyEl = this.container.getElement('.bDiv');
		bodyEl.setStyle('width', width);
		this.container.getElement('.pDiv').setStyle('width', width);
		
		// Height
		this.options.height = h ? h : this.options.height;

		bodyEl.setStyle('height', this.getBodyHeight() );
		this.container.setStyle('height', this.options.height);
		
		// ako je kojim slucajem whiteOverflow namjesti
		var gBlock = this.container.getElement('.gBlock');
		if (gBlock)
			gBlock.setStyles({width:this.options.width, height: bodyEl.getSize().y });
	},
	
	onBodyScroll: function(){
		var hbox = this.container.getElement('.hDivBox');
		
		var bbox = this.container.getElement('.bDiv');
		
		var xs = bbox.getScroll().x;
		
		//hbox.setStyle('position', 'relative');
		hbox.setStyle('left', -xs);

		this.rePosDrag();
		//console.debug(xs);
	},
	
	onBodyClick: function(){
		
	},	
	
	onBodyMouseOver: function(){
		//console.debug(this.onBodyScrollID);
		
	},	
	
	onBodyMouseOut: function(){
		
	},	
	
	// ************************************************************************
	// ************************* Drag columns events **************************
	// ************************************************************************
	
	rePosDrag: function(){
		if (!this.options.resizeColumns)
			return;
			
		var dragTempWidth = 0;
		var cDrags = this.container.getElements('.cDrag div');
		
		var scrollX = this.container.getElement('div.bDiv').getScroll().x;
		
		for (var c = 0; c < this.options.columnModel.length; c++) {
			var columnModel = this.options.columnModel[c];
			
			//if (columnModel.hidden) continue;
			
			// hidden-1
			var dragSt = cDrags[c];
		
			dragSt.setStyle('left', dragTempWidth+columnModel.width+(Browser.Engine.trident ? 1 : 1 )-scrollX);
			//console.log(dragTempWidth+columnModel.width+2);
			
			if (!columnModel.hidden)
				dragTempWidth += columnModel.width;
		}
	},
	
	onColumnDragComplete: function(target){
		this.dragging = false;
		
		var colindex = target.retrieve('column');
		
		// nadi poziciju prvo
		var cDrag = this.container.getElement('div.cDrag');
		var dragSt = cDrag.getElements('div')[colindex];
		var scrollX = this.container.getElement('div.bDiv').getScroll().x;
		
		// izracunaj nove ukupne duljine 
		this.sumWidth = 0;
		for (var c = 0; c < this.options.columnModel.length; c++) {
			var columnModel = this.options.columnModel[c];
			
			//if (columnModel.hidden) continue;

			if (c == colindex)
			{
				// nova vrijednost pomaknute kolone
				var pos = dragSt.getStyle('left').toInt()+scrollX-this.sumWidth-(Browser.Engine.trident ? -1 : 1 ); // zato sto je u dragSt.left +2
			}else if (!columnModel.hidden)			
				this.sumWidth += columnModel.width;
		}
		//console.log(pos);
		
		if (pos<30) // minimalna velicina kolone
			pos = 30
		
		this.options.columnModel[colindex].width = pos;
		
		this.sumWidth += pos;
		//console.log(this.sumWidth);
		
		this.ulBody.setStyle('width', this.sumWidth+this.visibleColumns*(Browser.Engine.trident ? 1 : 1 ));
		var hDivBox = this.container.getElement('div.hDivBox');
		
		hDivBox.setStyle('width', this.sumWidth+this.visibleColumns*2);
	
		// header
		var columns = hDivBox.getElements('div.th');
		var columnObj = columns[colindex];
		
		columnObj.setStyle('width', pos-(Browser.Engine.trident ? 6 : 6 ));

		var visibleColumns = this.visibleColumns; // radi this. u each-u
		
		// radi accordiana
		var elements = this.ulBody.getElements('li.tr');

		// sve kolone u body
		elements.each(function(el, i){
			el.setStyle('width', this.sumWidth+2*visibleColumns); // inace se Div-ovi wrapaju
			
			if (!el.hasClass('section'))	
			{
				var columns = el.getElements('div.td');
				var columnObj = columns[colindex];
				columnObj.setStyle('width', pos-(Browser.Engine.trident ? 6 : 6 ));
			}
			
		});
		
		this.rePosDrag();		
	},
	
	onColumnDragStart: function(target){
		this.dragging = true;
	},
	
	onColumnDragging: function(target){
		target.setStyle('top', 1);
	},
	
	overDragColumn: function(evt){
		evt.target.addClass('dragging');
	},
	
	outDragColumn: function(evt){
		evt.target.removeClass('dragging');
	},
	
	// ************************************************************************
	// ************************* Header events ********************************
	// ************************************************************************

	clickHeaderColumn: function(evt){
		if (this.dragging) return;
		
		var colindex = evt.target.retrieve('column');
		var columnModel = this.options.columnModel[colindex];
		
		evt.target.removeClass(columnModel.sort);
		columnModel.sort = (columnModel.sort == 'ASC') ? 'DESC' : 'ASC';
		evt.target.addClass(columnModel.sort);

		//hidden-1
		this.sort(colindex);
	},
	
	overHeaderColumn: function(evt){
		if (this.dragging) return;
		
		var colindex = evt.target.retrieve('column');
		var columnModel = this.options.columnModel[colindex];

		evt.target.addClass(columnModel.sort);
	},
	
	outHeaderColumn: function(evt){
		if (this.dragging) return;
		
		var colindex = evt.target.retrieve('column');
		var columnModel = this.options.columnModel[colindex];
		
		evt.target.removeClass(columnModel.sort);
	},
	
	getBodyHeight: function(){
		// da ukupna visina cijelog grida bude this.options.height za body moramo oduzeti header
		
		// header
		var headerHeight = this.options.showHeader ? 24+2 : 0;  //+2 radi bordera
		
		// toolbar
		var toolbarHeight = this.options.buttons ? this.container.getElement('.tDiv').getStyle('height').toInt() : 0;

		// pagination toolbar height 25px + 1px bottom border
		var paginationToolbar = this.options.pagination ? 26 : 0;
			
		return this.options.height-headerHeight-toolbarHeight-paginationToolbar-2; //+2 radi bordera
	},		
	
	renderData: function(){
		this.ulBody.empty();
		this.inlineEditSafe = null;
		
		if (this.options.data)
		{
			
			var columnCount = this.options.columnModel.length;
			var rowCount = this.options.data.length;
			
			for (var r=0; r<rowCount; r++)
			{
				var rowdata = this.options.data[r];
				
				var li = new Element('li');
				li.setStyle('width', this.sumWidth+2*this.visibleColumns); // inace se Div-ovi wrapaju, a u IE nastaje cudan 1px border ispod LI el.
				li.store('row', r);
				li.addClass('tr');

				
				this.ulBody.appendChild(li);
				
				if (this.options.tooltip)
				{
					this.options.tooltip.attach( tr );											
				}
				
				var firstvisible = -1;
				for (var c=0; c<columnCount; c++)
				{
					var columnModel = this.options.columnModel[c];
					
					//if (columnModel.hidden)
					//	continue;
					
					var div = new Element('div');
					div.addClass('td');
					div.setStyle('width', columnModel.width-6); // zbog paddinga u ff
					//div.setStyle('overflow-x', 'hidden');
						
					li.appendChild(div);
					
					firstvisible = (!columnModel.hidden && firstvisible == -1) ? c : firstvisible;
					
					var toggleicon = "";
					if (firstvisible==c && this.options.accordion && this.options.showtoggleicon)
					{					
						toggleicon = "<div class='toggleicon'></div>";
					}
					
					if (columnModel.hidden) div.setStyle('display', 'none');					
					
					if (columnModel.onMouseOver)
					{
						div.onmouseover = this.onMouseOver.bind(this, {element:div, columnModel:columnModel, data:rowdata });												
					}
					
					// title
					if (columnModel.title) div.title = rowdata[columnModel.title];

					
					if (columnModel.dataType == "checkbox")
					{
						
						var input = new Element('input', {type:"checkbox"});
							
						
						if (columnModel.onChange)
						{
							input.onclick = this.onSelect.bind(this, {columnModel:columnModel, row:r, input:input});												
						}
						
						div.appendChild(input);
						
						var val = rowdata[columnModel.dataIndex];
						if ( val == 1 || val=='t') {
							input.set('checked', true);
						}
						
					}else if (columnModel.type == "image") {
					/*	var img = new Element('img');
						img.src = this.options.data[r][columnModel.dataIndex];
						td.appendChild(img);*/
						
					}else if (columnModel.type == 'custom') {
						//columnModel.labelFunction(td, this.options.data[r], r);
					}else if (columnModel.labelFunction != null) {
							div.innerHTML = columnModel.labelFunction(rowdata, r);
					}else {
							var str = new String(rowdata[columnModel.dataIndex]); // mora biti string, jer ako dode 0 kao broj error

							if (str == null || str == 'null' || str == "" ) str = '&nbsp;';

							var trimmed = str.replace(/^\s+|\s+$/g, ''); // ako je prazan string
							if(trimmed.length==0) str = '&nbsp;';
							
							// Column text align propert.
							// moram prije srediti racunanje width radi padding:0 kad se aling
							//if (columnModel.align) div.setStyles({'text-align': columnModel.align, 'padding-left':0});
							
							div.innerHTML = toggleicon+str;
					}
					
				} // for column
				
				// ***********************
				
				if (this.options.accordion)
				{
				/*	var div = new Element('div');
					div.addClass('section');
					
					li.appendChild(div);
				*/
					var li2 = new Element('li');
					li2.addClass('section');
					li2.addClass('section-'+r);
					li2.setStyle('width', this.sumWidth+2*this.visibleColumns); // inace se Div-ovi wrapaju, a u IE nastaje cudan 1px border ispod LI el.
					
					this.ulBody.appendChild(li2);
					
					if (this.options.accordionRenderer)	
						this.options.accordionRenderer({parent:li2, row:r, grid:this, rowdata: rowdata});
				}
				
			}
		}
	},
	
	// ************************************************************************
	// ************************* Main draw function ***************************
	// ************************************************************************
	draw: function(){	
		this.removeAll(); // reset variables and only empty ulBody 
		this.container.empty(); // empty all 
		
		// ************************************************************************
		// ************************* Common ***************************************
		// ************************************************************************
		var width = this.options.width - (Browser.Engine.trident ? 2 : 2 ); //-2 radi bordera
		var columnCount = this.options.columnModel ? this.options.columnModel.length : 0;
		
		// ************************************************************************
		// ************************* Container ************************************
		// ************************************************************************
		if (this.options.width)
			this.container.setStyle('width', this.options.width);
		this.container.addClass('omnigrid');

		// ************************************************************************
		// ************************* Toolbar **************************************
		// ************************************************************************
		
		if (this.options.buttons)
		{
			var tDiv = new Element('div');
			tDiv.addClass('tDiv');
			tDiv.setStyle('width', width); 
			tDiv.setStyle('height', 25+(Browser.Engine.trident ? 2 : 0 ));// borderi u FF
			this.container.appendChild(tDiv);
			
			var bt = this.options.buttons;
			for (var i = 0; i < bt.length; i++) {
				var fBt = new Element('div');
				tDiv.appendChild(fBt);
				if (bt[i].separator)
				{
					fBt.addClass('btnseparator');
					continue;
				}
				
				fBt.addClass('fbutton');
				
				var cBt = new Element('div');
				cBt.addEvent('click', bt[i].onclick.bind(this, [bt[i].bclass, this])); 
				cBt.addEvent('mouseover', function(){this.addClass('fbOver'); }); 
				cBt.addEvent('mouseout', function(){this.removeClass('fbOver'); }); 
				
				fBt.appendChild(cBt);
				
				var spanBt = new Element('span');
				spanBt.addClass(bt[i].bclass);
				spanBt.setStyle('padding-left', 20 );
				spanBt.set('html', bt[i].name);
				cBt.appendChild(spanBt);
			}
		}
		
		// ************************************************************************
		// ************************* Header ***************************************
		// ************************************************************************
		var hDiv = new Element('div');
		hDiv.addClass('hDiv');
		hDiv.setStyle('width', width ); // borderi u FF
		this.container.appendChild(hDiv);
		
		var hDivBox = new Element('div');
		hDivBox.addClass('hDivBox');
		
		hDiv.appendChild(hDivBox);
		
		this.sumWidth = 0;
		this.visibleColumns = 0; // razlikuje se od columnCount jer podaci za neke kolone su ocitani ali se ne prikazuju, npr. bitno kod li width
		for (var c = 0; c < columnCount; c++) {
			var columnModel = this.options.columnModel[c];
			
			var div = new Element('div');
			// ******************************************
			// ****** default postavke columnModela *****
			if (columnModel.width == null)  this.options.columnModel[c].width = 100; 
			columnModel.sort = 'ASC'; 
			// ******************************************

			
			// ********************** Header events **************************
			if (this.options.sortHeader)
			{
				div.addEvent('click', this.clickHeaderColumn.bind(this));
				div.addEvent('mouseout', this.outHeaderColumn.bind(this));
				div.addEvent('mouseover', this.overHeaderColumn.bind(this));
			}
			
			div.store('column', c);
			div.store('dataType', columnModel.dataType);
			div.addClass('th');
			div.setStyle('width', columnModel.width-(Browser.Engine.trident ? 6 : 6 ));
			hDivBox.appendChild(div);
	
			if (columnModel.hidden) 
				div.setStyle('display', 'none');
			else{
				this.sumWidth += columnModel.width;
				this.visibleColumns++;
			}
			
			var header = columnModel.header;
			
			if (header)
				div.innerHTML = header;		
		}
		hDivBox.setStyle('width', this.sumWidth+this.visibleColumns*2);
		if (!this.options.showHeader)
			hDiv.setStyle('display', 'none');
		// ************************************************************************
		// ************************* Column size drag *****************************
		// ************************************************************************
		
		// odredivanje visine body dijela
		
		if (this.options.height)
		{
			var bodyHeight = this.getBodyHeight();
			this.container.setStyle('height', this.options.height);
		}
		
		if (this.options.resizeColumns)
		{
			var cDrag = new Element('div');
			cDrag.addClass('cDrag');
			var toolbarHeight = this.options.buttons ? tDiv.getStyle('height').toInt() : 0; // toolbar
			cDrag.setStyle('top', toolbarHeight);
			this.container.appendChild(cDrag);
			
			var dragTempWidth = 0;
			for (var c = 0; c < columnCount; c++) {
				var columnModel = this.options.columnModel[c];
				
				//if (columnModel.hidden) continue;
					
				var dragSt = new Element('div');
				
				//alert(dragTempWidth+' '+columnModel.width);
				// -(Browser.Engine.trident ? 10 : 0 )
				var headerHeight = this.options.showHeader ? 24+2 : 0; // +2 border
				
				dragSt.setStyles({top:1,left: dragTempWidth+columnModel.width, height: headerHeight, display:'block'}); // bodyHeight+
				dragSt.store('column', c);
				cDrag.appendChild(dragSt);
				
				// Events
				dragSt.addEvent('mouseout', this.outDragColumn.bind(this));
				dragSt.addEvent('mouseover', this.overDragColumn.bind(this));
				
				var dragMove = new Drag(dragSt, {snap:0}); // , {container: this.container.getElement('.cDrag') }
				dragMove.addEvent('drag', this.onColumnDragging.bind(this) );
				dragMove.addEvent('start', this.onColumnDragStart.bind(this) );
				dragMove.addEvent('complete', this.onColumnDragComplete.bind(this) );
				
				
				if (columnModel.hidden) 
					dragSt.setStyle('display', 'none');
				else
					dragTempWidth += columnModel.width;
			}
		}
		
		// ************************************************************************
		// ************************* Body *****************************************
		// ************************************************************************
		
		var bDiv = new Element('div');
		bDiv.addClass('bDiv');
		
		if (this.options.width)
			bDiv.setStyle('width', width);

		bDiv.setStyle('height', bodyHeight);	
		this.container.appendChild(bDiv);

		//  scroll event
		this.onBodyScrollBind = this.onBodyScroll.bind(this);
		bDiv.addEvent('scroll', this.onBodyScrollBind);
		//alert(this.visibleColumns);
		this.ulBody = new Element('ul');
		this.ulBody.setStyle('width', this.sumWidth+this.visibleColumns*(Browser.Engine.trident ? 1 : 1 )); // da se ne vidi visak, ul je overflow hidden
		bDiv.appendChild(this.ulBody);


		if (this.options.pagination && !this.container.getElement('div.pDiv') )
		{
			var pDiv = new Element('div');
			pDiv.addClass('pDiv');
			pDiv.setStyle('width', width); 
			pDiv.setStyle('height', 25);
			this.container.appendChild(pDiv);
			
			var pDiv2 = new Element('div');
			pDiv2.addClass('pDiv2');
			pDiv.appendChild(pDiv2);
			
			var h = '<div class="pGroup"><select class="rp" name="rp">';
			
			// *****
			var optIdx;
			var setDefaultPerPage = false;
			for (optIdx=0; optIdx<this.options.perPageOptions.length; optIdx++)
			{
				if (this.options.perPageOptions[optIdx] != this.options.perPage)
					h += '<option value="' + this.options.perPageOptions[optIdx] + '">' + this.options.perPageOptions[optIdx] +'</option>';
				else{
					setDefaultPerPage = true;
					h += '<option selected="selected" value="' + this.options.perPageOptions[optIdx] + '">' + this.options.perPageOptions[optIdx] +'</option>' ;
				}
			}
			// *****

			h += '</select></div>';
			
			h += '<div class="btnseparator"></div><div class="pGroup"><div class="pFirst pButton"></div><div class="pPrev pButton"></div></div>';
			h += '<div class="btnseparator"></div><div class="pGroup"><span class="pcontrol"><input type="text" value="1" size="4" style="text-align:center"/> / <span></span></span></div>';
			h += '<div class="btnseparator"></div><div class="pGroup"><div class="pNext pButton"></div><div class="pLast pButton"></div></div>';
			h += '<div class="btnseparator"></div><div class="pGroup"><div class="pReload pButton"></div></div>';
			h += '<div class="btnseparator"></div><div class="pGroup"><span class="pPageStat"></div>';
			
			pDiv2.innerHTML = h;

			// set this.options.perPage value from this.options.perPageOptions array
			var rpObj = pDiv2.getElement('.rp');
			if (!setDefaultPerPage && rpObj.options.length>0){
				this.options.perPage = rpObj.options[0].value;
				rpObj.options[0].selected = true;
			}
			// ********

			pDiv2.getElement('.pFirst').addEvent('click', this.firstPage.bind(this) );
			pDiv2.getElement('.pPrev').addEvent('click', this.prevPage.bind(this) );
			pDiv2.getElement('.pNext').addEvent('click', this.nextPage.bind(this) );
			pDiv2.getElement('.pLast').addEvent('click', this.lastPage.bind(this) );
			pDiv2.getElement('.pReload').addEvent('click', this.refresh.bind(this) );
			pDiv2.getElement('.rp').addEvent('change', this.perPageChange.bind(this));
			pDiv2.getElement('input').addEvent('keyup', this.pageChange.bind(this) );
		}

	},
	
	firstPage: function(){
		this.options.page = 1;		
		this.refresh();
	},
	
	prevPage: function(){
		if (this.options.page>1){
			this.options.page--;		
			this.refresh();
		}
	},
	
	nextPage: function(){

		if( (this.options.page+1) > this.options.maxpage)
			return;
		
		this.options.page++;		
		this.refresh();
	},
		
	lastPage: function(){
		this.options.page = this.options.maxpage;		
		this.refresh();
	},
	
	perPageChange: function(){
		this.options.page = 1;
		this.options.perPage = this.container.getElement('.rp').value;		
		this.refresh();
	},
		
	pageChange: function(){
		
		var np = this.container.getElement('div.pDiv2 input').value;
		
		if (np>0 && np<=this.options.maxpage)
		{
			if (this.refreshDelayID)
				$clear(this.refreshDelayID)
			
			this.options.page = np;
			
			this.refreshDelayID = this.refresh.delay(1000, this);
		}
	},
	
	// API
	gotoPage: function(p){
		if (p>0 && p<=this.options.maxpage)
		{
			this.options.page = p;
			
			this.refresh();
		}
	},
	
	setPerPage: function(p){
		if (p>0)
		{
			this.options.perPage = p;
			
			this.refresh();
		}
	},
	
	// API, not doc
	sort: function(index, by){
		
		if ( index<0 || index>=this.options.columnModel.length )
			return;

		if(this.options.onStart){
			this.fireEvent('onStart');
		}
		
		//
		var header = this.container.getElements('.th');
		var el = header[index];
		
		if (by != null)
			el.addClass(by.toLowerCase());
		
		if(el.hasClass('ASC')){
			el.sortBy = 'ASC';
		}else if(el.hasClass('DESC')){
			el.sortBy = 'DESC';
		}
		
		if (this.options.serverSort){
			this.options.sortOn = this.options.columnModel[index].dataIndex;
			this.options.sortBy = el.sortBy;
			
			this.refresh();
		}else{
			// Sorting...
			this.elements.sort(el.compare);
			this.elements.injectInside(this.ulBody);
			
			// Update selection array because indices has been changed
			this.selected = new Array();
			this.elements.each(function(el ,i){
				if(el.hasClass('selected')){
					this.selected.push(el.retrieve('row'));
				}
			}, this);
			
			// Filter
			if(this.filtered){
				this.filteredAltRow();
			}else{
				this.altRow();
			}
		}	
	},
	
	altRow: function(){
		this.elements.each(function(el,i){
			
			if(i % 2){
				el.removeClass('erow');
			}else{
				el.addClass('erow');
			}
		});
	},
	
	filteredAltRow: function(){

		this.ulBody.getElements('.'+this.options.filterSelectedCls).each(function(el,i){
			if(i % 2){
				el.removeClass('erow');
			}else{
				el.addClass('erow');
			}
		});
	},
	
	// API
	filter: function(form){
		//var form = $(form);
		var col = 0;
		var key = '';
		
		if ( !(form.length>0) )
			this.clearFilter();
		
		
		key = form;
		
		if(key)
		{			
			for (var i=0; i<this.options.data.length; i++)
			{
				var dat = this.options.data[i];
			
				for (var c=0; c<this.options.columnModel.length; c++)
				{
					var columnModel = this.options.columnModel[c];
					
					if ( columnModel.type == "checkbox")
						continue;
					
					var el = this.elements[i];
					
					if(this.options.filterHide){
						el.removeClass('erow');
					}
					
					if(dat[columnModel.dataIndex] != null && dat[columnModel.dataIndex].toLowerCase().indexOf(key) > -1)
					{
						el.addClass(this.options.filterSelectedCls);
						if(this.options.filterHide){
							el.removeClass(this.options.filterHideCls);
						}
						
						break;
					}else{
						el.removeClass(this.options.filterSelectedCls);
						if(this.options.filterHide){
							el.addClass(this.options.filterHideCls);
						}
					}
				}				
			}
			
			if(this.options.filterHide){
				this.filteredAltRow();
				this.filtered = true;
			}
		}
	},
	
	// API
	clearFilter: function(){
		this.elements.each(function(el,i){
			el.removeClass(this.options.filterSelectedCls);
			if(this.options.filterHide){
				el.removeClass(this.options.filterHideCls);
			}
		}, this);
		if(this.options.filterHide){
			this.altRow();
			this.filtered = false;
		}
	}

});


/*************************************************************/


// ********************************************************************************
3// ****************************** Forme *******************************************
var omFormManager = new Class({

	Implements: [Events, Options],
	
	getOptions: function(){
		return {
			buttons: null
		};
	},

	initialize: function(options){
		this.setOptions(this.getOptions(), options);
		
		this.openforms = [];
		this.formsWithOverylay = 0;
	},
	
	$: function(fid){
		for (var i = 0; i < this.openforms.length; i++) {
			if (fid == this.openforms[i].options.fid) {
				return this.openforms[i];
			}
		}
	},
	
	open: function(options, newfrm){
		
		for (var i = 0; i < this.openforms.length; i++) {
			this.openforms[i].container.hide();
		}
		
		// tako da svaka forma ima svoj unique id
		if (!options.fid)
			options.fid = "fid_"+this.openforms.length;
		
		if (!newfrm) 
		{
			if (options.wizard)
				newfrm = new omWizardForm(options);
			else
				newfrm = new omForm(options);
		}
		
		if (options.overlay) 
		{
			
			// ako nije otvoren niti jedan overlay
			if (this.formsWithOverylay == 0)
			{
				this.mol = document.modalOverlay = new ModalOverlay();

				if (options.closeOverlayClick) 
				{
					var onCloseBindFunction = this.close.bind(this, newfrm);
					
					this.mol.addEvent("click", onCloseBindFunction );
				}
			}
		
			this.formsWithOverylay++;
		}
		
		this.openforms.push( newfrm );
		
		return newfrm;
	},
	
	style: function(options){
		styleform = formManager.open({
			overlay:true,
			title: 'Style properties',
			width:300,
			height:250, 
			url:'modules/layer/style_form.php',
			buttons:[{html:'OK', click:'styleFormOkClick();'}, {html:'Back', click:'styleform.close();'}]
		});
		
		// globalna varijabla za style form
		styledata = options.data;
				
		// globalna varijabla za style form
		icondiv = options.element;
		
		if (options.onClose)
			styleform.addEvent('close', options.onClose);	
		
		return styleform;
	},
		
	fileBrowser: function(options){
		
		var buttons = [{click:"onSelectFiles();", html: 'Open'}, 
						{click:"formManager.close('filemanager');", html: 'Cancel'}];
	
		if (!options)
			options = {};
		
		if (options.upload)
			buttons.push({click:'showUploadForm();', html: 'Upload', title: 'Upload new files in current directory'});
		
		var formdata = {};
		formdata.currentDir = '';
		formdata.selectmode = options.selectmode;	
		
		if (options.extensions)
			formdata.extensions = options.extensions;	
		
		if (options.postgis)
			formdata.postgis = options.postgis;	
			
		if (options.showimages)
			formdata.showimages = options.showimages;	
			
		var nfb = this.open({
				overlay:true,
				fid:'filemanager',
				width:830,
				height:400,
				title:"Files browser",				
				url:"modules/filemanager/filemanager_form.php",
				data: formdata,
				buttons: buttons
			});
			
		return nfb;
	},
		
	close: function(frm, data){
		
		if (!frm)
			return;
		
		var asobj = true;
		
		// arg. u close moze biti object od forme ili fid od forme, 'string'
		if(typeof(frm) == 'string')
			asobj = false;
	
		var ind = -1;
		
		
		for (var i=0; i<this.openforms.length; i++)
		{
			
			if (asobj) {
				if (frm == this.openforms[i]) {
					ind = i;
					break;
				}
			}
			else {
				if (frm == this.openforms[i].options.fid) {
					
					ind = i;
					break;
				}
			}
		}
		
		// znaci da nije nasao formu u listu, mozda je bolje ostaviti komen. radi greske
		//if (!(ind>0)) return;
		
		var frmobj = this.openforms[ind];
		//console.log(frmobj);
		
		if (frmobj.options.overlay)
			this.formsWithOverylay--;
		
		if (this.formsWithOverylay == 0)
		{
			this.mol.dispose();
		}
		
		// izbaci je iz liste aktivnih formi
		this.openforms.pop();
		
		// akcije
		frmobj.fireEvent("close", data);
	
		frmobj.container.dispose();
		
		//
		// postavi vidljivost ostalih formi
		for (var i = 0; i < this.openforms.length; i++) {
			this.openforms[i].container.show();
		}
	}
	
});
 
var formManager = new omFormManager();

var omForm = new Class({

	Implements: [Events, Options],
	
	getOptions: function(){
		return {
			id:'form_container',
			onClickDispose : false,
			container: document.body,
			width: 500,
			height: 400,
			buttons: null
		};
	},
	
	fdata:{}, // collected data on form

	initialize: function(options){
		this.setOptions(this.getOptions(), options);
		
		this.container = new Element('div', {} );
		
		this.container.addClass(this.options.id);
		
		this.form = new Element('div', {id:'formmain'} );
		
		this.form.inject(this.container);
		
		this.createFooter();
		
		if (this.options.title) {
			
			this.header = new Element('div', {
				id: 'form_header', html: this.options.title
			});
			this.header.setStyle('width', this.options.width-20);
			this.header.inject(this.container, 'top');
			
		}
		
		if (this.options.buttons) {
			
			for (var b=0; b<this.options.buttons.length; b++)
			{
				var aobj = this.options.buttons[b];
				
				aobj.href = 'javascript:;';
				
				this.save = new Element('a', aobj);
				
				if (aobj.click) {
					
					// kompliciran nacin za click event, ali kad ne radi u IE
					function abind(ao){
						eval(ao.click);
					}
					
					this.save.addEvent('click', abind.bind(this, aobj) );
				}
				
				this.save.addClass('formbutton');
				this.save.inject(this.footer);
			}
		}
		this.form.setStyle('height', this.options.height-60-(this.options.buttons ? 30 : 0) );
		
		this.closebtcont = new Element('div', {id:'form_closebt'});
		//this.closebt = new Element('img', {src:'include/omFramework/images/close.png',  );
		this.closebtcont.addEvent('click', this.close.bindWithEvent(this) );
		this.closebtcont.inject(this.container);
		//this.closebt.inject(this.closebtcont);
		
		// loader
		this.loader = new Element('div', {id:'form_loader'} );
		
		this.container.setStyle('width', this.options.width-60); // paddings
		this.container.setStyle('height', this.options.height-60); // paddings
		this.container.injectInside(document.body);
		
		var size = this.container.getSize();
		this.loader.setStyle('left', size.x/2-20); 
		this.loader.setStyle('top', size.y/2-40); 
		this.loader.inject(this.container);
		
		//

		this.update();

		this.load(this.options.url);

		document.modalForm = this;


		// **********************************************************************		
		// ********************** Events ****************************************
		
		window.addEvent("resize", this.update.bindWithEvent(this));

		// event register zadan preko param.
		if (options.onClose)
		{
			this.addEvent("close", options.onClose );
		}
		
		/*var myFx2 = new Fx.Tween(this.container);
		myFx2.start('opacity', 0.1, 1);*/
	},
	
	createFooter: function() {
		if (!this.options.buttons)
			return;
			
		this.footer = new Element('div', {
				id: 'form_footer'
			});
		this.footer.setStyle('width', this.options.width-20); // +padding	
			
		this.footer.inject(this.container);
	},
	
	showLoader: function(b) {
		if (b)
		{
			this.loader.setStyle('display', 'block'); 
		}else{
			this.loader.setStyle('display', 'none'); 
		}
	},
	
	resize: function(w, h) {
		var myEffect = new Fx.Morph(this.container, {duration: 'short', transition: Fx.Transitions.Sine.easeOut, onChange: this.update.bindWithEvent(this) });
		myEffect.start({'height': h, 'width': w});
		
		this.loader.setStyle('left', w/2-20); 
		
		var top = h/2-40;
		
		if (top<10)	top = 10;			
		this.loader.setStyle('top', top);
		
		this.footer.setStyle('width', w+40); // +padding	
	},
	
	load: function(url) {
		this.showLoader(true);
		
		// animated fading
		//this.form.fade(0.1);
		this.form.hide();
		
		var myHTMLRequest = new Request.HTML({url:url, update: this.form, 
					onComplete: this.onLoadComplete.bindWithEvent(this), evalResponse: false, evalScripts: true
				}
			).get(this.options.data); ;
	},
	
	refresh: function(url) {
		this.load(this.options.url);
	},
	
	onLoadComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
		this.showLoader(false);
		//if (Browser.Engine.trident4) this.pngfix(this.closebtcont);
		
		this.form.show();
		//this.form.fade(1);
	},
	
	update: function(e) {

		var size = window.getSize();
		var scrollSize = window.getScrollSize();
		
		var winheight = size.y; // tu moras staviti uvjet scroll position i onda scroll event //(size.y > scrollSize.y) ? size.y : scrollSize.y;
		
		var xpos = document.getScrollSize().x/2-this.container.getStyle('width').toInt()/2; 		
		var ypos = winheight/2-this.container.getStyle('height').toInt()/2-100; 

		this.container.setStyle('left', xpos);
		
		if (ypos<10) ypos = 10;
		this.container.setStyle('top', ypos);
	},
	
	close : function()
	{
		formManager.close(this, this.fdata);
	}

	
});

var omWizardForm = new Class({
	Extends: omForm,
	
	initialize: function(options){
		this.parent(options);
		
		this.options.currentStep = 1;
		
		this.leftbtcont = new Element('div');
		this.leftbt = new Element('img', {src:'include/fn/images/left.png', id:'form_leftbt'} );
		this.leftbtcont.addEvent('click', this.gotoPrevious.bindWithEvent(this) );
		this.leftbt.inject(this.leftbtcont);
		this.leftbtcont.inject(this.footer);
		
		this.leftbt.setStyle('visibility', 'hidden');
		
		this.rightbtcont = new Element('div');
		this.rightbt = new Element('img', {src:'include/fn/images/right.png', id:'form_rightbt', title:'Next step'} );
		this.rightbtcont.addEvent('click', this.gotoNext.bindWithEvent(this) );
		this.rightbt.inject(this.rightbtcont);
		this.rightbtcont.inject(this.footer);
		
		if (this.h1)
			this.h1.setStyle('margin-left', 40);
		
		this.status = new Element('div', {id:'form_status'} );
		this.status.inject(this.footer);
		
		// register to formManager
		formManager.open(this.options, this);
	},
	
	updateButtons:function(){
		
		var step = this.options.currentStep;
		
		if (step > 1)
			this.leftbt.setStyle('visibility', 'visible');
		else
			this.leftbt.setStyle('visibility', 'hidden');
		
		
		if (step >= this.options.steps)
			this.rightbt.set('title', 'Finish');
		else
			this.rightbt.set('title', 'Next step');
		
			
		this.status.set('text', 'Step '+step+' of '+this.options.steps);
	},
	
	gotoStep:function(step){
	
		if (eval(this.options.stepFunction)(step)) {
			this.options.currentStep = step;
			this.updateButtons();
		}
	},
	
	onLoadComplete: function(responseTree, responseElements, responseHTML, responseJavaScript) {
		this.showLoader(false);
		//if (Browser.Engine.trident4) pngfix(this.closebtcont);
		
		//this.form.fade(1);
		this.form.show();
	},
	
	gotoNext:function(step){
	
		if ( (this.options.currentStep ) <= this.options.steps ) 
		{
			if ( eval(this.options.stepFunction)( this.options.currentStep+1 ) )
			{
				this.options.currentStep++;
				this.updateButtons();
			}
		}
	},
	
	gotoPrevious:function(step){
		
		if ( this.options.currentStep > 0 ) 
		{

			if ( eval(this.options.stepFunction)( this.options.currentStep-1 ) )
			{
				this.options.currentStep--;
				this.updateButtons();
			}
		}
		
	}
	
});
	

/*************************************************************/
var omApplication = new Class({
	Implements: [Events, Options],
						  
	getOptions: function(){
		return {
			hideAuxMenu:true,
			auxMenuOpacity:0.0
		};
	},

	initialize: function(container, options){
		this.setOptions(this.getOptions(), options);
		
		//
		this.path = null;
		this.liveSite = null;
		//
		
		// LOADER CREATION
		this.loader = new Element('div', {id:'loader'});			
		document.getElement('body').insertBefore(this.loader, document.getElement('body').firstChild);
		$('loader').hide();
		
		//this.queue = new Roar();
		
	},
	
	showOverlay: function(){
		if (this.overlay)
			return;

		$('flashcontent').hide();

		this.overlay = new ModalOverlay({});
	},
	
	hideOverlay: function(){
		if (this.overlay){
			this.overlay.dispose();
			$('flashcontent').show();
			this.overlay = null;
			

		}
	},

	loadModule: function(container, options, callbackFunction){
		
		var myHTMLRequest = new Request.HTML({url:options.url, update: $(container), onComplete:callbackFunction, evalResponse: false, evalScripts: true
				}
			).get(options.data); ;
	
	},
	
	unloadModule: function(container){
		$(container).empty();
	},
	
	call: function(url, onComplete){
		var request = new Request.JSON({url:url, onComplete: function (data){
																onComplete(data);
															}
												}).send();
	},
	
	showMessage: function(showText)
	{
		/*var message = new Element('div', {id:'messagecont'});	
		
		$('main').insertBefore(message, $('main').firstChild);
		message.innerHTML = showText;
		
		(function(){
				if ( $('messagecont') )
					$('messagecont').dispose(); 
			}
		).delay(5000);*/
		
		//this.queue.alert("Alert", showText);	
	},

	showConfirm: function(showText)
	{	
		this.showMessage( "<span class='messages'>"+showText+"</span>" );
	},
	
	showError: function(showText)
	{	
		this.showMessage( "<span class='messages error'>Error: "+showText+"</span>" );
	},	

	showLoader: function(text)
	{
		if (text)
			this.loader.set('html', text);
		else
			this.loader.set('html', 'Pričekajte molim...');
		
		this.loader.show();

		//this.queue.alert("Loader", showText);
	},
	
	hideLoader: function(el)
	{
		this.loader.hide();
	},
	
	showLoaderWithOverlay: function(showText)
	{
		
		this.showOverlay();
		
		this.showLoader(showText);
	},
	
	
	
	getFormValues: function(formEl)
	{
		if (!formEl)
			return null;
			
		var queryString = {};
		formEl.getElements('input, select, textarea').each(function(el){
			
			if (!el.name || el.disabled) 
				return;
			
			var value = (el.tagName.toLowerCase() == 'select') ? Element.getSelected(el).map(function(opt){
				return opt.value;
			}) : ((el.type == 'radio' || el.type == 'checkbox') && !el.checked) ? null : el.value;
			
			$splat(value).each(function(val){
				if (val) 
					queryString[el.name] = val; //encodeURIComponent(val)
			});
			
		});
		
		return queryString;
		
	},
		
	clearFormValues: function(formEl)
	{
		if (!formEl)
			return null;
			
		var queryString = {};
		formEl.getElements('input, select, textarea').each(function(el){
			
			if (!el.name || el.disabled) 
				return;
			
			if (el.tagName.toLowerCase() == 'input' || el.tagName.toLowerCase() == 'textarea')
				el.value = '';
			
		});
		
	}
	
});
/*************************************************************/

/* ************************************************************************************* */
/* ************************** Element extension functions ****************************** */
/* ************************************************************************************* */

Element.Properties.red = {
    set: function(value){
        this.set('html', '<span class="red">'+value+'</span>');
    }
};

Element.Properties.green = {
    set: function(value){
        this.set('html', '<span class="green">'+value+'</span>');
    }
};

Element.implement({
	overlay: function(v, withLoader){

		
		var noe = this.getElement('.element_overlay');
		var loader = this.getElement('.elementloader_black');
	
		if (!v){
			loader.dispose();
			noe.dispose();

			return;
		}
		
		if (!noe) {
			noe = new Element('div');
			noe.addClass('element_overlay');
			
			noe.inject(this);
		}

		var size = this.getSize();
		
		noe.setStyles({ width:size.x, height:size.y });
		
		if (withLoader) {
			var loader = new Element('div');
			loader.addClass('elementloader_black');
			loader.setStyle('top', size.y / 2 - 8);
			loader.setStyle('left', size.x / 2 - 8);
			loader.inject(this);
		}
		
		this.setStyle('position', 'relative');
	},
	
	showLoader: function()
	{
		// ako vec postoji loader
		if (this.getElement('.loader'))
			return;
			
		var loaderdiv = new Element('div', {style: 'width:100%; text-align:center;'} );
		loaderdiv.addClass('loader');
		loaderdiv.set('html', "<div style='margin:0px auto;'><img src='/images/loader.gif' alt='Loading...' /> </div>" );
		
		this.appendChild(loaderdiv);

		//this.queue.alert("Loader", showText);
	},
	
	hideLoader: function(el)
	{
		var loader = this.getElement('.loader');
		
		if (loader) loader.dispose();
	},
			
	hide: function(){
		this.setStyle('display', 'none');
	},
	
	show: function(){
		this.setStyle('display', 'block');
	},
	
	toggle: function(){
		if ( this.getStyle('display') == 'block' )
		{
			this.hide();
		}else{
			this.show();
		}
	}
});

/* ************************************************************************************* */
/* ************************** Modal overlay ******************************************** */
/* ************************************************************************************* */

var ModalOverlay = new Class({

	Implements: [Events, Options],
	
	getOptions: function(){
		return {
			onClickDispose : false,
			container: document.body
		};
	},
	
	initialize: function(options){

		if ( $('overlay') )
			if (document.overlay)
				return document.overlay;
		
		this.setOptions(this.getOptions(), options);
		
		this.overlay = document.overlay = new Element('div', {id:'overlay', style:'opacity:0.7; filter:alpha(Opacity=70);'});	

		//var myFx = new Fx.Tween(this.overlay);
		//myFx.start('opacity', 0.1, 0.7);
		
		this.overlay.setStyle("height", document.getScrollSize().y );
	
		this.options.container.insertBefore(this.overlay, this.options.container.firstChild);
		
		// ************************************************
		// ****************** Events **********************
		if (this.options.onClickDispose)
		{
			this.overlay.addEvent("click", function(){	
				this.close();
			});
		}
		window.addEvent("resize", this.update.bindWithEvent(this));
		// ************************************************
		
		return this.overlay;
	},
	
	update: function(e) {
		//if(e) e = new Event(e).stop();
		
		if (document.overlay) {
					var size = window.getSize();
					var scrollSize = window.getScrollSize();

					document.overlay.setStyles({
						'height': (size.y > scrollSize.y) ? size.y : scrollSize.y,
						'width': size.x
					});
				}
	},
	
	close: function(){
		document.overlay = null;
		
		this.dispose();
	}

});

/* ************************************************************************************* */
/* ************************** Modules ************************************************** */
/* ************************************************************************************* */

var omModule = new Class({
	
	Implements: [Events, Options],
	
	options: {
		url : ""
	},
	
	initialize: function(options){
		this.setOptions(options);
	},
	
	call: function(taskData, eventName, callBack, arg){
		//var url = this.options.url+"?"+ Hash.toQueryString(taskData);
		
		var url = this.options.url;
		
		var noloader = taskData.noloader;
		delete taskData.noloader;
			
		var request = new Request.JSON({url:url, data:taskData, method:'post' });
		
		var myf = function (data){
			om.hideLoader();
			
			this.fireEvent(eventName, [data]);
			
			if (callBack)
				callBack(data, arg);
		};
		var myfb = myf.bind(this);
		
		request.addEvent("complete", myfb ) ;

		if (!noloader)
			om.showLoader();
		request.send();
	}

});	





// ******************************************************************************************
window.addEvent("domready", function(){
	om = new omApplication();

});


  /*********************************************************/
 /*   vlaCalendar version 2.1 for mootools release 1.2    */
/*********************************************************/

var vlaCalendar = new Class({
	Implements: [Events],
		
	'slideDuration': 500,
	'fadeDuration': 500,
	'transition': Fx.Transitions.Quart.easeOut,
	'startMonday': false,
	'filePath': 'include/components/vlacalendar/inc/',
	'defaultView': 'month',
	'style': '',
	'monthselect': false,	//marko
	
	initialize: function(_container, _options) {
		//Add the provided options to this object by extending
		if(_options) $extend(this, _options);
		
		this.loading = false;
		this.container = _container = $(_container);
		var _class = this;
		
		//Insert the base into the container and initialize elements
		var  pars = 'defaultView='+ this.defaultView;
		if(this.picker) {
			if($type(this.prefillDate) == 'object' && this.getInputDate(this.prefillDate)) pars += '&pickedDate='+ this.getInputDate(this.prefillDate);
			if(this.linkWithInput) pars += '&gotoPickedDate=1';
		}
		this.u('base', pars, function() { 
			_class.mainLoader = _container.getElement('div[class=loaderA]');
			_class.tempLoader = _container.getElement('div[class=loaderB]');
			_class.label 	  = _container.getElement('span[class=label]');
			_class.arrowLeft  = _container.getElement('div[class=arrowLeft]');
			_class.arrowRight = _container.getElement('div[class=arrowRight]');				
			_class.initializeCalendarFunctions();
			
			//Prefill/load picker date elements
			if(_class.picker) {
				if($type(_class.prefillDate) == 'object' && _class.getInputDate(_class.prefillDate)) _class.pick(_class.prefillDate, true);
				else if(_class.prefillDate == true) _class.pick(JSON.decode(_class.label.getProperty('date')), true);
			}
		}, _container);
	},
	
	initializeCalendarFunctions: function() {
		this.resetArrows();
		
		//Retrieve data (label, timestamp etc) which are stored as a Json string in the table attribute summary
		var vars = JSON.decode(this.mainLoader.getElement('table').getProperty('summary'));
		var _class = this; 
		
		//Change the label
		this.label.removeClass('noHover').set('html', vars.label)
			.onclick = vars.parent ? function() { _class.u(vars.parent, 'ts=' + vars.ts + '&parent=' + vars.current, function() { _class.fade() }) } : null;
			
		//Hide arrows if necessary and add arrow click events
		if(vars.hide_left_arrow) this.hideLeftArrow();
		else if(vars.hide_right_arrow) this.hideRightArrow();
		
		this.arrowLeft.onclick  = function() { _class.u(vars.current, 'ts=' + vars.pr_ts, function() { _class.slideLeft() }) }
		this.arrowRight.onclick = function() { _class.u(vars.current, 'ts=' + vars.nx_ts, function() { _class.slideRight() }) }		
		
		//Add cell click events
		var clickables = this.mainLoader.getElements('td');
		switch(vars.current) {
			case 'month':
				if(this.picker) {
					clickables.each(function(_clickable) {
						_clickable.onclick = function() { 
							_class.pick(JSON.decode(_clickable.getProperty('date')));
							_class.mainLoader.getElements('td').each(function(_clickable) { _clickable.removeClass('selected') });
							this.addClass('selected'); 
						}
					});
				}
				break;
			case 'year':
				clickables.each(function(_clickable) {
					//marko
					if (!_class.monthselect)
						_clickable.onclick = function() { _class.u('month', 'ts=' + _clickable.getProperty('ts'), function() { _class.fade() }) }
					else{
						_clickable.onclick = function() { 
							_class.pick(JSON.decode(_clickable.getProperty('date')));
							_class.mainLoader.getElements('td').each(function(_clickable) { _clickable.removeClass('current') });
							this.addClass('current'); 
						}
					}
				});
				break;
			case 'decade':
				this.label.addClass('noHover');
				clickables.each(function(_clickable) {
					_clickable.onclick = function() { _class.u('year', 'ts=' + _clickable.getProperty('ts') + '&m_ts=' + _clickable.getProperty('m_ts'), function() { _class.fade() }) }
				});
				break;
		}
	},
	
	//Ajax updater function which handles all requests
	u: function(_url, _pars, _onComplete, _id) {
		if(!this.loading && !this.transitioning) {
			var _class = this;
			this.loading = true;
			var element = $(_id ? _id : this.tempLoader);
			_pars += '&picker=' + (this.picker ? 1 : 0) + '&startMonday=' + (this.startMonday ? 1 : 0) + '&style=' +  this.style;
			if(this.picker && this.getInputDate()) _pars += '&pickedDate='+ this.getInputDate();
			new Request({ method: 'post',
						  url: this.filePath + _url + '.php',
						  onComplete: function(data) { element.set('html', data); _onComplete(); _class.loading = false; }
						}).send(_pars);
		}
	},
	
	slideLeft: function() {
		var _class = this;
		this.transitioning = true;	
		this.tempLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition }).tween('margin-left', [-164, 0]);
		this.mainLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition, onComplete: function() { _class.transitioning = false } })
			.tween('margin-left', [0, 164]);
		this.switchLoaders();
	},
	
	slideRight: function() {
		var _class = this;
		this.transitioning = true;
		this.mainLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition }).tween('margin-left', [0, -164]);
		this.tempLoader.setStyle('opacity', 1).set('tween', { duration: this.slideDuration, transition: this.transition, onComplete: function() { _class.transitioning = false } })
			.tween('margin-left', [164, 0]);
		this.switchLoaders();
	},
	
	fade: function(overRuleTrans) {
		var _class = this;
		this.transitioning = overRuleTrans ? false : true;
		this.tempLoader.setStyles({'opacity': 0, 'margin-left': 0});
		this.mainLoader.set('tween', { duration: this.fadeDuration, transition: this.transition}).fade('out');
		this.tempLoader.set('tween', { duration: this.fadeDuration, transition: this.transition, 
			onComplete: function() { 
					_class.tempLoader.setStyles({'opacity': 1, 'margin-left': -999});
					_class.transitioning = false;
				} 
			}).fade('in');
		this.switchLoaders();
	},
	
	switchLoaders: function() {
		this.mainLoader = this.mainLoader.className == 'loaderA' ? this.container.getElement('div[class=loaderB]') : this.container.getElement('div[class=loaderA]');
		this.tempLoader = this.tempLoader.className == 'loaderA' ? this.container.getElement('div[class=loaderB]') : this.container.getElement('div[class=loaderA]');
		this.initializeCalendarFunctions();
	},
	
	resetArrows: function() {
		this.arrowLeft.setStyle('visibility', 'visible');
		this.arrowRight.setStyle('visibility', 'visible');
	},
	
	hideLeftArrow: function() {
		this.arrowLeft.setStyle('visibility', 'hidden');
	},
	
	hideRightArrow: function() {
		this.arrowRight.setStyle('visibility', 'hidden');
	} 
});

var vlaDatePicker = new Class({
	Extends: vlaCalendar,
	
	'separateInput': false,
	'prefillDate': true,
	'linkWithInput': true,
	'leadingZero': true,
	'twoDigitYear': false,
	'separator': '/',
	'format': 'd/m/y',
	'openWith': null,
	'alignX': 'right',
	'alignY': 'inputTop',
	'offset': { 'x': 0, 'y': 0 },
	'style': '',
	'ieTransitionColor' : '#ffffff',
	'toggleDuration': 350,
	
	initialize: function(_element, _options) {
		//Add the provided options to this object by extending
		if(_options) $extend(this, _options);
		
		this.element = $(_element);
		if(!this.element) throw 'No (existing) element to create a datepicker for specified: new vlaDatePicker(ELEMENT, [options])';
		
		//Check if the user wants multiple input
		if(this.separateInput) {
			this.element.day   = this.element.getElement('input[name='+ this.separateInput.day +']');
			this.element.month = this.element.getElement('input[name='+ this.separateInput.month +']');
			this.element.year  = this.element.getElement('input[name='+ this.separateInput.year +']');
		}
		
		//Create the picker and calendar and inject in in the body
		this.picker = new Element('div', { 'class': 'vlaCalendarPicker' + (this.style != '' ? ' ' + this.style : '') }).injectTop($(document.body));
		this.pickerContent = new Element('div', { 'class': 'pickerBackground' }).injectTop(this.picker);
		this.parent(this.pickerContent);
		
		//Add events for showing and hiding the picker
		var _class = this;
		(this.openWith ? $(this.openWith) : this.element)
			.addEvent('focus',  function() { _class.show(); })
			.addEvent('click',  function() { _class.openWith ? _class.toggle() : _class.show() })
			.addEvent('change', function() { _class.hide(); });
		
		//If the datepicker is visible an outside click makes it hide
		document.addEvent('mousedown', function(e) { if(_class.outsideHide && _class.outsideClick(e, _class.picker)) _class.hide() });
		
		//linkWithInput
		if(this.linkWithInput) {
			if(this.separateInput) {
				this.element.day.addEvent('keyup',  function() { _class.linkedUpdate() });
				this.element.month.addEvent('keyup',  function() { _class.linkedUpdate() });
				this.element.year.addEvent('keyup',  function() { _class.linkedUpdate() });
			} else {
				this.element.addEvent('keyup',  function() { _class.linkedUpdate() });
			}
		}
		
		this.visible = false;
		this.outsideHide = false;
	},
	
	//Position the picker
	position: function() {
		var top, left;
		
		switch(this.alignX) {
			case 'left':
				left = this.element.getLeft();
				break;
			case 'center':
				var pickerMiddle = this.pickerContent.getStyle('width').toInt() / 2;
				if(pickerMiddle == 0) pickerMiddle = 83;
				left = this.element.getLeft() + (this.element.getSize().x / 2) - pickerMiddle -
						((parseInt(this.pickerContent.getStyle('padding-left')) + parseInt(this.pickerContent.getStyle('padding-right'))) / 2);
				break;
			case 'right': default:
				left = this.element.getLeft() + this.element.getSize().x;
				break;
		}
		
		switch(this.alignY) {
			case 'bottom':
				top = this.getPos(this.element).y + this.element.getSize().y;
				break;
			case 'top': 
				top = this.getPos(this.element).y - parseInt(this.pickerContent.getStyle('height')) - 
					(parseInt(this.pickerContent.getStyle('padding-top')) + parseInt(this.pickerContent.getStyle('padding-bottom')));
				break;
			case 'inputTop': default:
				top = this.getPos(this.element).y;
		}
		
		if(this.isNumber(this.offset.x)) left += this.offset.x;
		if(this.isNumber(this.offset.y)) top += this.offset.y;
		
		this.picker.setStyles({ 'top': top, 'left': left });
	},
	
	show: function() {
		this.position();
		if(!this.visible) {
			this.visible = true;
			var _class = this;
			this.picker.setStyles({ 'opacity': 0, 'display': 'inline' });
			if(Browser.Engine.trident5) this.picker.setStyle('background-color', this.ieTransitionColor); //Ugly transition fix for IE7
			this.picker.set('tween', { onComplete: function() { 
					if(Browser.Engine.trident5) _class.picker.setStyle('background-color', 'transparent');
					_class.outsideHide = true; 
				}, duration: this.toggleDuration }).fade('in');
		}
	},
	
	hide: function() {
		if(this.visible) {
			this.visible = false;
			var _class = this;
			if(Browser.Engine.trident5) this.picker.setStyle('background-color', this.ieTransitionColor); //Ugly transition fix for IE7
			this.picker.set('tween', { onComplete: function() { _class.picker.setStyle('display', 'none'); _class.outsideHide = false; }, duration: this.toggleDuration }).fade('out');
		}
	},
	
	toggle: function() {
		if(this.visible) this.hide();
		else this.show();
	},
	
	pick: function(_date, noevent) {
		if(this.leadingZero) {
			if(_date.day < 10)   _date.day = '0' + _date.day;
			if(_date.month < 10) _date.month = '0' + _date.month;
		}
		if(this.twoDigitYear) _date.year = _date.year.toString().substring(2, 4);
		
		if(this.separateInput) {
			if(this.element.day)   this.element.day.set('value', _date.day);
			if(this.element.month) this.element.month.set('value', _date.month);
			if(this.element.year)  this.element.year.set('value', _date.year);
			this.hide();
		} else {
			switch(this.format) {
				case "m/d/y": this.element.set('value', _date.month + this.separator + _date.day + this.separator + _date.year); break;
				case "y/m/d": this.element.set('value', _date.year + this.separator + _date.month + this.separator + _date.day); break;
				case "y/d/m": this.element.set('value', _date.year + this.separator +  _date.day + this.separator + _date.month); break;
				case "d/m/y": default: this.element.set('value', _date.day + this.separator + _date.month + this.separator + _date.year);
			}
			this.hide();
		}
		
		if (!noevent)
			this.fireEvent("change", {target:this, date:_date });
	},
	
	getInputDate: function(_date) {
		var day, month, year;
		
		if(_date) {
			day = _date.day;
			month = _date.month;
			year = _date.year;
		} else if(this.separateInput) {
			day = this.element.day.get('value').toInt();
			month = this.element.month.get('value').toInt();
			year = this.element.year.get('value').toInt();
		} else {
			var date = this.element.get('value').split(this.separator);
			if(date.length != 3) return null;
			switch(this.format) {
				case "m/d/y": day = date[1]; month = date[0]; year = date[2]; break;
				case "y/m/d": day = date[2]; month = date[1]; year = date[0]; break;
				case "y/d/m": day = date[1]; month = date[2]; year = date[0]; break;
				case "d/m/y": default: day = date[0]; month = date[1]; year = date[2];
			}
		}
		
		if( !this.isNumber(day) || !this.isNumber(month) || !this.isNumber(year) ||	day == 0 || month == 0 || year == '0' ||
		    (this.twoDigitYear && year > 99) || (!this.twoDigitYear && year < 1979) || (!this.twoDigitYear && year > 2030) || month > 12 || day > 31 ) return null;
		
		if(this.twoDigitYear && this.isNumber(year) && year < 100) {
			year = year.toInt();
			if(year < 10) year = '200'+  year;
			else if(year < 70) year = '20'+  year;
			else if(year > 69) year = '19'+  year;
			else year = new Date().getFullYear();
		}
		
		return day +'/'+ month +'/'+ year;
	},
	
	//This function is being called on keyup event if linkWithInput is set to true and when a date is picked
	//If the full date is inserted the picker will change itself to that specific date (month view)
	linkedUpdate: function() {
		var _class = this;
		var date = this.getInputDate();
		if(date && this.pickedDate != date) {
			this.u('month', 'gotoPickedDate=1', function() { _class.fade(true) });
			this.pickedDate = date;
		}
	},
	
	outsideClick: function(_event, _element) {
		var mousePos = this.getMousePos(_event);
		var elementData = _element.getCoordinates();
		return (mousePos.x > elementData.left && mousePos.x < (elementData.left + elementData.width)) &&
			   (mousePos.y > elementData.top  && mousePos.y < (elementData.top + elementData.height)) ? false : true;
	},
	
	getMousePos: function(_event) {
		if(document.all) {
			return { 'x': window.event.clientX + window.getScrollLeft(),
					 'y': window.event.clientY + window.getScrollTop() };
		} else {
			return { 'x': _event.page['x'],
					 'y': _event.page['y'] };
		}
	},
	
	isNumber: function(_number) {
		if(_number == '') return false;
		return (_number >= 0) || (_number < 0) ? true : false;
	},
	
	//Retrieving positition funtions (like getCoordinates, getTop etc) don't seem to return correct values in some situations in mootools 1.2; 
	//Opera returns wrong values, IE returns too small values. This function returns the correct coordinates.
	getPos: function(_element) { 
		var x, y = 0;
		if(_element.offsetParent) {
			do {
				x += _element.offsetLeft;
				y += _element.offsetTop;
			} while(_element = _element.offsetParent);
		} else if(_element.x) {
			x += _element.x;
			y += _element.y;
		}
		return { 'x': x, 'y': y };
	}
});
/* ************************************************************************************* */
/* ************************** Toolbar ************************************************** */
/* ************************************************************************************* */

activeTool = null;


function toolClick(toolName, toolObj)
{
	if (activeTool == toolObj)
		return;
		
	if (activeTool)
		activeTool.style.backgroundPosition = "0px 0px";
		
	
	fn.setTool(toolName);
	activeTool = toolObj;
}

function setToolEvents(toolName, obj, toggle)
{
	if (toggle && !obj.onclick)
		obj.onclick = function(){
			toolClick(toolName, obj);
		}

	obj.onmouseout = function(){
		if (activeTool != obj)
			obj.style.backgroundPosition = "0px 0px";
	}
}

function toolOver(toolName, obj, toggle)
{
	// prvi put inic. evente	
	if ( !obj.onclick || obj.id == 'activeTool' )
	{
		obj.id = toolName;
		setToolEvents(toolName, obj, toggle);
	}

	obj.style.backgroundPosition = "-16px 0px"; 
}

function toolOverY24(obj)
{
	if (!obj.toolData.toggleObj || (obj.toolData.toggleObj.activeTool != obj))
	obj.style.backgroundPosition = "-20px 0px"; 
}

function setToolEventsY24(obj,data)
{
	if (!obj.onclick)
		obj.onclick = function(){
			toolClickY24(this,data);
		}

	obj.onmouseout = function(){
		if (!obj.toolData.toggleObj || (obj.toolData.toggleObj.activeTool != obj))
			obj.style.backgroundPosition = "0px 0px";
	}
}

function toolClickY24(toolObj)
{
	if (toolObj.toolData && toolObj.toolData.onClick)
	toolObj.toolData.onClick();
	
	if (toolObj.clicked) return;
	toolObj.clicked = true;
//	if (activeTool == toolObj)
	//	return;
		
	if (toolObj.toolData.toggleObj && toolObj.toolData.toggleObj.activeTool)
	{
		toolObj.toolData.toggleObj.activeTool.style.backgroundPosition = "0px 0px";
		toolObj.toolData.toggleObj.activeTool.clicked = false;
	}
	if (toolObj.toolData.toggleObj)
		toolObj.toolData.toggleObj.activeTool = toolObj;
//	if (activeTool)
	  //activeTool = toolObj;
	 if (toolObj.toolData.thirdstate)
		toolObj.style.backgroundPosition = "-40px 0px";
		
	
	//fn.setTool(toolName);
	//activeTool = toolObj;
}

function setupToolIcon(obj)
{
	var o = $(obj.id);
	o.toolData = obj;
	o.addEvent('mouseover', function(evt){
			toolOverY24(o);	
	});	
	
	setToolEventsY24(o,obj);
}


function measureTool(obj)
{
	//canvas.add("measure_line");
	
	toolClick('MeasureTool', obj);
}

// ********************************************************************************************************
currentRule = 1;
selectedNodeId = null;
treeo = null;
var tree2 = null;
messages_mini_datagrid = null;

var init_route = 1;

var treeData = new Array();
var treeData_map = new Array();

function treeClick2(data)
{		
	if (!data.id || data.id < 0) return;
	selectedNodeId = data.id;	
	showInfo(data.id);

	
	console.log("tclick2");
	
	//selectTab(1);
	
	//console.log(data);
	//tree.select(data);
}


function treeClick(data)
{		
	if (!data.id || data.id < 0) return;
	selectedNodeId = data.id;	
	showInfo(data.id);

	console.log("tclick");
	
	selectTab(1);
	
	//console.log(data);
	//tree.select(data);
}

function chboxClick(data)
{
	console.log(data);
}

function treeTestFunc()
{
	alert(12);
}

function loadPoi(p,force_active)
{	
	if (p.marker_id)
	marker.removePoi(p.marker_id);	
	
	if (p.marker_icon && !force_active)
		p.marker_id = marker.loadPoi(p.x,p.y,"/images/icons/"+p.marker_icon,p.device_id,true);
	else
		p.marker_id = marker.loadPoi(p.x,p.y,"/images/icons/arrow.swf?_s=60&_c1=0x70D71C&_c2=0x96E15B&_c3=0x005500",p.device_id,true);
	
	var status_marker_info_checked = $('status_marker_info').checked;	
	if (status_marker_info_checked)
					populateMarkerInfoWindow(p);
}

function treeCheckboxClick(data)
{		
	if (!follow_moving_marker_map) return;
//	console.log(data);	
	if (data)
	{
		if (data.parent && data.parent.div.checkbox.checked)
		treeo.setNodeCheck(data.parent.id,false);
	  
	  if (!data.parent && data.id)  
	  	treeo.setNodeCheck(null,false);
  }
 			
	var follow_moving_marker_new = new Array();
	var status_marker_info_checked = $('status_marker_info').checked;
	var l = getCheckedList();
	//console.log(l);
//console.log("checkDeviceActivity_data",checkDeviceActivity_data);
		for (var i=0; i < checkDeviceActivity_data.length;i++) 		
		{	
			var k = "c"+checkDeviceActivity_data[i].device_id;
			if (checked_items_list[k])						
			{		
				var p = checkDeviceActivity_data[i];
				
				if (!follow_moving_marker_map[k])						
				{										
					loadPoi(p);					
				
				}
				checkDeviceActivity_data[i] = p;								
				follow_moving_marker_new.push(p);														
			}
			
		
		}

	var follow_moving_marker_map_new = new Array();										
	
	follow_moving_marker_new.each(function(el) {
		follow_moving_marker_map_new["c"+el.device_id] = el;						
	});			
	
	follow_moving_marker.each(function(el){
		//console.log(el.device_id+" "+follow_moving_marker_map_new["c"+el.device_id]);
		//follow_moving_marker_map_new["c"+el.device_id]
		//console.log("bla "+el.last_data);
	});
	
	
	follow_moving_marker.each(function(el) {
		if (!follow_moving_marker_map_new["c"+el.device_id])
		{			
			if (el.marker_info)
			marker.removePoi(el.marker_info);	
			
			marker.removePoi(el.marker_id);				
			
			if (follow_moving_marker_map["c"+el.device_id].markdata)
			{
				var m = follow_moving_marker_map["c"+el.device_id];
				canvas.remove(m.markdata.shape);
				m.markdata.data.length = 0;
				m.markdata.data = null;
				m.markdata = null;
			}
		}
	});	
	
	follow_moving_marker = follow_moving_marker_new;
	follow_moving_marker_map = follow_moving_marker_map_new;
	if (checkDeviceActivity_data[0] && regata && !dos)
	{
		//alert(checkDeviceActivity_data[i].id);
		treeClick2(checkDeviceActivity_data[0].treeNode);
		//tree.select(checkDeviceActivity_data[0].treeNode);
	}
	
	if (tracing)
		mod_query.followGPSTrace();
															
}

function removeclick()
{
	treeo.remove(4);
}

function changeclick()
{					
	treeo.change({id:1, category:'stand', text:'Kamion 1.1.', buttons: buttons2});
}

function sortclick()
{					
	treeo.sort({field: 'data.f1', category: 'active'}); //'active'
}


function nodeLabelFunction(node)
{					
	var x = node.div.text;
	x.empty();
	//x.appendText(node.text);
	
	//var span = new Element('span', {html:node.data.time});
		
	x.innerHTML = '<span>'+node.text+'</span> <a href="#" style="font-size:9px;">'+node.data.text_right+'</a>';
}

var treeMainCat = new Array();

function setTree(rule)
{			  
	if (dos)
	{
		sortMode = "dos_avg_speed";
		sortDirection = -1;
	}
  currentRule = rule;
	var catNodes2 = new Array();
	var r = rules[currentRule];
	
	for (var i = 0; i < r.length; i++)
	{						
		catNodes2.push({property:{name:lang[r[i].name],id:'c'+r[i].id},data:{basename:lang[r[i].name]},state:{open:true}});
	}
	
	if (tree2)
		getCheckedList();
		
		Mif.Tree.Node.implement({
	
		switchSelect: function(state){
			this.tree[state ? 'select' : 'unselect'](this);
		}
		
	});

	
  tree2 = new Mif.Tree({
		container: $('mymiftree'),// tree container
		forest: true,

		initialize: function(){
			this.initCheckbox('deps');	
			//this.initSortable();	
			new Mif.Tree.KeyNav(this);
			
			var storage=new Mif.Tree.CookieStorage(this);
			var switchStorage=new Mif.Tree.CookieStorage(this, {event: 'switch', action: 'switch'});
			var selectStorage=new Mif.Tree.CookieStorage(this, {event: 'selectChange', action: 'switchSelect'});
			/*
			this.addEvent('load', function(){
				storage.restore();
				switchStorage.restore();
				selectStorage.restore();
				//alert(storage);
			}).addEvent('loadChildren', function(){
				storage.restore();
				switchStorage.restore();
				selectStorage.restore();
			});
			*/

			
		},
		types: {// node types
			root:{
				openIcon: 'mif-tree-geotrag-root-icon',//css class open icon
			},
			folder:{
				openIcon: 'mif-tree-open-icon',//css class open icon
				closeIcon: 'mif-tree-close-icon'// css class close icon
			}
		},
		dfltType:'folder',//default node type
		height: 22,//node height
		onCheck: function(node){
			//console.log("node",node);
			if ( (node.data && !node.data.dontupdate) || !node.data)
			treeCheckboxClick();
			//$('log').adopt(new Element('li').set('html', node.name+' checked'));	
		},
		onUnCheck: function(node){
			//console.log("node1",node);
		if ( (node.data && !node.data.dontupdate) || !node.data)
			treeCheckboxClick();
			//$('log').adopt(new Element('li').set('html', node.name+' unchecked'));
		}

	});

	var json=[
		{
			"property": {
				"name": gClient
			},
			"state": {
						"open": true
					},
			"type":"root",
			"children": catNodes2
		}
	];
	
	// load tree from json.
	tree2.load({
		json: json,
	});
	
	tree2.addEvent('select',function(node){
		treeClick(node);
	});
	

		//console.log("ch",this.root.childrea);
		
		tree2.root.children[0].children.each(function(el){
		//console.log("yyy",el);
		treeMainCat[el.id] = el;

		});

	  //tree2storage = new Mif.Tree.CookieStorage(tree2);

		if (checkDeviceActivity_data)
			parseDeviceActivity();
		else
			checkDeviceActivity();	
			
		resize();	
		
		if (!tracing)
		
		$('globalTime').innerHTML = formatTimeInfo((new Date())/1000);


	

	//alert(1);
//console.log(tree.root.children,tree.root.getChildren().length);


				
}

var used_pallete_color = 0;

var pallete = [0x32CD32,0xFF1493,0x0000FF,0xF0E68C,0x8B4513,0x00FF00,0xFF0000,0x00FFFF,0xFFFF00,0xA52A2A,0x008000,0xFF00FF,0x000080,0xFFA500,0xFA8072,0x008080,0x800080,0x4682B4,0xFFD700,0xD2691E,0x808000,0xDA70D6,0x7B68EE,0xADFF2F,0xBC8F8F,0x00FF7F,0xFF4500,0x708090,0x000000,0x808080];


function setDeviceActivity(p,cr,isVisible)
{
		/*
		if (treeData["c"+p.device_id] && 0)
		{
		   treeData["c"+p.device_id].timestamp = parseInt(p.timestamp);
			 treeData["c"+p.device_id].covered_dist = parseFloat(p.covered_dist);		
			 var p = treeData["c"+p.device_id];
			 if (isVisible || p.treeNode.parent.div.checkbox.checked)
   				p.treeNode.div.checkbox.checked = true;	
   		
			 return;
		}
		*/

		var i = p.device_id;
		p.rules = new Array();
		if (p.id*1 > checkDeviceActivity_last_id)
				checkDeviceActivity_last_id = p.id*1;
		//if (!$('status_'+i)) return;
		
		//var s = $('status_'+i);
		
		var v = p.dt;
		
		h = "";
		m = "";
		day = "";		   
			if (v > 60)
			{
				if (v < 3600)
					m = parseInt(v/60)+" min";
				else
				if (v < 86400)
				{		
					h = parseInt(v/3600)+" h";
					m = parseInt((v % 3600)/60)+" min"		
				}
				else
				{
					d = parseInt(v/86400);
					v0 = v;
					day = d+" dan";					
					if (d > 1) day += "a";
					
					if (d == 0)
					{
						v += " ";
						h = parseInt((v0 % 86400)/3600);
						if (h > 0)
							h = h+" h";
					}

				}
			}
			//s.innerHTML = "";
			var buttons = new Array();
			var k = -1;
			var text_right = "";
			var ce = 0;
		
			for(var e=0; e < p.r.length; e++)
			{	
				i = p.r[e][0]*1;								
				v = p.r[e][1]*1;
				var lab = rules[i][v].label;
				tooltip = lang[rules[i][v].name];
			
				if (!lab)
				{
					lab = "";
				}
				else
				{				
					lab = lab.replace("%hours",h);
					lab = lab.replace("%mins",m);
					lab = lab.replace("%days",day);
				}
				
				if (currentRule*1 == i)
				{
					ce = e;
					text_right = lab;
					continue;
				}
				else
				if (lab)
					tooltip += " - "+lab;
				
				if (i == 1)
				text_right = lab;
	
				if (rules[i][v].icon)
				buttons.unshift({icon:'/include/omf/omtree/icons/'+rules[i][v].icon, tooltip:tooltip, text:lab});
				
				p.rules[e] = rules[i][v];
				//s.innerHTML += lab+" ";
			}			
			
			if (p.mark)
				txt = p.mark;
			else
				txt = p.device_id;
		 	
		 //	p.treeNode = treeo.insert({category:'c'+p.r[ce][1], selected:(p.device_id == selectedNodeId), text:txt, id:p.device_id, buttons:buttons, data:{ text_right:text_right}, labelFunction:nodeLabelFunction, onCheckboxClick:treeCheckboxClick});					
		 	//console.log(treeMainCat, treeMainCat['c'+p.r[ce][1]]);
		 
		 	
		 	//console.log(tree.roo
		 	
		 	var hue = Math.round( Math.random()*359 );
    
			var bordercolor = $HSB(hue, 80, 100).join();
			var color = $HSB(hue, 20, 100);

			var c = parseInt(color[0].toString(16)+color[1].toString(16)+color[2].toString(16),16);
			var chex = p.tragColor.toString(16);
			while (chex && chex.length < 6) chex = "0"+chex;
							
							/*
		 	p.treeNode.div.checkbox2.setStyle("backgroundColor","#"+ chex);   	
		 	
		 if (regata || leavemark)
		 		p.treeNode.div.checkbox2.setStyle("display","block");
		 	
   		p.treeNode.div.checkbox2.setStyle("borderColor","#555");  
   		*/
   		 var edata = {text_right:text_right};
   		 
   		 if (regata || leavemark)
   		 {
   		 	edata.color = "border:1px solid #555;background-color:#"+chex;
   		 }
   		
   		 if (!treeData["c"+p.device_id])
   		 {   	
	   		 var newnode = new Mif.Tree.Node({
					parentNode: null,
				  tree: tree2},
				  {
				   property:{name:txt, id:p.device_id, openIconUrl:'/include/omf/omtree/icons/'+rules[i][v].icon, closeIconUrl:'/include/omf/omtree/icons/'+rules[i][v].icon},
				  data:edata	  
							 
				  });   					
	   		 tree2.add(newnode, treeMainCat['c'+p.r[ce][1]], 'inside');
	   		 
	   		// console.log(treeMainCat['c'+p.r[ce][1]],newnode);
	   		 
	   		if (checked_items_list["c"+p.device_id] || treeMainCat['c'+p.r[ce][1]].state.checked == "checked")
	   		{
	   			
	   			newnode.data.dontupdate = 1;	   			
	   			newnode["switch"]("checked");
	   			newnode.data.dontupdate = 0;
	   		}
	   		 
	   		 p.treeNode = newnode;		 	   		   
   		 } 
   		 else
   		 {
   		 	p.treeNode = treeData["c"+p.device_id].treeNode;
   		 	p.treeNode.data.text_right = text_right;   
   		 	//Mif.Tree.Draw.update(p.treeNode);
   		  //console.log(p.treeNode.parentNode.id,treeMainCat['c'+p.r[ce][1]].id);
   		  //p.treeNode.getDOM('name-small').set('html', text_right);
   		  if (p.treeNode.parentNode.id != treeMainCat['c'+p.r[ce][1]].id)
   		  {
   		  	tree2.move(p.treeNode, treeMainCat['c'+p.r[ce][1]], "inside");
   		  }
   		 }   		   		   		      				   		
   		//if (isVisible || p.treeNode.getParent().checked)
   		//p.treeNode.switch("checked");
   		
   		//console.log(p.treeNode.div.checkbox.checked,p.treeNode.parent.div.checkbox.checked,isVisible);   		   		
   		
   		treeData["c"+p.device_id] = p;
   		treeData_map.push(p.device_id);
   		//console.log(p.max_timestamp,p.max_covered_dist);
   		if (p.max_timestamp)
 			{
 				treeData["c"+p.device_id].timestamp = parseInt(p.max_timestamp);
 				treeData["c"+p.device_id].covered_dist = parseFloat(p.max_covered_dist);
 			}
 			else
 			{
 				treeData["c"+p.device_id].timestamp = parseInt(p.timestamp); 	 			
				treeData["c"+p.device_id].covered_dist = parseFloat(p.covered_dist);			
			}
   		
			return p;			
}

var checkDeviceActivity_timer = null;
var checkDeviceActivity_data = null;
var checkDeviceActivity_last_id = 0;

function parseDeviceActivity()
{
		var first_time = 0;
		//console.log("d1");
		//console.log("map",treeData);
		var dev_id_present = new Array();;
		for (var i=0; i < checkDeviceActivity_data.length;i++) 		
		{
			dev_id_present[checkDeviceActivity_data[i].device_id] = 1;		
		}
		for (var i in treeData)
		{
			//console.log("t",treeData[i]);
			if (treeData[i].treenNode)
			{
				if (dev_id_present[treeData[i].device_id])
				{
					treeData[i].treenNode["switch"]("uncheck");
					treeData[i].treenNode.remove();				
				}
		  }
				
		}
		dev_id_present.length = 0;
		if (treeData_map.length == 0 || 1)
		{
			treeData_map.length = 0;
			first_time = 1;
		  //treeo.disable();	
		  	  
		 // var cr = $('current_rule').options[$('current_rule').selectedIndex].value;
		
			var r = rules[currentRule];
			
			for (var i = 0; i < r.length; i++)	
			{	
				//treeo.clear({category:'c'+r[i].id});								
				//treeo.setNodeCheck("c"+r[i].id,checked_items_list["cc"+r[i].id]);			
			}
		}	
//	console.log("d2");
		var shouldBeVisible = false;
		for (var i=0; i < checkDeviceActivity_data.length;i++) 		
		{									
			
			if (follow_moving_marker_map && !follow_moving_marker_map["c"+checkDeviceActivity_data[i].device_id])
			shouldBeVisible = true;
//		console.log("d21");
			//var checkForTreeData = treeData["c"+checkDeviceActivity_data[i].device_id];
			setDeviceActivity(checkDeviceActivity_data[i],null,checked_items_list["c"+checkDeviceActivity_data[i].device_id]);						
	//	console.log("d22");
			//console.log("color2 "+checkDeviceActivity_data[i].tragColor+" "+follow_moving_marker_map["c"+checkDeviceActivity_data[i].device_id].tragColor);
			//if (!checkForTreeData || 1)
			if (1)
			{
				if (follow_moving_marker_map && follow_moving_marker_map["c"+checkDeviceActivity_data[i].device_id])
				populateMarkerInfoWindow(checkDeviceActivity_data[i]);		
			}
		}
	//console.log("d3");
		if (first_time)
		{
			//treeo.expand();				
			//treeo.enable();
			//tree.setCheckedList(checked_items_list);												
		}
	
		if (!follow_moving_marker)
		{  				
			follow_moving_marker = new Array();
			follow_moving_marker_map = new Array();  		
			shouldBeVisible = true;			
		}
		
		//console.log("d4");
		afterTreeLoad();
		
		//follow_current_sec=0;
		//followGPS(true);
		treeSort();
	
		
		//console.log("d5");
	  if (shouldBeVisible)	
			treeCheckboxClick();	
}

function checkDeviceActivity()
{

	  if (checkDeviceActivity_timer)
	  window.clearTimeout(checkDeviceActivity_timer);
	  
		var jsonRequest = new Request.JSON({url: "/modules/tree/db/status.php", onComplete: function(d)
  	{	 
  			if (!d || !d.data) return;
  			
  			 if (d && d.newnch)
			   {
			  	 reloadGeotrag();
			  	 return;
			   }
			   
			   global_timestamp = d.t*1;
			   
			   //console.log("ajd1");
			   
			   // poruke
			  var n = 0;
			  if (messages_mini_datagrid && messages_mini_datagrid.options && messages_mini_datagrid.options.data)
			  {
			  				   //console.log("ajd101");
			  	n = messages_mini_datagrid.options.data.length; 
			  				   //console.log("ajd102");
			  }
			  
			   //console.log("ajd10");
			  if (d.msg && n > 0)
			  {			  		
			  	
			   //console.log("ajd123");	 					 
				 	var o = messages_mini_datagrid.getDataByRow(0);
				 	if (d.msg[0].id != o.id)
				 	{
				 		messages_mini_datagrid.refresh();
				 	}
				 	else
				 	{				 
				 		var nn = d.msg.length;
					 	for (i = 0; i < n; i++)
					 	{
					 		var o = messages_mini_datagrid.getDataByRow(i);
					 		if (o.status == 2) continue;
					 		if (!o) break;
					 		
					 		for (k = 0; k < nn; k++)
					 		{
					 			if (d.msg[k].id == o.id && d.msg[k].status == 2)
					 			{
					 				o.status = 2;
					 				messages_mini_datagrid.setDataByRow(i,o);		
					 			}
					 		}					 		
					 	}
					}
			  }			
  			//console.log("ajd11");
  			if (checkDeviceActivity_data)
  			{
  				checkDeviceActivity_data = d.data;
  				follow_moving_marker = new Array();
  				for (var i = 0; i<checkDeviceActivity_data.length;i++)
  				{  				  					
  					var k = "c"+checkDeviceActivity_data[i].device_id;			
  					if (!treeData[k] || 1)
  					{
			   			checkDeviceActivity_data[i].tragColor = pallete[i % pallete.length];;			
				
	  					if (follow_moving_marker_map[k])
	  					{  					
	  						checkDeviceActivity_data[i].marker_info = follow_moving_marker_map[k].marker_info;
	  						checkDeviceActivity_data[i].marker_id = follow_moving_marker_map[k].marker_id;
	  						checkDeviceActivity_data[i].last_data = follow_moving_marker_map[k].last_data;
	  						checkDeviceActivity_data[i].traceData = follow_moving_marker_map[k].traceData;
	  						checkDeviceActivity_data[i].rules = follow_moving_marker_map[k].rules;
	  						checkDeviceActivity_data[i].markdata = follow_moving_marker_map[k].markdata;
	  						checkDeviceActivity_data[i].covered_path = follow_moving_marker_map[k].covered_path;	  					
	  						
	  						if (checkDeviceActivity_data[i].speed*1 == 0 && follow_moving_marker_map[k].last_data && follow_moving_marker_map[k].last_data.speed)
	  						checkDeviceActivity_data[i].speed = follow_moving_marker_map[k].last_data.speed;
	  						
	  						//console.log("last_marker_data "+follow_moving_marker_map[k].marker_icon+" "+checkDeviceActivity_data[i].marker_icon);
	  						if (follow_moving_marker_map[k].marker_icon != checkDeviceActivity_data[i].marker_icon)
	  						loadPoi(checkDeviceActivity_data[i]);
	  						
	  						//console.log("last_marker_data "+follow_moving_marker_map[k].last_data+" "+checkDeviceActivity_data[i].speed+" "+follow_moving_marker_map[k].last_data.speed);
	  						
	  						if (follow_moving_marker_map[k].hasVariableData)
	  							checkDeviceActivity_data[i].hasVariableData = true;
	  						
	  						follow_moving_marker_map[k] = checkDeviceActivity_data[i];  					  					
	  						follow_moving_marker.push(checkDeviceActivity_data[i]);
	  					}
  					}
  				}
  				
  			}
  			else  		
  			{	  				
  				checkDeviceActivity_data = d.data;
  				for (var i = 0; i<checkDeviceActivity_data.length;i++)
  				{
  					var k = "c"+checkDeviceActivity_data[i].device_id;			
		   			checkDeviceActivity_data[i].tragColor = pallete[i % pallete.length];;
		   		}
  			}
 
//			   console.log("ajd2");
  			parseDeviceActivity();			
 
	//		   console.log("ajd3");
  			/*  			
  			var dd = new Date();
				global_timestamp = Math.round(dd.getTime()/1000);
				*/
				$('globalTime').innerHTML = formatTimeInfo(global_timestamp);	  			
				
				//treeSort();  			
				
//				console.log("checkdev");

				checkDeviceActivity_timer = window.setTimeout(checkDeviceActivity,60000);

		}}).get({'_nch':_nch,'last_activity': checkDeviceActivity_last_id, 'sort':sortMode});
}

/*
function getCheckedList_old()
{
	if (!treeo) return null;
		
	var arr = treeo.getCheckedList(true);
	//console.log(arr);
	var arr2 = new Array();
	
	for (var i = 0; i < arr.length; i++)
	{
		if (arr[i])
		arr2.push(arr[i]);
	}
	var arr = treeo.getCheckedList();	
	
	for (var i = 0; i < arr.length; i++)
	{
		if (arr[i])
		arr2.push(arr[i]);
	}

	checked_items_list = new Array();	
	for (var i = 0; i < arr2.length; i++)
	{
		checked_items_list["c"+arr2[i]] = 1;											
	}
	return arr2;
}
*/
function getCheckedList()
{
	if (!tree2) return null;
	
		var arr2 = new Array();
		
	tree2.getChecked().each(function(node){
			arr2.push(node.id);
		});

	checked_items_list = new Array();	
	for (var i = 0; i < arr2.length; i++)
	{
		checked_items_list["c"+arr2[i]] = 1;											
	}
	
	//console.log("lista ",checked_items_list);
	
	return arr2;
}

var sortMode="mark";


function setSortMode(sort1)
{
	sortMode = sort1;
	if (sort1 == "mark") sortDirection = 1;
	else
	if (sort1 == "timestamp" || sort1 == "dos_avg_speed") sortDirection = -1;
	treeSort();
	//checkDeviceActivity();
}

function treeTest()
{
	treeSort();
	return;
	//var len = treeData.length;
	//console.log("len",len);
	//for (var i=0; i < len; i++)
	//{
		//console.log(i,treeData[i]);
	//}
	treeo.disable();
	var n = treeData["c7040"];
	//console.log(n.treeNode);
	//console.log(n.treeNode.div.main);
	var p = n.treeNode.div.main.getParent();
	
/*
	var c = n.treeNode.div.main.clone();
	
	n.treeNode.div.main.dispose();
	c.inject(p);
	*/
	var p = n.treeNode.parent;
	var o = n.treeNode.options;
	var color;
	if (regata || leavemark)
 	 color = n.treeNode.div.checkbox2.getStyle("backgroundColor");   	
 	
 	var check = n.treeNode.div.checkbox.checked;
	
//	console.log(n);
	n.treeNode.remove();
	
	//o.category = 'c0';

	n.treeNode = treeo.insert(o);
	
	if (regata || leavemark)
	{
		 n.treeNode.div.checkbox2.setStyle("display","block");
		 n.treeNode.div.checkbox2.setStyle("backgroundColor",color);  
		 n.treeNode.div.checkbox2.setStyle("borderColor","#555"); 
	}
		 	   	    		
  n.treeNode.div.checkbox.checked = check;
	
		treeo.enable();
	//console.log(p);

	
	//n.treeNode.parent.adopt(n.treeNode.parent);
}

var sortProperty = "mark";

var sortDirection = 1;

function tree2sortfunction1(aa, bb)
{	
  var a = treeData["c"+aa.id];
	var b = treeData["c"+bb.id];
	//console.log(a,b,sortProperty,a[sortProperty],b[sortProperty],sortDirection);
	if (a[sortProperty] < b[sortProperty]) return -sortDirection;
  if (a[sortProperty] > b[sortProperty]) return sortDirection;
  return 0;
}


function treesortfunction(aa, bb)
{	
	var a = treeData["c"+aa];
	var b = treeData["c"+bb];
  if (a[sortProperty] < b[sortProperty]) return -sortDirection;
  if (a[sortProperty] > b[sortProperty]) return sortDirection;
  return 0;
}

function treesortfunction2(aa, bb)
{	
	var a = treeData["c"+aa];
	var b = treeData["c"+bb];
  if (a[sortProperty]*1 < b[sortProperty]*1) return -sortDirection;
  if (a[sortProperty]*1 > b[sortProperty]*1) return sortDirection;
  return 0;
}

function treesortfunction_extra(aa, bb)
{	
	var a = treeData["c"+aa];
	var b = treeData["c"+bb];	
	//a.extra_int = 0;
	//b.extra_int = 0;
	var d1 = a.covered_dist*(1+a.extra_int/(a.timestamp-time_from));
	var d2 = b.covered_dist*(1+b.extra_int/(b.timestamp-time_from));
	
	//if (d1 < 0) d1 += 100000000000000;
	//if (d2 < 0) d2 += 100000000000000;
  if (d1 < d2) return 1;
  if (d1 > d2) return -1;
  return 0;
}


var sortTimer = null;

function treeSort()
{			
	console.log("treeSort",global_timestamp);
	var tmp = global_timestamp;
	/*
	if (max_timestamp2 && sortMode == "order")
	{
		for (var k =0; k < treeData_map.length; k++)
		{
			var n = treeData["c"+treeData_map[k]];
			if (n.max_timestamp)
			{
				n.covered_dist *= max_timestamp2/n.max_timestamp;
				n.timestamp = n.max_timestamp;				
			}
			else
			{
				//n.covered_dist *= max_timestamp2/n.timestamp;
			}
			
		}
		global_timestamp = max_timestamp2;
	}
	*/
	sortProperty = sortMode;
	
	//treeo.disable();
	/*
	
	if (sortMode == "order")
	{
		sortProperty = "covered_dist";
		sortDirection = -1;
		treeData_map = treeData_map.sort(treesortfunction2);	
	}
	else
	if (sortMode == "order2")
	{
		sortDirection = -1;		
		treeData_map = treeData_map.sort(treesortfunction_extra);			
	}
	else
	if (sortMode == "covered_dist")
	{
		sortDirection = -1;
		treeData_map = treeData_map.sort(treesortfunction2);
	}
	else
	{
		sortDirection = 1;
		treeData_map = treeData_map.sort(treesortfunction);			
	}
	
	var n0 = treeData["c"+treeData_map[0]];
	var t;
	var s;
	
	if (sortMode == "order2")
	{
		t = n0.timestamp-time_from+n0.extra_int*1;
		s = n0.covered_dist*(1+n0.extra_int/(n0.timestamp-time_from));;
	}
	else
	if (sortMode == "order")
	{
		t = n0.timestamp-time_from;
		s = n0.covered_dist;
	}
	
	if (regata && !time_from)
	{
		time_from = 1258149600;
	}
	*/
	
	 tree2.root.children[0].children.each(function(el)
	 {
	 	el.data.count = 0;
	});
	var dos_max_avg_speed = 0;
	var dos_max_avg_speed_path = 0;
	var dos_max_avg_speed_time = 0;
	if (sortMode == "dos_avg_speed")
	{
		
		for (var k = 0; k < treeData_map.length; k++)
	  {											
			var n = treeData["c"+treeData_map[k]];
			
			if (!n.covered_path) n.covered_path = 0;	
			
			//console.log("p",n.covered_path);
			
			if (Math.abs(n.timestamp*1-global_timestamp*1) < 1000)
			{		
				n.dos_avg_speed = n.covered_path/(global_timestamp-time_from-n.dos_offset);
				n.dos_time = global_timestamp-time_from-n.dos_offset;
				
				if (n.dos_avg_speed > dos_max_avg_speed) {
					dos_max_avg_speed = n.dos_avg_speed;
					dos_max_avg_speed_time = n.dos_time;
				}
	   }
	   else
	   	n.dos_avg_speed = 0;
		}
	}

	for (var k = 0; k < treeData_map.length; k++)
	{											
			var n = treeData["c"+treeData_map[k]];
			
			var dt = global_timestamp*1-n.timestamp*1;
			
			var o = n.treeNode.parentNode;
			
			var newcat = o.id;						
						
			if (dt >= 180 && !parseInt(n.connected))
				newcat = 'c2';
			else
			if (dt >= 180 && parseInt(n.connected))
				newcat = 'c1';
			else
				newcat= 'c0';
			
			if (sortMode == "dos_avg_speed")
		  {
		  	if (n.dos_avg_speed != dos_max_avg_speed)
		  	 n.treeNode.data.text_right = "+"+formatTime3((1-n.dos_avg_speed/dos_max_avg_speed)*dos_max_avg_speed_time,3);
		  	else
		  		n.treeNode.data.text_right = formatTime3(dos_max_avg_speed_time,3);
		 	  n.treeNode.getDOM('name-small').set('html', n.treeNode.data.text_right);
	   	}
	   	else	   	
	    {
	    	if (newcat != 'c0')
	   		n.treeNode.data.text_right = formatTime(dt,4);
	   		else
	   		n.treeNode.data.text_right = "";
	   		 n.treeNode.getDOM('name-small').set('html', n.treeNode.data.text_right);
	   	}
	  
			
			//console.log(n,n.mark,n.covered_path/(n.timestamp-time_from-n.dos_offset)*3.6);
			
			//console.log(treeData_map[k],n.timestamp,n.covered_dist,global_timestamp);
			
			
			if (regata && sortMode != "timestamp")
			newcat = 'c0';
			
			if (isNaN(n.timestamp))
			{
				newcat = 'c2';
			}
			
		  if (o.id != newcat)
 		  {
 		  	tree2.move(n.treeNode, treeMainCat['c0'], "inside");
 		  }
 		  
 		  treeMainCat[newcat].data.count ++;
 		  
 		  
			
			continue;
			
//			console.log(dt,formatTime(dt,3),o.category);	
			//console.log(global_timestamp-n.timestamp);
							
			//o.category = 'c0';
		//	console.log(time_from);
		  if (sortMode == "order2")
		  {
			  if (k == 0)
				o.data.text_right = formatTime(t-n0.extra_int);
				else
				{
					var s1 = n.covered_dist*(1+n.extra_int/(n.timestamp-time_from));;
					o.data.text_right = "+"+formatTime(t-s1*t/s+n.extra_int);
				}
			}
			else
			if (sortMode == "order")
		  {
			  if (k == 0)
				o.data.text_right = formatTime(t);
				else
				{
					var s1 = n.covered_dist;
					if (n.max_timestamp  && sortMode == "order")
					{								
						o.data.text_right = "+"+formatTime(n.timestamp-n0.timestamp);
					}
					else
						if (max_timestamp2  && sortMode == "order")
						{
							o.data.text_right = "+"+formatTime(n.timestamp-n0.timestamp);
						}
						else
						o.data.text_right = "+"+formatTime(t-s1*t/s);
				}
			}
			else
			if (sortMode == "covered_dist")
			{				
				o.data.text_right = formatDist(n.covered_dist);			
			}
			else
			{
				if (o.category != "c0")
					o.data.text_right = formatTime(dt,3);			
				else
					o.data.text_right = "";
			}
		
			n.treeNode = treeo.insert(o);
			
			if (regata || leavemark)
			{
				 n.treeNode.div.checkbox2.setStyle("display","block");
				 n.treeNode.div.checkbox2.setStyle("backgroundColor",color);  
				 n.treeNode.div.checkbox2.setStyle("borderColor","#555"); 
			}
				 	   	    		
		  n.treeNode.div.checkbox.checked = check;		
		  		  		
	}
	
	 tree2.root.children[0].children.each(function(el)
	 {
	 	 el.getDOM('name').set('html', el.property.name+"&nbsp;("+el.data.count+")");
	});
	
	global_timestamp = tmp;
	//sortDirection = -1;
	//tree2.sortFunction = tree2sortfunction1;
	treeMainCat['c0'].sort(tree2sortfunction1);	
	//treMainCat['c0'].update(treeMainCat['c0']);
	Mif.Tree.Draw.children(treeMainCat['c0']);
	var s = "";
	for (var i = 0; i < treeMainCat['c0'].children.length; i++)
	{
		s += ", "+treeData["c"+treeMainCat['c0'].children[i].id].mark+" "+treeData["c"+treeMainCat['c0'].children[i].id].timestamp;
		Mif.Tree.Draw.node(treeMainCat['c0'].children[i]);
	}
	//console.log("data",s);
 //treeMainCat['c0'].drawToggle();
	//console.log(treeMainCat['c0']);
	
	//treeo.enable();
	if (tracing)
	{
		
		window.clearTimeout(sortTimer);
		if (sortMode == "covered_dist" || sortMode == "order" || sortMode == "order2")
		{		
			sortTimer = window.setTimeout(treeSort,5000);
		}
	}
}
var OmniTabs = new Class({
	Implements: [Events, Options],
		
	options: {
		
	},
	
	initialize: function(el, options){
		//this.setOptions(this.getOptions(), options);
		
		this.container = $(el);
		
		this.currentTab = 1;
		this.lastTab = 1;
	},
	
	showTab: function(tabnum){
	
		if (this.currentTab == tabnum) return;
		
		//console.log(this.currentTab+' '+tabnum);
		
		if (this.currentTab == 0)
			$('tab-header-'+this.currentTab).setStyle("display", "none");
		
		
		$('tab-header-'+this.currentTab).removeClass("activetab");
		$('tab-'+this.currentTab).hide();
		
		$('tab-header-'+tabnum).addClass("activetab");		
		$('tab-'+tabnum).show();

		this.lastTab = this.currentTab;	
		this.currentTab = tabnum;
		
		this.fireEvent("change", {tab:tabnum});			
	},
	
	showLastTab: function(){
		this.showTab(this.lastTab);
	}
});



var last_panel_width = null;

function setPanelWidth(w)
{	
	$('tabs').getElement('.tabs-container').setStyle("width",w-17);
	$('leftPanel').setStyle("width",w+"px");
	
	$('rightPanel').setStyle("left",w+"px");
	$('rightPanel').setStyle('width', window.getSize().x-(w+20));
}
var tree = null;
var tree2 = null;
var fn = null;
var marker = null;
var load_check = 2;
var last_offset = -1; 
var current_info_id = null;
var status_subpanels = new Array("ss_vehicle","ss_groups","ss_drivers","ss_companies");
var status_subpanels1 = new Array("su_user","su_company");
var protocols = new Array();
var tracing = 0;
var global_timestamp = 0;
protocols[1] = "RPTRACK01";
protocols[2] = "G200X";
protocols[3] = "Aspicore";
protocols[4] = "Aplicom";

if (!window.console)
{
	window.console = console = new Object();
	console.log = function(x) {};
}

var geotrag_f = function()
{
}

geotrag_f.prototype.setTraceMode = function()
{
		tracing = 1;
}

geotrag_f.prototype.setFollowMode = function()
{
		tracing = 0;
		follow_current_sec=0;
		followGPS(true);
		fn.setQuality("BEST"); 	
}


var geotrag = new geotrag_f();

function reloadGeotrag()
{
	//alert("Postoji nova verzija 
	window.location.href = "/?upgrade=1";
}

var getInfoRequest = new Request.JSON({url: "/data.php", onComplete: onShowInfo});

function formatTime(t,p)
{
	var f = "";
	if (t < 0) f = "-";
	
	var t = Math.abs(t);
	var days = parseInt(t / (24*3600));
	t -= days*24*3600;
	var hours = parseInt(t / 3600);
	t -= hours*3600;
	var mins = parseInt(t / 60);
	t -= mins*60;
	var sec = parseInt(t);
	
	var s = "";
	if (days > 0 && (!p || p >= 1)) 
	{	
		s += days+" dan";
		if (days > 1) s+="a ";
		else
			s+= " ";
	}
	if (hours > 0  && (!p || p >= 2)) s += hours+" h ";
	if (mins > 0  && (!p || p >= 3)) s += mins+" min ";
	if (sec > 0  && (!p || p >= 4 || s == "")) s += sec+" s ";
	
	return f+s;
}

function formatTime3(t,p)
{
	var f = "";
	if (t < 0) f = "-";
	
	var t = Math.abs(t);
	var days = parseInt(t / (24*3600));
	t -= days*24*3600;
	var hours = parseInt(t / 3600);
	t -= hours*3600;
	var mins = parseInt(t / 60);
	t -= mins*60;
	var sec = parseInt(t);
	
	if (hours < 10) hours = "0"+hours;
	if (mins < 10) mins = "0"+mins;
	if (sec < 10) sec = "0"+sec;
	return hours+":"+mins+":"+sec;
}

function formatTime2(t,p)
{
	var days = parseInt(t / (24*3600));
	t -= days*24*3600;
	var hours = parseInt(t / 3600);
	t -= hours*3600;
	var mins = parseInt(t / 60);
	t -= mins*60;
	var sec = parseInt(t);
	
	var s = "";
	if (days > 0 && (!p || p >= 1)) 
	{	
		s += days+" d ";
	}
	if (hours > 0  && (!p || p >= 2)) s += hours+" h ";
	if (mins > 0  && (!p || p >= 3)) s += mins+" m ";
	if (sec > 0  && (!p || p >= 4 || s == "")) s += sec+" s ";
	
	return s;
}
	
function showInfo(cid,dontposition)
{
	if (!follow_moving_marker_map["c"+cid]) return;


	// update poruka 
	msgdid = $('msg_device_id');
	if (msgdid)
	{
		for (var i=0; i < msgdid.options.length; i++)
		{
			if (msgdid.options[i].value == cid)
			{
				msgdid.selectedIndex = i;
				break;											
			}
		}
	}

	current_info_id = cid;	

	if ($('followOnMap1Label'))
	$('followOnMap1Label').innerHTML = "Prati odabrano ("+follow_moving_marker_map["c"+cid].mark+")";
		
	getInfoRequest.dontposition = dontposition;
	getInfoRequest.get({'_nch':_nch,'getinfo':current_info_id });

	
}

	
function onShowInfo(d)
{
	if (!d || !d[0]) return;
	if (d && d.newnch)
	{
	 reloadGeotrag();
	 return;
	}
	
	if (!this.dontposition && !follow_moving_marker_map["c"+d[0].device_id].traceData)				
		fn.setLocation(d[0].x,d[0].y); 		
		
	updateInfo(d[0]);
	//marker.loadPoi(d[0].x,d[0].y,"/images/icons/arrow.png");
	
}

function formatTimeInfo(timestamp)
{
	if (!timestamp) return "";
	var dd = new Date(); 
	dd.setTime(timestamp*1000); 	
	var mins = dd.getMinutes();
	var hours = dd.getHours();
	var month = dd.getMonth()+1;
	var year = dd.getFullYear()-2000;
	var day = dd.getDate();
	if (mins < 10) mins = "0"+mins;			
	if (hours < 10) hours = "0"+hours;			
	if (month < 10) month = "0"+month;
	if (year < 10) year = "0"+year;			
	if (day < 10) day = "0"+day;			
	
	return day+"."+month+"."+year+". "+hours+":"+mins;
}

function formatSpeedInfo(speed)
{
	var s = speed;
	if (s*1 < 0) s = 0;
	if (regata && !kmh && !dos)
	{
		s = Math.round(s/1.852*10)/10; 
    s += ' čvor</li>';
  }
  else
    s += ' km/h</li>';
  return s;
}

function formatDist(s)
{
	return Math.round(s/1.852/100)/10+" nm";
}

function updateInfo(p,smallupdate,speedup)
{

  if (!p) return;
 
	if (!smallupdate)
	{
		if (p && p.mark)
			id = p.mark;
		else
	 		id = p.device_id;
	 		
	 			 	 			 	
		$('status_dev_id_data').innerHTML = lang['tab_label_vehicle']+": "+id;
	
		if ($('t_info_company'))
		if (p.company) $('t_info_company').innerHTML = p.company; else $('t_info_company').innerHTML = "";
			
		if ($('ti_type'))
		if (p.type) $('ti_type').innerHTML = p.type; else $('ti_type').innerHTML = "";
			
		if ($('ti_model'))
		if (p.model) $('ti_model').innerHTML = p.model; else $('ti_model').innerHTML = "";
		
		if ($('ti_invno'))
		if (p.invnum) $('ti_invno').innerHTML = p.invnum; else $('ti_invno').innerHTML = "";
			
		if ($('ti_company'))
		if (p.company_name) $('ti_company').innerHTML = p.company_name; else $('ti_company').innerHTML = "";
			
		if ($('ti_regno'))
		if (p.reg) $('ti_regno').innerHTML = p.reg; else $('ti_regno').innerHTML = "";
			
		if ($('ti_driver'))
		if (p.driver_name) $('ti_driver').innerHTML = p.driver_name; else $('ti_driver').innerHTML = "";
			
		if ($('ti_extra_int'))
		if (p.extra_int) $('ti_extra_int').innerHTML = p.extra_int; else $('ti_extra_int').innerHTML = "";
			
			if ($('ti_bonitet'))
		if (p.bonitet) $('ti_bonitet').innerHTML = p.bonitet; else $('ti_bonitet').innerHTML = "";
		
			if ($('ti_kazna'))
		if (p.kazna) $('ti_kazna').innerHTML = p.kazna; else $('ti_kazna').innerHTML = "";
			
		if ($('ti_offset'))
		if (p.offset) $('ti_offset').innerHTML = p.offset; else $('ti_offset').innerHTML = "";							
			
		if ($('ti_altitude'))
		if (p.offset) $('ti_altitude').innerHTML = p.altitude; else $('ti_altitude').innerHTML = "";	
										
	}
	var m = follow_moving_marker_map["c"+p.device_id];
  
	var active = (m.marker_icon == 'arrow.swf?_s=60&_c1=0x70D71C&_c2=0x96E15B&_c3=0x005500');
	
	if ($('ti_curs'))
	$('ti_curs').innerHTML = (Math.round(360-follow_moving_marker_map["c"+p.device_id].curs+90) % 360 )+"°";

	if ($('ti_time'))
	$('ti_time').innerHTML = formatTimeInfo(p.timestamp);

	if ($('ti_speed'))
	{
		if (active)
  	$('ti_speed').innerHTML = formatSpeedInfo(p.speed,speedup);
  	else
  		$('ti_speed').innerHTML = formatSpeedInfo(0,speedup);
  }
  
  if ($('ti_ds1'))
  {
  	if (p.ds1 == 't' && active)
  		$('ti_ds1').innerHTML = '<img src="/images/sensor_g.png" />';
  	else
  		$('ti_ds1').innerHTML = '<img src="/images/sensor_r.png" />';
  }
  	 
  if ($('ti_ds2'))
  {
  	if (p.ds2 == 't' && active)
  		$('ti_ds2').innerHTML = '<img src="/images/sensor_g.png" />';
  	else
  		$('ti_ds2').innerHTML = '<img src="/images/sensor_r.png" />';
  }
  
  if ($('ti_ds3'))
  {
  if (p.ds3 == 't' && active)
  		$('ti_ds3').innerHTML = '<img src="/images/sensor_g.png" />';
  	else
  		$('ti_ds3').innerHTML = '<img src="/images/sensor_r.png" />';
  }
  
  var asmax = 3500.0;
  
  if (p.device_id == 6467)
  asmax = 1560.0;
  
  if ($('ti_as1')) 
  {
  	var f = (p.as1/asmax);
  	if (f > 1) f = 1;
  	$('ti_as1').innerHTML = (Math.round(f*100/10)*10)+" %";
  }
  if ($('ti_as2')) {
  	var f = (p.as2/asmax);
  	if (f > 1) f = 1;
  	$('ti_as2').innerHTML = (Math.round(f*100/10)*10)+" %";
  }
  if ($('ti_as3')) 
  {
  	var f = (p.as3/asmax);
  	if (f > 1) f = 1;
  	$('ti_as3').innerHTML = (Math.round(f*100/10)*10)+" %";
  }
  if ($('ti_as4')) $('ti_as4').innerHTML = p.as4;

	if (p.satellites && $('ti_satnum')) $('ti_satnum').innerHTML = p.satellites; else 
		if ($('ti_satnum'))
		$('ti_satnum').innerHTML = "";
 
  //$('status_info').innerHTML = s;
}

function showStatusSubpanel(sid,subp)
{
	if (!subp) subp = status_subpanels;

	for (var i = 0; i < subp.length; i++)
	{
		if (subp[i] != sid)
		{
			if ($(subp[i]))
			{
				$(subp[i]).setStyle("display","none");
				//$(subp[i]+"_button").setStyle("fontWeight","normal");			
			}
		}
	}
	$(sid).setStyle("display","block");
//	$(sid+"_button").setStyle("fontWeight","bold");
}

function populateMarkerInfoWindow(p)
{	
	//console.log("p",p);
	var o;
	if (p.mark)
		lab = p.mark;
	else
		lab = p.device_id;
	var txt = '<TEXTFORMAT LEADING="4"><FONT FACE="_sans" SIZE="10" COLOR="#000000" LETTERSPACING="0" KERNING="0"><P ALIGN="LEFT"><IMG SRC="/include/omf/omtree/icons/'+p.rules[1].icon+'" VSPACE="0" HSPACE="0" ALIGN="left">     '+lab+'</P>';
	
  p.hasVariableData = false;
  o = $('a_info_time');
  if (o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+formatTimeInfo(p.timestamp)+'</P>';
  }
  
  o = $('a_info_curs');
  if (o && o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+(Math.round(360-follow_moving_marker_map["c"+p.device_id].curs+90) % 360 )+"°"+'</P>';
  }
      
  o = $('a_info_speed');
  if (o && o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+formatSpeedInfo(p.speed,1)+'</P>';
  }
  
 
  
  o = $('a_info_satnum');
  if (o && o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+p.satellites+'</P>';
  }
  
  o = $('a_info_bonitet');
  if (o && o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+p.bonitet+'</P>';
  }
  
   o = $('a_info_kazna');
  if (o && o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+p.kazna+'</P>';
  }
  
   o = $('a_info_offset');
  if (o && o.checked)
  {
  	p.hasVariableData = true;
  	txt += '<P>'+o.innerHTML+': '+p.offset+'</P>';
  }
  
  
	txt += '</FONT></TEXTFORMAT>';	
	
	//if (p.hasVariableData || !p.marker_info)
	{	
		if (p.marker_info)
			marker.removePoi(p.marker_info);
	  //p.marker_info = 
	  marker.attachLabel({background:0xFFFFFF,border:0xaaaaaa,data:txt,x:20,y:-10,r:20,marker:p.marker_id });
		//p.marker_info = marker.addSimple( {x:p.x, y:p.y,background:0xffffff,border:0xaaaaaa,data:txt,offsetx:17,offsety:-12});
	}
}

function setMarkerInfoWindow()
{
	var c = $('status_marker_info').checked;
	
	if (!$('status_marker_info').checked)
	{
		follow_moving_marker.each(function(el) {
		if (el.marker_info)
		{
			marker.removePoi(el.marker_info);
			el.marker_info = null;
		}
		});	
	}
	else
	{
		follow_moving_marker.each(function(el) {
		populateMarkerInfoWindow(el);
		});	
	}
	
	/*
	follow_moving_marker.each(funtion(el) {
		alert(el.marker_id);
	});
	*/
	/*
	for (var i=0; i < checkDeviceActivity_data.length;i++) 		
	{	
		var k = "c"+checkDeviceActivity_data[i].device_id;
		if (checked_items_list[k])						
		{	
			var p = checkDeviceActivity_data[i];
				
			if (!follow_moving_marker_map[k])						
			{		
			}
		}
	}
	*/
}

function toggleMarkerItem(o)
{
	if (!o.checked)
	{
		o.checked = true;
		o.setStyle("color","#ff0000");
	}
	else
	{
		o.checked = false;
		o.setStyle("color","#000");
	}
	setMarkerInfoWindow();
}

// *********************************************************************************************
// ********************************** Date & Time pomocne funkcije *****************************
// *********************************************************************************************

function retrieveTime(cookie_name)
{
	var t = null;
	
	if (cookie_name)
		t = Cookie.read(cookie_name);
		
	if ( !t )
	{	
		var d = new Date();
		var hh = d.getHours();
		var mm = d.getMinutes();
		if (hh < 10) hh = "0"+hh;
		if (mm < 10) mm= "0"+mm;
		
		t = hh+":"+mm;
	}
		
	return t;
}

function storeTime(element, cookie_name)
{
	var obj = null;
	
	if (typeof(element) != 'object')
		obj = $(element_id);
	else
		obj = element;
		
	if ( obj )
	{
		Cookie.write(cookie_name, obj.value);
	}
}
					
function setDateAndTime(d_id,t_id,fd,ft,yoffset)
{
	prefillDate = Cookie.read(fd);
	
	if (!prefillDate)
		prefillDate = true;
	else
	{
			 	var dd = prefillDate.split(".");
			 	prefillDate = {day:dd[0]*1, month:dd[1]*1, year:dd[2]*1};						 							 
	}

	new vlaDatePicker(d_id, { 
		separator: '.', leadingZero: true, twoDigitYear: false, offset: { y: yoffset}, alignX: 'right', 
		alignY: '',
		startMonday:true,
		prefillDate:prefillDate,
		weekDayLabels:['&nbsp;P', '&nbsp;U', '&nbsp;S', '&nbsp;Č', '&nbsp;P', '&nbsp;S', '&nbsp;N'],
		monthLabels:['Siječanj','Veljača','Ožujak','Travanj','Svibanj','Lipanj','Srpanj','Kolovoz','Rujan','Listopad','Studeni','Prosinac']
	});
	
	$(t_id).value = retrieveTime(ft);	
}

function toggleMapExpand(full)
{
	if (footer_height == 220 || full)
	{
		footer_height = 100;
		$('leftPanel').setStyle("display","none");
		$('tabs').setStyle("display","none");
		$('rightPanel').setStyle("left","0px");
		Cookie.write('geotrag_fullscreeen',1);
	}
	else
	{
		footer_height = 220;
		$('leftPanel').setStyle("display","block");
		$('tabs').setStyle("display","block");
		$('rightPanel').setStyle("left","300px");
		Cookie.write('geotrag_fullscreeen',0);
	}
	resize();
}

function openAdminWindow(evt)
{
	$("flashcontent").setStyle("visibility", "hidden");

//	console.log($('report_vozila_form').report_vozila);
	
	adminform = formManager.open({
		overlay:true,
		closeOverlayClick:true, 
		width:800,
		height:600, 
		buttons:[{html:'Zatvori', click:'adminform.close();'}, {html:'Ok', click:''}],
		url:"/admin.php",
		onClose:function(){
			$("flashcontent").setStyle("visibility", "visible");
		}
	});
}

function formatDateAndTime(d)
{
	  	var h = d.getHours();
     	if (h < 10) h = "0"+h;
     		var m = d.getMinutes();
     	if (m < 10) m = "0"+m;
     	var mm = d.getMonth()+1;
     	if (mm < 10) mm = "0"+mm;
     		var dd = d.getDate();
     	if (dd < 10) dd = "0"+dd;
     	var yy = d.getFullYear()-2000;
     	if (yy < 10) yy = "0"+yy;
     	 
     	return dd+"."+mm+"."+yy+". "+h+":"+m; 
}

function onPrintComplete(evt)
{
	var fullpath = '/include/amfphp/services/save/'+evt.name;
	

	//window.open ("http://unstable.giscloud.com/modules/print/pdf.php?f="+evt.name,"mywindow"); 
	
	//console.log( fullpath );
	//savedTempBound = bnd;
	//resize();	
	printCallBack(evt);
	printCallBack = null;	
}
var shouldPrintBitmap = 0;
var shouldResizeApplication = 0;
var printCallBack;
var printObj = {"name":"Ispis"};
var   loadStart = 0;   

printW = 784;
printH = 420;

function printBitmap(callback)
{
	printCallBack = callback;
	//bnd = savedTempBound = fn.getViewBound();
	//$('flashcontent').setStyles({width:400, height:300});
	//fn.setViewBound(bnd);
	
	//console.log( bnd );
	//shouldPrintBitmap = 1;
	//bitmap.bitmap('http://unstable.giscloud.com/pixels.php');

	shouldPrint = 1;	
	
	//fn.setViewBound(2457625.28917379,5070045.90022352,2461892.62773279,5071486.12698718);
	
//	fn.setViewBound(2446751.11830974,5075863.40321168,2475310.68257277,5085943.24942217);
	
	var b = fn.getViewBound();
	savedTempBound = fn.getViewBound();
	//console.log(savedTempBound);
	var w = fn.getWidth();
	var h = fn.getHeight();
	 
	b.xMax = b.xMin+(b.xMax-b.xMin)*(w/printW);
	b.yMin = b.yMax-(b.yMax-b.yMin)*(h/printH);
			
			loadStart = 0;
	fn.setViewBound(b);
	

  $('print_confirm').hide();	
  $('print_message_text').show();		 	
		
	$("flashcontent").setStyle("visibility", "hidden");	
	
window.setTimeout(function() {
		if (!loadStart)
		{
			shouldPrint = 0;
			bitmap.print2('/include/amfphp/gateway.php',printW,printH);
		}
	},3000);

}

var printUrl;

function printMap(evt)
{	
	fn.setViewBound(savedTempBound);
	
	var s = "";
	
	for (var i in printObj)
	{
		s += "&"+i+"="+printObj[i];
	}
	
	//alert("/modules/reports/pdf/pdf_print.php?mapimg="+evt.name+s);
	printUrl = "/modules/reports/pdf/pdf_print.php?mapimg="+evt.name+s;
	
	$('print_message_text').hide();		 	
  $('print_confirm').show();		
}

function openPrintReport()
{
	window.open(printUrl,"Slika");
	$("flashcontent").setStyle("visibility", "visible");	
}

var follow_counter = 0; 
var follow_timer_id = 0; 
var follow_array=new Array();
var follow_mode1=0;
var follow_moving_marker = null;
var follow_moving_marker_map = null;
var follow_last_id = 0;
var follow_current_sec = 0;
var follow_update_counter=1;
var time_interval_value;
var time_offset = 0; 
var follow_leave_mark = 1;

function followSetTimeOffset(d_id,t_id,fd,ft)
{ 
  if (!d_id || !$(d_id)) return;
  
	var d2 = new Date(); 
	
	var dd = $(d_id).value.split(".");

 	Cookie.write(fd, $(d_id).value);
 	Cookie.write(ft, $(t_id).value);

 	var tt = $(t_id).value.split(":");

 	d2.setFullYear(dd[2]*1,dd[1]*1-1,dd[0]*1);

	d2.setHours(tt[0]*1,tt[1]*1,0,0);

 	return Math.round(d2.getTime()/1000);
}


function followGPS(dontset)
{ 
		//console.log("change");
		follow_update_counter = 1;
		
		//	alert("follow");
			ti = $('time_interval');
		//$('time_interval').value = "za "+i+" s";
		/*
		ti = $('time_interval');
			ti.options.length = 0;
		for (i =1; i < 5;i++)
		{
				o = new Option(i+" s");
				o.value = i;
				ti.options[i] = o;
		}
		*/
		if (!dontset)
		{
		  if (ti.selectedIndex < 5)
		  ti.selectedIndex = 5;
			i = $('time_interval').value;
			follow_current_sec = i*1;
			time_interval_value = i*1;   				
		}
		 
		followGPSRefresh(); 					
}

var max_timestamp2 = null;

function getGPSPoint()
{
	console.log("getGPSPoint "+follow_array.length);
  var pdata = follow_array.shift();     

  if (!pdata) return;
 
  var minx = 100000000000000;
  var miny = 100000000000000;
  var maxx = -100000000000000;
  var maxy = -100000000000000;
  
  max_timestamp2 = 0;
  var p = null;


  for (var i=0; i <  pdata.data.length; i++)
  {
	 	p = pdata.data[i];
	 	
	 	if (!p) continue;
	 
	 	if (p.x < minx) minx = p.x;
	 	if (p.y < miny) miny = p.y;
	 	if (p.x > maxx) maxx = p.x;
	 	if (p.y > maxy) maxy = p.y;
	 	
	 	if (p.traceMode) continue;
	 	
	 	 if (p.id*1 > follow_last_id) follow_last_id = p.id*1;
	 	 
	 	 var m = follow_moving_marker_map["c"+p.device_id];
	 	 
	 	
			if (m)
	    { 						
				kut = Math.atan2(p.y2-p.y,p.x2-p.x)*180/Math.PI+180;				
				if (kut < 0) kut += 360;
				m.curs = kut;
				
				marker.move2(m.marker_id,p.x,p.y,-kut,0); 		
			//	if (m.marker_info)
 	 		//	marker.move2(m.marker_info,p.x,p.y,0,0);	
 	 		 	 //console.log(p.timestamp);	
 	 			if (p.max_timestamp && 0)
 	 			{
 	 				treeData["c"+p.device_id].timestamp = parseInt(p.max_timestamp);
 	 				treeData["c"+p.device_id].covered_dist = parseFloat(p.max_covered_dist);
 	 				treeData["c"+p.device_id].max_timestamp = parseInt(p.max_timestamp);
 	 				max_timestamp2 = parseInt(p.max_timestamp2);
 	 			}
 	 			else
 	 			{ 	 		
 	 				treeData["c"+p.device_id].timestamp = parseInt(p.timestamp); 	 			
 	 				if (isNaN(treeData["c"+p.device_id].timestamp)) treeData["c"+p.device_id].timestamp = 0;
					treeData["c"+p.device_id].covered_dist = parseFloat(p.covered_dist);	
					treeData["c"+p.device_id].max_timestamp = null;		
				}
				
				//console.log(p.timestamp);
 	 			
 	 			if (p.speed*1 <= 0)
		  	{
		  		p.speed = 0;
		  		//console.log("set speed "+m.last_data);
		  		
		  		if (m.last_data && m.last_data.device_id == p.device_id)
		  		{
		  			
		  			if (p.timestamp > m.last_data.timestamp)
		  			p.speed = Math.round((Math.sqrt(Math.pow(m.last_data.x-p.x,2)+Math.pow(m.last_data.y-p.y,2))/(p.timestamp-m.last_data.timestamp))*3.6);
		  			else
		  			if (m.last_data.speed > 0)
		  			p.speed = m.last_data.speed;
		  			
		  			//console.log(p.device_id+" set speed2 "+p.speed+" "+p.timestamp+" "+m.last_data.timestamp+" "+m.last_data.speed)
		  	  }    		 
		  	}
		  	
		  	if (follow_leave_mark && m.last_data && (regata || leavemark) && !dos)
		  	{
		  		
		  		//console.log("mark ");
		  		/*
		  		var fm = new Object();
		  		
		  		
		  		fm.geom = 'LINESTRING('+m.last_data.x+' '+m.last_data.y+','+p.x+' '+p.y+')';
		  		fm.color = m.tragColor;		  	
		    	//d[i].color = c;
		   		fm.alpha = 85; 
		   		fm.width = 3; 
		   		*/
		   		var lastm = m.last_data;;
		   	  if (!m.markdata)
		   	  {		   	  	
		   	  		m.markdata = {};
		   	  		m.markdata.data = new Array();			   	  	    	  		
		   	  	
		   	  		m.markdata.marklength = 0;				   	 		   	  	
		   	  		m.markdata.shape = canvas.newShape({color:m.tragColor,alpha:90,width:3});
		   	  	
		   	  		canvas.moveTo(m.markdata.shape,p.x,p.y); 		   	  				   	  	
		   	  }
		   	  else		   	  
		   	  {		   	  
		   	  	canvas.lineTo(m.markdata.shape,p.x,p.y);	
		   	  	 m.markdata.marklength += Math.sqrt((lastm.x-p.x)*(lastm.x-p.x)+(lastm.y-p.y)*(lastm.y-p.y));
		   	  }
		   	
		   	  m.markdata.data.push({"x":p.x,"y":p.y});
		   	  		   	  		   	 
		   	 // console.log("len ",m.markdata.marklength);
		   	   
		   	  var maxLength = 4000;
		   	  var minLength = 3000;
		   	  if (m.markdata.marklength > maxLength)
		   	  {		   	  	
		   	    canvas.remove(m.markdata.shape);		   	  		
		   	  			  //console.log("m3 "+m.markdata.data.length);  	  			   	  				   	 		   	  	
		   	  	m.markdata.shape = canvas.newShape({color:m.tragColor,alpha:90,width:3});
		   	  	//  console.log("cistim");
		   	  	if (m.markdata.data.length > 0)
		   	  	{		   	  		 	  		
		   	  		//console.log("ima nesto u array "+m.markdata.data.length+" "+m.markdata.marklength+"  "+(maxLength/2));
		   	  		var lastm = {};
		   	  	  var md = m.markdata.data.shift();  
		   	  		lastm.x = md.x;
		   	  		lastm.y = md.y;
		   	      //console.log(md.x+" "+md.y);		
		   	     	  	
			   	  	while (m.markdata.data.length > 0 && m.markdata.marklength > minLength)
			   	  	{					   	  		  	  		
			   	  		md = m.markdata.data.shift();
			   	  		//console.log("vrti "+md.x+" "+md.y);	 
			   	  		m.markdata.marklength -= Math.sqrt((lastm.x-md.x)*(lastm.x-md.x)+(lastm.y-md.y)*(lastm.y-md.y)); 	
			   	  		lastm.x = md.x;
		   	  		  lastm.y = md.y;
			   	  	} 
             
              m.markdata.data.unshift({"x":lastm.x,"y":lastm.y});
						//console.log("ostalo "+m.markdata.marklength+" "+m.markdata.data.length);
						  if (m.markdata.data.length > 0)
						  {
			   	  		canvas.moveTo(m.markdata.shape,m.markdata.data[0].x,m.markdata.data[0].y);
			   	 
			   	  		for (var t = 1; t < m.markdata.data.length; t++)
			   	  		{			  
			   	  			canvas.lineTo(m.markdata.shape,m.markdata.data[t].x,m.markdata.data[t].y); 
			   	  		}
			   	  	}					   	   	  	
		   	  	}		   	  	
		   	  				   	  			   	  	   	  				   	  	
		   	  }
		   		
		   		//console.log(m.markdata.marklength);
		   		
					//canvas.deserializeGeometryOpenGISSimple(fm);
		  	}
		  	
		  	var lencheck = 0;
		  	
		  	if (m.markdata)
		  	{
			  	if (m.markdata.data.length > 0)
			  	{
			  		lastm.x = m.markdata.data[0].x;
			  		lastm.y = m.markdata.data[0].y;
				  	for (var t = 1; t < m.markdata.data.length; t++)
		   	  	{			  	   	  		
		   	  		lencheck += Math.sqrt((lastm.x-m.markdata.data[t].x)*(lastm.x-m.markdata.data[t].x)+(lastm.y-m.markdata.data[t].y)*(lastm.y-m.markdata.data[t].y));
		   	  		lastm.x = m.markdata.data[t].x;
			  		  lastm.y = m.markdata.data[t].y;
		   	  	}		
	   	 	  }
			  
			   // console.log("lencheck ",m.markdata.marklength,lencheck);
		  	}
		  	
		  	if (!m.last_data) m.last_data = {};
		  	m.last_data.x = p.x;
		  	m.last_data.y = p.y;
		  	
		  	for(var k in p)
		  	{
		  		m[k] = p[k];
		  	}
		
		  	follow_moving_marker_map["c"+p.device_id] = m;
 	 			
			}      	 
			//console.log("var data "+m.mark+" "+m.hasVariableData);
			if (m && m.hasVariableData)
			{
				populateMarkerInfoWindow(m);
			}
			
			if (p.device_id == current_info_id)
			{			  	    		    	  	
	  		updateInfo(p,true);
	  	}
   }

	 if ($('followOnMap').checked && !tracing) 
			{
				/*
				if (time_offset == 0)
				{
					offset = 700;
					fn.setViewBoundAnim(p.x-offset,p.y-offset,p.x*1+offset,p.y*1+offset,null,follow_counter != 0);
				}
				else
				*/
				var f = 1.00001;
				minx /= f;
				miny /= f;
				maxx *= f;
				maxy *= f;
				if (pdata.data.length > 1)
				fn.setViewBound(minx,miny,maxx,maxy); //fn.setQuality("LOW"); 
				else
				if (p)
				fn.setLocation(p.x,p.y); 
		}
		
		if (!tracing) 
		{
			global_timestamp = pdata.t;
			console.log("pdata.t",global_timestamp);
			/*
			var d = new Date();
			global_timestamp = Math.round(d.getTime()/1000);*/
			$('globalTime').innerHTML = formatTimeInfo(global_timestamp);	
			treeSort();
		}
}

var follow_update_folow_mode = 1;

function followCounterClicked()
{
	follow_update_counter = 0;
	//follow_update_folow_mode = 0;
	
	ti = $('time_interval');
	 ti.selectedIndex = 0;
	//ti.selectedIndex = 0;
	
	/*
	var o = new Option("0 s");
	o.value = 0;
	ti.options[0] = o;
	
	var o = new Option("5 s");
	o.value = 5;
	ti.options[1] = o;
	
  o = new Option("15 s");
	o.value = 15;
	ti.options[2] = o;
	
	o = new Option("30 s");
	o.value = 30;
	ti.options[3] = o;
	
	o = new Option("40 s");
	o.value = 45;
	ti.options[4] = o;
	
	o = new Option("60 s");
	o.value = 60;
	ti.options[5] = o;
	*/
	/*
	ti.options.length = 0;
		for (i =1; i < 5;i++)
		{
				o = new Option(i+" s");
				o.value = i;
				ti.options[i] = o;
		}
		*/
	
	
	//ti.options.length = 5;
	
	//ti.innerHTML = "<option>bla</option><option>blue</option>";
	
	for (i =0; i < ti.options.length;i++)
	{
	    if (i != 5 && i != 15 && i != 30 && i != 45 && i != 60)
	    {	    	
	    	//ti.options[i] = null;	   
	    	//ti.options[i].remove(); 
				ti.options[i].style.display = "none";
			}
	}

}

function followCounterOver()
{
alert("over");	
}

function followGPSRefresh()
{ 	

	//console.log("followGPSRefresh");
	//
			
	if (follow_update_counter)
	{
	
		ti = $('time_interval');
		if (!follow_update_folow_mode)
		{
			/*
			for (i =0; i < 60;i++)
			{
					var o = new Option(i+" s");
					o.value = i;
					ti.options[i] = o;
			}
			*/
			follow_update_folow_mode = 1;
		}
		
		
		
		ti.selectedIndex = follow_current_sec;
		
		//ti.options[ti.selectedIndex].setStyle("display","block");
		//alert("ok1");
	}
		
	if (follow_current_sec > 0)
	{		
		window.clearTimeout(follow_timer_id); 

		follow_current_sec --;
		if (time_offset == 0)
			follow_timer_id = window.setTimeout(followGPSRefresh, 1000); 
		return;
	}
	//console.log(time_interval_value);
	follow_current_sec = time_interval_value;
	
	lista = null;

	lista = getCheckedList();
	if (tracing)
	{
		var lista1 = new Array();
		lista.each(function(el)
		{
			if (follow_moving_marker_map["c"+el] && !follow_moving_marker_map["c"+el].traceData)
			lista1.push(el);
		});
		lista = lista1;
	}
  
  //alert(lista);
	if (!lista || lista.length == 0)
	{
		window.clearTimeout(follow_timer_id); 
		//if (time_offset == 0)
	  follow_timer_id = window.setTimeout(followGPSRefresh, 1000); 
		return;
	}
	
	
	//$("info").innerHTML = "Ucitavam...";
	var jsonRequest = new Request.JSON({url: "/data.php", onComplete: function(d)
	{									
		  if (d && d.newnch)
		  {
		  	window.location.href = "/?upgrade=1";
		  	return;
		  }
		  
		  	
			if (!d) 
			{ 
				//$("info").innerHTML = lang['numberofpoint']+": 0"; 
			}
			else
			{
				 if (d.r_msg && messages_mini_datagrid)
				 {				 	
				 	var n = messages_mini_datagrid.options.data.length;
				 	for (i = 0; i < n; i++)
				 	{
				 		var o = messages_mini_datagrid.getDataByRow(i);
				 		if (o.status == 2) continue;
				 		if (!o) break;
				 		
				 		if (d.r_msg.indexOf(o.id) != -1)
				 		{
				 			o.status = 2;
				 			messages_mini_datagrid.setDataByRow(i,o);				 				 	
				 		}
				 	}
				 }
				 	 
				 follow_array = follow_array.concat(d);
				//$("info").innerHTML = lang['numberofpoint']+": "+d.data.length;
	
				follow_counter++;	  
				
				getGPSPoint();
				
				console.log("point je");
			}
							
			if (init_route && regata && !dos)
			{
				init_route = 0;
				mod_query2.clearRoute();
				//replayonstart = 1;
				//showRoute();
						
				$('followOnMap').checked = "checked";
				$('followOnMap1').checked = false;				
				
				if (replayonstart)
					toolClickY24($('player_tool_play'));
				else
				{
					//toggleMarkerItem($('a_info_curs'));
				  toggleMarkerItem($('a_info_speed'));
					//mod_query2.showRoute();
					//mod_query2.followGPSTrace();		
				}
			  //				
			}
			
			window.clearTimeout(follow_timer_id); 
			console.log("toff "+time_offset);
			if (time_offset == 0)
		  follow_timer_id = window.setTimeout(followGPSRefresh, 1000); 

	}}).get({'_nch':_nch,'follow': follow_last_id, 'list': lista, 'timeoffset':time_offset });
		
}
