/*!
 * jQuery JavaScript Library v1.4.4
 * http://jquery.com/
 *
 * Copyright 2010, John Resig
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 * Copyright 2010, The Dojo Foundation
 * Released under the MIT, BSD, and GPL Licenses.
 *
 * Date: Thu Nov 11 19:04:53 2010 -0500
 */
if (window.jQuery==undefined){
 (function(E,B){function ka(a,b,d){if(d===B&&a.nodeType===1){d=a.getAttribute("data-"+b);if(typeof d==="string"){try{d=d==="true"?true:d==="false"?false:d==="null"?null:!c.isNaN(d)?parseFloat(d):Ja.test(d)?c.parseJSON(d):d}catch(e){}c.data(a,b,d)}else d=B}return d}function U(){return false}function ca(){return true}function la(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function Ka(a){var b,d,e,f,h,l,k,o,x,r,A,C=[];f=[];h=c.data(this,this.nodeType?"events":"__events__");if(typeof h==="function")h=
h.events;if(!(a.liveFired===this||!h||!h.live||a.button&&a.type==="click")){if(a.namespace)A=RegExp("(^|\\.)"+a.namespace.split(".").join("\\.(?:.*\\.)?")+"(\\.|$)");a.liveFired=this;var J=h.live.slice(0);for(k=0;k<J.length;k++){h=J[k];h.origType.replace(X,"")===a.type?f.push(h.selector):J.splice(k--,1)}f=c(a.target).closest(f,a.currentTarget);o=0;for(x=f.length;o<x;o++){r=f[o];for(k=0;k<J.length;k++){h=J[k];if(r.selector===h.selector&&(!A||A.test(h.namespace))){l=r.elem;e=null;if(h.preType==="mouseenter"||
h.preType==="mouseleave"){a.type=h.preType;e=c(a.relatedTarget).closest(h.selector)[0]}if(!e||e!==l)C.push({elem:l,handleObj:h,level:r.level})}}}o=0;for(x=C.length;o<x;o++){f=C[o];if(d&&f.level>d)break;a.currentTarget=f.elem;a.data=f.handleObj.data;a.handleObj=f.handleObj;A=f.handleObj.origHandler.apply(f.elem,arguments);if(A===false||a.isPropagationStopped()){d=f.level;if(A===false)b=false;if(a.isImmediatePropagationStopped())break}}return b}}function Y(a,b){return(a&&a!=="*"?a+".":"")+b.replace(La,
"`").replace(Ma,"&")}function ma(a,b,d){if(c.isFunction(b))return c.grep(a,function(f,h){return!!b.call(f,h,f)===d});else if(b.nodeType)return c.grep(a,function(f){return f===b===d});else if(typeof b==="string"){var e=c.grep(a,function(f){return f.nodeType===1});if(Na.test(b))return c.filter(b,e,!d);else b=c.filter(b,e)}return c.grep(a,function(f){return c.inArray(f,b)>=0===d})}function na(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var e=c.data(a[d++]),f=c.data(this,
e);if(e=e&&e.events){delete f.handle;f.events={};for(var h in e)for(var l in e[h])c.event.add(this,h,e[h][l],e[h][l].data)}}})}function Oa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function oa(a,b,d){var e=b==="width"?a.offsetWidth:a.offsetHeight;if(d==="border")return e;c.each(b==="width"?Pa:Qa,function(){d||(e-=parseFloat(c.css(a,"padding"+this))||0);if(d==="margin")e+=parseFloat(c.css(a,
"margin"+this))||0;else e-=parseFloat(c.css(a,"border"+this+"Width"))||0});return e}function da(a,b,d,e){if(c.isArray(b)&&b.length)c.each(b,function(f,h){d||Ra.test(a)?e(a,h):da(a+"["+(typeof h==="object"||c.isArray(h)?f:"")+"]",h,d,e)});else if(!d&&b!=null&&typeof b==="object")c.isEmptyObject(b)?e(a,""):c.each(b,function(f,h){da(a+"["+f+"]",h,d,e)});else e(a,b)}function S(a,b){var d={};c.each(pa.concat.apply([],pa.slice(0,b)),function(){d[this]=a});return d}function qa(a){if(!ea[a]){var b=c("<"+
a+">").appendTo("body"),d=b.css("display");b.remove();if(d==="none"||d==="")d="block";ea[a]=d}return ea[a]}function fa(a){return c.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var t=E.document,c=function(){function a(){if(!b.isReady){try{t.documentElement.doScroll("left")}catch(j){setTimeout(a,1);return}b.ready()}}var b=function(j,s){return new b.fn.init(j,s)},d=E.jQuery,e=E.$,f,h=/^(?:[^<]*(<[\w\W]+>)[^>]*$|#([\w\-]+)$)/,l=/\S/,k=/^\s+/,o=/\s+$/,x=/\W/,r=/\d/,A=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,
C=/^[\],:{}\s]*$/,J=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,w=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,I=/(?:^|:|,)(?:\s*\[)+/g,L=/(webkit)[ \/]([\w.]+)/,g=/(opera)(?:.*version)?[ \/]([\w.]+)/,i=/(msie) ([\w.]+)/,n=/(mozilla)(?:.*? rv:([\w.]+))?/,m=navigator.userAgent,p=false,q=[],u,y=Object.prototype.toString,F=Object.prototype.hasOwnProperty,M=Array.prototype.push,N=Array.prototype.slice,O=String.prototype.trim,D=Array.prototype.indexOf,R={};b.fn=b.prototype={init:function(j,
s){var v,z,H;if(!j)return this;if(j.nodeType){this.context=this[0]=j;this.length=1;return this}if(j==="body"&&!s&&t.body){this.context=t;this[0]=t.body;this.selector="body";this.length=1;return this}if(typeof j==="string")if((v=h.exec(j))&&(v[1]||!s))if(v[1]){H=s?s.ownerDocument||s:t;if(z=A.exec(j))if(b.isPlainObject(s)){j=[t.createElement(z[1])];b.fn.attr.call(j,s,true)}else j=[H.createElement(z[1])];else{z=b.buildFragment([v[1]],[H]);j=(z.cacheable?z.fragment.cloneNode(true):z.fragment).childNodes}return b.merge(this,
j)}else{if((z=t.getElementById(v[2]))&&z.parentNode){if(z.id!==v[2])return f.find(j);this.length=1;this[0]=z}this.context=t;this.selector=j;return this}else if(!s&&!x.test(j)){this.selector=j;this.context=t;j=t.getElementsByTagName(j);return b.merge(this,j)}else return!s||s.jquery?(s||f).find(j):b(s).find(j);else if(b.isFunction(j))return f.ready(j);if(j.selector!==B){this.selector=j.selector;this.context=j.context}return b.makeArray(j,this)},selector:"",jquery:"1.4.4",length:0,size:function(){return this.length},
toArray:function(){return N.call(this,0)},get:function(j){return j==null?this.toArray():j<0?this.slice(j)[0]:this[j]},pushStack:function(j,s,v){var z=b();b.isArray(j)?M.apply(z,j):b.merge(z,j);z.prevObject=this;z.context=this.context;if(s==="find")z.selector=this.selector+(this.selector?" ":"")+v;else if(s)z.selector=this.selector+"."+s+"("+v+")";return z},each:function(j,s){return b.each(this,j,s)},ready:function(j){b.bindReady();if(b.isReady)j.call(t,b);else q&&q.push(j);return this},eq:function(j){return j===
-1?this.slice(j):this.slice(j,+j+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(N.apply(this,arguments),"slice",N.call(arguments).join(","))},map:function(j){return this.pushStack(b.map(this,function(s,v){return j.call(s,v,s)}))},end:function(){return this.prevObject||b(null)},push:M,sort:[].sort,splice:[].splice};b.fn.init.prototype=b.fn;b.extend=b.fn.extend=function(){var j,s,v,z,H,G=arguments[0]||{},K=1,Q=arguments.length,ga=false;
if(typeof G==="boolean"){ga=G;G=arguments[1]||{};K=2}if(typeof G!=="object"&&!b.isFunction(G))G={};if(Q===K){G=this;--K}for(;K<Q;K++)if((j=arguments[K])!=null)for(s in j){v=G[s];z=j[s];if(G!==z)if(ga&&z&&(b.isPlainObject(z)||(H=b.isArray(z)))){if(H){H=false;v=v&&b.isArray(v)?v:[]}else v=v&&b.isPlainObject(v)?v:{};G[s]=b.extend(ga,v,z)}else if(z!==B)G[s]=z}return G};b.extend({noConflict:function(j){E.$=e;if(j)E.jQuery=d;return b},isReady:false,readyWait:1,ready:function(j){j===true&&b.readyWait--;
if(!b.readyWait||j!==true&&!b.isReady){if(!t.body)return setTimeout(b.ready,1);b.isReady=true;if(!(j!==true&&--b.readyWait>0))if(q){var s=0,v=q;for(q=null;j=v[s++];)j.call(t,b);b.fn.trigger&&b(t).trigger("ready").unbind("ready")}}},bindReady:function(){if(!p){p=true;if(t.readyState==="complete")return setTimeout(b.ready,1);if(t.addEventListener){t.addEventListener("DOMContentLoaded",u,false);E.addEventListener("load",b.ready,false)}else if(t.attachEvent){t.attachEvent("onreadystatechange",u);E.attachEvent("onload",
b.ready);var j=false;try{j=E.frameElement==null}catch(s){}t.documentElement.doScroll&&j&&a()}}},isFunction:function(j){return b.type(j)==="function"},isArray:Array.isArray||function(j){return b.type(j)==="array"},isWindow:function(j){return j&&typeof j==="object"&&"setInterval"in j},isNaN:function(j){return j==null||!r.test(j)||isNaN(j)},type:function(j){return j==null?String(j):R[y.call(j)]||"object"},isPlainObject:function(j){if(!j||b.type(j)!=="object"||j.nodeType||b.isWindow(j))return false;if(j.constructor&&
!F.call(j,"constructor")&&!F.call(j.constructor.prototype,"isPrototypeOf"))return false;for(var s in j);return s===B||F.call(j,s)},isEmptyObject:function(j){for(var s in j)return false;return true},error:function(j){throw j;},parseJSON:function(j){if(typeof j!=="string"||!j)return null;j=b.trim(j);if(C.test(j.replace(J,"@").replace(w,"]").replace(I,"")))return E.JSON&&E.JSON.parse?E.JSON.parse(j):(new Function("return "+j))();else b.error("Invalid JSON: "+j)},noop:function(){},globalEval:function(j){if(j&&
l.test(j)){var s=t.getElementsByTagName("head")[0]||t.documentElement,v=t.createElement("script");v.type="text/javascript";if(b.support.scriptEval)v.appendChild(t.createTextNode(j));else v.text=j;s.insertBefore(v,s.firstChild);s.removeChild(v)}},nodeName:function(j,s){return j.nodeName&&j.nodeName.toUpperCase()===s.toUpperCase()},each:function(j,s,v){var z,H=0,G=j.length,K=G===B||b.isFunction(j);if(v)if(K)for(z in j){if(s.apply(j[z],v)===false)break}else for(;H<G;){if(s.apply(j[H++],v)===false)break}else if(K)for(z in j){if(s.call(j[z],
z,j[z])===false)break}else for(v=j[0];H<G&&s.call(v,H,v)!==false;v=j[++H]);return j},trim:O?function(j){return j==null?"":O.call(j)}:function(j){return j==null?"":j.toString().replace(k,"").replace(o,"")},makeArray:function(j,s){var v=s||[];if(j!=null){var z=b.type(j);j.length==null||z==="string"||z==="function"||z==="regexp"||b.isWindow(j)?M.call(v,j):b.merge(v,j)}return v},inArray:function(j,s){if(s.indexOf)return s.indexOf(j);for(var v=0,z=s.length;v<z;v++)if(s[v]===j)return v;return-1},merge:function(j,
s){var v=j.length,z=0;if(typeof s.length==="number")for(var H=s.length;z<H;z++)j[v++]=s[z];else for(;s[z]!==B;)j[v++]=s[z++];j.length=v;return j},grep:function(j,s,v){var z=[],H;v=!!v;for(var G=0,K=j.length;G<K;G++){H=!!s(j[G],G);v!==H&&z.push(j[G])}return z},map:function(j,s,v){for(var z=[],H,G=0,K=j.length;G<K;G++){H=s(j[G],G,v);if(H!=null)z[z.length]=H}return z.concat.apply([],z)},guid:1,proxy:function(j,s,v){if(arguments.length===2)if(typeof s==="string"){v=j;j=v[s];s=B}else if(s&&!b.isFunction(s)){v=
s;s=B}if(!s&&j)s=function(){return j.apply(v||this,arguments)};if(j)s.guid=j.guid=j.guid||s.guid||b.guid++;return s},access:function(j,s,v,z,H,G){var K=j.length;if(typeof s==="object"){for(var Q in s)b.access(j,Q,s[Q],z,H,v);return j}if(v!==B){z=!G&&z&&b.isFunction(v);for(Q=0;Q<K;Q++)H(j[Q],s,z?v.call(j[Q],Q,H(j[Q],s)):v,G);return j}return K?H(j[0],s):B},now:function(){return(new Date).getTime()},uaMatch:function(j){j=j.toLowerCase();j=L.exec(j)||g.exec(j)||i.exec(j)||j.indexOf("compatible")<0&&n.exec(j)||
[];return{browser:j[1]||"",version:j[2]||"0"}},browser:{}});b.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(j,s){R["[object "+s+"]"]=s.toLowerCase()});m=b.uaMatch(m);if(m.browser){b.browser[m.browser]=true;b.browser.version=m.version}if(b.browser.webkit)b.browser.safari=true;if(D)b.inArray=function(j,s){return D.call(s,j)};if(!/\s/.test("\u00a0")){k=/^[\s\xA0]+/;o=/[\s\xA0]+$/}f=b(t);if(t.addEventListener)u=function(){t.removeEventListener("DOMContentLoaded",u,
false);b.ready()};else if(t.attachEvent)u=function(){if(t.readyState==="complete"){t.detachEvent("onreadystatechange",u);b.ready()}};return E.jQuery=E.$=b}();(function(){c.support={};var a=t.documentElement,b=t.createElement("script"),d=t.createElement("div"),e="script"+c.now();d.style.display="none";d.innerHTML="   <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";var f=d.getElementsByTagName("*"),h=d.getElementsByTagName("a")[0],l=t.createElement("select"),
k=l.appendChild(t.createElement("option"));if(!(!f||!f.length||!h)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(h.getAttribute("style")),hrefNormalized:h.getAttribute("href")==="/a",opacity:/^0.55$/.test(h.style.opacity),cssFloat:!!h.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:k.selected,deleteExpando:true,optDisabled:false,checkClone:false,
scriptEval:false,noCloneEvent:true,boxModel:null,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableHiddenOffsets:true};l.disabled=true;c.support.optDisabled=!k.disabled;b.type="text/javascript";try{b.appendChild(t.createTextNode("window."+e+"=1;"))}catch(o){}a.insertBefore(b,a.firstChild);if(E[e]){c.support.scriptEval=true;delete E[e]}try{delete b.test}catch(x){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function r(){c.support.noCloneEvent=
false;d.detachEvent("onclick",r)});d.cloneNode(true).fireEvent("onclick")}d=t.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=t.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var r=t.createElement("div");r.style.width=r.style.paddingLeft="1px";t.body.appendChild(r);c.boxModel=c.support.boxModel=r.offsetWidth===2;if("zoom"in r.style){r.style.display="inline";r.style.zoom=
1;c.support.inlineBlockNeedsLayout=r.offsetWidth===2;r.style.display="";r.innerHTML="<div style='width:4px;'></div>";c.support.shrinkWrapBlocks=r.offsetWidth!==2}r.innerHTML="<table><tr><td style='padding:0;display:none'></td><td>t</td></tr></table>";var A=r.getElementsByTagName("td");c.support.reliableHiddenOffsets=A[0].offsetHeight===0;A[0].style.display="";A[1].style.display="none";c.support.reliableHiddenOffsets=c.support.reliableHiddenOffsets&&A[0].offsetHeight===0;r.innerHTML="";t.body.removeChild(r).style.display=
"none"});a=function(r){var A=t.createElement("div");r="on"+r;var C=r in A;if(!C){A.setAttribute(r,"return;");C=typeof A[r]==="function"}return C};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=f=h=null}})();var ra={},Ja=/^(?:\{.*\}|\[.*\])$/;c.extend({cache:{},uuid:0,expando:"jQuery"+c.now(),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},data:function(a,b,d){if(c.acceptData(a)){a=a==E?ra:a;var e=a.nodeType,f=e?a[c.expando]:null,h=
c.cache;if(!(e&&!f&&typeof b==="string"&&d===B)){if(e)f||(a[c.expando]=f=++c.uuid);else h=a;if(typeof b==="object")if(e)h[f]=c.extend(h[f],b);else c.extend(h,b);else if(e&&!h[f])h[f]={};a=e?h[f]:h;if(d!==B)a[b]=d;return typeof b==="string"?a[b]:a}}},removeData:function(a,b){if(c.acceptData(a)){a=a==E?ra:a;var d=a.nodeType,e=d?a[c.expando]:a,f=c.cache,h=d?f[e]:e;if(b){if(h){delete h[b];d&&c.isEmptyObject(h)&&c.removeData(a)}}else if(d&&c.support.deleteExpando)delete a[c.expando];else if(a.removeAttribute)a.removeAttribute(c.expando);
else if(d)delete f[e];else for(var l in a)delete a[l]}},acceptData:function(a){if(a.nodeName){var b=c.noData[a.nodeName.toLowerCase()];if(b)return!(b===true||a.getAttribute("classid")!==b)}return true}});c.fn.extend({data:function(a,b){var d=null;if(typeof a==="undefined"){if(this.length){var e=this[0].attributes,f;d=c.data(this[0]);for(var h=0,l=e.length;h<l;h++){f=e[h].name;if(f.indexOf("data-")===0){f=f.substr(5);ka(this[0],f,d[f])}}}return d}else if(typeof a==="object")return this.each(function(){c.data(this,
a)});var k=a.split(".");k[1]=k[1]?"."+k[1]:"";if(b===B){d=this.triggerHandler("getData"+k[1]+"!",[k[0]]);if(d===B&&this.length){d=c.data(this[0],a);d=ka(this[0],a,d)}return d===B&&k[1]?this.data(k[0]):d}else return this.each(function(){var o=c(this),x=[k[0],b];o.triggerHandler("setData"+k[1]+"!",x);c.data(this,a,b);o.triggerHandler("changeData"+k[1]+"!",x)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var e=
c.data(a,b);if(!d)return e||[];if(!e||c.isArray(d))e=c.data(a,b,c.makeArray(d));else e.push(d);return e}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),e=d.shift();if(e==="inprogress")e=d.shift();if(e){b==="fx"&&d.unshift("inprogress");e.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b===B)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,
a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var sa=/[\n\t]/g,ha=/\s+/,Sa=/\r/g,Ta=/^(?:href|src|style)$/,Ua=/^(?:button|input)$/i,Va=/^(?:button|input|object|select|textarea)$/i,Wa=/^a(?:rea)?$/i,ta=/^(?:radio|checkbox)$/i;c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",
colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};c.fn.extend({attr:function(a,b){return c.access(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(x){var r=c(this);r.addClass(a.call(this,x,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===
1)if(f.className){for(var h=" "+f.className+" ",l=f.className,k=0,o=b.length;k<o;k++)if(h.indexOf(" "+b[k]+" ")<0)l+=" "+b[k];f.className=c.trim(l)}else f.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(o){var x=c(this);x.removeClass(a.call(this,o,x.attr("class")))});if(a&&typeof a==="string"||a===B)for(var b=(a||"").split(ha),d=0,e=this.length;d<e;d++){var f=this[d];if(f.nodeType===1&&f.className)if(a){for(var h=(" "+f.className+" ").replace(sa," "),
l=0,k=b.length;l<k;l++)h=h.replace(" "+b[l]+" "," ");f.className=c.trim(h)}else f.className=""}return this},toggleClass:function(a,b){var d=typeof a,e=typeof b==="boolean";if(c.isFunction(a))return this.each(function(f){var h=c(this);h.toggleClass(a.call(this,f,h.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var f,h=0,l=c(this),k=b,o=a.split(ha);f=o[h++];){k=e?k:!l.hasClass(f);l[k?"addClass":"removeClass"](f)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,
"__className__",this.className);this.className=this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(sa," ").indexOf(a)>-1)return true;return false},val:function(a){if(!arguments.length){var b=this[0];if(b){if(c.nodeName(b,"option")){var d=b.attributes.value;return!d||d.specified?b.value:b.text}if(c.nodeName(b,"select")){var e=b.selectedIndex;d=[];var f=b.options;b=b.type==="select-one";
if(e<0)return null;var h=b?e:0;for(e=b?e+1:f.length;h<e;h++){var l=f[h];if(l.selected&&(c.support.optDisabled?!l.disabled:l.getAttribute("disabled")===null)&&(!l.parentNode.disabled||!c.nodeName(l.parentNode,"optgroup"))){a=c(l).val();if(b)return a;d.push(a)}}return d}if(ta.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Sa,"")}return B}var k=c.isFunction(a);return this.each(function(o){var x=c(this),r=a;if(this.nodeType===1){if(k)r=
a.call(this,o,x.val());if(r==null)r="";else if(typeof r==="number")r+="";else if(c.isArray(r))r=c.map(r,function(C){return C==null?"":C+""});if(c.isArray(r)&&ta.test(this.type))this.checked=c.inArray(x.val(),r)>=0;else if(c.nodeName(this,"select")){var A=c.makeArray(r);c("option",this).each(function(){this.selected=c.inArray(c(this).val(),A)>=0});if(!A.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},
attr:function(a,b,d,e){if(!a||a.nodeType===3||a.nodeType===8)return B;if(e&&b in c.attrFn)return c(a)[b](d);e=a.nodeType!==1||!c.isXMLDoc(a);var f=d!==B;b=e&&c.props[b]||b;var h=Ta.test(b);if((b in a||a[b]!==B)&&e&&!h){if(f){b==="type"&&Ua.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed");if(d===null)a.nodeType===1&&a.removeAttribute(b);else a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&
b.specified?b.value:Va.test(a.nodeName)||Wa.test(a.nodeName)&&a.href?0:B;return a[b]}if(!c.support.style&&e&&b==="style"){if(f)a.style.cssText=""+d;return a.style.cssText}f&&a.setAttribute(b,""+d);if(!a.attributes[b]&&a.hasAttribute&&!a.hasAttribute(b))return B;a=!c.support.hrefNormalized&&e&&h?a.getAttribute(b,2):a.getAttribute(b);return a===null?B:a}});var X=/\.(.*)$/,ia=/^(?:textarea|input|select)$/i,La=/\./g,Ma=/ /g,Xa=/[^\w\s.|`]/g,Ya=function(a){return a.replace(Xa,"\\$&")},ua={focusin:0,focusout:0};
c.event={add:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(c.isWindow(a)&&a!==E&&!a.frameElement)a=E;if(d===false)d=U;else if(!d)return;var f,h;if(d.handler){f=d;d=f.handler}if(!d.guid)d.guid=c.guid++;if(h=c.data(a)){var l=a.nodeType?"events":"__events__",k=h[l],o=h.handle;if(typeof k==="function"){o=k.handle;k=k.events}else if(!k){a.nodeType||(h[l]=h=function(){});h.events=k={}}if(!o)h.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,
arguments):B};o.elem=a;b=b.split(" ");for(var x=0,r;l=b[x++];){h=f?c.extend({},f):{handler:d,data:e};if(l.indexOf(".")>-1){r=l.split(".");l=r.shift();h.namespace=r.slice(0).sort().join(".")}else{r=[];h.namespace=""}h.type=l;if(!h.guid)h.guid=d.guid;var A=k[l],C=c.event.special[l]||{};if(!A){A=k[l]=[];if(!C.setup||C.setup.call(a,e,r,o)===false)if(a.addEventListener)a.addEventListener(l,o,false);else a.attachEvent&&a.attachEvent("on"+l,o)}if(C.add){C.add.call(a,h);if(!h.handler.guid)h.handler.guid=
d.guid}A.push(h);c.event.global[l]=true}a=null}}},global:{},remove:function(a,b,d,e){if(!(a.nodeType===3||a.nodeType===8)){if(d===false)d=U;var f,h,l=0,k,o,x,r,A,C,J=a.nodeType?"events":"__events__",w=c.data(a),I=w&&w[J];if(w&&I){if(typeof I==="function"){w=I;I=I.events}if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(f in I)c.event.remove(a,f+b)}else{for(b=b.split(" ");f=b[l++];){r=f;k=f.indexOf(".")<0;o=[];if(!k){o=f.split(".");f=o.shift();x=RegExp("(^|\\.)"+
c.map(o.slice(0).sort(),Ya).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(A=I[f])if(d){r=c.event.special[f]||{};for(h=e||0;h<A.length;h++){C=A[h];if(d.guid===C.guid){if(k||x.test(C.namespace)){e==null&&A.splice(h--,1);r.remove&&r.remove.call(a,C)}if(e!=null)break}}if(A.length===0||e!=null&&A.length===1){if(!r.teardown||r.teardown.call(a,o)===false)c.removeEvent(a,f,w.handle);delete I[f]}}else for(h=0;h<A.length;h++){C=A[h];if(k||x.test(C.namespace)){c.event.remove(a,r,C.handler,h);A.splice(h--,1)}}}if(c.isEmptyObject(I)){if(b=
w.handle)b.elem=null;delete w.events;delete w.handle;if(typeof w==="function")c.removeData(a,J);else c.isEmptyObject(w)&&c.removeData(a)}}}}},trigger:function(a,b,d,e){var f=a.type||a;if(!e){a=typeof a==="object"?a[c.expando]?a:c.extend(c.Event(f),a):c.Event(f);if(f.indexOf("!")>=0){a.type=f=f.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[f]&&c.each(c.cache,function(){this.events&&this.events[f]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===
8)return B;a.result=B;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(e=d.nodeType?c.data(d,"handle"):(c.data(d,"__events__")||{}).handle)&&e.apply(d,b);e=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+f]&&d["on"+f].apply(d,b)===false){a.result=false;a.preventDefault()}}catch(h){}if(!a.isPropagationStopped()&&e)c.event.trigger(a,b,e,true);else if(!a.isDefaultPrevented()){var l;e=a.target;var k=f.replace(X,""),o=c.nodeName(e,"a")&&k===
"click",x=c.event.special[k]||{};if((!x._default||x._default.call(d,a)===false)&&!o&&!(e&&e.nodeName&&c.noData[e.nodeName.toLowerCase()])){try{if(e[k]){if(l=e["on"+k])e["on"+k]=null;c.event.triggered=true;e[k]()}}catch(r){}if(l)e["on"+k]=l;c.event.triggered=false}}},handle:function(a){var b,d,e,f;d=[];var h=c.makeArray(arguments);a=h[0]=c.event.fix(a||E.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive;if(!b){e=a.type.split(".");a.type=e.shift();d=e.slice(0).sort();e=RegExp("(^|\\.)"+
d.join("\\.(?:.*\\.)?")+"(\\.|$)")}a.namespace=a.namespace||d.join(".");f=c.data(this,this.nodeType?"events":"__events__");if(typeof f==="function")f=f.events;d=(f||{})[a.type];if(f&&d){d=d.slice(0);f=0;for(var l=d.length;f<l;f++){var k=d[f];if(b||e.test(k.namespace)){a.handler=k.handler;a.data=k.data;a.handleObj=k;k=k.handler.apply(this,h);if(k!==B){a.result=k;if(k===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix:function(a){if(a[c.expando])return a;var b=a;a=c.Event(b);for(var d=this.props.length,e;d;){e=this.props[--d];a[e]=b[e]}if(!a.target)a.target=a.srcElement||t;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=t.documentElement;d=t.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop||
d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(a.which==null&&(a.charCode!=null||a.keyCode!=null))a.which=a.charCode!=null?a.charCode:a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==B)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,Y(a.origType,a.selector),c.extend({},a,{handler:Ka,guid:a.handler.guid}))},remove:function(a){c.event.remove(this,
Y(a.origType,a.selector),a)}},beforeunload:{setup:function(a,b,d){if(c.isWindow(this))this.onbeforeunload=d},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};c.removeEvent=t.removeEventListener?function(a,b,d){a.removeEventListener&&a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent&&a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent=a;this.type=a.type}else this.type=a;this.timeStamp=
c.now();this[c.expando]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=ca;var a=this.originalEvent;if(a)if(a.preventDefault)a.preventDefault();else a.returnValue=false},stopPropagation:function(){this.isPropagationStopped=ca;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=ca;this.stopPropagation()},isDefaultPrevented:U,isPropagationStopped:U,isImmediatePropagationStopped:U};
var va=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},wa=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?wa:va,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?wa:va)}}});if(!c.support.submitBubbles)c.event.special.submit={setup:function(){if(this.nodeName.toLowerCase()!==
"form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length){a.liveFired=B;return la("submit",this,arguments)}});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13){a.liveFired=B;return la("submit",this,arguments)}})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}};if(!c.support.changeBubbles){var V,
xa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(e){return e.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},Z=function(a,b){var d=a.target,e,f;if(!(!ia.test(d.nodeName)||d.readOnly)){e=c.data(d,"_change_data");f=xa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data",f);if(!(e===B||f===e))if(e!=null||f){a.type="change";a.liveFired=
B;return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:Z,beforedeactivate:Z,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return Z.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return Z.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a,"_change_data",xa(a))}},setup:function(){if(this.type===
"file")return false;for(var a in V)c.event.add(this,a+".specialChange",V[a]);return ia.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return ia.test(this.nodeName)}};V=c.event.special.change.filters;V.focus=V.beforeactivate}t.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(e){e=c.event.fix(e);e.type=b;return c.event.trigger(e,null,e.target)}c.event.special[b]={setup:function(){ua[b]++===0&&t.addEventListener(a,d,true)},teardown:function(){--ua[b]===
0&&t.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,e,f){if(typeof d==="object"){for(var h in d)this[b](h,e,d[h],f);return this}if(c.isFunction(e)||e===false){f=e;e=B}var l=b==="one"?c.proxy(f,function(o){c(this).unbind(o,l);return f.apply(this,arguments)}):f;if(d==="unload"&&b!=="one")this.one(d,e,f);else{h=0;for(var k=this.length;h<k;h++)c.event.add(this[h],d,l,e)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&&!a.preventDefault)for(var d in a)this.unbind(d,
a[d]);else{d=0;for(var e=this.length;d<e;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,e){return this.live(b,d,e,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){var d=c.Event(a);d.preventDefault();d.stopPropagation();c.event.trigger(d,b,this[0]);return d.result}},toggle:function(a){for(var b=arguments,d=
1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(e){var f=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,f+1);e.preventDefault();return b[f].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var ya={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,e,f,h){var l,k=0,o,x,r=h||this.selector;h=h?this:c(this.context);if(typeof d===
"object"&&!d.preventDefault){for(l in d)h[b](l,e,d[l],r);return this}if(c.isFunction(e)){f=e;e=B}for(d=(d||"").split(" ");(l=d[k++])!=null;){o=X.exec(l);x="";if(o){x=o[0];l=l.replace(X,"")}if(l==="hover")d.push("mouseenter"+x,"mouseleave"+x);else{o=l;if(l==="focus"||l==="blur"){d.push(ya[l]+x);l+=x}else l=(ya[l]||l)+x;if(b==="live"){x=0;for(var A=h.length;x<A;x++)c.event.add(h[x],"live."+Y(l,r),{data:e,selector:r,handler:f,origType:l,origHandler:f,preType:o})}else h.unbind("live."+Y(l,r),f)}}return this}});
c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "),function(a,b){c.fn[b]=function(d,e){if(e==null){e=d;d=null}return arguments.length>0?this.bind(b,d,e):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});E.attachEvent&&!E.addEventListener&&c(E).bind("unload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});
(function(){function a(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1&&!q){y.sizcache=n;y.sizset=p}if(y.nodeName.toLowerCase()===i){F=y;break}y=y[g]}m[p]=F}}}function b(g,i,n,m,p,q){p=0;for(var u=m.length;p<u;p++){var y=m[p];if(y){var F=false;for(y=y[g];y;){if(y.sizcache===n){F=m[y.sizset];break}if(y.nodeType===1){if(!q){y.sizcache=n;y.sizset=p}if(typeof i!=="string"){if(y===i){F=true;break}}else if(k.filter(i,
[y]).length>0){F=y;break}}y=y[g]}m[p]=F}}}var d=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,e=0,f=Object.prototype.toString,h=false,l=true;[0,0].sort(function(){l=false;return 0});var k=function(g,i,n,m){n=n||[];var p=i=i||t;if(i.nodeType!==1&&i.nodeType!==9)return[];if(!g||typeof g!=="string")return n;var q,u,y,F,M,N=true,O=k.isXML(i),D=[],R=g;do{d.exec("");if(q=d.exec(R)){R=q[3];D.push(q[1]);if(q[2]){F=q[3];
break}}}while(q);if(D.length>1&&x.exec(g))if(D.length===2&&o.relative[D[0]])u=L(D[0]+D[1],i);else for(u=o.relative[D[0]]?[i]:k(D.shift(),i);D.length;){g=D.shift();if(o.relative[g])g+=D.shift();u=L(g,u)}else{if(!m&&D.length>1&&i.nodeType===9&&!O&&o.match.ID.test(D[0])&&!o.match.ID.test(D[D.length-1])){q=k.find(D.shift(),i,O);i=q.expr?k.filter(q.expr,q.set)[0]:q.set[0]}if(i){q=m?{expr:D.pop(),set:C(m)}:k.find(D.pop(),D.length===1&&(D[0]==="~"||D[0]==="+")&&i.parentNode?i.parentNode:i,O);u=q.expr?k.filter(q.expr,
q.set):q.set;if(D.length>0)y=C(u);else N=false;for(;D.length;){q=M=D.pop();if(o.relative[M])q=D.pop();else M="";if(q==null)q=i;o.relative[M](y,q,O)}}else y=[]}y||(y=u);y||k.error(M||g);if(f.call(y)==="[object Array]")if(N)if(i&&i.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&k.contains(i,y[g])))n.push(u[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&n.push(u[g]);else n.push.apply(n,y);else C(y,n);if(F){k(F,p,n,m);k.uniqueSort(n)}return n};k.uniqueSort=function(g){if(w){h=
l;g.sort(w);if(h)for(var i=1;i<g.length;i++)g[i]===g[i-1]&&g.splice(i--,1)}return g};k.matches=function(g,i){return k(g,null,null,i)};k.matchesSelector=function(g,i){return k(i,null,null,[g]).length>0};k.find=function(g,i,n){var m;if(!g)return[];for(var p=0,q=o.order.length;p<q;p++){var u,y=o.order[p];if(u=o.leftMatch[y].exec(g)){var F=u[1];u.splice(1,1);if(F.substr(F.length-1)!=="\\"){u[1]=(u[1]||"").replace(/\\/g,"");m=o.find[y](u,i,n);if(m!=null){g=g.replace(o.match[y],"");break}}}}m||(m=i.getElementsByTagName("*"));
return{set:m,expr:g}};k.filter=function(g,i,n,m){for(var p,q,u=g,y=[],F=i,M=i&&i[0]&&k.isXML(i[0]);g&&i.length;){for(var N in o.filter)if((p=o.leftMatch[N].exec(g))!=null&&p[2]){var O,D,R=o.filter[N];D=p[1];q=false;p.splice(1,1);if(D.substr(D.length-1)!=="\\"){if(F===y)y=[];if(o.preFilter[N])if(p=o.preFilter[N](p,F,n,y,m,M)){if(p===true)continue}else q=O=true;if(p)for(var j=0;(D=F[j])!=null;j++)if(D){O=R(D,p,j,F);var s=m^!!O;if(n&&O!=null)if(s)q=true;else F[j]=false;else if(s){y.push(D);q=true}}if(O!==
B){n||(F=y);g=g.replace(o.match[N],"");if(!q)return[];break}}}if(g===u)if(q==null)k.error(g);else break;u=g}return F};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var o=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+\-]*)\))?/,
POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}},relative:{"+":function(g,i){var n=typeof i==="string",m=n&&!/\W/.test(i);n=n&&!m;if(m)i=i.toLowerCase();m=0;for(var p=g.length,q;m<p;m++)if(q=g[m]){for(;(q=q.previousSibling)&&q.nodeType!==1;);g[m]=n||q&&q.nodeName.toLowerCase()===
i?q||false:q===i}n&&k.filter(i,g,true)},">":function(g,i){var n,m=typeof i==="string",p=0,q=g.length;if(m&&!/\W/.test(i))for(i=i.toLowerCase();p<q;p++){if(n=g[p]){n=n.parentNode;g[p]=n.nodeName.toLowerCase()===i?n:false}}else{for(;p<q;p++)if(n=g[p])g[p]=m?n.parentNode:n.parentNode===i;m&&k.filter(i,g,true)}},"":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=i=i.toLowerCase();q=a}q("parentNode",i,p,g,m,n)},"~":function(g,i,n){var m,p=e++,q=b;if(typeof i==="string"&&!/\W/.test(i)){m=
i=i.toLowerCase();q=a}q("previousSibling",i,p,g,m,n)}},find:{ID:function(g,i,n){if(typeof i.getElementById!=="undefined"&&!n)return(g=i.getElementById(g[1]))&&g.parentNode?[g]:[]},NAME:function(g,i){if(typeof i.getElementsByName!=="undefined"){for(var n=[],m=i.getElementsByName(g[1]),p=0,q=m.length;p<q;p++)m[p].getAttribute("name")===g[1]&&n.push(m[p]);return n.length===0?null:n}},TAG:function(g,i){return i.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,i,n,m,p,q){g=" "+g[1].replace(/\\/g,
"")+" ";if(q)return g;q=0;for(var u;(u=i[q])!=null;q++)if(u)if(p^(u.className&&(" "+u.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))n||m.push(u);else if(n)i[q]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()},CHILD:function(g){if(g[1]==="nth"){var i=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=i[1]+(i[2]||1)-0;g[3]=i[3]-0}g[0]=e++;return g},ATTR:function(g,i,n,
m,p,q){i=g[1].replace(/\\/g,"");if(!q&&o.attrMap[i])g[1]=o.attrMap[i];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,i,n,m,p){if(g[1]==="not")if((d.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,i);else{g=k.filter(g[3],i,n,true^p);n||m.push.apply(m,g);return false}else if(o.match.POS.test(g[0])||o.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===
true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,i,n){return!!k(n[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)},text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===
g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}},setFilters:{first:function(g,i){return i===0},last:function(g,i,n,m){return i===m.length-1},even:function(g,i){return i%2===0},odd:function(g,i){return i%2===1},lt:function(g,i,n){return i<n[3]-0},gt:function(g,i,n){return i>n[3]-0},nth:function(g,i,n){return n[3]-
0===i},eq:function(g,i,n){return n[3]-0===i}},filter:{PSEUDO:function(g,i,n,m){var p=i[1],q=o.filters[p];if(q)return q(g,n,i,m);else if(p==="contains")return(g.textContent||g.innerText||k.getText([g])||"").indexOf(i[3])>=0;else if(p==="not"){i=i[3];n=0;for(m=i.length;n<m;n++)if(i[n]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+p)},CHILD:function(g,i){var n=i[1],m=g;switch(n){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(n===
"first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":n=i[2];var p=i[3];if(n===1&&p===0)return true;var q=i[0],u=g.parentNode;if(u&&(u.sizcache!==q||!g.nodeIndex)){var y=0;for(m=u.firstChild;m;m=m.nextSibling)if(m.nodeType===1)m.nodeIndex=++y;u.sizcache=q}m=g.nodeIndex-p;return n===0?m===0:m%n===0&&m/n>=0}},ID:function(g,i){return g.nodeType===1&&g.getAttribute("id")===i},TAG:function(g,i){return i==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===
i},CLASS:function(g,i){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(i)>-1},ATTR:function(g,i){var n=i[1];n=o.attrHandle[n]?o.attrHandle[n](g):g[n]!=null?g[n]:g.getAttribute(n);var m=n+"",p=i[2],q=i[4];return n==null?p==="!=":p==="="?m===q:p==="*="?m.indexOf(q)>=0:p==="~="?(" "+m+" ").indexOf(q)>=0:!q?m&&n!==false:p==="!="?m!==q:p==="^="?m.indexOf(q)===0:p==="$="?m.substr(m.length-q.length)===q:p==="|="?m===q||m.substr(0,q.length+1)===q+"-":false},POS:function(g,i,n,m){var p=o.setFilters[i[2]];
if(p)return p(g,n,i,m)}}},x=o.match.POS,r=function(g,i){return"\\"+(i-0+1)},A;for(A in o.match){o.match[A]=RegExp(o.match[A].source+/(?![^\[]*\])(?![^\(]*\))/.source);o.leftMatch[A]=RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[A].source.replace(/\\(\d+)/g,r))}var C=function(g,i){g=Array.prototype.slice.call(g,0);if(i){i.push.apply(i,g);return i}return g};try{Array.prototype.slice.call(t.documentElement.childNodes,0)}catch(J){C=function(g,i){var n=0,m=i||[];if(f.call(g)==="[object Array]")Array.prototype.push.apply(m,
g);else if(typeof g.length==="number")for(var p=g.length;n<p;n++)m.push(g[n]);else for(;g[n];n++)m.push(g[n]);return m}}var w,I;if(t.documentElement.compareDocumentPosition)w=function(g,i){if(g===i){h=true;return 0}if(!g.compareDocumentPosition||!i.compareDocumentPosition)return g.compareDocumentPosition?-1:1;return g.compareDocumentPosition(i)&4?-1:1};else{w=function(g,i){var n,m,p=[],q=[];n=g.parentNode;m=i.parentNode;var u=n;if(g===i){h=true;return 0}else if(n===m)return I(g,i);else if(n){if(!m)return 1}else return-1;
for(;u;){p.unshift(u);u=u.parentNode}for(u=m;u;){q.unshift(u);u=u.parentNode}n=p.length;m=q.length;for(u=0;u<n&&u<m;u++)if(p[u]!==q[u])return I(p[u],q[u]);return u===n?I(g,q[u],-1):I(p[u],i,1)};I=function(g,i,n){if(g===i)return n;for(g=g.nextSibling;g;){if(g===i)return-1;g=g.nextSibling}return 1}}k.getText=function(g){for(var i="",n,m=0;g[m];m++){n=g[m];if(n.nodeType===3||n.nodeType===4)i+=n.nodeValue;else if(n.nodeType!==8)i+=k.getText(n.childNodes)}return i};(function(){var g=t.createElement("div"),
i="script"+(new Date).getTime(),n=t.documentElement;g.innerHTML="<a name='"+i+"'/>";n.insertBefore(g,n.firstChild);if(t.getElementById(i)){o.find.ID=function(m,p,q){if(typeof p.getElementById!=="undefined"&&!q)return(p=p.getElementById(m[1]))?p.id===m[1]||typeof p.getAttributeNode!=="undefined"&&p.getAttributeNode("id").nodeValue===m[1]?[p]:B:[]};o.filter.ID=function(m,p){var q=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&q&&q.nodeValue===p}}n.removeChild(g);
n=g=null})();(function(){var g=t.createElement("div");g.appendChild(t.createComment(""));if(g.getElementsByTagName("*").length>0)o.find.TAG=function(i,n){var m=n.getElementsByTagName(i[1]);if(i[1]==="*"){for(var p=[],q=0;m[q];q++)m[q].nodeType===1&&p.push(m[q]);m=p}return m};g.innerHTML="<a href='#'></a>";if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")o.attrHandle.href=function(i){return i.getAttribute("href",2)};g=null})();t.querySelectorAll&&
function(){var g=k,i=t.createElement("div");i.innerHTML="<p class='TEST'></p>";if(!(i.querySelectorAll&&i.querySelectorAll(".TEST").length===0)){k=function(m,p,q,u){p=p||t;m=m.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!u&&!k.isXML(p))if(p.nodeType===9)try{return C(p.querySelectorAll(m),q)}catch(y){}else if(p.nodeType===1&&p.nodeName.toLowerCase()!=="object"){var F=p.getAttribute("id"),M=F||"__sizzle__";F||p.setAttribute("id",M);try{return C(p.querySelectorAll("#"+M+" "+m),q)}catch(N){}finally{F||
p.removeAttribute("id")}}return g(m,p,q,u)};for(var n in g)k[n]=g[n];i=null}}();(function(){var g=t.documentElement,i=g.matchesSelector||g.mozMatchesSelector||g.webkitMatchesSelector||g.msMatchesSelector,n=false;try{i.call(t.documentElement,"[test!='']:sizzle")}catch(m){n=true}if(i)k.matchesSelector=function(p,q){q=q.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!k.isXML(p))try{if(n||!o.match.PSEUDO.test(q)&&!/!=/.test(q))return i.call(p,q)}catch(u){}return k(q,null,null,[p]).length>0}})();(function(){var g=
t.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){o.order.splice(1,0,"CLASS");o.find.CLASS=function(i,n,m){if(typeof n.getElementsByClassName!=="undefined"&&!m)return n.getElementsByClassName(i[1])};g=null}}})();k.contains=t.documentElement.contains?function(g,i){return g!==i&&(g.contains?g.contains(i):true)}:t.documentElement.compareDocumentPosition?
function(g,i){return!!(g.compareDocumentPosition(i)&16)}:function(){return false};k.isXML=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false};var L=function(g,i){for(var n,m=[],p="",q=i.nodeType?[i]:i;n=o.match.PSEUDO.exec(g);){p+=n[0];g=g.replace(o.match.PSEUDO,"")}g=o.relative[g]?g+"*":g;n=0;for(var u=q.length;n<u;n++)k(g,q[n],m);return k.filter(p,m)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=k.getText;c.isXMLDoc=k.isXML;
c.contains=k.contains})();var Za=/Until$/,$a=/^(?:parents|prevUntil|prevAll)/,ab=/,/,Na=/^.[^:#\[\.,]*$/,bb=Array.prototype.slice,cb=c.expr.match.POS;c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,e=0,f=this.length;e<f;e++){d=b.length;c.find(a,this[e],b);if(e>0)for(var h=d;h<b.length;h++)for(var l=0;l<d;l++)if(b[l]===b[h]){b.splice(h--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,e=b.length;d<e;d++)if(c.contains(this,b[d]))return true})},
not:function(a){return this.pushStack(ma(this,a,false),"not",a)},filter:function(a){return this.pushStack(ma(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){var d=[],e,f,h=this[0];if(c.isArray(a)){var l,k={},o=1;if(h&&a.length){e=0;for(f=a.length;e<f;e++){l=a[e];k[l]||(k[l]=c.expr.match.POS.test(l)?c(l,b||this.context):l)}for(;h&&h.ownerDocument&&h!==b;){for(l in k){e=k[l];if(e.jquery?e.index(h)>-1:c(h).is(e))d.push({selector:l,elem:h,level:o})}h=
h.parentNode;o++}}return d}l=cb.test(a)?c(a,b||this.context):null;e=0;for(f=this.length;e<f;e++)for(h=this[e];h;)if(l?l.index(h)>-1:c.find.matchesSelector(h,a)){d.push(h);break}else{h=h.parentNode;if(!h||!h.ownerDocument||h===b)break}d=d.length>1?c.unique(d):d;return this.pushStack(d,"closest",a)},index:function(a){if(!a||typeof a==="string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var d=typeof a==="string"?c(a,b||this.context):
c.makeArray(a),e=c.merge(this.get(),d);return this.pushStack(!d[0]||!d[0].parentNode||d[0].parentNode.nodeType===11||!e[0]||!e[0].parentNode||e[0].parentNode.nodeType===11?e:c.unique(e))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode",d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,
2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,
b){c.fn[a]=function(d,e){var f=c.map(this,b,d);Za.test(a)||(e=d);if(e&&typeof e==="string")f=c.filter(e,f);f=this.length>1?c.unique(f):f;if((this.length>1||ab.test(e))&&$a.test(a))f=f.reverse();return this.pushStack(f,a,bb.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return b.length===1?c.find.matchesSelector(b[0],a)?[b[0]]:[]:c.find.matches(a,b)},dir:function(a,b,d){var e=[];for(a=a[b];a&&a.nodeType!==9&&(d===B||a.nodeType!==1||!c(a).is(d));){a.nodeType===1&&
e.push(a);a=a[b]}return e},nth:function(a,b,d){b=b||1;for(var e=0;a;a=a[d])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var za=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,Aa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Ba=/<([\w:]+)/,db=/<tbody/i,eb=/<|&#?\w+;/,Ca=/<(?:script|object|embed|option|style)/i,Da=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/\=([^="'>\s]+\/)>/g,P={option:[1,
"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};P.optgroup=P.option;P.tbody=P.tfoot=P.colgroup=P.caption=P.thead;P.th=P.td;if(!c.support.htmlSerialize)P._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d=
c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==B)return this.empty().append((this[0]&&this[0].ownerDocument||t).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this},
wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})},
prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,
this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,e;(e=this[d])!=null;d++)if(!a||c.filter(a,[e]).length){if(!b&&e.nodeType===1){c.cleanData(e.getElementsByTagName("*"));c.cleanData([e])}e.parentNode&&e.parentNode.removeChild(e)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild);
return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,e=this.ownerDocument;if(!d){d=e.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(za,"").replace(fb,'="$1">').replace($,"")],e)[0]}else return this.cloneNode(true)});if(a===true){na(this,b);na(this.find("*"),b.find("*"))}return b},html:function(a){if(a===B)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(za,""):null;
else if(typeof a==="string"&&!Ca.test(a)&&(c.support.leadingWhitespace||!$.test(a))&&!P[(Ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Aa,"<$1></$2>");try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(e){this.empty().append(a)}}else c.isFunction(a)?this.each(function(f){var h=c(this);h.html(a.call(this,f,h.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=
c(this),e=d.html();d.replaceWith(a.call(this,b,e))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){var e,f,h,l=a[0],k=[];if(!c.support.checkClone&&arguments.length===3&&typeof l==="string"&&Da.test(l))return this.each(function(){c(this).domManip(a,
b,d,true)});if(c.isFunction(l))return this.each(function(x){var r=c(this);a[0]=l.call(this,x,b?r.html():B);r.domManip(a,b,d)});if(this[0]){e=l&&l.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:c.buildFragment(a,this,k);h=e.fragment;if(f=h.childNodes.length===1?h=h.firstChild:h.firstChild){b=b&&c.nodeName(f,"tr");f=0;for(var o=this.length;f<o;f++)d.call(b?c.nodeName(this[f],"table")?this[f].getElementsByTagName("tbody")[0]||this[f].appendChild(this[f].ownerDocument.createElement("tbody")):
this[f]:this[f],f>0||e.cacheable||this.length>1?h.cloneNode(true):h)}k.length&&c.each(k,Oa)}return this}});c.buildFragment=function(a,b,d){var e,f,h;b=b&&b[0]?b[0].ownerDocument||b[0]:t;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===t&&!Ca.test(a[0])&&(c.support.checkClone||!Da.test(a[0]))){f=true;if(h=c.fragments[a[0]])if(h!==1)e=h}if(!e){e=b.createDocumentFragment();c.clean(a,b,e,d)}if(f)c.fragments[a[0]]=h?e:1;return{fragment:e,cacheable:f}};c.fragments={};c.each({appendTo:"append",
prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var e=[];d=c(d);var f=this.length===1&&this[0].parentNode;if(f&&f.nodeType===11&&f.childNodes.length===1&&d.length===1){d[b](this[0]);return this}else{f=0;for(var h=d.length;f<h;f++){var l=(f>0?this.clone(true):this).get();c(d[f])[b](l);e=e.concat(l)}return this.pushStack(e,a,d.selector)}}});c.extend({clean:function(a,b,d,e){b=b||t;if(typeof b.createElement==="undefined")b=b.ownerDocument||
b[0]&&b[0].ownerDocument||t;for(var f=[],h=0,l;(l=a[h])!=null;h++){if(typeof l==="number")l+="";if(l){if(typeof l==="string"&&!eb.test(l))l=b.createTextNode(l);else if(typeof l==="string"){l=l.replace(Aa,"<$1></$2>");var k=(Ba.exec(l)||["",""])[1].toLowerCase(),o=P[k]||P._default,x=o[0],r=b.createElement("div");for(r.innerHTML=o[1]+l+o[2];x--;)r=r.lastChild;if(!c.support.tbody){x=db.test(l);k=k==="table"&&!x?r.firstChild&&r.firstChild.childNodes:o[1]==="<table>"&&!x?r.childNodes:[];for(o=k.length-
1;o>=0;--o)c.nodeName(k[o],"tbody")&&!k[o].childNodes.length&&k[o].parentNode.removeChild(k[o])}!c.support.leadingWhitespace&&$.test(l)&&r.insertBefore(b.createTextNode($.exec(l)[0]),r.firstChild);l=r.childNodes}if(l.nodeType)f.push(l);else f=c.merge(f,l)}}if(d)for(h=0;f[h];h++)if(e&&c.nodeName(f[h],"script")&&(!f[h].type||f[h].type.toLowerCase()==="text/javascript"))e.push(f[h].parentNode?f[h].parentNode.removeChild(f[h]):f[h]);else{f[h].nodeType===1&&f.splice.apply(f,[h+1,0].concat(c.makeArray(f[h].getElementsByTagName("script"))));
d.appendChild(f[h])}return f},cleanData:function(a){for(var b,d,e=c.cache,f=c.event.special,h=c.support.deleteExpando,l=0,k;(k=a[l])!=null;l++)if(!(k.nodeName&&c.noData[k.nodeName.toLowerCase()]))if(d=k[c.expando]){if((b=e[d])&&b.events)for(var o in b.events)f[o]?c.event.remove(k,o):c.removeEvent(k,o,b.handle);if(h)delete k[c.expando];else k.removeAttribute&&k.removeAttribute(c.expando);delete e[d]}}});var Ea=/alpha\([^)]*\)/i,gb=/opacity=([^)]*)/,hb=/-([a-z])/ig,ib=/([A-Z])/g,Fa=/^-?\d+(?:px)?$/i,
jb=/^-?\d/,kb={position:"absolute",visibility:"hidden",display:"block"},Pa=["Left","Right"],Qa=["Top","Bottom"],W,Ga,aa,lb=function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){if(arguments.length===2&&b===B)return this;return c.access(this,a,b,true,function(d,e,f){return f!==B?c.style(d,e,f):c.css(d,e)})};c.extend({cssHooks:{opacity:{get:function(a,b){if(b){var d=W(a,"opacity","opacity");return d===""?"1":d}else return a.style.opacity}}},cssNumber:{zIndex:true,fontWeight:true,opacity:true,
zoom:true,lineHeight:true},cssProps:{"float":c.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,d,e){if(!(!a||a.nodeType===3||a.nodeType===8||!a.style)){var f,h=c.camelCase(b),l=a.style,k=c.cssHooks[h];b=c.cssProps[h]||h;if(d!==B){if(!(typeof d==="number"&&isNaN(d)||d==null)){if(typeof d==="number"&&!c.cssNumber[h])d+="px";if(!k||!("set"in k)||(d=k.set(a,d))!==B)try{l[b]=d}catch(o){}}}else{if(k&&"get"in k&&(f=k.get(a,false,e))!==B)return f;return l[b]}}},css:function(a,b,d){var e,f=c.camelCase(b),
h=c.cssHooks[f];b=c.cssProps[f]||f;if(h&&"get"in h&&(e=h.get(a,true,d))!==B)return e;else if(W)return W(a,b,f)},swap:function(a,b,d){var e={},f;for(f in b){e[f]=a.style[f];a.style[f]=b[f]}d.call(a);for(f in b)a.style[f]=e[f]},camelCase:function(a){return a.replace(hb,lb)}});c.curCSS=c.css;c.each(["height","width"],function(a,b){c.cssHooks[b]={get:function(d,e,f){var h;if(e){if(d.offsetWidth!==0)h=oa(d,b,f);else c.swap(d,kb,function(){h=oa(d,b,f)});if(h<=0){h=W(d,b,b);if(h==="0px"&&aa)h=aa(d,b,b);
if(h!=null)return h===""||h==="auto"?"0px":h}if(h<0||h==null){h=d.style[b];return h===""||h==="auto"?"0px":h}return typeof h==="string"?h:h+"px"}},set:function(d,e){if(Fa.test(e)){e=parseFloat(e);if(e>=0)return e+"px"}else return e}}});if(!c.support.opacity)c.cssHooks.opacity={get:function(a,b){return gb.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var d=a.style;d.zoom=1;var e=c.isNaN(b)?"":"alpha(opacity="+b*100+")",f=
d.filter||"";d.filter=Ea.test(f)?f.replace(Ea,e):d.filter+" "+e}};if(t.defaultView&&t.defaultView.getComputedStyle)Ga=function(a,b,d){var e;d=d.replace(ib,"-$1").toLowerCase();if(!(b=a.ownerDocument.defaultView))return B;if(b=b.getComputedStyle(a,null)){e=b.getPropertyValue(d);if(e===""&&!c.contains(a.ownerDocument.documentElement,a))e=c.style(a,d)}return e};if(t.documentElement.currentStyle)aa=function(a,b){var d,e,f=a.currentStyle&&a.currentStyle[b],h=a.style;if(!Fa.test(f)&&jb.test(f)){d=h.left;
e=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;h.left=b==="fontSize"?"1em":f||0;f=h.pixelLeft+"px";h.left=d;a.runtimeStyle.left=e}return f===""?"auto":f};W=Ga||aa;if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b=a.offsetHeight;return a.offsetWidth===0&&b===0||!c.support.reliableHiddenOffsets&&(a.style.display||c.css(a,"display"))==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var mb=c.now(),nb=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
ob=/^(?:select|textarea)/i,pb=/^(?:color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,qb=/^(?:GET|HEAD)$/,Ra=/\[\]$/,T=/\=\?(&|$)/,ja=/\?/,rb=/([?&])_=[^&]*/,sb=/^(\w+:)?\/\/([^\/?#]+)/,tb=/%20/g,ub=/#.*$/,Ha=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!=="string"&&Ha)return Ha.apply(this,arguments);else if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var f=a.slice(e,a.length);a=a.slice(0,e)}e="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b===
"object"){b=c.param(b,c.ajaxSettings.traditional);e="POST"}var h=this;c.ajax({url:a,type:e,dataType:"html",data:b,complete:function(l,k){if(k==="success"||k==="notmodified")h.html(f?c("<div>").append(l.responseText.replace(nb,"")).find(f):l.responseText);d&&h.each(d,[l.responseText,k,l])}});return this},serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&
!this.disabled&&(this.checked||ob.test(this.nodeName)||pb.test(this.type))}).map(function(a,b){var d=c(this).val();return d==null?null:c.isArray(d)?c.map(d,function(e){return{name:b.name,value:e}}):{name:b.name,value:d}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:e})},
getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,e){if(c.isFunction(b)){e=e||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:e})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href,global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:function(){return new E.XMLHttpRequest},accepts:{xml:"application/xml, text/xml",html:"text/html",
script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},ajax:function(a){var b=c.extend(true,{},c.ajaxSettings,a),d,e,f,h=b.type.toUpperCase(),l=qb.test(h);b.url=b.url.replace(ub,"");b.context=a&&a.context!=null?a.context:b;if(b.data&&b.processData&&typeof b.data!=="string")b.data=c.param(b.data,b.traditional);if(b.dataType==="jsonp"){if(h==="GET")T.test(b.url)||(b.url+=(ja.test(b.url)?"&":"?")+(b.jsonp||"callback")+"=?");else if(!b.data||
!T.test(b.data))b.data=(b.data?b.data+"&":"")+(b.jsonp||"callback")+"=?";b.dataType="json"}if(b.dataType==="json"&&(b.data&&T.test(b.data)||T.test(b.url))){d=b.jsonpCallback||"jsonp"+mb++;if(b.data)b.data=(b.data+"").replace(T,"="+d+"$1");b.url=b.url.replace(T,"="+d+"$1");b.dataType="script";var k=E[d];E[d]=function(m){if(c.isFunction(k))k(m);else{E[d]=B;try{delete E[d]}catch(p){}}f=m;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);r&&r.removeChild(A)}}if(b.dataType==="script"&&b.cache===null)b.cache=
false;if(b.cache===false&&l){var o=c.now(),x=b.url.replace(rb,"$1_="+o);b.url=x+(x===b.url?(ja.test(b.url)?"&":"?")+"_="+o:"")}if(b.data&&l)b.url+=(ja.test(b.url)?"&":"?")+b.data;b.global&&c.active++===0&&c.event.trigger("ajaxStart");o=(o=sb.exec(b.url))&&(o[1]&&o[1].toLowerCase()!==location.protocol||o[2].toLowerCase()!==location.host);if(b.dataType==="script"&&h==="GET"&&o){var r=t.getElementsByTagName("head")[0]||t.documentElement,A=t.createElement("script");if(b.scriptCharset)A.charset=b.scriptCharset;
A.src=b.url;if(!d){var C=false;A.onload=A.onreadystatechange=function(){if(!C&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){C=true;c.handleSuccess(b,w,e,f);c.handleComplete(b,w,e,f);A.onload=A.onreadystatechange=null;r&&A.parentNode&&r.removeChild(A)}}}r.insertBefore(A,r.firstChild);return B}var J=false,w=b.xhr();if(w){b.username?w.open(h,b.url,b.async,b.username,b.password):w.open(h,b.url,b.async);try{if(b.data!=null&&!l||a&&a.contentType)w.setRequestHeader("Content-Type",
b.contentType);if(b.ifModified){c.lastModified[b.url]&&w.setRequestHeader("If-Modified-Since",c.lastModified[b.url]);c.etag[b.url]&&w.setRequestHeader("If-None-Match",c.etag[b.url])}o||w.setRequestHeader("X-Requested-With","XMLHttpRequest");w.setRequestHeader("Accept",b.dataType&&b.accepts[b.dataType]?b.accepts[b.dataType]+", */*; q=0.01":b.accepts._default)}catch(I){}if(b.beforeSend&&b.beforeSend.call(b.context,w,b)===false){b.global&&c.active--===1&&c.event.trigger("ajaxStop");w.abort();return false}b.global&&
c.triggerGlobal(b,"ajaxSend",[w,b]);var L=w.onreadystatechange=function(m){if(!w||w.readyState===0||m==="abort"){J||c.handleComplete(b,w,e,f);J=true;if(w)w.onreadystatechange=c.noop}else if(!J&&w&&(w.readyState===4||m==="timeout")){J=true;w.onreadystatechange=c.noop;e=m==="timeout"?"timeout":!c.httpSuccess(w)?"error":b.ifModified&&c.httpNotModified(w,b.url)?"notmodified":"success";var p;if(e==="success")try{f=c.httpData(w,b.dataType,b)}catch(q){e="parsererror";p=q}if(e==="success"||e==="notmodified")d||
c.handleSuccess(b,w,e,f);else c.handleError(b,w,e,p);d||c.handleComplete(b,w,e,f);m==="timeout"&&w.abort();if(b.async)w=null}};try{var g=w.abort;w.abort=function(){w&&Function.prototype.call.call(g,w);L("abort")}}catch(i){}b.async&&b.timeout>0&&setTimeout(function(){w&&!J&&L("timeout")},b.timeout);try{w.send(l||b.data==null?null:b.data)}catch(n){c.handleError(b,w,null,n);c.handleComplete(b,w,e,f)}b.async||L();return w}},param:function(a,b){var d=[],e=function(h,l){l=c.isFunction(l)?l():l;d[d.length]=
encodeURIComponent(h)+"="+encodeURIComponent(l)};if(b===B)b=c.ajaxSettings.traditional;if(c.isArray(a)||a.jquery)c.each(a,function(){e(this.name,this.value)});else for(var f in a)da(f,a[f],b,e);return d.join("&").replace(tb,"+")}});c.extend({active:0,lastModified:{},etag:{},handleError:function(a,b,d,e){a.error&&a.error.call(a.context,b,d,e);a.global&&c.triggerGlobal(a,"ajaxError",[b,a,e])},handleSuccess:function(a,b,d,e){a.success&&a.success.call(a.context,e,d,b);a.global&&c.triggerGlobal(a,"ajaxSuccess",
[b,a])},handleComplete:function(a,b,d){a.complete&&a.complete.call(a.context,b,d);a.global&&c.triggerGlobal(a,"ajaxComplete",[b,a]);a.global&&c.active--===1&&c.event.trigger("ajaxStop")},triggerGlobal:function(a,b,d){(a.context&&a.context.url==null?c(a.context):c.event).trigger(b,d)},httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status===1223}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),
e=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(e)c.etag[b]=e;return a.status===304},httpData:function(a,b,d){var e=a.getResponseHeader("content-type")||"",f=b==="xml"||!b&&e.indexOf("xml")>=0;a=f?a.responseXML:a.responseText;f&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b==="json"||!b&&e.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&e.indexOf("javascript")>=0)c.globalEval(a);return a}});
if(E.ActiveXObject)c.ajaxSettings.xhr=function(){if(E.location.protocol!=="file:")try{return new E.XMLHttpRequest}catch(a){}try{return new E.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}};c.support.ajax=!!c.ajaxSettings.xhr();var ea={},vb=/^(?:toggle|show|hide)$/,wb=/^([+\-]=)?([\d+.\-]+)(.*)$/,ba,pa=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b,d){if(a||a===0)return this.animate(S("show",
3),a,b,d);else{d=0;for(var e=this.length;d<e;d++){a=this[d];b=a.style.display;if(!c.data(a,"olddisplay")&&b==="none")b=a.style.display="";b===""&&c.css(a,"display")==="none"&&c.data(a,"olddisplay",qa(a.nodeName))}for(d=0;d<e;d++){a=this[d];b=a.style.display;if(b===""||b==="none")a.style.display=c.data(a,"olddisplay")||""}return this}},hide:function(a,b,d){if(a||a===0)return this.animate(S("hide",3),a,b,d);else{a=0;for(b=this.length;a<b;a++){d=c.css(this[a],"display");d!=="none"&&c.data(this[a],"olddisplay",
d)}for(a=0;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b,d){var e=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||e?this.each(function(){var f=e?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(S("toggle",3),a,b,d);return this},fadeTo:function(a,b,d,e){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d,e)},animate:function(a,b,d,e){var f=c.speed(b,
d,e);if(c.isEmptyObject(a))return this.each(f.complete);return this[f.queue===false?"each":"queue"](function(){var h=c.extend({},f),l,k=this.nodeType===1,o=k&&c(this).is(":hidden"),x=this;for(l in a){var r=c.camelCase(l);if(l!==r){a[r]=a[l];delete a[l];l=r}if(a[l]==="hide"&&o||a[l]==="show"&&!o)return h.complete.call(this);if(k&&(l==="height"||l==="width")){h.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY];if(c.css(this,"display")==="inline"&&c.css(this,"float")==="none")if(c.support.inlineBlockNeedsLayout)if(qa(this.nodeName)===
"inline")this.style.display="inline-block";else{this.style.display="inline";this.style.zoom=1}else this.style.display="inline-block"}if(c.isArray(a[l])){(h.specialEasing=h.specialEasing||{})[l]=a[l][1];a[l]=a[l][0]}}if(h.overflow!=null)this.style.overflow="hidden";h.curAnim=c.extend({},a);c.each(a,function(A,C){var J=new c.fx(x,h,A);if(vb.test(C))J[C==="toggle"?o?"show":"hide":C](a);else{var w=wb.exec(C),I=J.cur()||0;if(w){var L=parseFloat(w[2]),g=w[3]||"px";if(g!=="px"){c.style(x,A,(L||1)+g);I=(L||
1)/J.cur()*I;c.style(x,A,I+g)}if(w[1])L=(w[1]==="-="?-1:1)*L+I;J.custom(I,L,g)}else J.custom(I,C,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]);this.each(function(){for(var e=d.length-1;e>=0;e--)if(d[e].elem===this){b&&d[e](true);d.splice(e,1)}});b||this.dequeue();return this}});c.each({slideDown:S("show",1),slideUp:S("hide",1),slideToggle:S("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){c.fn[a]=function(d,e,f){return this.animate(b,
d,e,f)}});c.extend({speed:function(a,b,d){var e=a&&typeof a==="object"?c.extend({},a):{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};e.duration=c.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in c.fx.speeds?c.fx.speeds[e.duration]:c.fx.speeds._default;e.old=e.complete;e.complete=function(){e.queue!==false&&c(this).dequeue();c.isFunction(e.old)&&e.old.call(this)};return e},easing:{linear:function(a,b,d,e){return d+e*a},swing:function(a,b,d,e){return(-Math.cos(a*
Math.PI)/2+0.5)*e+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]||c.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a=parseFloat(c.css(this.elem,this.prop));return a&&a>-1E4?a:0},custom:function(a,b,d){function e(l){return f.step(l)}
var f=this,h=c.fx;this.startTime=c.now();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start;this.pos=this.state=0;e.elem=this.elem;if(e()&&c.timers.push(e)&&!ba)ba=setInterval(h.tick,h.interval)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;
this.custom(this.cur(),0)},step:function(a){var b=c.now(),d=true;if(a||b>=this.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var e in this.options.curAnim)if(this.options.curAnim[e]!==true)d=false;if(d){if(this.options.overflow!=null&&!c.support.shrinkWrapBlocks){var f=this.elem,h=this.options;c.each(["","X","Y"],function(k,o){f.style["overflow"+o]=h.overflow[k]})}this.options.hide&&c(this.elem).hide();if(this.options.hide||
this.options.show)for(var l in this.options.curAnim)c.style(this.elem,l,this.options.orig[l]);this.options.complete.call(this.elem)}return false}else{a=b-this.startTime;this.state=a/this.options.duration;b=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||b](this.state,a,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=
c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length||c.fx.stop()},interval:13,stop:function(){clearInterval(ba);ba=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===
b.elem}).length};var xb=/^t(?:able|d|h)$/i,Ia=/^(?:body|html)$/i;c.fn.offset="getBoundingClientRect"in t.documentElement?function(a){var b=this[0],d;if(a)return this.each(function(l){c.offset.setOffset(this,a,l)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);try{d=b.getBoundingClientRect()}catch(e){}var f=b.ownerDocument,h=f.documentElement;if(!d||!c.contains(h,b))return d||{top:0,left:0};b=f.body;f=fa(f);return{top:d.top+(f.pageYOffset||c.support.boxModel&&
h.scrollTop||b.scrollTop)-(h.clientTop||b.clientTop||0),left:d.left+(f.pageXOffset||c.support.boxModel&&h.scrollLeft||b.scrollLeft)-(h.clientLeft||b.clientLeft||0)}}:function(a){var b=this[0];if(a)return this.each(function(x){c.offset.setOffset(this,a,x)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d,e=b.offsetParent,f=b.ownerDocument,h=f.documentElement,l=f.body;d=(f=f.defaultView)?f.getComputedStyle(b,null):b.currentStyle;
for(var k=b.offsetTop,o=b.offsetLeft;(b=b.parentNode)&&b!==l&&b!==h;){if(c.offset.supportsFixedPosition&&d.position==="fixed")break;d=f?f.getComputedStyle(b,null):b.currentStyle;k-=b.scrollTop;o-=b.scrollLeft;if(b===e){k+=b.offsetTop;o+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&xb.test(b.nodeName))){k+=parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}e=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&d.overflow!=="visible"){k+=
parseFloat(d.borderTopWidth)||0;o+=parseFloat(d.borderLeftWidth)||0}d=d}if(d.position==="relative"||d.position==="static"){k+=l.offsetTop;o+=l.offsetLeft}if(c.offset.supportsFixedPosition&&d.position==="fixed"){k+=Math.max(h.scrollTop,l.scrollTop);o+=Math.max(h.scrollLeft,l.scrollLeft)}return{top:k,left:o}};c.offset={initialize:function(){var a=t.body,b=t.createElement("div"),d,e,f,h=parseFloat(c.css(a,"marginTop"))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",
height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>";a.insertBefore(b,a.firstChild);d=b.firstChild;e=d.firstChild;f=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=e.offsetTop!==5;this.doesAddBorderForTableAndCells=
f.offsetTop===5;e.style.position="fixed";e.style.top="20px";this.supportsFixedPosition=e.offsetTop===20||e.offsetTop===15;e.style.position=e.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=e.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==h;a.removeChild(b);c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.css(a,
"marginTop"))||0;d+=parseFloat(c.css(a,"marginLeft"))||0}return{top:b,left:d}},setOffset:function(a,b,d){var e=c.css(a,"position");if(e==="static")a.style.position="relative";var f=c(a),h=f.offset(),l=c.css(a,"top"),k=c.css(a,"left"),o=e==="absolute"&&c.inArray("auto",[l,k])>-1;e={};var x={};if(o)x=f.position();l=o?x.top:parseInt(l,10)||0;k=o?x.left:parseInt(k,10)||0;if(c.isFunction(b))b=b.call(a,d,h);if(b.top!=null)e.top=b.top-h.top+l;if(b.left!=null)e.left=b.left-h.left+k;"using"in b?b.using.call(a,
e):f.css(e)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),e=Ia.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.css(a,"marginTop"))||0;d.left-=parseFloat(c.css(a,"marginLeft"))||0;e.top+=parseFloat(c.css(b[0],"borderTopWidth"))||0;e.left+=parseFloat(c.css(b[0],"borderLeftWidth"))||0;return{top:d.top-e.top,left:d.left-e.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||t.body;a&&!Ia.test(a.nodeName)&&
c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(e){var f=this[0],h;if(!f)return null;if(e!==B)return this.each(function(){if(h=fa(this))h.scrollTo(!a?e:c(h).scrollLeft(),a?e:c(h).scrollTop());else this[d]=e});else return(h=fa(f))?"pageXOffset"in h?h[a?"pageYOffset":"pageXOffset"]:c.support.boxModel&&h.document.documentElement[d]||h.document.body[d]:f[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();
c.fn["inner"+b]=function(){return this[0]?parseFloat(c.css(this[0],d,"padding")):null};c.fn["outer"+b]=function(e){return this[0]?parseFloat(c.css(this[0],d,e?"margin":"border")):null};c.fn[d]=function(e){var f=this[0];if(!f)return e==null?null:this;if(c.isFunction(e))return this.each(function(l){var k=c(this);k[d](e.call(this,l,k[d]()))});if(c.isWindow(f))return f.document.compatMode==="CSS1Compat"&&f.document.documentElement["client"+b]||f.document.body["client"+b];else if(f.nodeType===9)return Math.max(f.documentElement["client"+
b],f.body["scroll"+b],f.documentElement["scroll"+b],f.body["offset"+b],f.documentElement["offset"+b]);else if(e===B){f=c.css(f,d);var h=parseFloat(f);return c.isNaN(h)?f:h}else return this.css(d,typeof e==="string"?e:e+"px")}})})(window);
}/*
 * Modified to use '@' character as template marker. [Freddie]
 */
(function($) {
    /*
    * jBind 1.5.3
    *
    * Copyright (c) 2009 Arash Karimzadeh (arashkarimzadeh.com)
    * Licensed under the MIT (MIT-LICENSE.txt)
    * http://www.opensource.org/licenses/mit-license.php
    *
    * Date: Jan 30 2009
    */
    $.fn.bindTo = function(data, options) {
        var defaults = {
            appendTo: null,
            root: 'data',
            onBind: null,
            onBound: null,
            fill: false
        };

        var options = $.extend(defaults, options);

        if ($.isFunction(options.onBind))
            options.onBind();
        var template = '<!--bind.template-->' + ((options.fill) ? this.html() : this.parent().html()) + '<!--bind.template-->';
        var repeaters = this.bindTo.findRepeaters(template);
        var fixedData = {};
        fixedData[options.root] = data;
        var content = this.bindTo.traverse(
									  'bind.template',
									  fixedData,
									  repeaters['<!--bind.template-->'].template,
									  repeaters,
									  'bind.template'
									 );
        if (options.fill)
            this.html(content);
        if (options.appendTo != null)
            content = $(content).appendTo($(options.appendTo));
        if ($.isFunction(options.onBound))
            options.onBound(content, data);
        return content;
    }
    $.extend($.fn.bindTo,
	{
	    templates: {},
	    traverse: function(key, data, template, repeaters, parent) {
	        if (typeof data == 'string') {
	            //var regExpString = "(?:%7B)" + key + "(?:%7D)\{" + key + "\}";
	            //return template.replace(new RegExp(regExpString), data);
	            Encoder.EncodeType = "entity";
	            var encodedData = Encoder.htmlEncode(data);
	            template = template.replace(new RegExp("\@" + key + "\@", "ig"), encodedData);
	            template = template.replace(new RegExp("\@#" + key + "\@", "ig"), data);
	            return template;
	        } else if (typeof data == 'number' || typeof data == 'boolean') {
	            return template.replace(new RegExp("\@" + key + "\@", "ig"), data);
	        } else if (typeof data == 'object') {
	            if (typeof data.length == 'undefined') {
	                if (repeaters['<!--' + parent + '-->'].action)
	                    template = $.fn.bindTo[repeaters['<!--' + parent + '-->'].action](template, data) || template;
	                for (var item in data) {
	                    if (typeof data[item] == 'object') {
	                        if (typeof repeaters['<!--' + item + '-->'] != 'undefined') {//Skip not defined templates for child in aggregate object
	                            var temp = $.fn.bindTo.traverse(item, data[item], repeaters['<!--' + item + '-->'].template, repeaters, item);
	                            template = template.replace('<!--' + item + '-->', temp);
	                        }
	                    } else {
	                        var temp = $.fn.bindTo.traverse(item, data[item], template, repeaters);
	                        template = temp;
	                    }
	                }
	                return template;
	            } else {
	                var listTemplate = '';
	                for (var item in data) {
	                    listTemplate += $.fn.bindTo.traverse(item, data[item], repeaters['<!--' + key + '-->'].template, repeaters, key);
	                }
	                return listTemplate;
	            }
	        }
	        return ''; //(handle extjs) this will return '' for function in case you extned array or object
	    },
	    findRepeaters: function(template) {
	        $this = this;
	        var templates = {};
	        var reg = new RegExp('<!--[.a-zA-Z1-9]*-->', 'g');
	        var regAction = new RegExp('<!--action:[$.a-zA-Z1-9]*-->', 'g');
	        var matches = (template.match(reg));
	        $.each(matches,
				   function() {
				       if (templates[this] != undefined)/*template is already added because end tag and start tags are the same*/
				           return true;
				       templates[this] = {};
				       var temp = template.substring(template.indexOf(this) + this.length, template.lastIndexOf(this));
				       var innerMatches = (temp.match(reg)) || [];
				       $.each(innerMatches,
							   function() {
							       if (temp.indexOf(this) > -1) {
							           var innerRepeater = temp.substring(temp.indexOf(this), temp.lastIndexOf(this) + this.length);
							           temp = temp.replace(innerRepeater, this);
							       }
							   }
						)
				       var actions = (temp.match(regAction)) || [];
				       var key = this;
				       $.each(actions,
							   function() {
							       var action = this.substring(11, this.length - 3);
							       templates[key].action = action;
							       temp = temp.replace(actions, '');
							   }
						)
				       templates[this].template = temp;
				   }
			)
	        return templates;
	    }
	}
);
    //
})(jQuery);
/*********/
/* TIMER */
/*********/

jQuery.fn.extend({
    everyTime: function(interval, label, fn, times, belay) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, times, belay);
        });
    },
    oneTime: function(interval, label, fn) {
        return this.each(function() {
            jQuery.timer.add(this, interval, label, fn, 1);
        });
    },
    stopTime: function(label, fn) {
        return this.each(function() {
            jQuery.timer.remove(this, label, fn);
        });
    }
});

jQuery.extend({
    timer: {
        guid: 1,
        global: {},
        regex: /^([0-9]+)\s*(.*s)?$/,
        powers: {
            // Yeah this is major overkill...
            'ms': 1,
            'cs': 10,
            'ds': 100,
            's': 1000,
            'das': 10000,
            'hs': 100000,
            'ks': 1000000
        },
        timeParse: function(value) {
            if (value == undefined || value == null)
                return null;
            var result = this.regex.exec(jQuery.trim(value.toString()));
            if (result[2]) {
                var num = parseInt(result[1], 10);
                var mult = this.powers[result[2]] || 1;
                return num * mult;
            } else {
                return value;
            }
        },
        add: function(element, interval, label, fn, times, belay) {
            var counter = 0;

            if (jQuery.isFunction(label)) {
                if (!times)
                    times = fn;
                fn = label;
                label = interval;
            }

            interval = jQuery.timer.timeParse(interval);

            if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
                return;

            if (times && times.constructor != Number) {
                belay = !!times;
                times = 0;
            }

            times = times || 0;
            belay = belay || false;

            if (!element.$timers)
                element.$timers = {};

            if (!element.$timers[label])
                element.$timers[label] = {};

            fn.$timerID = fn.$timerID || this.guid++;

            var handler = function() {
                if (belay && this.inProgress)
                    return;
                this.inProgress = true;
                if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
                    jQuery.timer.remove(element, label, fn);
                this.inProgress = false;
            };

            handler.$timerID = fn.$timerID;

            if (!element.$timers[label][fn.$timerID])
                element.$timers[label][fn.$timerID] = window.setInterval(handler, interval);

            if (!this.global[label])
                this.global[label] = [];
            this.global[label].push(element);

        },
        remove: function(element, label, fn) {
            var timers = element.$timers, ret;

            if (timers) {

                if (!label) {
                    for (label in timers)
                        this.remove(element, label, fn);
                } else if (timers[label]) {
                    if (fn) {
                        if (fn.$timerID) {
                            window.clearInterval(timers[label][fn.$timerID]);
                            delete timers[label][fn.$timerID];
                        }
                    } else {
                        for (var fn in timers[label]) {
                            window.clearInterval(timers[label][fn]);
                            delete timers[label][fn];
                        }
                    }

                    for (ret in timers[label]) break;
                    if (!ret) {
                        ret = null;
                        delete timers[label];
                    }
                }

                for (ret in timers) break;
                if (!ret)
                    element.$timers = null;
            }
        }
    }
});

if (jQuery.browser.msie)
    jQuery(window).one("unload", function() {
        var global = jQuery.timer.global;
        for (var label in global) {
            var els = global[label], i = els.length;
            while (--i)
                jQuery.timer.remove(els[i], label);
        }
    });

String.prototype.startsWith = function(str) {
    return (this.indexOf(str) === 0);
}

if (!window['Silobreaker']) {
    window['Silobreaker'] = {};
}

/// <summary>The base url to the Silobreaker API.</summary>
Silobreaker.apiBaseUrl = 'http://api.silobreaker.com/';

/// <summary>The link base url to use for document and entity links to Silobreaker.</summary>
Silobreaker.linkBaseUrl = 'http://www.silobreaker.com/';

/// <summary>The default target for links. Set to null to use current window.</summary>
Silobreaker.defaultTarget = '_blank';

/// <summary>The api key to use when calling the Silobreaker API.</summary>
Silobreaker.apiKey = '';

Silobreaker.timeZoneOffset = 0;

Silobreaker.currentLanguage = "English";

/// <summary>A global counter.</summary>
Silobreaker.globalCounter = 2759;

Silobreaker.getUniqueInteger = function() {
    /// <summary>Returns a unique int.</summary>
    Silobreaker.globalCounter++;
    return Silobreaker.globalCounter;
};

/// <summary>Sets global widget options.</summary>
Silobreaker.configureWidgets = function(options) {
    if (options) {
        if (options.apiBaseUrl) {
            Silobreaker.apiBaseUrl = options.apiBaseUrl;
        }

        if (options.linkBaseUrl) {
            Silobreaker.linkBaseUrl = options.linkBaseUrl;
        }

        if (options.defaultTarget) {
            Silobreaker.defaultTarget = options.defaultTarget;
        }

        if (options.apiKey) {
            Silobreaker.apiKey = options.apiKey;
        }

        if (options.currentLanguage) {
            Silobreaker.currentLanguage = options.currentLanguage;
        }

        if (options.timeZoneOffset) {
            Silobreaker.timeZoneOffset = options.timeZoneOffset;
        }                 
    }
};

/// <summary>Click handler, if set, will be used when an item is clicked in any widget.</summary>
Silobreaker.clickHandler = null;

Silobreaker.injectWidget = function(element, widget) {
    /// <summary>Injects widget html template code within a DOM element and invokes the widget's initialization code.</summary>
    /// <param name="element" mayBeNull="false">An id of the DOM element OR the DOM element itself OR the JQuery object of the element.</param>
    /// <param name="widget" mayBeNull="false">The widget that will be initalized with the new template.</param>

    Silobreaker.injectWidgetTemplateFromHtml(element, widget, widget.htmlTemplate, widget.defaultCss);
};

Silobreaker.injectWidgetTemplateFromUrl = function(element, widget, templateUrl) {
    /// <summary>Injects widget html template code within a DOM element and invokes the widget's initialization code.</summary>
    /// <param name="element" mayBeNull="false">An id of the DOM element OR the DOM element itself OR the JQuery object of the element.</param>
    /// <param name="templateUrl" mayBeNull="false">The url from where to get the html template.</param>

    var templateHtml = jQuery.ajax({
        url: templateUrl,
        async: false
    }).responseText;

    Silobreaker.injectWidgetTemplateFromHtml(element, widget, templateHtml);
};

Silobreaker.injectWidgetTemplateFromHtml = function(element, widget, htmlTemplate, defaultCss) {
    /// <summary>Injects widget html template code within a DOM element and invokes the widget's initialization code.</summary>
    /// <param name="element" mayBeNull="false">An id of the DOM element OR the DOM element itself OR the JQuery object of the element.</param>
    /// <param name="widget" mayBeNull="false">The widget that will be initalized with the new template.</param>
    /// <param name="htmlTemplate" mayBeNull="false">The html template that will be injected.</param>

    if (!widget.id)
        throw "InvalidOperationException: widget has no id.";

    var jqElements = Silobreaker.getJQueryFromElement(element);

    if (jqElements.length != 1)
        throw "No unique element found " + element;

    // Instead of setting html() which in jquery 1.4.2 strips comments in IE
    jqElements.empty().append(htmlTemplate);
    //jqElements.html(htmlTemplate);

    var newHeadElements = '';

    // Append widget style sheet to header if not added before
    if (defaultCss && jQuery('style[id="' + widget.id + '"]').length == 0) {
        newHeadElements += '<style type="text/css" id="' + widget.id + '">' + defaultCss + '</style>';
    }

    // Append default style sheet to header if not added before
    if (Silobreaker.defaultCss && jQuery('style[id="' + 'Silobreaker.defaultCss' + '"]').length == 0) {
        newHeadElements += '<style type="text/css" id="' + 'Silobreaker.defaultCss' + '">' + Silobreaker.defaultCss + '</style>';
    }

    if (newHeadElements.length > 0) {
        jQuery('head').append(newHeadElements);
    }
    if (widget.initialize)
        widget.initialize(jqElements[0]);
};


Silobreaker.invokeApi = function(url, callback, apiKey) {
    /// <summary>Invokes the Silobreaker rest API and sends the data back to a callback function.</summary>
    /// <param name="url">A relative Url to the rest api, i.e. "documents/United Nations".</param>
    /// <param name="callback">A callback function to pass the result data to.</param>
    /// <param name="apiKey">Optional. The api key to use when invoking the silobreaker api.</param>


    if (!apiKey || apiKey == null) {
        apiKey = Silobreaker.apiKey;
    }

    var invokeUrl = Silobreaker.apiBaseUrl;

    if (!invokeUrl.endsWith('/'))
        invokeUrl += '/';

    invokeUrl += url;

    var separator = "?";
    if (invokeUrl.indexOf("?") != -1)
        separator = "&";
    invokeUrl += separator + "apikey=" + apiKey + "&type=jsonp&callback=?";

    jQuery.getJSON(invokeUrl, callback);
};


Silobreaker.getJQueryFromElement = function(element) {
    /// <summary>
    ///     Gets a jquery object from an element, an element id or a jquery object iteself
    /// </summary>
    /// <param name="element" mayBeNull="true">An id of the DOM element OR the DOM element itself OR the JQuery object of the element.</param>
    var jqElements = null;

    if (typeof element == "string")
        jqElements = jQuery("#" + element);
    else if (element instanceof jQuery)
        jqElements = element;
    else
        jqElements = jQuery(element);

    return jqElements;
};

Silobreaker.groupByItemType = function(data) {
    /// <summary>
    ///     Groups an item set on format returned from the Silobreaker API to the following format:
    ///     [{ Type: "Organization", Items: [ { Description: "United Nations", ... }, {...} ] }]
    /// </summary>
    /// <param name="data">An item set returned from the Silobreaker API. E.g.: [{Description: "United Nations", Type: "Organization" }, {...} ]</param>

    if (!data)
        throw "ArgumentNullException: data is undefined.";

    if (!jQuery.isArray(data))
        throw "ArgumentException: data is not an array.";

    var groupedByType = {};
    for (var i = 0; i < data.length; i++) {

        var item = data[i];

        if (!groupedByType[item.Type]) {
            groupedByType[item.Type] = {};
            groupedByType[item.Type].Items = [];
            groupedByType[item.Type].Type = item.Type;
        }

        groupedByType[item.Type].Items.push(item);
    }

    var groupedData = [];
    for (property in groupedByType) {
        var item = groupedByType[property];
        groupedData.push(item);
    }

    return groupedData;
};

Silobreaker.decorateItemLinks = function(links, items, target, linkBaseUrl) {
    /// <summary>
    ///     Decorates a set of links with href attributes pointing to correct page in Silobreaker.
    ///     Note, that this function assumes that the link contains an itemref attribute.
    /// </summary>
    /// <param name="links">
    ///     A jQuery object containing all selected links to decorate.
    /// </param>
    /// <param name="items">
    ///     Array of item data. Each item data will be attached to matching element.
    /// </param>
    /// <param name="target">
    ///     The target to assign to the anchor element.
    /// </param>
    /// <param name="linkBaseUrl">
    ///     The url from where all item links will base from.
    /// </param>

    if (!(links instanceof jQuery))
        throw "links must be a jQuery array.";

    var linkTarget = Silobreaker.defaultTarget;
    if (target && target != null) {
        linkTarget = target;
    }


    // Attach item data to each link element
    Silobreaker.attachItemDataToElements(links, items);

    links.each(function() {
        var link = jQuery(this);
        var entityId = link.attr("itemref");
        if (!entityId) {
            return;
        }

        // Apply link only if current link is empty
        if (!(link.attr("href") && link.attr("href") != '')) {
            var url = Silobreaker.getUrlForItem(entityId, linkBaseUrl);
            link.attr("href", url);
            link.attr("target", linkTarget);
        }
    });
};

Silobreaker.attachItemDataToElements = function(elements, items) {
    /// <summary>
    ///     Given a set of elements (having an itemref attribute)
    ///     attach corresponding item data found in the items dictionary.
    /// </summary>
    /// <param name="elements">
    ///     A jquery object containing a list of elements with itemref attributes
    ///     that should have item data attached.
    /// </param>
    /// <param name="items">
    ///     A dictionary of itemref -> itemdata
    /// </param>

    elements.each(function() {
        var element = jQuery(this);
        var itemref = element.attr("itemref");

        var entity;
        for (index in items) {
            if (items[index].Id == itemref) {
                entity = items[index];
                break;
            }
        }
        if (typeof (entity) != 'undefined') {
            element.data("entity", entity)
        }
    });

};

Silobreaker.getUrlForItem = function(id, linkBaseUrl) {
    /// <summary>
    ///     Creates an url pointing to a Silobreaker page for an item.
    /// </summary>
    /// <param name="id">The id of the item create an url for.</param>
    /// <param name="linkBaseUrl">
    ///     The url from where all item links will base from.
    /// </param>
    
    if (typeof (id) != "string")
        throw "Parameter id must be a string";

    if (!linkBaseUrl || linkBaseUrl == null) {
        linkBaseUrl = Silobreaker.linkBaseUrl;
    }

    if (id.beginsWith("11_") || id.beginsWith("7_")) {
        return linkBaseUrl + "View360.aspx?Item=" + id;
    }
    else if (id.beginsWith("5_")) {
        return linkBaseUrl + "DocumentReader.aspx?Item=" + id;
    }
    else if (id.beginsWith("16_")) {
        return linkBaseUrl + "DocumentClusterReader.aspx?Item=" + id;
    }

    throw "Unknown item id.";
};



Silobreaker.WireUpItems = function(links, items, popupHandler, clickHandler, linkBaseUrl) {
    /// <summary>
    ///     Registers hover and click events for item elements.
    /// </summary>
    /// <param name="links">
    ///     Arrray of jQuery elements to apply popup functionality to.
    /// </param>
    /// <param name="items">
    ///     [Optional] Array of item data. Each item data will be attached to matching element.
    /// </param>
    /// <param name="popupHandler">
    ///     [Optional] Popup handler that handles hover of items.
    /// </param>
    /// <param name="clickHandler">
    ///     [Optional] Click handler that handles click of items.
    /// </param>
    /// <param name="linkBaseUrl">
    ///     The url from where all item links will base from.
    /// </param>
            

    // Wire up the behavior when entities are clicked
    if (clickHandler) {
        clickHandler.wireUpClickBehavior(links, items);
    } else if (Silobreaker.clickHandler) {
        Silobreaker.clickHandler.wireUpClickBehavior(links, items);
    }
    else {
        Silobreaker.decorateItemLinks(links, items, null, linkBaseUrl);
    }

    // Wire up hover popups
    if (popupHandler) {
        popupHandler.clickHandler = clickHandler;
        popupHandler.wireUpHoverBehavior(links);
    }
};

Silobreaker.AddBranding = function(widget, infoText, helpText) {
    /// <summary>
    ///     Surrounds a widget with Silobreaker branding.
    /// </summary>
    /// <param name="widget">
    ///     The widget to brand (as a jQuery object).
    /// </param>
    /// <param name="infoText">
    ///     Text to show in the footer of the widget.
    /// </param>
    /// <param name="helpText">
    ///     Text to show when hovering the help icon.
    /// </param>

    widget.append("<div class='footer'><a href='http://www.silobreaker.com'><img height='23' src='" + Silobreaker.apiBaseUrl + "Content/Silobreaker_logo_159px.png'/></a></div>");
    widget.prepend("<div class='header'><img src='http://www.silobreaker.com/Images/Help.gif' title='Show Help'/><div class='helptext' style='display:none;'><div class='title'>About " + infoText + "</div>" + helpText + "<div class='close'>close</div></div><div class='infotext'>" + infoText + "</div></div>");

    var popup = jQuery(".header .helptext");
    var img = jQuery(".header img", widget);



    img.click(function() {
        var imgPos = jQuery(this).position();
        popup.css("top", imgPos.top + 20);
        popup.css("left", imgPos.left - popup.width() + 10);            
        popup.show();
    });

    jQuery(".close", popup).click(function() {
        popup.hide();
    });
};


Silobreaker.UpdateInfoText = function(widget, text) {
    /// <summary>
    ///     Updated the footer text in the widget.
    /// </summary>
    /// <param name="text">
    ///     The text to show.
    /// </param>

    jQuery(".header .infotext", widget).text(text);
};

/****** Helper functions for strings *****/
String.prototype.beginsWith = function(t, i) {
    var reg = new RegExp("^" + t);
    return reg.test(this);
};

String.prototype.endsWith = function(t, i) {
    var reg = new RegExp(t + "$");
    return reg.test(this);
};

/****** Helper functions for date *****/
Date.prototype.setIsoDate = function(string) {
    var regexp = "([0-9]{4})(-([0-9]{2})(-([0-9]{2})" +
    "(T([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?" +
    "(Z|(([-+])([0-9]{2}):([0-9]{2})))?)?)?)?";
    var d = string.match(new RegExp(regexp));

    var offset = 0;
    var date = new Date(d[1], 0, 1);

    if (d[3]) { date.setMonth(d[3] - 1); }
    if (d[5]) { date.setDate(d[5]); }
    if (d[7]) { date.setHours(d[7]); }
    if (d[8]) { date.setMinutes(d[8]); }
    if (d[10]) { date.setSeconds(d[10]); }
    if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
    if (d[14]) {
        offset = (Number(d[16]) * 60) + Number(d[17]);
        offset *= ((d[15] == '-') ? 1 : -1);
    }

    offset -= date.getTimezoneOffset();
    time = (Number(date) + (offset * 60 * 1000));
    this.setTime(Number(time));
};



Date.prototype.getIsoString = function() {
    function pad(n) { return n < 10 ? '0' + n : n }
    return this.getUTCFullYear() + '-'
      + pad(this.getUTCMonth() + 1) + '-'
      + pad(this.getUTCDate()) + 'T'
      + pad(this.getUTCHours()) + ':'
      + pad(this.getUTCMinutes()) + ':'
      + pad(this.getUTCSeconds()) + 'Z'
};

Date.fromIsoDate = function(string) {
    var d = new Date();
    d.setIsoDate(string);
    return d;
};

Date.prototype.prettyString = function() {
    var diff = (((new Date()).getTime() - this.getTime()) / 1000);
    var day_diff = Math.floor(diff / 86400);

    if (isNaN(day_diff) || day_diff < 0)
        return "";

    return day_diff == 0 && (
		diff < 60 && "just now" ||
		diff < 120 && "1 minute ago" ||
		diff < 3600 && Math.floor(diff / 60) + " minutes ago" ||
		diff < 7200 && "1 hour ago" ||
		diff < 86400 && Math.floor(diff / 3600) + " hours ago") ||
	    day_diff == 1 && "Yesterday" ||
	    day_diff < 7 && day_diff + " days ago" ||
	    this.toDateString();

};

Silobreaker.Resources = function() {

    var translations = {};
    var defaultLanguage = "en";

    this.add = function(language, addedTranslations) {
        if (!translations[language]) {
            translations[language] = {};
        }

        var matchingDictionary = translations[language];

        for (var entry in addedTranslations) {
            matchingDictionary[entry] = addedTranslations[entry];
        }
    };

    this.getTranslation = function(entry) {
        if (translations[Silobreaker.currentLanguage] && translations[Silobreaker.currentLanguage][entry]) {
            return translations[Silobreaker.currentLanguage][entry];
        }

        if (translations[defaultLanguage]) {
            return translations[defaultLanguage][entry];
        }
        
        return null;
    };
};

Silobreaker.Strings = new Silobreaker.Resources();
/********************************/
/****** Popup functionality *****/
/********************************/
Silobreaker.PopupUrlResolver = function() {
    this.createUrl = function(itemId, context) {
        /// <summary>
        ///     Returns Silobreaker urls to popup pages.
        /// </summary>
        var popupUrl = "";
        if (itemId.beginsWith("11_"))
            popupUrl = "/TermPopup.aspx?itemRef=" + itemId;
        else if (itemId.beginsWith("5_"))
            popupUrl = "/DocumentPopup.aspx?itemRef=" + itemId;

        if (context)
            popupUrl += "&FreetextSearchStrings=" + context;

        return "http://www.silobreaker.com" + popupUrl;
    };
};

Silobreaker.IFramePopup = function() {
    /// <summary>
    ///     A widget instanciator that creates a popup showing an iframe.
    /// </summary>
    this.popupUrlResolver = new Silobreaker.PopupUrlResolver();

    this.createPopup = function(itemData, context) {
        var url = this.popupUrlResolver.createUrl(itemData.Id, context);
        var popup = jQuery("<iframe style='display:none; position:absolute; padding:0px; height:100%; width:400px;' scrolling='no' frameborder='0'></iframe>");
        popup.attr("src", url);
        return popup;
    };
};

Silobreaker.WidgetPopup = function(widgetName, apiKey, linkBaseUrl) {
    /// <summary>
    ///     A widget instanciator that creates a popup showing a widget.
    /// </summary>  
    /// <param name="widgetName">
    ///     Name of the widget. Used for logging.
    /// </param>

    var _widgetName = widgetName;
    var _apiKey = apiKey;
    var _linkBaseUrl = linkBaseUrl;

    this.popupUrlResolver = new Silobreaker.PopupUrlResolver();

    this.createPopup = function(itemData, context, clickHandler) {

        var popup = jQuery("<div style='display:none; position:absolute; padding:0px; background-color:white; z-index:5000;'> </div>");

        var popupWidget = null;

        if (itemData.Id.beginsWith('11_')) {
            popupWidget = new Silobreaker.EntitySummary({ context: context, entity: itemData.EntityReference, widgetName: _widgetName, operation: "Popup", apiKey: _apiKey, linkBaseUrl: _linkBaseUrl });
        }

        if (popupWidget) {
            Silobreaker.injectWidget(popup, popupWidget);
            popupWidget.showPopups = false;
            popupWidget.clickHandler = clickHandler;
        }

        return popup;
    };
};

Silobreaker.EvidencePopup = function(widgetName, apiKey, linkBaseUrl) {

    var _apiKey = apiKey;
    var _linkBaseUrl = linkBaseUrl;

    if (widgetName && widgetName != null) {
        this.widgetName = widgetName;
    }

    this.createPopup = function(context, node1, node2, clickHandler) {
        var popup = jQuery("<div style='display:none; position:absolute; padding:0px; z-index:5000;'>EvidencePopup</div>");
        var popupWidget = new Silobreaker.Evidence({ context: context, node1: node1, node2: node2, apiKey: _apiKey, linkBaseUrl:_linkBaseUrl });
        Silobreaker.injectWidget(popup, popupWidget);
        popupWidget.clickHandler = clickHandler;
        return popup;
    };
};

Silobreaker.PopupHandler = function(widgetName, clickHandler, apiKey, linkBaseUrl) {
    /// <summary>
    ///     Class holding functionality to show a popup when an element is hovered. 
    /// </summary>
    /// <param name="widgetName">
    ///     Name of the widget. Used for logging.
    /// </param>
    /// <param name="clickHandler">
    ///     Optionally a click handler the popup should use.
    /// </param>

   
    this.clickHandler = null;
    this.apiKey = null;
    this.linkBaseUrl = null;

    if (clickHandler) {
        this.clickHandler = clickHandler;
    }

    if (apiKey) {
        this.apiKey = apiKey;
    }
    
    if (linkBaseUrl) {
        this.linkBaseUrl = linkBaseUrl;
    }

    this.popupInstatiator = new Silobreaker.WidgetPopup(widgetName, apiKey, linkBaseUrl);
    
    var _self = this;
    var _popupElement = null;
    var _hoveredElement = null;

    this.wireUpHoverBehavior = function(links) {
        /// <summary>
        ///     Registers popup events for a set of elements.
        /// </summary>
        /// <param name="links">
        ///     Arrray of jQuery elements to apply popup functionality to.
        /// </param>

        jQuery(links).hover(this.beginShowPopup, this.hidePopup);
    };

    this.beginShowPopup = function() {
        /// <summary>
        ///     Starts a timer that calls the showPopup method.
        /// </summary>
        _hoveredElement = jQuery(this);
        _hoveredElement.oneTime(1000, "showpopup", _self.showPopup);
    };

    this.showPopup = function() {
        if (!_hoveredElement) {
            return;
        }

        if (_popupElement) {
            return;
        }

        var itemData = _hoveredElement.data("entity");

        var context = _self.getContext(_hoveredElement);
        _popupElement = _self.popupInstatiator.createPopup(itemData, context, _self.clickHandler);
        _popupElement.mouseleave(_self.hidePopup);

        var position = _hoveredElement.position();
        _popupElement.css("top", position.top + _hoveredElement.height());
        _popupElement.css("left", position.left);


        _popupElement.insertAfter(_hoveredElement);

        _popupElement.show();
    };


    this.hidePopup = function(event) {
        _hoveredElement.stopTime("showpopup");
        if (_popupElement) {

            if (jQuery(event.relatedTarget).parents().index(_popupElement) == -1 && jQuery(event.relatedTarget).parents().index(_hoveredElement) == -1) {
                _popupElement.remove();
                _popupElement = null;
            }
        }
    };

    this.getContext = function(hoveredElement) {
        var context = hoveredElement.parents("[context]");
        if (context.length > 0) {
            return jQuery(context[0]).attr("context"); // TODO: If there are multiple parents with context, concatenate them with AND!
        }
    };
};/// <reference path="Silobreaker.js" />
/// <reference path="jquery-1.3.2-vsdoc2.js" />

Silobreaker.EntitySummary = function(params) {
    /// <summary> 
    ///     Widget showing entity summary.
    /// </summary>

    this.id = "Silobreaker.EntitySummary";
    var _instanciatedIn = null;
    var _self = this;

    this.entity = null;
    this.context = null;
    this.widgetName = null;
    this.operation = null;
    this.linkBaseUrl = null;
    this.apiKey = null;

    if (params) {
        if (params.entity) {
            this.entity = params.entity;
        }
        if (params.context) {
            this.context = params.context;
        }
        if (params.widgetName) {
            this.widgetName = params.widgetName;
        }
        if (params.operation) {
            this.operation = params.operation;
        }
        if (params.linkBaseUrl) {
            this.linkBaseUrl = params.linkBaseUrl;
        }
        if (params.apiKey) {
            this.apiKey = params.apiKey;
        }
    }

    this.searchCompleteCallback = null;
    this.clickHandler = null;
    this.popupHandler = null;
    this.dataSource = new Silobreaker.EntitySummary.DataSource();

    var _data = null;
    var _documentWidget = null;

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);
        _documentWidget = new Silobreaker.Documents();
        Silobreaker.injectWidget(jQuery(".relatedDocuments", _instanciatedIn), _documentWidget);

        if (this.entity) {
            _self.search();
        }

    };

    this.search = function() {
        var params = { entityReference: this.entity, context: this.context };
        if (this.widgetName != null)
            params.widget = this.widgetName;
        if (this.operation != null)
            params.operation = this.operation;

        this.dataSource.getSummary(this.fillTemplate, params, this.apiKey);
    };

    this.fillTemplate = function(data) {
        /// <summary>
        ///     Updates the template with data.
        /// </summary>
        /// <param name="data">
        ///     The data to update the template with.
        /// </param>

        _data = data;
        var items = [];

        // Create a more bindable data object
        var bindableData = {};

        if (data.Extras) {
            if (data.Extras.RelatedDocuments) {
                bindableData.RelatedDocuments = data.Extras.RelatedDocuments.Items;
                jQuery.merge(items, data.Extras.RelatedDocuments.Items);
            }

            if (data.Extras.Metadata) {
                if (data.Extras.Metadata.TextFields) {
                    bindableData.TextFields = data.Extras.Metadata.TextFields;
                }
                if (data.Extras.Metadata.ItemFields) {
                    bindableData.ItemFields = data.Extras.Metadata.ItemFields;
                    for (var i = 0; i < bindableData.ItemFields.length && typeof (bindableData.ItemFields[i]) != 'undefined'; i++) {
                        items.push(bindableData.ItemFields[i].Value);
                    }
                }
            }

            if (data.Extras.Images) {
                bindableData.Images = data.Extras.Images.Items.slice(0, 1);
                bindableData.Images[0].ImageSrc = 'src="' + bindableData.Images[0].ImageSrc + '"';
            }

            if (data.Extras.Evidence) {
                var evidence = data.Extras.Evidence;             
                items.push(evidence.SnippetSource);

                // Add pretty date
                var prettyDate = new Date();
                prettyDate.setIsoDate(evidence.SnippetSource.PublicationDate);
                evidence.SnippetSource.PrettyPublicationDate = prettyDate.prettyString()
                bindableData.Evidence = evidence;
            }
        }
        bindableData.Id = data.Id;
        bindableData.Description = data.Description;
        bindableData.Type = data.Type;
        bindableData.LocalizedType = data.LocalizedType;
        bindableData.EntityReference = data.EntityReference;

        items.push(data);

        // Inject document list
        _documentWidget.clickHandler = _self.clickHandler;
        _documentWidget.popupHandler = _self.popupHandler;
        _documentWidget.fillTemplate(data.Extras.RelatedDocuments);

        // Get the template and fill it with data
        var template = jQuery(_instanciatedIn).find(".contentTemplate:first");
        var html = template.bindTo(bindableData);
        html = jQuery(html).html();

        jQuery(".content", _instanciatedIn).html(html);

        // Extract all items
        for (var i = 0; i < items.length && typeof (items[i]) != 'undefined'; i++) {
            var entity = items[i];
            _data[entity.Id] = entity;
        }

        var links = jQuery(".content a[itemref]", _instanciatedIn);

        // Wire up the behavior when entities are clicked
        Silobreaker.WireUpItems(links, _data, _self.popupHandler, _self.clickHandler, _self.linkBaseUrl);
    };
};


Silobreaker.EntitySummary.DataSource = function() {
    /// <summary>Data Source class for Entity Summary Widget</summary>

    this.getSummary = function(callback, params, apiKey) {
        /// <summary>
        ///     Get summary for an entity.
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request. Required parameters are params.entity.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>        
        if (!params)
            throw "ArgumentNullException: No parameters specified.";

        if (!params.entityReference)
            throw "ArgumentException: No entity reference specified.";

        var url = "entity?entityReference=" + params.entityReference + "&Extras=RelatedDocuments,Evidence";

        var parameters = {};

        if (params.context && params.context != null) {
            parameters.context = params.context;
        }

        if (params.widget && params.widget != null) {
            parameters.widget = params.widget;
        }

        if (params.operation && params.operation != null) {
            parameters.operation = params.operation;
        }

        url += "&" + jQuery.param(parameters);

        Silobreaker.invokeApi(url, callback, apiKey);
    };
};
Silobreaker.Documents = function (params) {
    /// <summary> 
    ///     Widget listing documents given a document query
    /// </summary>

    var _instanciatedIn = null;
    var _self = this;
    var _data = {};

    this.id = "Silobreaker.Documents";
    this.query = null;
    this.pageSize = 10;
    this.pageNumber = 0;
    this.types = null;
    this.searchCompleteCallback = null;
    this.dataSource = new Silobreaker.Documents.DataSource();
    this.clickHandler = null;
    this.popupHandler = null;
    this.linkBaseUrl = null;
    this.apiKey = null;
    this.showSourceUrl = false;
    this.showTeasers = false;
    this.sortBy = null;

    if (params) {
        if (params.query)
            this.query = params.query;

        if (params.pageSize)
            this.pageSize = params.pageSize;

        // backward compatibility
        if (params.count)
            this.pageSize = params.count;

        if (params.pageNumber)
            this.pageNumber = params.pageNumber;

        if (params.types)
            this.types = params.types;

        if (params.linkBaseUrl) {
            this.linkBaseUrl = params.linkBaseUrl;
        }

        if (params.sortBy) {
            this.sortBy = params.sortBy;
        }

        if (params.apiKey) {
            this.apiKey = params.apiKey;
        }
        if (params.showSourceUrl) {
            this.showSourceUrl = params.showSourceUrl;
        }
        if (params.showTeasers) {
            this.showTeasers = params.showTeasers;
        }
    }

    this.initialize = function (element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);

        //if (this.query && this.query != "")
        //search();
    };

    this.search = function () {
        /// <summary>
        ///     Executes the search and fills the template with the result.
        /// </summary>
        jQuery(_instanciatedIn).attr("context", this.query);
        if (jQuery(_instanciatedIn).block) {
            jQuery(_instanciatedIn).block({ message: "Working..." });
        }
        var params = { query: this.query, pageSize: this.pageSize, types: this.types, showTeasers: this.showTeasers, pageNumber: this.pageNumber, sortBy : this.sortBy };
        if (_self.widgetName) {
            params.widget = _self.widgetName;
            params.operation = "Search";
        }

        this.dataSource.getDocuments(this.fillTemplate, params, this.apiKey);
    };

    var gotoPage = function (page) {
        /// Create function that will go to pageNumber when invoked
        var f = function () {
            _self.pageNumber = page;
            _self.search();
            return false;
        };

        return f;
    };

    var createPagination = function (totalCount) {
        var lastPage = Math.floor(totalCount / _self.pageSize);
        var pagination = jQuery("<div class='pagination'/>");

        if (_self.pageNumber > 0) {
            var previous = jQuery("<a>Previous</a>");
            previous.click(gotoPage(_self.pageNumber - 1));
            pagination.append(previous);

            var stepBackCount = Math.min(_self.pageNumber, 4);

            for (var i = -stepBackCount; i <= -1; ++i) {
                var step = jQuery("<a>" + (_self.pageNumber + i + 1) + "</a>");
                step.click(gotoPage(_self.pageNumber + i));
                pagination.append("&nbsp;", step);
            }
        }

        var pageNumber = jQuery("<b>" + (_self.pageNumber + 1) + "</b>");
        pagination.append("&nbsp;", pageNumber);

        if (_self.pageNumber < lastPage) {

            var stepForwardCount = Math.min(lastPage - _self.pageNumber, 4);

            for (var i = 1; i <= stepForwardCount; ++i) {
                var step = jQuery("<a>" + (_self.pageNumber + i + 1) + "</a>");
                step.click(gotoPage(_self.pageNumber + i));
                pagination.append("&nbsp;", step);
            }

            var next = jQuery("<a>Next</a>");
            next.click(gotoPage(_self.pageNumber + 1));
            pagination.append("&nbsp;", next);
        }

        return pagination;
    }

    this.fillTemplate = function (data) {
        /// <summary>
        ///     Fills the template html with data.
        /// </summary>

        if (jQuery(_instanciatedIn).unblock) {
            jQuery(_instanciatedIn).unblock();
        }
        jQuery(_instanciatedIn).find(".content").html('');

        for (var i = 0; i < data.Items.length && typeof (data.Items[i]) != 'undefined'; i++) {
            var prettyDate = new Date();
            prettyDate.setIsoDate(data.Items[i].PublicationDate);
            data.Items[i].PrettyPublicationDate = prettyDate.prettyString();
            data.Items[i].SourceUrlRef = '';

            if (Silobreaker.defaultTarget) {
                data.Items[i].SourceUrlRef = 'target="' + Silobreaker.defaultTarget + '" ';
            }

            if (_self.showSourceUrl) {
                data.Items[i].SourceUrlRef += 'href="' + data.Items[i].SourceUrl + '"';
            }

            if (data.Items[i].Extras && data.Items[i].Extras.DocumentTeasers) {
                data.Items[i].Teaser = data.Items[i].Extras.DocumentTeasers.HtmlSnippet;
            }

            var document = data.Items[i];
            _data[document.Id] = document;
        }

        // Get the template and fill it with data
        var template = jQuery(".contentTemplate", _instanciatedIn);

        if (!_self.showTeasers) {
            template.find(".teaser").remove();
        }

        var html = template.bindTo(data);
        var pagination = createPagination(data.TotalCount);

        jQuery(".content", _instanciatedIn).html(html);
        jQuery(".content", _instanciatedIn).append(pagination);
        var links = jQuery(".content a[itemref]", _instanciatedIn);
        Silobreaker.WireUpItems(links, _data, _self.popupHandler, _self.clickHandler, _self.linkBaseUrl);

        if (_self.searchCompleteCallback) {
            _self.searchCompleteCallback(data);
        }
    };
};

Silobreaker.Documents.DataSource = function () {
    /// <summary>Data Source class for Documents Widget</summary>

    this.getDocuments = function (callback, params, apiKey) {
        /// <summary>
        ///     Get documents based on a set of parameters. Supported parameters are:
        ///     query (the query to use, optional),
        ///     pageSize (number of documents to retrieve, optional)
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>

        var url = "documents/";

        if (!params)
            throw "ArgumentNullException: No parameters specified.";

        var querySet = params.query && params.query != null && params.query != "";

        var parameters = {};

        if (querySet) {
            parameters.q = params.query;
        }

        if (params.types && params.types != null && params.types.length > 0) {
            parameters.types = params.types.join(",");
        }

        if (params.sortBy && params.sortBy != null) {
            parameters.sortBy = params.sortBy;
        }

        if (params.pageSize) {
            parameters.pageSize = params.pageSize;
        }

        if (params.pageNumber) {
            parameters.pageNumber = params.pageNumber;
        }

        if (params.widget) {
            parameters.widget = params.widget;
        }

        if (params.operation) {
            parameters.operation = params.operation;
        }

        if (params.showTeasers) {
            parameters.Extras = "DocumentTeasers";
        }

        url += "?" + jQuery.param(parameters);

        Silobreaker.invokeApi(url, callback, apiKey);
    };
};
Silobreaker.Evidence = function(params) {
    /// <summary>
    /// View evidence between 2 items given a context
    /// of the form {name: <display name>, id: <search friendly id>}
    /// </summary>
    /// <param name="context">The context filter. Required.</param>
    ///
    /// <param name="node1">First item to obtain evidence about.
    /// {name: <display name>, id: <search friendly id>}
    /// Required.</param>
    ///
    /// <param name="node2">Second item to obtain evidence about.
    /// {name: <display name>, id: <search friendly id>}
    /// Required. </param>
    ///
    /// <param name="count">Number of evidence documents. Optional.</param>

    var _instanciatedIn = null;
    var _self = this;
    var _documents = null;

    this.id = "Silobreaker.Evidence";
    this.widgetName = null;
    this.operation = null;
    this.searchCompleteCallback = null;
    this.dataSource = null; // Data source for documents instance
    this.context = null;
    this.node1 = null;
    this.node2 = null;
    this.count = null;
    this.popupHandler = null;
    this.clickHandler = null;
    this.dataSource = new Silobreaker.Evidence.DataSource();
    this.linkBaseUrl = null;
    this.apiKey = null;

    if (!params) {
        throw "ArgumentNullException: No parameters specified.";
    }

    if (params.context) {
        this.context = params.context;
    }
    else {
        throw "ArgumentException: No context specified.";
    }

    if (params.node1) {
        this.node1 = params.node1;
    }
    else {
        throw "ArgumentException: No node1 specified.";
    }

    if (params.node2) {
        this.node2 = params.node2;
    }
    else {
        throw "ArgumentException: No node2 specified.";
    }

    if (params.count) {
        this.count = params.count;
    }

    if (params.count) {
        this.count = params.count;
    }
    if (params.widgetName) {
        this.widgetName = params.widgetName;
    }
    if (params.operation) {
        this.operation = params.operation;
    }
    if (params.linkBaseUrl) {
        this.linkBaseUrl = params.linkBaseUrl;
    }
    if (params.apiKey) {
        this.apiKey = params.apiKey;
    }


    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on
        /// </param>

        if (element == null)
            throw "ArgumentNullException: No element specified.";

        _instanciatedIn = jQuery(element);
        _documentWidget = new Silobreaker.Documents();
        Silobreaker.injectWidget(jQuery(".evidenceDocuments", _instanciatedIn), _documentWidget);

        if (this.context && this.context != "") {
            _self.search();
        }
    };

    this.search = function() {
        jQuery(_instanciatedIn).attr("context", _self.context);
        var params = { entities: _self.node1.id + "," + _self.node2.id, context: _self.context };
        if (this.widgetName != null)
            params.widget = this.widgetName;
        if (this.operation != null)
            params.operation = this.operation;

        this.dataSource.getEvidence(this.fillTemplate, params, this.apiKey);
    };

    this.fillTemplate = function(data) {

        var itemData = {};

        // Title
        var contentTemplate = jQuery(".contentTemplate", _instanciatedIn);

        var bindableData = {};
        bindableData.node1 = _self.node1.name;
        bindableData.node2 = _self.node2.name;
        bindableData.context = _self.context;
        if (data.Extras && data.Extras.Evidence) {
            bindableData.Evidence = data.Extras.Evidence;

            // Add pretty date
            var prettyDate = new Date();
            prettyDate.setIsoDate(bindableData.Evidence.SnippetSource.PublicationDate);
            bindableData.Evidence.SnippetSource.PrettyPublicationDate = prettyDate.prettyString()
        }


        titleHtml = contentTemplate.bindTo(bindableData);
        jQuery(".content", _instanciatedIn).html(titleHtml);

        // Search further
        var searchFurther = jQuery(".searchFurtherAnchor", _instanciatedIn);
        var searchFurtherUrl = _self.searchUri(); // TODO: Make this a real url
        searchFurther.attr("href", searchFurtherUrl);

        // Inject document list
        _documentWidget.clickHandler = _self.clickHandler;
        _documentWidget.popupHandler = _self.popupHandler;
        _documentWidget.fillTemplate(data.Extras.RelatedDocuments);

        // Wire up item links
        if (data.Extras && data.Extras.Evidence) {
            itemData[data.Extras.Evidence.SnippetSource.Id] = data.Extras.Evidence.SnippetSource;
        }

        var links = jQuery(".content a[itemref]", _instanciatedIn);
        Silobreaker.WireUpItems(links, itemData, _self.popupHandler, _self.clickHandler, _self.linkBaseUrl);

    };

    this.searchUri = function() {
        var linkBaseUrl = Silobreaker.linkBaseUrl;
        if (_self.linkBaseUrl && _self.linkBaseUrl != null) {
            linkBaseUrl = _self.linkBaseUrl;
        }
        return linkBaseUrl + "Search.aspx?q=itemref:" + _self.node1.id + " and itemref:" + _self.node2.id + " and " + _self.context;
    };
};

Silobreaker.Evidence.DataSource = function() {
    /// <summary>Data Source class for Evidence Widget</summary>

    this.getEvidence = function(callback, params, apiKey) {
        /// <summary>
        ///     Get evidence for two entities
        /// <param name="params">
        ///     An object containing parameters for the request. Required parameters are params.entities.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>

        if (!params)
            throw "ArgumentNullException: No parameters specified.";

        if (!params.entities)
            throw "ArgumentException: No entities specified.";

        var url = "evidence";

        var parameters = {};

        parameters.entityReferences = params.entities;

        if (params.context && params.context != null) {
            parameters.context = params.context;
        }

        if (params.widget && params.widget != null) {
            parameters.widget = params.widget;
        }

        if (params.operation && params.operation != null) {
            parameters.operation = params.operation;
        }

        url += "?" + jQuery.param(parameters);

        Silobreaker.invokeApi(url, callback, apiKey);
    };
};
/// <reference path="Silobreaker.js" />
/// <reference path="jquery-1.3.2-vsdoc2.js" />

Silobreaker.InFocus = function(params) {
    /// <summary> 
    ///     Widget listing entities related to a document search query 
    /// </summary>

    this.id = "Silobreaker.InFocus";
    var _instanciatedIn = null;
    var _self = this;
    var _helptext = "The list shows the most related people, companies, organisations, places and keyphrases to the search term in question. By hovering over a name you can see how it fits in.";

    this.query = null;
    this.types = ["Person", "Company", "Organization", "City", "Keyphrase", "Product"];
    this.count = 10;
    this.moreCount = this.count * 2;
    this.showPopups = true;
    this.searchCompleteCallback = null;
    this.dataSource = new Silobreaker.InFocus.DataSource();
    this.clickHandler = null;    
    this.linkBaseUrl = null;
    this.apiKey = null;

    if (params) {
        if (params.types && jQuery.isArray(params.types) && params.types.length > 0) {
            this.types = params.types;
        }

        if (params.query) {
            this.query = params.query;
        }

        if (params.count) {
            this.count = params.count;
            this.moreCount = this.count * 2;
        }

        if (params.moreCount) {
            this.moreCount = params.moreCount;
        }

        if (params.showPopups == false) {
            this.showPopups = false;
        }

        if (params.linkBaseUrl) {
            this.linkBaseUrl = params.linkBaseUrl;
        }

        if (params.apiKey) {
            this.apiKey = params.apiKey;
        }
    }

    this.popupHandler = new Silobreaker.PopupHandler("InFocus", null, this.apiKey, this.linkBaseUrl);
    var _data = {};
    var _displayCountPerType = {};

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);

        Silobreaker.AddBranding(jQuery(".widget", _instanciatedIn), "Silobreaker In Focus Widget", _helptext);

        _self.search();
    };

    this.search = function() {
        /// <summary>
        ///     Executes the search and fills the template with the result.
        /// </summary>
        if (this.query && this.query != null) {
            jQuery(_instanciatedIn).attr("context", this.query);
        }

        // Set the display count for each type        
        for (var i = 0; i < this.types.length; i++) {
            _displayCountPerType[this.types[i]] = this.count;
        }

        // Clean the data object and request the datasource
        _data = {};
        var params = { query: this.query, count: this.count, types: this.types, widget: "InFocus", operation: "Search" };
        this.dataSource.getEntities(updateListWithData, params, this.apiKey);
    };

    this.fillTemplate = function() {
        /// <summary>
        ///     Fills the template html with data.
        /// </summary>

        // Group the data into types
        var entities = [];

        for (index in _data) {
            var entity = _data[index];
            entities.push(entity);
        }

        var groupedData = Silobreaker.groupByItemType(entities);

        // Make sure we display the correct number of entities per each type
        var actualCountPerType = {};

        for (var i = 0; i < groupedData.length && typeof (groupedData[i]) != 'undefined'; i++) {

            var typeName = groupedData[i].Type;
            groupedData[i].TypeClass = typeName.replace(/ /, "");
            var count = _displayCountPerType[typeName];
            if (groupedData[i].Items.length > count) {
                groupedData[i].Items.length = count;
            }

            actualCountPerType[typeName] = groupedData[i].Items.length;
        }

        // Get the template and fill it with data
        var template = jQuery(".contentTemplate", _instanciatedIn);
        var html = template.bindTo(groupedData);
        jQuery(".content", _instanciatedIn).html(html);

        // Remove last separator from each list
        jQuery(".separator:last", jQuery(".content .typeList", _instanciatedIn)).remove();

        // Find all item links
        var links = jQuery(".content a[itemref]", _instanciatedIn);

        var popupHandler = null;
        if (_self.showPopups) {
            popupHandler = _self.popupHandler;
        }

        Silobreaker.WireUpItems(links, _data, popupHandler, _self.clickHandler, _self.linkBaseUrl);

        // Wire up Show More click links
        wireUpShowMore(actualCountPerType);

        // Update help text
        if (!_self.query || _self.query == "") {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "Most frequent mentioned entities");
        }
        else if (entities.length == 0) {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "No related entities found to " + _self.query);
        }
        else if (_self.query && _self.query != "") {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "Most related entities to " + _self.query);
        }


        // Fire callback for search complete
        if (_self.searchCompleteCallback)
            _self.searchCompleteCallback();
    };

    this.showMore = function(typeName) {
        /// <summary>Expands the entity list with more entities of a specific type.</summary>
        /// <param name="typeName">The name of the entity type.</param>
        _displayCountPerType[typeName] = this.moreCount;

        var entityCount = 0;

        for (var i = 0; i < _data.length; i++) {
            if (_data[i].Type == typeName)
                entityCount++;
        }

        // If we already have enough entities of this type, just refresh the html
        if (entityCount > this.count) {
            _self.fillTemplate();
            return;
        }

        // Request Api for more entities
        var params = { query: this.query, count: this.moreCount, types: [typeName], widget: "InFocus", operation: "ShowMore" };
        this.dataSource.getEntities(updateListWithData, params);
    };

    this.showLess = function(typeName) {
        /// <summary>Expands the entity list with more entities of a specific type.</summary>
        /// <param name="typeName">The name of the entity type.</param>
        _displayCountPerType[typeName] = this.count;
        _self.fillTemplate();
    };

    var updateListWithData = function(data) {
        /// <summary>
        ///     Updates the list with data.
        /// </summary>
        /// <param name="data">
        ///     The data to update the list with.
        /// </param>

        for (var i = 0; i < data.Items.length && typeof (data.Items[i]) != 'undefined'; i++) {
            var entity = data.Items[i];
            _data[entity.Id] = entity;
        }

        _self.fillTemplate();
    };

    var wireUpShowMore = function(actualCountPerType) {
        /// <summary>Sets up behvior for show more buttons.</summary>
        /// <param name="actualCountPerType">
        ///     Hashtable containing actual number of entities per type.
        /// </param>

        jQuery(".content .showMore", _instanciatedIn).each(function() {

            var link = jQuery(this);
            link.unbind("click"); // unbind any old show more click event

            var typeName = link.attr("data");
            if (_displayCountPerType[typeName] > _self.count) {
                // Show less
                link.html("[less]");

                // Wire up click
                link.one("click", function() {
                    var typeName = jQuery(this)[0].attributes["data"].value;
                    _self.showLess(typeName);
                });
            }
            else if (_displayCountPerType[typeName] == actualCountPerType[typeName]) {
                // Show more
                link.html("[more]");

                // Wire up click
                link.one("click", function() {
                    jQuery(this).html("[Loading...]");
                    var typeName = jQuery(this)[0].attributes["data"].value;
                    _self.showMore(typeName);
                });
            } else {
                link.remove();
            }
        });
    };
};

Silobreaker.InFocus.DataSource = function() {
    /// <summary>Data Source class for InFocus Widget</summary>

    this.getEntities = function(callback, params, apiKey) {
        /// <summary>
        ///     Get entities based on a set of parameters. Supported parameters are: 
        ///     types (array of type names, required), 
        ///     count (number of entities to retrieve for each type, required), 
        ///     query (the query to use, optional)
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request. Required parameters are params.types and params.count.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>

        if (!params)
            throw "ArgumentNullException: No parameters specified.";

        if (!params.types)
            throw "ArgumentException: No entity types specified.";

        if (!params.count)
            throw "ArgumentException: No count specified.";

        var url = "documents/entities";

        var parameters = {};

        if (params.query && params.query != null) {
            parameters.q = params.query;
        }
        
        var counts = [];
        for (var i = 0; i < params.types.length; i++) {
            counts.push(params.count);
        }

        parameters.types = params.types.join(",");
        parameters.entityTypeLimits = counts.join(",");

        if (params.widget) {
            parameters.widget = params.widget;
        }

        if (params.operation) {
            parameters.operation = params.operation;
        }

        url += "?" + jQuery.param(parameters);

        Silobreaker.invokeApi(url, callback, apiKey);
    };
};/// <reference path="Silobreaker.js" />
/// <reference path="jquery-1.3.2-vsdoc2.js" />

Silobreaker.Network = function(params) {
    /// <summary> 
    ///     Widget showing related entities in an interactive network.
    /// </summary>
    /// <param name="params">
    ///     Object containing parameters for initializing a network. The following parameters are available:
    ///
    ///     width: Integer declaring the desired width of the network. Can be omitted and will then be set to 900 pixels.
    ///     height: Integer declaring the desired height of the network. Can be omitted and will then be set to 900 pixels.
    ///     showSliders: Boolean declaring if entity type sliders should be visible in the network. Default is true.
    ///     showTrashcan: Boolean declaring if trash can should be visible in the network. Default is true.
    ///     showZoom: Boolean declaring if zoom slider should be visible in the network. Default is true.
    ///     networkNodeClickHandler: An instance of Silobreaker.ClickHandler. It's handler will be invoked with parameters id, description.
    ///     networkEdgeClickHandler: An instance of Silobreaker.ClickHandler. It's handler will be invoked with parameters id1, description1, id2, description2.
    /// </param>

    this.id = "Silobreaker.Network";

    var _instanciatedIn = null;
    var _self = this;
    var _itemData = {};
    var _currentNetworkNodes = [];

    // A unique id for this widget instance.
    // Used when assigning a unique id to a div element in the template html,
    // and creating a unique javascript function callback from the flash app.
    var _uniqueId = "Network" + Silobreaker.getUniqueInteger().toString();
    var _uniqueNodePopupName = _uniqueId + "_NodePopup";
    var _uniqueEvidencePopupName = _uniqueId + "_EvidencePopup";
    var _uniqueNetworkEdgeClickName = _uniqueId + "_NetworkEdgeClick";
    var _uniqueNetworkNodeClickName = _uniqueId + "_NetworkNodeClick";

    var _helptext = "The network shows connections found in the news flow. By hovering over a name or the midpoint of any relationship you can see how the name or the connection fits in.";

    var _showSliders = true;
    var _showTrashcan = true;
    var _showZoom = true;
    var _width = 900;
    var _height = 600;

    var _entityTypeImage = {
        "Person": "IcPerson.gif",
        "Journalist": "IcPerson.gif",
        "City": "IcCity.gif",
        "Company": "IcCompany.gif",
        "Organization": "IcOrganization.gif",
        "Product": "IcProduct.gif",
        "Country": "IcCountry.gif",
        "World Region": "IcCountry.gif",
        "Continent": "IcCountry.gif",
        "Province": "IcCountry.gif",
        "Keyphrase": "IcKeyphrase.gif",
        "Music Band": "IcMusicBand.gif",
        "Sports Team": "IcSportsTeam.gif"
    };
    var _entityTypeDefaultImage = "IcKeyphrase.gif";

    this.query = "";
    this.totalNodes = 20;
    this.expandEntities = [];
    this.includeEntities = [];
    this.highlightEntities = [];
    this.entityTypes = ["Company", "Organization", "Person", "City", "Keyphrase", "Product"];
    this.showPopups = true;
    this.networkEdgeClickHandler = null;
    this.networkNodeClickHandler = null;
    this.searchCompleteCallback = null;
    this.dataSource = new Silobreaker.Network.DataSource();
    this.popupHandler = null;
    this.linkBaseUrl = null;
    this.apiKey = null;

    var _popupHandler = null;

    // Set values from params object
    if (params) {
        if (params.width) {
            _width = params.width;
        }

        if (params.height) {
            _height = params.height;
        }

        if (params.showSliders == false) {
            _showSliders = false;
        }

        if (params.showTrashcan == false) {
            _showTrashcan = false;
        }

        if (params.showZoom == false) {
            _showZoom = false;
        }

        if (params.showPopups == false) {
            this.showPopups = false;
        }

        if (params.query) {
            this.query = params.query;
        }

        if (params.totalNodes) {
            this.totalNodes = params.totalNodes;
        }

        if (params.includeEntities) {
            this.includeEntities = params.includeEntities;
        }        

        if (params.highlightEntities) {
            this.highlightEntities = params.highlightEntities;
        }

        if (params.expandEntities) {
            this.expandEntities = params.expandEntities;
        }

        if (params.entityTypes) {
            this.entityTypes = params.entityTypes;
        }

        if (params.networkNodeClickHandler) {
            this.networkNodeClickHandler = params.networkNodeClickHandler;
        }

        if (params.networkEdgeClickHandler) {
            this.networkEdgeClickHandler = params.networkEdgeClickHandler;
        }
        if (params.linkBaseUrl) {
            this.linkBaseUrl = params.linkBaseUrl;
        }
        if (params.apiKey) {
            this.apiKey = params.apiKey;
        }
    }


    var typesCount = [];

    var imagesBaseUrl = "http://www.silobreaker.com/Images/";

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);

        createGlobalFlashFunction();
        createFlashObject();
        setWidgetSize();
        attachMouseWheelEventListeners();
        if (_self.showPopups) {
            if (_self.popupHandler) {
                _popupHandler = _self.popupHandler;
            }
            else {
                _popupHandler = new Silobreaker.Network.PopupHandler(jQuery(".content", _instanciatedIn), _self.apiKey, _self.linkBaseUrl);
            }
            _popupHandler.clickHandler = _self.clickHandler;
        }

        Silobreaker.AddBranding(jQuery(".widget", _instanciatedIn), "Silobreaker Network Widget", _helptext);
    };

    this.search = function() {
        /// <summary>
        ///     Executes a search on the network.
        /// </summary>

        if (this.query && this.query != null) {
            jQuery(_instanciatedIn).attr("context", this.query);
        }

        internalSearch(this.entityTypes, typesCount, this.totalNodes, this.expandEntities, "Search");
    };

    var internalSearch = function(types, typesCount, totalNoNodes, expandEntities, operation) {
        /// <summary>
        ///     Performs the search for a network.
        /// </summary>
        /// <param name="types">
        ///     Array of entity types that should be included in the network.
        /// </param>
        /// <param name="typesCount">
        ///     Array of integers representing the count for each type that should be included in the network.
        /// </param>
        /// <param name="totalNoNodes">
        ///     Integer declaring the number of nodes to be returned for the network.
        /// </param>
        /// <param name="expandEntities">
        ///     Array of entity ids of entities that should be expanded in the network.
        /// </param>
        /// <param name="operation">
        ///     The operation for the network. Typical "Search", "Expand" or "Slider"
        /// </param>

        _self.types = types;

        var graphEntities = [];
        var exEntities = [];

        // Create a list of expand entities, and send current graphEntities to the query
        if (_self.expandEntities && _self.expandEntities.length > 0) {
            exEntities = _self.expandEntities;
            graphEntities = _currentNetworkNodes;
        }
        if (expandEntities && expandEntities.length > 0) {
            for (var i = 0; i < expandEntities.length; i++) {
                if (jQuery.inArray(expandEntities[i], exEntities) == -1) {
                    exEntities.push(expandEntities[i]);
                }
            }
        }

        var incEntities = [];
        if (_self.includeEntities && _self.includeEntities.length > 0) {
            for (var i = 0; i < _self.includeEntities.length; i++) {
                if (jQuery.inArray(_self.includeEntities[i], incEntities) == -1) {
                    incEntities.push(_self.includeEntities[i]);
                }
            }
        }

        var params = { query: _self.query, graphEntities: graphEntities, types: types, typesCount: typesCount, totalNoNodes: totalNoNodes, expandEntities: exEntities, includeEntities: incEntities, widget: "Network", operation: operation  };
        _self.dataSource.getGraph(_self.getGraphDone, params, _self.apiKey);
    };

    var createGlobalFlashFunction = function() {
        /// <summary>
        ///     Creates a global unique function for the flash object to call when it wants to retrieve data.
        /// </summary>
        window[_uniqueId] = function(types, typesCount, totalNoNodes, expandEntities) {
            // Default operation is search
            var operation = "Search";

            // If types are defined, the sliders has been used
            if (typesCount && typesCount.length > 0) {
                operation = "Slider";
            }

            // If expand entites are defined, we have expanded
            if (expandEntities && expandEntities.length > 0) {
                operation = "Expand";
            }

            internalSearch(types, typesCount, totalNoNodes, expandEntities, operation);
        };


        if (_self.showPopups == true) {
            window[_uniqueNodePopupName] = function(x, y, itemId, width, height, context, divId) {
                var item = _itemData[itemId];
                _popupHandler.showNodePopup(x, y, item, width, height, _self.query);
            };

            window[_uniqueEvidencePopupName] = function(x, y, width, height, fromId, fromName, toId, toName) {
                _popupHandler.showEvidencePopup(x, y, width, height, fromId, fromName, toId, toName, _self.query);
            };
        }

        if (_self.networkEdgeClickHandler != null) {
            window[_uniqueNetworkEdgeClickName] = function(id1, desc1, id2, desc2) {
                _self.networkEdgeClickHandler.triggerClick(id1, desc1, id2, desc2);
            };
        }

        if (_self.networkNodeClickHandler != null) {
            window[_uniqueNetworkNodeClickName] = function(id, desc) {
                _self.networkNodeClickHandler.triggerClick(id, desc);
            };
        }
    };

    var createFlashObject = function() {
        /// <summary>
        ///     Creates the network flash object and set all parameters on it.
        /// </summary>    
        var flashvars = {
            maxItems: _self.totalNodes.toString(),
            drillDownFilter: _self.query,
            getDataFunctionName: _uniqueId,
            highlightItems: _self.includeEntities.concat(_self.highlightEntities).join(","),
            entityTypes: _self.entityTypes.join(","),
            showSliders: _showSliders.toString(),
            trashcanVisibility: _showTrashcan.toString(),
            zoomVisibility: _showZoom.toString()
        };

        if (_self.showPopups == true) {
            flashvars.showNodePopupFunctionName = _uniqueNodePopupName;
            flashvars.showEvidencePopupFunctionName = _uniqueEvidencePopupName;
        }

        if (_self.networkEdgeClickHandler) {
            flashvars.edgeClickFunctionName = _uniqueNetworkEdgeClickName;
        }

        if (_self.networkNodeClickHandler) {
            flashvars.nodeClickFunctionName = _uniqueNetworkNodeClickName;
        }

        var params = {
            wmode: "transparent",
            quality: "autohigh",
            allowscriptaccess: "always"
        };

        jQuery(".networkDiv", _instanciatedIn)[0].id = _uniqueId;

        silobreaker_swfobject.embedSWF(Silobreaker.apiBaseUrl + "Content/Network-v10.swf", _uniqueId, _width.toString(), _height.toString(), "9.0.0", null, flashvars, params, {});

    };

    var attachMouseWheelEventListeners = function() {
        /// <summary>
        ///     Adds event listeners to the mouse scroll wheel.
        /// </summary>

        var contentDOMElement = jQuery(".content", _instanciatedIn)[0];
        if (contentDOMElement.addEventListener) {
            contentDOMElement.addEventListener('DOMMouseScroll', mouseWheelCallback, false);
        }
        else if (contentDOMElement.attachEvent)
            contentDOMElement.attachEvent("onmousewheel", mouseWheelCallback);
    };

    var mouseWheelCallback = function(e) {
        /// <summary>
        ///     The callback used for the mouse scroll wheel. Passes the wheel data to the flash app.
        /// </summary>

        e = e ? e : window.event;
        var scrollDist = e.detail ? e.detail * -1 : e.wheelDelta / 40;

        var flashobj = jQuery("#" + _uniqueId, _instanciatedIn)[0];
        if (flashobj && flashobj.scrollWheel)
            flashobj.scrollWheel(scrollDist);

        if (e.stopPropagation)
            e.stopPropagation();
        if (e.preventDefault)
            e.preventDefault();
        e.cancelBubble = true;
        e.cancel = true;
        e.returnValue = false;
        return false;
    };

    var setWidgetSize = function() {
        /// <summary>
        ///     Sets the size of the widget as a css directive on the widget div.
        /// </summary>
        jQuery(".widget", _instanciatedIn).css("width", _width.toString() + "px");
    };

    this.getGraphDone = function(data) {
        /// <summary>
        ///     Passes the graph data to the flash object.
        /// </summary>
        /// <param name="data">
        ///     Data to send to the flash object.
        /// </param>

        // Iterate over all nodes and store the data internally
        _currentNetworkNodes = [];

        for (var i = 0; i < data.Nodes.length && typeof (data.Nodes[i]) != 'undefined'; i++) {
            var node = data.Nodes[i];
            if (!node.Image) {
                node.Image = imagesBaseUrl + _entityTypeImage[node.Type];
                if (!node.Image) {
                    node.Image = imagesBaseUrl + _entityTypeDefaultImage;
                }
            }            
            _itemData[node.Id] = node;
            _currentNetworkNodes.push(node.Id);
        }

        var networkDOMobject = jQuery("#" + _uniqueId, _instanciatedIn)[0];
        if (networkDOMobject.receiveData) {
            networkDOMobject.receiveData(data);
        }

        // Update help text
        if (!_self.query || _self.query == "") {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "Network on most frequent mentioned entities");
        }
        else if (_itemData.length == 0) {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "No network found for " + _self.query);
        }
        else if (_self.query && _self.query != "") {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "Network around " + _self.query);
        }

        // Fire callback for search complete
        if (_self.searchCompleteCallback)
            _self.searchCompleteCallback();
    };
};


Silobreaker.Network.DataSource = function() {
    /// <summary>Data Source class for Network Widget</summary>

    this.getGraph = function(callback, params, apiKey) {
        /// <summary>
        /// Retrieves an entity graph from the silobreaker api.
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>  

        var url = this.createApiUrl(params);
        Silobreaker.invokeApi(url, callback, apiKey);
    };

    this.createApiUrl = function(params) {
        /// <summary>
        /// Creates an url for retrieving graph data from Silobreaker API.
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request. Required parameters are params.query.
        /// </param>

        if (!params)
            throw "ArgumentNullException: No parameters specified.";

        var url = "entitygraph";

        var parameters = {};

        if (params.query) {
            parameters.q = params.query;
        }

        if (!params.totalNoNodes) {
            param.totalNoNodes = 20;
        }

        if (params.types) {
            parameters.types = params.types.join(",");
        }

        if (params.typesCount && params.typesCount.length > 0) {
            parameters.entityTypeLimits = params.typesCount.join(",");
        }
        else {
            parameters.noNodes = params.totalNoNodes.toString();
        }

        if (params.graphEntities && params.graphEntities.length > 0) {
            parameters.graphEntities = params.graphEntities.join(",");
        }

        if (params.includeEntities && params.includeEntities.length > 0) {
            parameters.includeEntities = params.includeEntities.join(",");
        }

        if (params.expandEntities && params.expandEntities.length > 0) {
            parameters.expandEntities = params.expandEntities.join(",");
        }

        if (params.widget && params.widget != null) {
            parameters.widget = params.widget;
        }

        if (params.operation && params.operation != null) {
            parameters.operation = params.operation;
        }

        url += "?" + jQuery.param(parameters);

        return url;
    };
};


Silobreaker.Network.PopupHandler = function(networkElement, apiKey, linkBaseUrl) {
    /// <summary>
    /// Popup handler specific for the flash network application.
    /// </summary>
    /// <param name="networkElement">
    ///     The DOM element (jQuery object) where the flash network resides.
    /// </param>
    /// <param name="apiKey">
    ///     Optional. The Api key to be used by the popups.
    /// </param>
    /// <param name="linkBaseUrl">
    ///     Optional. The base url from where to base item links.
    /// </param>

    this.nodePopupInstatiator = new Silobreaker.WidgetPopup("Network", apiKey, linkBaseUrl);
    this.evidencePopupInstantiator = new Silobreaker.EvidencePopup("Network", apiKey, linkBaseUrl);
    this.clickHandler = null;

    var _self = this;
    var _popupElement = null;
    var _hoveredElement = null;
    var _networkElement = networkElement;

    this.showPopup = function(x, y, popupElement, itemWidth, itemHeight) {
        /// <summary>
        ///     Shows the popup at the specified position.
        /// </summary>
        /// <param name="x">
        ///     Specifies the left corner (relative to the network element) where to place the popup.
        /// </param>
        /// <param name="y">
        ///     Specifies the upper corner (relative to the network element) where to place the popup.
        /// </param>
        /// <param name="popupElement">
        ///     Content of the popup
        /// </param>
        /// <param name="itemWidth">
        ///     Specifies the width of the bounding box where to trigger the popup.
        /// </param>
        /// <param name="itemHeight">
        ///     Specifies the hight of the bounding box where to trigger the popup.
        /// </param>
        /// <param name="context">
        ///     Optionally, the context to use. 
        /// </param>

        var networkPosition = _networkElement.position();

        // Create a dummy div surrounding the hovered element in the flash app
        var dummyDiv = jQuery("<div></div>");
        dummyDiv.css("width", itemWidth);
        dummyDiv.css("height", itemHeight);
        dummyDiv.css("background-color", "red");
        dummyDiv.css("filter", "alpha(opacity=0)");
        dummyDiv.css("-moz-opacity", "0.0");
        dummyDiv.css("-khtml-opacity", "0.0");
        dummyDiv.css("opacity", "0.0");
        dummyDiv.css("position", "absolute");
        dummyDiv.css("top", y + networkPosition.top - itemHeight);
        dummyDiv.css("left", x + networkPosition.left);

        // Insert the dummy div to the network
        dummyDiv.insertAfter(_networkElement);
        dummyDiv.mouseleave(_self.hidePopup);

        // Make the dummy div the "hovered element"
        if (_hoveredElement != null)
            _hoveredElement.remove();
        _hoveredElement = dummyDiv;

        // Create the popup element
        var hoveredElementPosition = _hoveredElement.position();
        if (_popupElement != null) {
            _popupElement.remove();
        }
        _popupElement = popupElement; // _self.popupInstatiator.createPopup(itemId, context, _self.clickHandler);
        _popupElement.mouseleave(_self.hidePopup);
        _popupElement.css("left", x + networkPosition.left);
        _popupElement.css("top", y + networkPosition.top);
        _popupElement.insertAfter(_hoveredElement);
        _popupElement.show();

    };

    this.hidePopup = function(event) {
        /// <summary>
        ///     Hides the popup.
        /// </summary>
        /// <param name="event">
        ///     The event object passed when hover out is fired.
        /// </param>

        //alert("hidepopup");
        if (jQuery(event.relatedTarget).parents().index(_popupElement) == -1 && jQuery(event.relatedTarget).parents().index(_hoveredElement) == -1) {
            if (_hoveredElement) {
                _hoveredElement.remove();
                _hoveredElement = null;
            }

            if (_popupElement) {
                _popupElement.remove();
                _popupElement = null;
            }
        }
    };

    this.showNodePopup = function(x, y, item, itemWidth, itemHeight, context) {
        var popupElement = _self.nodePopupInstatiator.createPopup(item, context, _self.clickHandler);
        _self.showPopup(x, y, popupElement, itemWidth, itemHeight);
    };

    this.showEvidencePopup = function(x, y, itemWidth, itemHeight, fromId, fromName, toId, toName, context) {
        var node1 = { id: fromId, name: fromName };
        var node2 = { id: toId, name: toName };
        var popupElement = _self.evidencePopupInstantiator.createPopup(context, node1, node2, _self.clickHandler);
        _self.showPopup(x, y, popupElement, itemWidth, itemHeight);
    };
};
    /// <reference path="Silobreaker.js" />
/// <reference path="jquery-1.3.2-vsdoc2.js" />


Silobreaker.TopStories = function(params) {
    /// <summary> 
    ///     Widget showing top stories.
    /// </summary>

    this.id = "Silobreaker.TopStories";
    var _helptext = "The list shows the top related stories to the given query. Each story contains a list of most related entities to that story. By hovering over a name you can see how it fits in.";

    var _instanciatedIn = null;
    var _self = this;
    var _data = {};

    this.query = null;
    this.count = 10;
    this.showPopups = true;
    this.showImages = true;
    this.showSourceUrl = false;
    this.searchCompleteCallback = null;
    this.dataSource = new Silobreaker.TopStories.DataSource();
    this.clickHandler = null;
    this.linkBaseUrl = null;
    this.apiKey = null;

    // Set parameters from constructor
    if (params) {
        if (params.query) {
            this.query = params.query;
        }

        if (params.count) {
            this.count = params.count;
        }

        if (params.showPopups == false) {
            this.showPopups = false;
        }

        if (params.showImages == false) {
            this.showImages = false;
        }
        if (params.linkBaseUrl) {
            this.linkBaseUrl = params.linkBaseUrl;
        }
        if (params.apiKey) {
            this.apiKey = params.apiKey;
        }
        if (params.showSourceUrl) {
            this.showSourceUrl = params.showSourceUrl;
        }
    }

    this.popupHandler = new Silobreaker.PopupHandler("TopStories", null, this.apiKey, this.linkBaseUrl);

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);
        Silobreaker.AddBranding(jQuery(".widget", _instanciatedIn), "Silobreaker Top Story Widget", _helptext);

        _self.search();
    };

    this.search = function() {
        /// <summary>
        ///     Executes the search and fills the template with the result.
        /// </summary>
        jQuery(_instanciatedIn).attr("context", this.query);

        var params = { query: this.query, count: this.count, widget: "TopStories", operation: "Search", showImages: _self.showImages };
        this.dataSource.getTopStories(this.fillTemplate, params, this.apiKey);
    };

    this.fillTemplate = function(data) {
        /// <summary>
        ///     Fills the template html with data.
        /// </summary>

        var bindableData = data.Items;

        for (var i = 0; i < bindableData.length && typeof (bindableData[i]) != 'undefined'; i++) {

            var document = bindableData[i];
            document.StoryGroup = i % 5;

            document.SourceUrlRef = '';
            if (_self.showSourceUrl) {
                document.SourceUrlRef = 'href="' + document.SourceUrl + '"';
            }

            var prettyDate = new Date();
            var prettyFirstReported = new Date();
            var prettyLastUpdated = new Date();

            prettyDate.setIsoDate(document.PublicationDate);
            prettyFirstReported.setIsoDate(document.FirstReported);
            prettyLastUpdated.setIsoDate(document.LastUpdated);

            // Add new pretty dates to the template data object
            document.PrettyPublicationDate = prettyDate.prettyString();
            document.PrettyFirstReported = prettyFirstReported.prettyString();
            document.PrettyLastUpdated = prettyLastUpdated.prettyString();

            //Fix so that it does not only check latest data
            if (document.Extras.Images) {
                document.Images = document.Extras.Images.Items;
                document.Images[0].ImageSrc = 'src="' + document.Images[0].ImageSrc + '"';
            }

            document.HtmlSnippet = document.Extras.DocumentTeasers.HtmlSnippet;
            document.RelatedEntities = document.Extras.RelatedEntities.Items;

            for (var j = 0; j < document.RelatedEntities.length && typeof (document.RelatedEntities[j]) != 'undefined'; j++) {
                var entity = document.RelatedEntities[j];
                _data[entity.Id] = entity;
            }

            _data[document.Id] = document;
        }

        // Get the template and fill it with data
        var template = jQuery(".contentTemplate", _instanciatedIn);

        var html = template.bindTo(bindableData);
        jQuery(".content", _instanciatedIn).html(html);

        // Insert comma chars between entities
        jQuery(".content .entities a:not(:last-child)", _instanciatedIn).after(",");

        // Wire up item links with popup and click handlers        
        var popupHandler = null;
        if (_self.showPopups) {
            popupHandler = _self.popupHandler;
        }

        var links = jQuery(".content a[itemref]", _instanciatedIn);

        Silobreaker.WireUpItems(links, _data, popupHandler, _self.clickHandler, _self.linkBaseUrl);

        // Update help text
        if (!_self.query || _self.query == "") {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "Top Stories right now.");
        }
        else if (data.Items.length == 0) {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "No stories found for " + _self.query);
        }
        else if (_self.query && _self.query != "") {
            Silobreaker.UpdateInfoText(jQuery(".widget", _instanciatedIn), "Top stories for " + _self.query);
        }

        if (_self.searchCompleteCallback) {
            _self.searchCompleteCallback();
        }
    };
};


Silobreaker.TopStories.DataSource = function() {
    /// <summary>Data Source class for TopStory Widget</summary>
    this.getTopStories = function(callback, params, apiKey) {
        /// <summary>
        ///     Get top stories based on a set of parameters. Supported parameters are:
        ///     query (the query to use, optional),
        ///     count (number of top stories to retrieve, optional)
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>    

        var url = "topstories/";

        if (!params)
            throw "ArgumentNullException: No parameters specified.";



        var extras = "RelatedEntities,DocumentTeasers";

        if (params.showImages && params.showImages == true) {
            extras += ",Images"
        }

        var parameters = {};

        parameters.extras = extras;

        if (params.query) {
            parameters.q = params.query;
            parameters.Context = params.query;
        }

        if (params.count && params.count != null) {
            parameters.noStories = params.count;
        }

        if (params.widget && params.widget != null) {
            parameters.widget = params.widget;
        }

        if (params.operation && params.operation != null) {
            parameters.operation = params.operation;
        }

        url += "?" + jQuery.param(parameters);

        Silobreaker.invokeApi(url, callback, apiKey);
    };
};
    Silobreaker.DocumentVolume = function(params) {
    /// <summary> 
    ///     Widget displaying bar chart for document volume over time.
    /// </summary>
    /// <param name="params">
    ///     Parameters for the widget. Example:
    /// {
    ///     query : 'Environment [Keyphrase]',
    ///     apiKey : 'apiKeyHere',
    ///     granularity: 1440, // 24 hour in minutes
    ///     timeRange: -43200 // 30 days in minutes, chart will always show the last 30 days. OR:
    ///     timeRange: { from Date.parse('2010-11-09'), to: Date.parse('2010-10-09') } // explicit declare date range
    ///     timeInterval : {} // use a custom time interval model object
    ///     chartRendering : function(){} // function called before chart is rendered.
    ///     chartRendered : function(){} // function called after chart is rendered.
    ///     autoRefreshMinutes : 0 // Auto refresh chart with this time interval. Set to 0 to disable (default).
    /// }
    /// </param>

    var _instanciatedIn = null;
    var _documentsElement = null;
    var _self = this;
    var _chartModel = null;
    var _chartController = null;

    this.id = "Silobreaker.DocumentVolume";
    this.apiKey = null;
    this.chartRendering = null;
    this.chartRendered = null;
    this.autoRefreshMinutes = 0;
    this.serieClicked = null;
    var _autoRefreshTimer;
    var _chartModel = new Silobreaker.Chart.ChartModel();
    var _documentsWidget = null;

    Silobreaker.Strings.add('en', {
        "showdocuments": "Show Documents",
        "hidedocuments": "Hide Documents"
    });
    Silobreaker.Strings.add('sv', {
        "showdocuments": "Visa dokument",
        "hidedocuments": "Dölj dokument"
    });

    if (!params) {
        params = {};
    }

    if (params.apiKey) {
        this.apiKey = params.apiKey;
    }
    if (params.chartRendering) {
        this.chartRendering = params.chartRendering;
    }
    if (params.chartRendered) {
        this.chartRendered = params.chartRendered;
    }
    if (params.autoRefreshMinutes) {
        this.autoRefreshMinutes = params.autoRefreshMinutes;
    }
    if (params.serieClicked) {
        this.serieClicked = params.serieClicked;
    }
    if (params.chartModel) {
        _chartModel = params.chartModel;
    }
    if (params.documentElement) {
        _documentsElement = jQuery(params.documentElement);
    }

    _chartModel.setDataSource(new Silobreaker.DocumentVolume.DataSource());

    this.setChartMode = function(mode) {
        _chartController.setChartMode(mode);
    };

    this.setSplitContextProvider = function(provider) {
        _chartModel.setSplitContextProvider(provider);
    };

    this.getSplitContextProvider = function() {
        return _chartModel.getSplitContextProvider();
    };

    /// <summary>
    /// Gets the chart model.
    /// </summary>
    this.getModel = function() {
        return _chartModel;
    };

    /// <summary>
    /// Sets the chart model.
    /// </summary>
    this.setModel = function(model) {
        _chartModel = model;
    };

    function callAutoRefresh() {
        if (_self.autoRefreshMinutes > 0) {
            if (!_chartModel.isRefreshing) {
                _self.search();
            }
        }
        else {
            clearInterval(_autoRefreshTimer);
        }
    }

    var serieClickedInternal = function() {
        flipDocumentVisibility(true);
        updateDocumentList();
        _documentsElement.find('.clearQuery').show();
        _self.serieClicked;
    };

    var flipDocumentVisibility = function(showOrHide) {
        if (typeof showOrHide === 'undefined') {
            _documentsElement.toggle();
        } else {
            _documentsElement.toggle(showOrHide);
        }
        var isVisible = _documentsElement.is(":visible");
        _instanciatedIn.find('.showHideDocs').html(isVisible ? Silobreaker.Strings.getTranslation('hidedocuments') : Silobreaker.Strings.getTranslation('showdocuments'));
    };

    var updateDocumentList = function() {
        _documentsWidget.query = _self.getCurrentQuery();
        _documentsWidget.pageNumber = 0;
        _documentsWidget.search();        

        var queryText = _self.getReadableQueryText();
        _documentsElement.find('.querytext').html(queryText);
    };

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);
        _instanciatedIn.addClass('SB widget documentVolume');

        _instanciatedIn.append('<div class="chartArea"></div>');

        if (!_documentsElement) {
            _instanciatedIn.append('<a class="showHideDocs" href="#">' + Silobreaker.Strings.getTranslation('showdocuments') + '</a>');
            _instanciatedIn.append('<div class="documentArea" style="display:none;"></div>');
            _documentsElement = _instanciatedIn.find('.documentArea');
        } else {
            _documentsElement.addClass('SB widget documentVolume');
        }

        _chartController =
            new Silobreaker.Chart.ChartController(
                { chartModel: _chartModel,
                    chartSettings: {},
                    guiReference: '#' + _instanciatedIn.attr('id') + ' .chartArea',
                    rendering: _self.chartRendering,
                    rendered: _self.chartRendered,
                    serieClicked: serieClickedInternal
                });

        // Create the documents widget
        _documentsWidget = new Silobreaker.Documents({ count: 6, showTeasers: true, disableBranding: true });
        _chartModel.parameterChanged.bind(updateDocumentList);

        Silobreaker.injectWidget(_documentsElement, _documentsWidget);
        _documentsElement.prepend('<div class="queryfilter"><span class="querytext"></span><a class="clearQuery">[x]</a></div>');

        _documentsElement.find('.clearQuery').click(function() {
            _documentsElement.find('.clearQuery').hide();
            _self.clearSelected();
            updateDocumentList();
        });

        _instanciatedIn.find('.showHideDocs').click(function() {
            flipDocumentVisibility();
            return false;
        });

        if (_self.autoRefreshMinutes > 0) {
            _autoRefreshTimer = setInterval(callAutoRefresh, _self.autoRefreshMinutes * 60 * 1000);
        }

        if (_chartModel.hasContent()) {
            _self.search();
        }
    };

    this.setAutoRefresh = function(autoRefreshMinutes) {
        /// <summary>
        ///     Update the autorefresh interaval and initializes autorefresh calls if needed.
        /// </summary>
        /// <param name="autoRefreshMinutes">
        ///     Auto refresh chart with this time interval. Set to 0 to disable (default)
        /// </param>

        _self.autoRefreshMinutes = autoRefreshMinutes;
        clearInterval(_autoRefreshTimer)
        _autoRefreshTimer = setInterval(callAutoRefresh, _self.autoRefreshMinutes * 60 * 1000);
    };

    this.clearSelected = function() {
        /// <summary>
        ///   Unselects all in the chart points.
        /// </summary>    
        _chartController.clearSelected();
    };

    this.search = function() {
        /// <summary>
        ///     Updates the chart based on the new parameters for the widget.
        /// </summary>
        jQuery(_instanciatedIn).attr("context", this.query);
        _chartModel.parameterChanged.trigger();
    };

    this.getCurrentQuery = function() {
        /// <summary>
        ///     Gets the current query based on time period and splitcontext
        ///</summary>
        var splitContextProvider = _chartModel.getSplitContextProvider();
        var baseQuery = splitContextProvider.getBaseQuery();

        if (_chartModel.getContext()) {
            baseQuery = _chartModel.getContext() + " AND " + baseQuery;
        }

        var selectedPoint = _chartController.getSelected();
        var timeRange = _chartModel.getTimeIntervalModel().getStartAndEndDate();

        var startDate = timeRange.startDate;
        var endDate = timeRange.endDate;

        if (selectedPoint) {
            startDate = new Date(selectedPoint.range.from);
            endDate = new Date(selectedPoint.range.to);
            baseQuery = selectedPoint.serieName;
        }


        return baseQuery + ' fromdate:' + startDate.getIsoString() + ' todate:' + endDate.getIsoString();
    };

    this.getReadableQueryText = function() {
        var splitContextProvider = _chartModel.getSplitContextProvider();
        var baseQuery = splitContextProvider.getBaseQuery();

        if (_chartModel.getContext()) {
            baseQuery = _chartModel.getContext() + " AND " + baseQuery;
        }

        var selectedPoint = _chartController.getSelected();
        if (selectedPoint) {
            startDate = new Date(selectedPoint.range.from);
            endDate = new Date(selectedPoint.range.to);
            baseQuery = selectedPoint.serieName;
            baseQuery += ' fromdate:' + startDate.getIsoString() + ' todate:' + endDate.getIsoString();
            return baseQuery.replace(/T00:00:00Z/gi, "");
        }
        return baseQuery;
    };
};

Silobreaker.DocumentVolume.DataSource = function() {
    this.getTimeSeries = function(params, callback) {
        var url = "documentvolume";
        var startDate;
        var endDate;
        var granularity = params.timeIntervalModel.granularity;
        var timeRange = params.timeIntervalModel.getStartAndEndDate();
        var binSize = granularity;

        // Craft the url
        var parameters = { startDate: timeRange.startDate.getIsoString(), endDate: timeRange.endDate.getIsoString(), binSize: binSize };

        // Create correct query. Tries to be a bit clever and uses subquery only if necessary.
        var splitContextParameters = params.splitContextProvider.getSplitContextParameters();
        jQuery.extend(parameters, splitContextParameters);

        // Add context (or extend if already exists from splitcontextprovider
        if (parameters.q && parameters.q.length > 0) {
            if (params.context && params.context.length > 0 && parameters.q != params.context) {
                parameters.q = parameters.q + " AND " + params.context;
            }
        } else if (params.context) {
            parameters.q = params.context;
        }

        url += "?" + jQuery.param(parameters);

        Silobreaker.invokeApi(url, function(response) {
            // Convert response from API to data series
            var result = [];

            for (var i = 0; i < response.Series.length; i++) {
                var serieData = response.Series[i];
                var pointData = serieData.Points;
                var points = [];
                var maxValue = 0;

                // Iterate all data points from response and convert to millisecond ticks
                for (var j = 0; j < pointData.length; j++) {
                    var d = Date.fromIsoDate(pointData[j].Time);
                    points.push([d.getTime(), pointData[j].Value]);
                    if (pointData[j].Value > maxValue) {
                        maxValue = pointData[j].Value;
                    }
                }

                var start = Date.fromIsoDate(serieData.StartDate);
                var end = Date.fromIsoDate(serieData.EndDate);
                var binSize = serieData.BinSize * 60 * 1000; // convert from minutes to milliseconds

                points = padSerie(start.getTime(), end.getTime(), binSize, points);

                // Create the serie and push it to results
                var serie = { granularity: binSize, from: start, to: end, query: serieData.Query, points: points, maxValue: maxValue };
                result.push(serie);
            }

            callback(result);
        });

        // Appends zero values for missing points in a sparse serie.
        // This ensures all charts will be rendered with same x-axis and width on columns.
        var padSerie = function(startTick, endTick, binSize, serie) {
            var i = 0;

            var result = [];
            for (var time = startTick; time <= endTick; time += binSize) {
                var point = [time, 0];

                if (i < serie.length && time == serie[i][0]) {
                    point[1] = serie[i][1];
                    i++;
                }
                result.push(point);
            }

            return result;
        };
    };
};

/* SWFObject v2.1 <http://code.google.com/p/swfobject/>
Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

/* WARNING: Make sure VS do not beautify this line of code!! It will not work afterwards. A copy that is not beautified is in the commented row below. Copy and paste it if it gets messed up. */

if (!window['silobreaker_swfobject']) {
    window['silobreaker_swfobject']=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in silobreaker_swfobject){silobreaker_swfobject[X]=null}silobreaker_swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
}
//var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

// END SWFObject


Silobreaker.Tabs = function(params) {
    /// <summary> 
    ///     TODO
    /// </summary>

    var _instanciatedIn = null;
    var _self = this;
    var _tabs = params.tabs;

    this.id = "Silobreaker.Tabs";
    this.selectedTabChangedCallback = null;

    // Fix indata
    for (var i = 0; i < _tabs.length; i++) {
        if (!_tabs[i].cssClass || _tabs[i].cssClass == null)
            _tabs[i].cssClass = "";
    }

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);

        _self.renderTabs();
    };


    this.renderTabs = function() {
        /// <summary>
        ///     TODO
        /// </summary>
        var template = jQuery(".contentTemplate", _instanciatedIn);
        var html = template.bindTo(_tabs);
        jQuery(".content", _instanciatedIn).html(html);
        var tabs = jQuery(".content span", _instanciatedIn);

        tabs.each(function(index, element) {        
            jQuery(element).data("tabData", _tabs[index]);
        });

        tabs.click(_self.tabClicked);
    };
    
    this.tabClicked = function() {
        /// <summary>
        ///     Executes when a tab is clicked.
        /// </summary>
        var tab = jQuery(this);

        jQuery(".tab", tab.parent()).removeClass("selected");

        tab.addClass("selected");

        var tabData = tab.data("tabData");

        if (_self.selectedTabChangedCallback) {
            _self.selectedTabChangedCallback(tabData);
        }
    };
};Silobreaker.TabDocuments = function(params) {
    /// <summary> 
    ///     Widget showing document widget controlled by tabs
    /// </summary>

    var _instanciatedIn = null;
    var _self = this;

    var _tabs = null;
    var _documents = null;
    var _helptext = "The list shows all content related to your search.  Use the tabs to switch between content types and hover with your mouse over a headline to get a quick-view of the article.";
    var _disableBranding = false;

    // public vars
    this.id = "Silobreaker.TabDocuments";
    this.query = null;
    this.clickHandler = null;
    this.popupHandler = null;
    this.count = params.count;
    this.searchCompleteCallback = null;
    this.linkBaseUrl = null;
    this.showSourceUrl = false;
    this.apiKey = null;
    this.showTeasers = false;

    if (params.query) {
        this.query = params.query;
    }

    if (params.linkBaseUrl) {
        this.linkBaseUrl = params.linkBaseUrl;
    }

    if (params.apiKey) {
        this.apiKey = params.apiKey;
    }

    if (params.disableBranding) {
        _disableBranding = true;
    }

    if (params.showTeasers) {
        this.showTeasers = params.showTeasers;
    }

    if (params.showSourceUrl) {
        this.showSourceUrl = params.showSourceUrl;
    }

    // Transform indata to Tab-control format
    if (!params.tabs || params.tabs == null)
        params.tabs = [];

    _tabs = new Array(params.tabs.length);
    for (var i = 0; i < params.tabs.length; i++) {
        _tabs[i] = new Object();
        if (params.tabs[i].query) {
            _tabs[i].context = params.tabs[i].query;
        }
        if (params.tabs[i].types) {
            _tabs[i].types = params.tabs[i].types;
        }
        if (params.tabs[i].title) {
            _tabs[i].title = params.tabs[i].title;
        }
        _tabs[i].cssClass = "";
        if (params.tabs[i].selected && params.tabs[i].selected == true) {
            _tabs[i].cssClass = "selected";
        }
        if (params.tabs[i].cssClass && params.tabs[i].cssClass != null && params.tabs[i].cssClass != "") {
            if (_tabs[i].cssClass.length > 0)
                _tabs[i].cssClass += " ";
            _tabs[i].cssClass += params.tabs[i].cssClass;
        }
    }

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);

        if (_disableBranding == false) {
            Silobreaker.AddBranding(jQuery(".widget.tabDocuments", _instanciatedIn), "Silobreaker documents widget", _helptext);
        }
        
        _self.render();
    };

    this.render = function() {
        /// <summary>
        ///  Renders the widget
        /// </summary>

        // Create the tab control
        var tabs = new Silobreaker.Tabs({ tabs: _tabs });
        tabs.selectedTabChangedCallback = tabChanged;
        var tabPH = jQuery(".tabsPlaceholder", _instanciatedIn);
        Silobreaker.injectWidget(tabPH, tabs);

        // Create the document widget
        _documents = new Silobreaker.Documents({ count: this.count });
        if (_self.clickHandler && _self.clickHandler != null) {
            _documents.clickHandler = _self.clickHandler;
        }
        if (_self.popupHandler && _self.popupHandler != null) {
            _documents.popupHandler = _self.popupHandler;
        }
        if (_self.apiKey && _self.apiKey != null) {
            _documents.apiKey = _self.apiKey;
        }
        if (_self.linkBaseUrl && _self.linkBaseUrl != null) {
            _documents.linkBaseUrl = _self.linkBaseUrl;
        }
        if (_self.showSourceUrl && _self.showSourceUrl != null) {
            _documents.showSourceUrl = _self.showSourceUrl;
        }

        if (_self.showTeasers && _self.showTeasers != null) {
            _documents.showTeasers = _self.showTeasers;
        }


        // Set the widget name, is provided when document widget makes api request. Used for logging.
        _documents.widgetName = "TabDocuments";
        _documents.searchCompleteCallback = searchComplete;
        Silobreaker.injectWidget(jQuery(".documentsPlaceholder", _instanciatedIn), _documents);

        // Fires the click event on the selected tab
        jQuery("span.selected:first", tabPH).click();
    };

    this.search = function() {
        // Fires the click event on the selected tab
        jQuery("span.selected:first", _instanciatedIn).click();
    };

    var searchComplete = function(data) {
        // Update help text
        if (!_self.query || _self.query == "") {
            Silobreaker.UpdateInfoText(jQuery(".widget.tabDocuments", _instanciatedIn), "Latest content");
        }
        else if (data.Items.length == 0) {
            Silobreaker.UpdateInfoText(jQuery(".widget.tabDocuments", _instanciatedIn), "No content found for " + _self.query);
        }
        else {
            Silobreaker.UpdateInfoText(jQuery(".widget.tabDocuments", _instanciatedIn), "Search results for " + _self.query);
        }
        if (_self.searchCompleteCallback && _self.searchCompleteCallback != null) {
            _self.searchCompleteCallback(data);
        }
    };

    var tabChanged = function(tabData) {
        /// <summary>
        /// Called when the user has clicked a tab and on init when first tab is loaded
        /// </summary>

        var query = "";

        if (_self.query && _self.query != null && _self.query != "") {
            query = _self.query;
        }

        if (tabData.context && tabData.context != null && tabData.context != "") {
            if (query != "") {
                query += " AND ";
            }
            query += tabData.context;
        }

        _documents.query = query;

        if (tabData.types && tabData.types != null && tabData.types.length > 0) {
            _documents.types = tabData.types;
        }
        else {
            _documents.types = null;
        }

        _documents.search();


    };
};
Silobreaker.MetaSearch = function(params) {
    /// <summary> 
    ///     Widget listing meta search entries given a search query
    /// </summary>

    var _instanciatedIn = null;
    var _self = this;
    var _items = {};
    var _searchEntries = null;
    var _latestQuery = null;
    var _currentRefreshId;


    this.id = "Silobreaker.MetaSearch";
    var _helptext = "The list shows an aggregated view of meta searching to the given query. ";
    this.boxed = true;
    this.refreshIntervalInSeconds = 60;
    this.refreshEnabled = true;
    this.query = null;
    this.height = 500;
    this.count = 40;
    this.searchProviders = null;
    this.searchCompleteCallback = null;
    this.dataSource = new Silobreaker.MetaSearch.DataSource();
    this.clickHandler = null;
    this.popupHandler = null;
    this.linkBaseUrl = null;
    this.apiKey = null;
    this.timeOut = null;

    if (params) {
        if (params.query) {
            this.query = params.query;
        }

        if (params.count) {
            this.count = params.count;
        }

        if (params.searchProviders) {
            this.searchProviders = params.searchProviders; // Comma-separated string
        }

        if (params.linkBaseUrl) {
            this.linkBaseUrl = params.linkBaseUrl;
        }

        if (params.apiKey) {
            this.apiKey = params.apiKey;
        }

        if (params.boxed === false) {
            this.boxed = params.boxed;
        }

        if (params.refreshIntervalInSeconds) {
            this.refreshIntervalInSeconds = params.refreshIntervalInSeconds;
        }

        if (params.height) {
            this.height = params.height;
        }
    }

    this.initialize = function(element) {
        /// <summary>
        ///     Initializes the widget.
        /// </summary>
        /// <param name="element">
        ///     DOM element that the widget should operate on.
        /// </param>

        _instanciatedIn = jQuery(element);
        if (_instanciatedIn.length > 1) {
            alert('Warning, multiple elements');
        }


        if (_self.boxed) {
            Silobreaker.AddBranding(jQuery(".widget", _instanciatedIn), "Silobreaker Meta Search", _helptext);
        }

        // Handle checkbox changes
        jQuery(_instanciatedIn).find(".msRefresh").click(function() {
            _self.refreshEnabled = jQuery(_instanciatedIn).find(".msRefresh").attr('checked');
            _self.updateRefreshing();
        });

        _self.search();
    };

    this.search = function() {
        /// <summary>
        ///     Executes the search and fills the template with the result.
        /// </summary>

        // Clear entries if this is a new query
        if (_latestQuery != _self.query) {
            _searchEntries = null;
            _latestQuery = _self.query;

            if (_currentRefreshId) {
                clearInterval(_currentRefreshId);
            }
        }
        clearTimeout(_self.timeOut);

        jQuery(_instanciatedIn).attr("context", _self.query);


        var params = { query: _self.query, count: _self.count, searchProviders: _self.searchProviders };
        if (_self.widgetName) {
            params.widget = _self.widgetName;
            params.operation = "MetaSearch";
        }

        _self.dataSource.getMetaSearchEntries(_self.fillTemplate, params, _self.apiKey);
        _self.timeOut = setTimeout(_self.timeOutHandler, 5000);

        // Do search either regulary or once.
        if (_self.refreshEnabled === true) {
            _self.updateRefreshing();
        }
    };

    this.updateRefreshing = function() {
        /// <summary>
        ///     Updates search refresh-rate based on current settings
        /// </summary>

        // Clear current refreshs
        if (_currentRefreshId) {
            clearInterval(_currentRefreshId);
        }

        clearTimeout(_self.timeOut);

        // Update checkbox to match parameter
        jQuery(_instanciatedIn).find(".msRefresh").attr('checked', _self.refreshEnabled);

        // If enabled, start a refresh session
        if (_self.refreshEnabled) {

            var timer = Math.min(30000, 1000 * _self.refreshIntervalInSeconds);

            _currentRefreshId = setInterval(function() {
                var params = { query: _self.query, count: _self.count, searchProviders: _self.searchProviders };
                if (_self.widgetName) {
                    params.widget = _self.widgetName;
                    params.operation = "MetaSearch";
                }

                if (jQuery(_instanciatedIn).is(':hidden')) {
                    _self.refreshEnabled = false;
                }
                else {
                    _self.dataSource.getMetaSearchEntries(_self.fillTemplate, params, _self.apiKey);
                    _self.timeOut = setTimeout(_self.timeOutHandler, 30000);
                }
            }, timer);
        }
    };

    this.timeOutHandler = function() {

        var errorHtml = '<div class="error">There was a problem connecting to the meta search service.</div>';
        var errorElement = jQuery(_instanciatedIn).find('.msError');

        if (errorElement.length > 0) {
            errorElement.html(errorHtml);
        }
        else {
            var contentElement = jQuery(_instanciatedIn).find(".content");
            contentElement.html(errorHtml);
        }
    };

    this.fillTemplate = function(data) {
        /// <summary>
        ///     Fills the template html with data.
        /// </summary>

        clearTimeout(_self.timeOut);

        if (data.Statuses && data.Statuses.length > 0) {
            jQuery(_instanciatedIn).find('.msError').html('<div class="error">' + data.Statuses.join('<br/>') + '</div>');
        } else {
            jQuery(_instanciatedIn).find('.msError').html('');
        }

        var completeRefresh = false;
        if (_searchEntries === null) {
            completeRefresh = true;
            _searchEntries = {};
        }

        var newData = {};
        newData.Items = [];

        for (var i = 0; i < data.Items.length && typeof (data.Items[i]) != 'undefined'; i++) {

            var currentItem = data.Items[i];

            if (!_searchEntries[currentItem.Provider + "_" + currentItem.Id]) {
                _searchEntries[currentItem.Provider + "_" + currentItem.Id] = currentItem;
                newData.Items.push(currentItem);
            }

            var altLink;

            // Select related and alternate links
            currentItem.RelatedLinks = [];
            if (currentItem.Links) {
                var k = 0;
                for (var j = 0; j < currentItem.Links.length; j++) {
                    if (currentItem.Links[j].Rel == 'related') {

                        // Skip image links
                        if (currentItem.Links[j].Type && currentItem.Links[j].Type.startsWith('image')) {
                            continue;
                        }

                        var relatedLink = currentItem.Links[j];

                        // Set link name, ref and alt attributes on the related link                        
                        if (!relatedLink.Name) {
                            relatedLink.Name = relatedLink.Href;
                        }

                        if (!relatedLink.Description) {
                            relatedLink.Alt = relatedLink.Name;
                        } else {
                            relatedLink.Alt = relatedLink.Description;
                        }

                        if (relatedLink.Name.length > 40) {
                            relatedLink.Name = relatedLink.Name.substring(0, 40) + '...';
                        }

                        currentItem.RelatedLinks[k] = relatedLink;

                        k = k + 1;
                    } else if (currentItem.Links[j].Rel == 'alternate') {
                        altLink = currentItem.Links[j].Href;
                    }
                }
            }

            // Add pretty date
            var prettyDate = new Date();
            var updatedDate = currentItem.Updated;
            if (!updatedDate) {
                updatedDate = currentItem.Published;
            }
            prettyDate.setIsoDate(currentItem.Updated);
            currentItem.PrettyUpdatedDate = prettyDate.prettyString();

            // Set css class
            currentItem.CssClass = "ms" + currentItem.Provider.replace(/ /gi, "");

            // Set link on date when available
            if (altLink) {
                currentItem.PrettyUpdatedDate = '<a target="_blank" href="' + altLink + '">' + currentItem.PrettyUpdatedDate + '</a>';
            }

            // Add content
            if (currentItem.Contents[0].Text) {
                currentItem.Content = currentItem.Contents[0].Text;
            } else {
                currentItem.Content = "";
            }

            // Set author
            if (currentItem.Authors && currentItem.Authors.length > 0) {
                var firstAuthor = currentItem.Authors[0];

                if (!firstAuthor.Name) {
                    firstAuthor.Name = firstAuthor.UserId;
                }

                if (firstAuthor.Uri) {
                    currentItem.Author = '<a target="_blank" href="' + firstAuthor.Uri + '">' + firstAuthor.Name + '</a>';
                } else {
                    currentItem.Author = firstAuthor.Name;
                }
            }

            // Add title to content when available
            if (currentItem.Title) {
                var title;
                if (altLink) {
                    title = '<a target="_blank" href="' + altLink + '">' + currentItem.Title + '</a>';
                } else {
                    title = currentItem.Title;
                }

                currentItem.Content = '<div class="title">' + title + '</div>' + currentItem.Content;
            }
        }

        // Get the template and fill it with data
        var template = jQuery(_instanciatedIn).find(".contentTemplate");
        var html = template.bindTo(newData);

        // Skip the surrounding template tag
        html = jQuery(html).html();

        var contentElement = jQuery(_instanciatedIn).find(".content");

        // Completely new data, so fill the whole content section
        if (completeRefresh === true) {
            contentElement.html(html);
        }
        // Incremental data, so slide in new rows
        else if (newData.Items.length > 0) {
            html = html + '<div class="msUpdate">' + newData.Items.length + ' new entries.</div>';
            jQuery(html).filter("*").hide().prependTo(contentElement).slideDown('slow');
        }
        var links = jQuery(_instanciatedIn).find(".content a[itemref]");
        Silobreaker.WireUpItems(links, _items, _self.popupHandler, _self.clickHandler, _self.linkBaseUrl);

        jQuery(_instanciatedIn).find(".content").height(_self.height);

        if (_self.searchCompleteCallback) {
            _self.searchCompleteCallback(data);
        }
    };
};

Silobreaker.MetaSearch.DataSource = function() {
    /// <summary>Data Source class for MetaSearch Widget</summary>

    this.getMetaSearchEntries = function(callback, params, apiKey) {
        /// <summary>
        ///     Get meta search based on a set of parameters. Supported parameters are:
        ///     query (the query to use, optional),
        ///     count (number of documents to retrieve, optional)
        ///     searchProviders (list of providers to search)
        /// </summary>
        /// <param name="callback">
        ///     The callback function to call when data is retrieved.
        /// </param>
        /// <param name="params">
        ///     An object containing parameters for the request.
        /// </param>
        /// <param name="apiKey">
        ///    Optional. Specifies the api key to use when invoking the api.
        /// </param>

        var url = "meta/";

        if (!params) {
            throw "ArgumentNullException: No parameters specified.";
        }

        var querySet = params.query && params.query !== null && params.query != "";

        var parameters = {};

        if (querySet) {
            parameters.q = params.query;
        }

        if (params.searchProviders && params.searchProviders !== null && params.searchProviders.length > 0) {
            parameters.providers = params.searchProviders; 
        }

        if (params.count) {
            parameters.pageSize = params.count;
        }

        if (params.widget) {
            parameters.widget = params.widget;
        }

        if (params.operation) {
            parameters.operation = params.operation;
        }

        url += "?" + jQuery.param(parameters);
       
        Silobreaker.invokeApi(url, callback, apiKey);
    };
};
// http://www.strictly-software.com/scripts/downloads/encoder.js
Encoder = {

    // When encoding do we convert characters into html or numerical entities
    EncodeType: "entity",  // entity OR numerical

    isEmpty: function(val) {
        if (val) {
            return ((val === null) || val.length == 0 || /^\s+$/.test(val));
        } else {
            return true;
        }
    },
    // Convert HTML entities into numerical entities
    HTML2Numerical: function(s) {
        var arr1 = new Array('&nbsp;', '&iexcl;', '&cent;', '&pound;', '&curren;', '&yen;', '&brvbar;', '&sect;', '&uml;', '&copy;', '&ordf;', '&laquo;', '&not;', '&shy;', '&reg;', '&macr;', '&deg;', '&plusmn;', '&sup2;', '&sup3;', '&acute;', '&micro;', '&para;', '&middot;', '&cedil;', '&sup1;', '&ordm;', '&raquo;', '&frac14;', '&frac12;', '&frac34;', '&iquest;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&Auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&Ouml;', '&times;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&Uuml;', '&yacute;', '&thorn;', '&szlig;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&ouml;', '&divide;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&uuml;', '&yacute;', '&thorn;', '&yuml;', '&quot;', '&amp;', '&lt;', '&gt;', '&oelig;', '&oelig;', '&scaron;', '&scaron;', '&yuml;', '&circ;', '&tilde;', '&ensp;', '&emsp;', '&thinsp;', '&zwnj;', '&zwj;', '&lrm;', '&rlm;', '&ndash;', '&mdash;', '&lsquo;', '&rsquo;', '&sbquo;', '&ldquo;', '&rdquo;', '&bdquo;', '&dagger;', '&dagger;', '&permil;', '&lsaquo;', '&rsaquo;', '&euro;', '&fnof;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigmaf;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&thetasym;', '&upsih;', '&piv;', '&bull;', '&hellip;', '&prime;', '&prime;', '&oline;', '&frasl;', '&weierp;', '&image;', '&real;', '&trade;', '&alefsym;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&crarr;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&forall;', '&part;', '&exist;', '&empty;', '&nabla;', '&isin;', '&notin;', '&ni;', '&prod;', '&sum;', '&minus;', '&lowast;', '&radic;', '&prop;', '&infin;', '&ang;', '&and;', '&or;', '&cap;', '&cup;', '&int;', '&there4;', '&sim;', '&cong;', '&asymp;', '&ne;', '&equiv;', '&le;', '&ge;', '&sub;', '&sup;', '&nsub;', '&sube;', '&supe;', '&oplus;', '&otimes;', '&perp;', '&sdot;', '&lceil;', '&rceil;', '&lfloor;', '&rfloor;', '&lang;', '&rang;', '&loz;', '&spades;', '&clubs;', '&hearts;', '&diams;');
        var arr2 = new Array('&#160;', '&#161;', '&#162;', '&#163;', '&#164;', '&#165;', '&#166;', '&#167;', '&#168;', '&#169;', '&#170;', '&#171;', '&#172;', '&#173;', '&#174;', '&#175;', '&#176;', '&#177;', '&#178;', '&#179;', '&#180;', '&#181;', '&#182;', '&#183;', '&#184;', '&#185;', '&#186;', '&#187;', '&#188;', '&#189;', '&#190;', '&#191;', '&#192;', '&#193;', '&#194;', '&#195;', '&#196;', '&#197;', '&#198;', '&#199;', '&#200;', '&#201;', '&#202;', '&#203;', '&#204;', '&#205;', '&#206;', '&#207;', '&#208;', '&#209;', '&#210;', '&#211;', '&#212;', '&#213;', '&#214;', '&#215;', '&#216;', '&#217;', '&#218;', '&#219;', '&#220;', '&#221;', '&#222;', '&#223;', '&#224;', '&#225;', '&#226;', '&#227;', '&#228;', '&#229;', '&#230;', '&#231;', '&#232;', '&#233;', '&#234;', '&#235;', '&#236;', '&#237;', '&#238;', '&#239;', '&#240;', '&#241;', '&#242;', '&#243;', '&#244;', '&#245;', '&#246;', '&#247;', '&#248;', '&#249;', '&#250;', '&#251;', '&#252;', '&#253;', '&#254;', '&#255;', '&#34;', '&#38;', '&#60;', '&#62;', '&#338;', '&#339;', '&#352;', '&#353;', '&#376;', '&#710;', '&#732;', '&#8194;', '&#8195;', '&#8201;', '&#8204;', '&#8205;', '&#8206;', '&#8207;', '&#8211;', '&#8212;', '&#8216;', '&#8217;', '&#8218;', '&#8220;', '&#8221;', '&#8222;', '&#8224;', '&#8225;', '&#8240;', '&#8249;', '&#8250;', '&#8364;', '&#402;', '&#913;', '&#914;', '&#915;', '&#916;', '&#917;', '&#918;', '&#919;', '&#920;', '&#921;', '&#922;', '&#923;', '&#924;', '&#925;', '&#926;', '&#927;', '&#928;', '&#929;', '&#931;', '&#932;', '&#933;', '&#934;', '&#935;', '&#936;', '&#937;', '&#945;', '&#946;', '&#947;', '&#948;', '&#949;', '&#950;', '&#951;', '&#952;', '&#953;', '&#954;', '&#955;', '&#956;', '&#957;', '&#958;', '&#959;', '&#960;', '&#961;', '&#962;', '&#963;', '&#964;', '&#965;', '&#966;', '&#967;', '&#968;', '&#969;', '&#977;', '&#978;', '&#982;', '&#8226;', '&#8230;', '&#8242;', '&#8243;', '&#8254;', '&#8260;', '&#8472;', '&#8465;', '&#8476;', '&#8482;', '&#8501;', '&#8592;', '&#8593;', '&#8594;', '&#8595;', '&#8596;', '&#8629;', '&#8656;', '&#8657;', '&#8658;', '&#8659;', '&#8660;', '&#8704;', '&#8706;', '&#8707;', '&#8709;', '&#8711;', '&#8712;', '&#8713;', '&#8715;', '&#8719;', '&#8721;', '&#8722;', '&#8727;', '&#8730;', '&#8733;', '&#8734;', '&#8736;', '&#8743;', '&#8744;', '&#8745;', '&#8746;', '&#8747;', '&#8756;', '&#8764;', '&#8773;', '&#8776;', '&#8800;', '&#8801;', '&#8804;', '&#8805;', '&#8834;', '&#8835;', '&#8836;', '&#8838;', '&#8839;', '&#8853;', '&#8855;', '&#8869;', '&#8901;', '&#8968;', '&#8969;', '&#8970;', '&#8971;', '&#9001;', '&#9002;', '&#9674;', '&#9824;', '&#9827;', '&#9829;', '&#9830;');
        return this.swapArrayVals(s, arr1, arr2);
    },

    // Convert Numerical entities into HTML entities
    NumericalToHTML: function(s) {
        var arr1 = new Array('&#160;', '&#161;', '&#162;', '&#163;', '&#164;', '&#165;', '&#166;', '&#167;', '&#168;', '&#169;', '&#170;', '&#171;', '&#172;', '&#173;', '&#174;', '&#175;', '&#176;', '&#177;', '&#178;', '&#179;', '&#180;', '&#181;', '&#182;', '&#183;', '&#184;', '&#185;', '&#186;', '&#187;', '&#188;', '&#189;', '&#190;', '&#191;', '&#192;', '&#193;', '&#194;', '&#195;', '&#196;', '&#197;', '&#198;', '&#199;', '&#200;', '&#201;', '&#202;', '&#203;', '&#204;', '&#205;', '&#206;', '&#207;', '&#208;', '&#209;', '&#210;', '&#211;', '&#212;', '&#213;', '&#214;', '&#215;', '&#216;', '&#217;', '&#218;', '&#219;', '&#220;', '&#221;', '&#222;', '&#223;', '&#224;', '&#225;', '&#226;', '&#227;', '&#228;', '&#229;', '&#230;', '&#231;', '&#232;', '&#233;', '&#234;', '&#235;', '&#236;', '&#237;', '&#238;', '&#239;', '&#240;', '&#241;', '&#242;', '&#243;', '&#244;', '&#245;', '&#246;', '&#247;', '&#248;', '&#249;', '&#250;', '&#251;', '&#252;', '&#253;', '&#254;', '&#255;', '&#34;', '&#38;', '&#60;', '&#62;', '&#338;', '&#339;', '&#352;', '&#353;', '&#376;', '&#710;', '&#732;', '&#8194;', '&#8195;', '&#8201;', '&#8204;', '&#8205;', '&#8206;', '&#8207;', '&#8211;', '&#8212;', '&#8216;', '&#8217;', '&#8218;', '&#8220;', '&#8221;', '&#8222;', '&#8224;', '&#8225;', '&#8240;', '&#8249;', '&#8250;', '&#8364;', '&#402;', '&#913;', '&#914;', '&#915;', '&#916;', '&#917;', '&#918;', '&#919;', '&#920;', '&#921;', '&#922;', '&#923;', '&#924;', '&#925;', '&#926;', '&#927;', '&#928;', '&#929;', '&#931;', '&#932;', '&#933;', '&#934;', '&#935;', '&#936;', '&#937;', '&#945;', '&#946;', '&#947;', '&#948;', '&#949;', '&#950;', '&#951;', '&#952;', '&#953;', '&#954;', '&#955;', '&#956;', '&#957;', '&#958;', '&#959;', '&#960;', '&#961;', '&#962;', '&#963;', '&#964;', '&#965;', '&#966;', '&#967;', '&#968;', '&#969;', '&#977;', '&#978;', '&#982;', '&#8226;', '&#8230;', '&#8242;', '&#8243;', '&#8254;', '&#8260;', '&#8472;', '&#8465;', '&#8476;', '&#8482;', '&#8501;', '&#8592;', '&#8593;', '&#8594;', '&#8595;', '&#8596;', '&#8629;', '&#8656;', '&#8657;', '&#8658;', '&#8659;', '&#8660;', '&#8704;', '&#8706;', '&#8707;', '&#8709;', '&#8711;', '&#8712;', '&#8713;', '&#8715;', '&#8719;', '&#8721;', '&#8722;', '&#8727;', '&#8730;', '&#8733;', '&#8734;', '&#8736;', '&#8743;', '&#8744;', '&#8745;', '&#8746;', '&#8747;', '&#8756;', '&#8764;', '&#8773;', '&#8776;', '&#8800;', '&#8801;', '&#8804;', '&#8805;', '&#8834;', '&#8835;', '&#8836;', '&#8838;', '&#8839;', '&#8853;', '&#8855;', '&#8869;', '&#8901;', '&#8968;', '&#8969;', '&#8970;', '&#8971;', '&#9001;', '&#9002;', '&#9674;', '&#9824;', '&#9827;', '&#9829;', '&#9830;');
        var arr2 = new Array('&nbsp;', '&iexcl;', '&cent;', '&pound;', '&curren;', '&yen;', '&brvbar;', '&sect;', '&uml;', '&copy;', '&ordf;', '&laquo;', '&not;', '&shy;', '&reg;', '&macr;', '&deg;', '&plusmn;', '&sup2;', '&sup3;', '&acute;', '&micro;', '&para;', '&middot;', '&cedil;', '&sup1;', '&ordm;', '&raquo;', '&frac14;', '&frac12;', '&frac34;', '&iquest;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&Auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&Ouml;', '&times;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&Uuml;', '&yacute;', '&thorn;', '&szlig;', '&agrave;', '&aacute;', '&acirc;', '&atilde;', '&auml;', '&aring;', '&aelig;', '&ccedil;', '&egrave;', '&eacute;', '&ecirc;', '&euml;', '&igrave;', '&iacute;', '&icirc;', '&iuml;', '&eth;', '&ntilde;', '&ograve;', '&oacute;', '&ocirc;', '&otilde;', '&ouml;', '&divide;', '&oslash;', '&ugrave;', '&uacute;', '&ucirc;', '&uuml;', '&yacute;', '&thorn;', '&yuml;', '&quot;', '&amp;', '&lt;', '&gt;', '&oelig;', '&oelig;', '&scaron;', '&scaron;', '&yuml;', '&circ;', '&tilde;', '&ensp;', '&emsp;', '&thinsp;', '&zwnj;', '&zwj;', '&lrm;', '&rlm;', '&ndash;', '&mdash;', '&lsquo;', '&rsquo;', '&sbquo;', '&ldquo;', '&rdquo;', '&bdquo;', '&dagger;', '&dagger;', '&permil;', '&lsaquo;', '&rsaquo;', '&euro;', '&fnof;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&alpha;', '&beta;', '&gamma;', '&delta;', '&epsilon;', '&zeta;', '&eta;', '&theta;', '&iota;', '&kappa;', '&lambda;', '&mu;', '&nu;', '&xi;', '&omicron;', '&pi;', '&rho;', '&sigmaf;', '&sigma;', '&tau;', '&upsilon;', '&phi;', '&chi;', '&psi;', '&omega;', '&thetasym;', '&upsih;', '&piv;', '&bull;', '&hellip;', '&prime;', '&prime;', '&oline;', '&frasl;', '&weierp;', '&image;', '&real;', '&trade;', '&alefsym;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&crarr;', '&larr;', '&uarr;', '&rarr;', '&darr;', '&harr;', '&forall;', '&part;', '&exist;', '&empty;', '&nabla;', '&isin;', '&notin;', '&ni;', '&prod;', '&sum;', '&minus;', '&lowast;', '&radic;', '&prop;', '&infin;', '&ang;', '&and;', '&or;', '&cap;', '&cup;', '&int;', '&there4;', '&sim;', '&cong;', '&asymp;', '&ne;', '&equiv;', '&le;', '&ge;', '&sub;', '&sup;', '&nsub;', '&sube;', '&supe;', '&oplus;', '&otimes;', '&perp;', '&sdot;', '&lceil;', '&rceil;', '&lfloor;', '&rfloor;', '&lang;', '&rang;', '&loz;', '&spades;', '&clubs;', '&hearts;', '&diams;');
        return this.swapArrayVals(s, arr1, arr2);
    },


    // Numerically encodes all unicode characters
    numEncode: function(s) {

        if (this.isEmpty(s)) return "";

        var e = "";
        for (var i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (c < " " || c > "~") {
                c = "&#" + c.charCodeAt() + ";";
            }
            e += c;
        }
        return e;
    },

    // HTML Decode numerical and HTML entities back to original values
    htmlDecode: function(s) {

        var c, m, d = s;

        if (this.isEmpty(d)) return "";

        // convert HTML entites back to numerical entites first
        d = this.HTML2Numerical(d);

        // look for numerical entities &#34;
        arr = d.match(/&#[0-9]{1,5};/g);

        // if no matches found in string then skip
        if (arr != null) {
            for (var x = 0; x < arr.length; x++) {
                m = arr[x];
                c = m.substring(2, m.length - 1); //get numeric part which is refernce to unicode character
                // if its a valid number we can decode
                if (c >= -32768 && c <= 65535) {
                    // decode every single match within string
                    d = d.replace(m, String.fromCharCode(c));
                } else {
                    d = d.replace(m, ""); //invalid so replace with nada
                }
            }
        }

        return d;
    },

    // encode an input string into either numerical or HTML entities
    htmlEncode: function(s, dbl) {

        if (this.isEmpty(s)) return "";

        // do we allow double encoding? E.g will &amp; be turned into &amp;amp;
        dbl = dbl | false; //default to prevent double encoding

        // if allowing double encoding we do ampersands first
        if (dbl) {
            if (this.EncodeType == "numerical") {
                s = s.replace(/&/g, "&#38;");
            } else {
                s = s.replace(/&/g, "&amp;");
            }
        }

        // convert the xss chars to numerical entities ' " < >
        s = this.XSSEncode(s, false);

        if (this.EncodeType == "numerical" || !dbl) {
            // Now call function that will convert any HTML entities to numerical codes
            s = this.HTML2Numerical(s);
        }

        // Now encode all chars above 127 e.g unicode
        s = this.numEncode(s);

        // now we know anything that needs to be encoded has been converted to numerical entities we
        // can encode any ampersands & that are not part of encoded entities
        // to handle the fact that I need to do a negative check and handle multiple ampersands &&&
        // I am going to use a placeholder

        // if we don't want double encoded entities we ignore the & in existing entities
        if (!dbl) {
            s = s.replace(/&#/g, "##AMPHASH##");

            if (this.EncodeType == "numerical") {
                s = s.replace(/&/g, "&#38;");
            } else {
                s = s.replace(/&/g, "&amp;");
            }

            s = s.replace(/##AMPHASH##/g, "&#");
        }

        // replace any malformed entities
        s = s.replace(/&#\d*([^\d;]|$)/g, "$1");

        if (!dbl) {
            // safety check to correct any double encoded &amp;
            s = this.correctEncoding(s);
        }

        // now do we need to convert our numerical encoded string into entities
        if (this.EncodeType == "entity") {
            s = this.NumericalToHTML(s);
        }

        return s;
    },

    // Encodes the basic 4 characters used to malform HTML in XSS hacks
    XSSEncode: function(s, en) {
        if (!this.isEmpty(s)) {
            en = en || true;
            // do we convert to numerical or html entity?
            if (en) {
                s = s.replace(/\'/g, "&#39;"); //no HTML equivalent as &apos is not cross browser supported
                s = s.replace(/\"/g, "&quot;");
                s = s.replace(/</g, "&lt;");
                s = s.replace(/>/g, "&gt;");
            } else {
                s = s.replace(/\'/g, "&#39;"); //no HTML equivalent as &apos is not cross browser supported
                s = s.replace(/\"/g, "&#34;");
                s = s.replace(/</g, "&#60;");
                s = s.replace(/>/g, "&#62;");
            }
            return s;
        } else {
            return "";
        }
    },

    // returns true if a string contains html or numerical encoded entities
    hasEncoded: function(s) {
        if (/&#[0-9]{1,5};/g.test(s)) {
            return true;
        } else if (/&[A-Z]{2,6};/gi.test(s)) {
            return true;
        } else {
            return false;
        }
    },

    // will remove any unicode characters
    stripUnicode: function(s) {
        return s.replace(/[^\x20-\x7E]/g, "");

    },

    // corrects any double encoded &amp; entities e.g &amp;amp;
    correctEncoding: function(s) {
        return s.replace(/(&amp;)(amp;)+/, "$1");
    },


    // Function to loop through an array swaping each item with the value from another array e.g swap HTML entities with Numericals
    swapArrayVals: function(s, arr1, arr2) {
        if (this.isEmpty(s)) return "";
        var re;
        if (arr1 && arr2) {
            //ShowDebug("in swapArrayVals arr1.length = " + arr1.length + " arr2.length = " + arr2.length)
            // array lengths must match
            if (arr1.length == arr2.length) {
                for (var x = 0, i = arr1.length; x < i; x++) {
                    re = new RegExp(arr1[x], 'g');
                    s = s.replace(re, arr2[x]); //swap arr1 item with matching item from arr2	
                }
            }
        }
        return s;
    },

    inArray: function(item, arr) {
        for (var i = 0, x = arr.length; i < x; i++) {
            if (arr[i] === item) {
                return i;
            }
        }
        return -1;
    }

}
/// <reference path="..\jquery-1.3.2-vsdoc.js" />
/// <reference path="Controllers.js" />
/// <reference path="Views.js" />

Silobreaker = window.Silobreaker || {};
Silobreaker.Chart = window.Silobreaker.Chart || {};
Silobreaker.SplitModels = window.Silobreaker.SplitModels || {};

Silobreaker.EventHandler = function() {
    var _listeners = [];
    this.trigger = function() {
        /// <summary>
        ///    Calls each registered listener.
        /// </summary>
        for (var i = 0; i < _listeners.length; i++) {
            _listeners[i]();
        }
    };
    this.bind = function(listener) {
        /// <summary>
        ///    Adds a listener function which will be called when trigger is called.
        /// </summary>
        /// <param name="listener">
        ///     A function to be called when trigger is called.
        /// </param>
        if (jQuery.isFunction(listener)) {
            _listeners.push(listener);
        }
    };
    this.unbind = function(listener) {
        /// <summary>
        ///    Removes a previously added listener.
        /// </summary>
        /// <param name="listener">
        ///     The listener to remove.
        /// </param>
        var i = _listeners.indexOf(listener);
        if (i > -1) {
            _listeners.splice(i, 1);
        }
    };
};

Silobreaker.Chart.ChartModel = function (params) {
    /// <summary>
    ///     Creates a new instance of a Silobreaker.Chart.ChartModel.
    /// </summary>
    /// <param name="params">
    ///     splitContextProvider: {}
    ///     timeInterval: {}
    ///     query: ''
    ///     dataSource: {}
    /// </param>
    var _self = this;
    var _dataSeries = [];
    var _context = '';
    var _splitContextProvider = new Silobreaker.SplitModels.ManualSplitModel();
    var _timeIntervalModel = new Silobreaker.Chart.TimeIntervalModel();
    var _dataSource = new Silobreaker.Chart.ChartModel.DummyDataSource();
    this.isRefreshing = false;

    /// <summary>
    ///     Gets or sets the event handler which is triggered when a parameter has changed in the model.
    /// </summary>
    this.parameterChanged = new Silobreaker.EventHandler();

    if (params == undefined) {
        params = {};
    }

    if (params.context) {
        _context = params.context;
    }
    if (params.timeIntervalModel) {
        _timeIntervalModel = params.timeIntervalModel;
    }
    if (params.dataSource) {
        _dataSource = params.dataSource;
    }

    this.setContext = function (context) {
        _context = context;
        notifyParameterChanged();
    };

    this.getContext = function () {
        return _context;
    };

    this.getSplitContextProvider = function () {
        return _splitContextProvider;
    };

    this.setSplitContextProvider = function (provider) {
        _splitContextProvider = provider;
        notifyParameterChanged();
    };

    this.getTimeIntervalModel = function () {
        return _timeIntervalModel;
    };

    this.setDataSource = function (dataSource) {
        _dataSource = dataSource;
    };

    var notifyParameterChanged = function () {
        _self.parameterChanged.trigger();
    };

    this.refreshData = function (callback) {
        _self.isRefreshing = true;
        _dataSource.getTimeSeries({ context: _context, splitContextProvider: _splitContextProvider, timeIntervalModel: _timeIntervalModel }, function (data) {
            _dataSeries = data;
            _self.isRefreshing = false;
            callback(_dataSeries);
        });
    };

    // Registers notifyParameterChanged to time interval model change event.
    _timeIntervalModel.timeIntervalChanged.bind(notifyParameterChanged);

    /// <summary>
    ///     Returns true if the chart contains any data to show
    /// </summary>
    this.hasContent = function () {

        return _context!='' || _splitContextProvider.hasContent();
    };

    /// <summary>
    ///     Converts this object into a simple dictionary json object
    /// </summary>
    this.toDictionary = function () {

        var jsonObject = _timeIntervalModel.toDictionary();
        $.extend(jsonObject, _splitContextProvider.toDictionary());
        return jsonObject;
    };

    /// <summary>
    ///     Updates this object based on data in a simple dictionary.
    /// </summary>
    this.updateFromDictionary = function (jsonObject) {

        if (jsonObject.splitType) {
            var splitModel;

            // Perhaps extract this to a factory?
            switch (jsonObject.splitType) {
                case 'manual':
                    splitModel = new Silobreaker.SplitModels.ManualSplitModel();
                    break;
                default:
                    splitModel = new Silobreaker.SplitModels.AutoItemSplitModel();
                    break;
            }
            splitModel.updateFromDictionary(jsonObject);
            _splitContextProvider = splitModel;
        }

        _timeIntervalModel.updateFromDictionary(jsonObject);
        notifyParameterChanged();
    };

};



function QueryStringToObject(query) {
    var obj = {};
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var pair = vars[i].split("=");
        if (pair.length > 1) {
            pair[0] = decodeURIComponent(pair[0].replace(/\+/g, ' '));
            pair[1] = decodeURIComponent(pair[1].replace(/\+/g, ' '));
            // If first entry with this name
            if (typeof obj[pair[0]] === "undefined") {
                obj[pair[0]] = pair[1];
                // If second entry with this name
            } else if (typeof obj[pair[0]] === "string") {
                var arr = [obj[pair[0]], pair[1]];
                obj[pair[0]] = arr;
                // If third or later entry with this name
            } else {
                obj[pair[0]].push(pair[1]);
            }
        }
    }
    return obj;
};

/// <summary>
///   Class that is responsible for writing and parsing the state of a chart to the url
/// <summary>
Silobreaker.Chart.ChartModelUrlPersister = function() {
    var _model = {};
    var _self = this;

    this.parseModel = function() {

        var obj = QueryStringToObject(_self.getHashString());
        _model.updateFromDictionary(obj);
    };

    /// <summary>
    ///     Sets the model for which to persist
    /// </summary>
    this.setModel = function(chartModel) {
        _model = chartModel;
        _model.parameterChanged.bind(_self.modelChanged);
    };

    this.modelChanged = function() {
        // Update url
        var s = _self.serializeModel();
        location.hash = s;
    };

    this.serializeModel = function() {

        var m = _model.toDictionary();
        return jQuery.param(m);
    };

    this.getHashString = function() {
        return location.hash.substr(location.hash.indexOf('#') + 1, location.hash.length);
    };
};


Silobreaker.Chart.ChartModel.DummyDataSource = function() {
    this.getTimeSeries = function(params, callback) {

        // Dummy data loader
        var now = new Date();
        var from;
        var to;
        var granularity = params.timeInterval.granularity;

        if (jQuery.isPlainObject(params.timeInterval.timeRange)) {
            from = params.timeInterval.timeRange.from.getTime();
            to = params.timeInterval.timeRange.to.getTime();
        } else {
            from = now.getTime() + params.timeInterval.timeRange;
            to = now;
        }

        var noTicks = (to - from) / params.timeInterval.granularity;

        if (noTicks > 100) {
            noTicks = 100;
        }

        var points = [];
        for (i = 0; i < noTicks; i++) {
            tick = from + i * params.timeInterval.granularity;
            points.push([tick, Math.floor(Math.random() * 11)]);
        };

        var data = { granularity: params.timeIntervalModel.granularity, from: from, to: to, series: [{ label: 'Serie 1', points: points}] };
        callback(data);
    };

};

Silobreaker.SplitModels.ManualSplitModel = function (searchStrings, searchContext) {
    var _searchStrings = [];
    var _searchContext = '';
    var _self = this;

    if (searchStrings) {
        _searchStrings = searchStrings;
    }

    if (searchContext) {
        _searchContext = searchContext;
    }

    this.getSearchString = function () {
        return _searchStrings;
    };

    this.getSearchContext = function () {
        return _searchContext;
    };

    this.getPrimarySearch = function () {
        if (_searchContext && _searchContext != '') {
            return _searchContext;
        } else if (_searchStrings.length > 0) {
            return _searchStrings[0];
        }
    };

    this.setSplitContext = function (splitStrings) {
        _searchStrings = splitStrings;
    };

    this.setSearchContext = function (newSearchContext) {
        _searchContext = newSearchContext;
    };

    this.hasContent = function () {
        return _searchStrings.length > 0 || (_searchContext && _searchContext != '');
    };

    this.getBaseQuery = function () {
        var baseQuery = _searchStrings.join(" OR ");
        if (_searchContext && _searchContext != "") {
            if (_searchStrings.length > 0) {
                baseQuery = _searchContext + " AND (" + baseQuery + ")";
            } else {
                baseQuery = _searchContext;
            }
        }
        return baseQuery;
    };

    this.updateFromDictionary = function (obj) {
        _searchStrings = [];
        if (obj.splits) {
            var parts = obj.splits.split(';');
            for (var i = 0; i < parts.length; i++) {
                var part = parts[i].trim();
                if (part != '') {
                    _searchStrings.push(part);
                }
            }
        }

        _searchContext = obj.searchContext;
    };

    this.getSearchStrings = function () {
        return _searchStrings;
    };

    /// <summary>
    ///     Gets the parameters that should be passed to a datasource.
    /// </summary>
    this.getSplitContextParameters = function () {
        var parameters = {};
        parameters['splitType'] = 'manual';
        for (var i = 0; i < _searchStrings.length; i++) {
            parameters["subquery" + (i + 1).toString()] = _searchStrings[i]; ;
        }

        if (_searchContext && _searchContext != "") {
            parameters["q"] = _searchContext;
        }

        return parameters;
    };

    this.toDictionary = function () {
        return { splits: _searchStrings.join(';'), splitType: 'manual', searchContext: _searchContext };
    };
};

Silobreaker.SplitModels.AutoItemSplitModel = function(searchContext, splitType, numberOfSplits) {
    var _searchContext = "";
    var _numberOfSplits = 3;
    var _splitType = "";

    if (searchContext) {
        _searchContext = searchContext;
    }

    if (numberOfSplits) {
        _numberOfSplits = numberOfSplits;
    }

    if (splitType) {
        _splitType = splitType;
    }

    this.getSearchContext = function() {
        return _searchContext;
    };

    this.setSearchContext = function (newSearchContext) {
        _searchContext = newSearchContext;
    };    

    this.getPrimarySearch = function() {
        return _searchContext;
    };

    this.getSplitType = function() {
        return _splitType;
    };

    this.getNumberOfSplits = function() {
        return _numberOfSplits;
    };

    this.updateFromDictionary = function(obj) {
        _searchContext = obj.searchContext;
        _splitType = obj.splitType;
        _numberOfSplits = obj.noSplits;
    };

    this.getBaseQuery = function() {
        return _searchContext;
    };

    this.hasContent = function() {
        return _searchContext != '';
    };

    /// <summary>
    ///     Gets the parameters that should be passed to a datasource.
    /// </summary>
    this.getSplitContextParameters = function() {
        var parameters = {};

        if (_splitType != '') {
            if (_searchContext && _searchContext.length > 0) {
                parameters['q'] = _searchContext;
            }
            parameters['splitType'] = _splitType;
            parameters['noSplits'] = _numberOfSplits;
        }
        return parameters;
    };

    this.toDictionary = function() {
        return { splitType: _splitType, noSplits: _numberOfSplits, searchContext: _searchContext };
    };
};

Silobreaker.Chart.TimeIntervalModel = function(params) {
    /// <summary>
    ///    Model for time interval.
    /// </summary>

    var _self = this;
    var _timeInterval = { timeRange: -31 * 24 * 60, granularity: 24 * 60 };
    if (params && jQuery.isPlainObject(params.timeInterval)) {
        _timeInterval = params.timeInterval;
    }

    /// <summary>
    ///    Gets or sets the time range. Can either be a object {from: Date, to: Date} or negative number of minutes from now.
    /// </summary>
    this.timeRange = _timeInterval.timeRange

    /// <summary>
    ///    Gets or sets granularity.
    /// </summary>
    this.granularity = _timeInterval.granularity;

    /// <summary>
    ///    Gets or sets the event handler which is triggerd when the model has changed.
    /// </summary>
    this.timeIntervalChanged = new Silobreaker.EventHandler();


    this.getStartAndEndDate = function() {
        /// <summary>
        ///    Returns a start and end date (calculated if needed) as a json object {startDate, endDate}
        /// </summary>
        var startDate;
        var endDate;

        // Convert time range into suitable from/to-dates
        if (jQuery.isPlainObject(this.timeRange)) {
            startDate = this.timeRange.from;
            endDate = this.timeRange.to;
        } else {
            var now = new Date();
            startDate = new Date(now.getTime() + this.timeRange * 60000);
            endDate = now;
        }

        // Cap the start date so the bars are centered on a suitable time.
        if (this.granularity <= 1) {  // minute
            startDate.setUTCSeconds(0, 0);
        } else if (this.granularity <= 60) {  // hour
            startDate.setUTCMinutes(0, 0, 0);
        } else if (this.granularity <= 60 * 24) {  // day
            startDate.setUTCHours(0, 0, 0, 0);
        } else if (this.granularity < 60 * 24 * 31) {  // month
            startDate.setUTCHours(0, 0, 0, 0);
        }

        return { startDate: startDate, endDate: endDate };

    };

    /// <summary>
    ///     Converts this object into a simple dictionary json object
    /// </summary>
    this.toDictionary = function() {

        var jsonObject = { granularity: this.granularity };

        if (jQuery.isPlainObject(this.timeRange)) {
            jsonObject.startDate = this.timeRange.from.getIsoString();
            jsonObject.endDate = this.timeRange.to.getIsoString();
        } else {
            jsonObject.noMinutesFromNow = this.timeRange;
        }

        return jsonObject;
    };

    this.setAsLastHours = function() {
        _self.granularity = 5;
        _self.timeRange = -2 * 60;
        _self.timeIntervalChanged.trigger();
    };

    this.setAsLastDay = function() {
        _self.granularity = 60;
        _self.timeRange = -24 * 60;
        _self.timeIntervalChanged.trigger();
    };


    this.setAsLastMonth = function() {
        _self.granularity = 60 * 24;
        _self.timeRange = -31 * 24 * 60;
        _self.timeIntervalChanged.trigger();
    };

    this.isLastHours = function() {
        return _self.granularity === 5 && _self.timeRange === -2 * 60;
    };

    this.isLastDay = function() {
        return _self.granularity === 60 && _self.timeRange === -24 * 60;
    };

    this.isLastMonth = function() {
        return _self.granularity === 60 * 24 && _self.timeRange === -31 * 24 * 60;
    };


    /// <summary>
    ///     Updates this object based on data in a simple dictionary.
    /// </summary>
    this.updateFromDictionary = function(jsonObject) {
        if (jsonObject.granularity) {
            this.granularity = parseInt(jsonObject.granularity);
        }
        if (jsonObject.noMinutesFromNow) {
            this.timeRange = parseInt(jsonObject.noMinutesFromNow);
        } else if (jsonObject.fromDate && obj.fromDate) {
            this.timeRange = {};
            this.timeRange.from = Date.fromIsoDate(jsonObject.fromDate);
            this.timeRange.to = Date.fromIsoDate(jsonObject.toDate);
        }
    };
};


/// <reference path="..\jquery-1.3.2-vsdoc.js" />
/// <reference path="Controllers.js" />
/// <reference path="Models.js" />

Silobreaker = window.Silobreaker || {};
Silobreaker.Chart = window.Silobreaker.Chart || {};


Silobreaker.Chart.ChartToolView = function(params) {
    /// <summary>
    ///     View rendering placeholders for time interval and a chart.
    /// </summary>
    /// <param name="params">
    ///     Parameters for the view. Should contain:
    ///     guiReference: "#myChartTool" - where to render the view
    /// </param>

    this.timeIntervalGuiReference = params.guiReference + " .timeInterval"
    this.chartGuiReference = params.guiReference + " .chart"

    // Render
    var html = jQuery(params.guiReference);
    html.append('<div><span>Search Context:</span><input name="searchContext" type="text" /><input type="button" value="Set search context" /></div>')
    html.append('<div class="timeInterval"></div>')
    html.append('<div class="chart"></div>')

    return this;
};

Silobreaker.Chart.ChartView = function (params) {
    /// <summary>
    ///     View rendering a chart.
    /// </summary>
    /// <param name="params">
    ///     Parameters for the view. Should contain:
    ///     guiReference: "#myChart" - where to render the chart
    ///     serieClickedHandler: function (dateRange,value,serieName,selected, chart) {} - function called when a point is clicked.
    ///     maxY : number - sets the the max value for the y-axis.
    /// </param>

    var _chart;
    var _data = {};
    var _params = params;
    var _selectedPoint = null;

    var serieClicked = function (event) {
        if (jQuery.isFunction(_params.serieClickedHandler)) {
            var point = event.point;
            var from = new Date(point.x);
            var to = new Date(point.x + point.series.options.pointInterval);

            // Adjust back to UTC
            from.setHours(from.getHours() - Silobreaker.timeZoneOffset);
            to.setHours(to.getHours() - Silobreaker.timeZoneOffset);

            if (point.selected) {
                _selectedPoint = null;
            } else {
                _selectedPoint = point;
            }

            _params.serieClickedHandler({ from: from, to: to }, point.y, point.series.name, !point.selected, this);
        }
    };


    // Render
    var container = jQuery(_params.guiReference);
    container.empty();

    //var chartOptions = {
    var defaultChartOptions = {
        chart: {
            renderTo: container[0],
            defaultSeriesType: 'spline'
        },
        title: {
            text: null
        },
        subtitle: {
        },
        credits: {
            enabled: false
        },
        xAxis: {
            type: 'datetime',
            labels: {
                rotation: -80,
                align: 'right'
            }
        },
        yAxis: {
            min: 0,
            allowDecimals: false,
            title: { text: 'Documents' }
        },
        legend: {
            verticalAlign: 'top',
            borderWidth: 0
        },
        tooltip: {
            crosshairs: true,
            formatter: function () {
                var tooltipHtml = '<b>' + this.series.name + '</b><br/>';
                if (_chart.series.length > 0 && _chart.series[0].options.pointInterval < 7200001) {
                    tooltipHtml += Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + ': ';
                } else {
                    tooltipHtml += Highcharts.dateFormat('%Y-%m-%d', this.x) + ': ';
                }

                tooltipHtml += Highcharts.numberFormat(this.y, 0);
                return tooltipHtml;
            }
        },
        plotOptions: {
            spline: {
                marker: {
                    radius: 5
                }
            },
            column: {
                pointPadding: 0.2,
                borderWidth: 0,
                stacking: 'percent'
            },
            series: {
                pointInterval: 3600 * 1000,
                cursor: 'pointer',
                allowPointSelect: true,
                point: {
                    events: {
                        click: serieClicked
                    }
                }
            }
        }
    };

    this.chart = _chart;

    this.getSelected = function () {
        /// <summary>
        ///   Gets data about the first selected point. JSON object {range, value, serieName}
        /// </summary>
        if (_selectedPoint && _selectedPoint.series) {
            var from = new Date(_selectedPoint.x);
            var to = new Date(_selectedPoint.x + _selectedPoint.series.options.pointInterval);

            // Adjust back to UTC
            from.setHours(from.getHours() - Silobreaker.timeZoneOffset);
            to.setHours(to.getHours() - Silobreaker.timeZoneOffset);

            return { range: { from: from, to: to }, value: _selectedPoint.y, serieName: _selectedPoint.series.name };
        }

        return null;
    };

    this.clearSelected = function () {
        /// <summary>
        ///   Unselects all points.
        /// </summary>
        _selectedPoint = null;
        var points = _chart.getSelectedPoints();
        for (var j = 0; j < points.length; j++) {
            points[j].select(false);
        }
    };

    this.showPlotBand = function (from, to) {
        /// <summary>
        ///   Displays a plot band between to 2 points
        /// </summary>

        if (_chart.xAxis.length > 0) {
            _chart.xAxis[0].removePlotBand('selected-mask');
            _chart.xAxis[0].addPlotBand({
                id: 'selected-mask',
                from: from,
                to: to,
                color: 'rgba(0, 0, 0, 0.1)'
            });
        }
    };

    this.hidePlotBand = function (from, to) {
        /// <summary>
        ///   Displays a plot band between to 2 points
        /// </summary>
        if (_chart.xAxis.length > 0) {
            _chart.xAxis[0].removePlotBand('selected-mask');
        }
    };

    this.renderChart = function (seriesData) {
        /// <summary>
        ///     Renders the chart with provided data by creating a new chart object.
        /// </summary>

        // Copy default chart options
        var chartOptions = jQuery.extend({ series: [] }, defaultChartOptions);
        if (seriesData.length > 0) {
            chartOptions.plotOptions.series.pointInterval = seriesData[0].granularity;
            chartOptions.plotOptions.series.pointStart = seriesData[0].from;
        }



        // Convert series time to the users local time
        if (seriesData.length > 0 && Silobreaker.timeZoneOffset != 0) {
            for (var i = 0; i < seriesData.length; i++) {
                for (var j = 0; j < seriesData[i].points.length; j++) {
                    var d = new Date(seriesData[i].points[j][0]);
                    d.setHours(d.getHours() + Silobreaker.timeZoneOffset);
                    seriesData[i].points[j][0] = d.getTime();
                }
            }

        }


        var serieMap = {};
        var noMatches = 0;

        // Map the new series to the old ones
        if (_chart) {
            for (var i = 0; i < seriesData.length; i++) {
                for (var j = 0; j < _chart.series.length; j++) {
                    if (_chart.series[j].name == seriesData[i].query) {
                        serieMap[seriesData[i].query] = j;
                        noMatches++;
                        break;
                    }
                }
            }
        }

        // New set of series, lets refresh everything
        if (!_chart || noMatches != _chart.series.length || noMatches != seriesData.length) {

            // Destroy old chart if possible
            if (_chart && jQuery.isFunction(_chart.destroy)) {
                _chart.destroy();
                _chart = null;
            }

            // Add new series to the initialization parameters
            for (var i = 0; i < seriesData.length; i++) {
                var serie = {};
                serie.name = seriesData[i].query;
                serie.data = seriesData[i].points;
                chartOptions.series.push(serie);
            }
        }
        else {
            // Update existing series
            for (var i = 0; i < seriesData.length; i++) {
                var matchingSerieIndex = serieMap[seriesData[i].query];
                _chart.series[matchingSerieIndex].setData(seriesData[i].points);
                _chart.series[matchingSerieIndex].options.pointInterval = seriesData[i].granularity
                _chart.series[matchingSerieIndex].options.pointStart = seriesData[i].from
            }
        }

        if (!_chart) {
            _chart = new Highcharts.Chart(chartOptions);
        }



        // Set max value on y-axis if defined
        /*if (_params.maxY) {
        _chart.yAxis[0].setExtremes(0, _params.maxY);
        }*/

    };

    this.refreshChart = function(seriesData) {
        /// <summary>
        ///     Refreshes the chart with provided data by creating a new chart object.
        /// </summary>
    };

    return this;
};

Silobreaker.Chart.MultipleChartView = function(params) {
    /// <summary>
    ///     View rendering multiple charts; one for each serie.
    /// </summary>
    /// <param name="params">
    ///     Parameters for the view. Should contain:
    ///     guiReference: "#myChart" - where to render the charts
    ///     serieClickedHandler: function (x,y,serieName) {} - function called when a bar is clicked.
    /// </param>

    var _data = { };
    var _params = params;
    var _charts = [];
    var _chartElementPrefixId = _params.guiReference + '_chart';
    if (_chartElementPrefixId.startsWith('#')) {
        _chartElementPrefixId = _chartElementPrefixId.substr(1);
    }

    // Ensure element is empty
    jQuery(_params.guiReference).empty();

    var _container = jQuery(_params.guiReference);

    serieClickedHandler = function(dateRange, value, serie, selected, chart) {
        if (jQuery.isFunction(_params.serieClickedHandler)) {

            // Unselect all points in other charts
            for (var i = 0; i < _charts.length; i++) {
                if (_charts[i] != chart) {
                    var points = _charts[i].chart.getSelectedPoints();
                    for (var j = 0; j < points.length; j++) {
                        points[j].select(false);
                    }
                }
            }
            _params.serieClickedHandler(dateRange, value, serie, selected, chart);
        }
    };

    this.renderChart = function(data) {
        /// <summary>
        ///     Renders the chart with provided series data.
        /// </summary>
        _data = data;

        var maxY = findMaxY(_data);

        _container.empty();
        _charts = [];
        for (var i = 0; i < _data.length; i++) {
            var id = _chartElementPrefixId + i.toString();
            _container.append('<div id="' + id + '" style="width:100%;" class="chart"></div>');
            var chart = new Silobreaker.Chart.ChartView({ guiReference: '#' + id, maxY: maxY, serieClickedHandler: serieClickedHandler });
            _charts.push(chart);
            chart.renderChart([data[i]]);
        }
    };

    // Returns the maximum value found in a serie points. 
    var findMaxY = function(series) {
        var maxY = 0;
        for (var i = 0; i < series.length; i++) {
            for (var j = 0; j < series[i].points.length; j++) {
                if (series[i].points[j][1] > maxY) {
                    maxY = series[i].points[j][1];
                }
            }
        }
        return maxY;
    };

    return this;
};
/// <reference path="Models.js" />
/// <reference path="Views.js" />

Silobreaker = window.Silobreaker || {};
Silobreaker.Chart = window.Silobreaker.Chart || {};

Silobreaker.Chart.ChartToolController = function(params) {
    /// <summary>
    ///     Creates a new instance of a Silobreaker.Chart.ChartToolController.
    /// </summary>
    /// <param name="params">
    ///     Parameters for the chart. Should contain:
    ///     guiReference: "#myChartElement"
    ///     timeInterval: {timeRange: { from: "", to: "" }, granularity: ""}
    ///     chartSettings: {}
    ///     splitContextProvider: {}
    /// </param>

    var _params = jQuery.extend({ }, Silobreaker.Chart.ChartToolController.DefaultSettings, params);

    var _view = new Silobreaker.Chart.ChartToolView({ guiReference: _params.guiReference });

    var _timeIntervalController =
        new Silobreaker.Chart.TimeIntervalController(
            { timeInterval: _params.timeInterval,
                guiReference: _view.timeIntervalGuiReference
            });

    var _chartModel =
        new Silobreaker.Chart.ChartModel(
            { splitContextProvider: _params.splitContextProvider,
                timeIntervalModel: _timeIntervalController.model
            });

    var _chartController =
        new Silobreaker.Chart.ChartController(
            { chartModel: _chartModel,
                chartSettings: _params.chartSettings,
                guiReference: _view.chartGuiReference
            });


    this.view = _view;
    this.model = _chartModel;

    return this;
};
Silobreaker.Chart.ChartToolController.DefaultSettings = { timeInterval: { timeRange: -31 * 24 * 60, granularity: 24 * 60} };



Silobreaker.Chart.ChartController = function(params) {
    /// <summary>
    ///     Creates a new instance of a Silobreaker.Chart.TimeIntervalController
    /// </summary>
    /// <param name="params">
    ///     guiReference: "#myChart"
    ///     chartSettings: {}
    ///     rendering: function {} // function called before chart is rendered.
    ///     rendered: function {} // function called when chart has been rendered.
    ///     serieClicked : function(x,y,serie,selected,chart) {} // function called when a serie is clicked
    /// </param>

    var _params = jQuery.extend({ }, Silobreaker.Chart.ChartController.DefaultSettings, params);

    var chartModelParametersChanged = function() {
        if (_model.hasContent()) {
            if (jQuery.isFunction(_params.rendering)) {
                _params.rendering();
            }
            _model.refreshData(refreshDataDone);
        }
    }

    var refreshDataDone = function(data) {
        _latestData = data;
        _view.renderChart(data);

        if (jQuery.isFunction(_params.rendered)) {
            _params.rendered();
        }
    }

    var _view = new Silobreaker.Chart.ChartView({ guiReference: _params.guiReference, serieClickedHandler: _params.serieClicked });
    var _model = _params.chartModel;

    _model.parameterChanged.bind(chartModelParametersChanged);

    this.view = _view;

    this.setChartMode = function(mode) {
        if (mode == 'multiple') {
            _view = new Silobreaker.Chart.MultipleChartView({ guiReference: _params.guiReference, serieClickedHandler: serieClicked });

        } else {
            _view = new Silobreaker.Chart.ChartView({ guiReference: _params.guiReference, serieClickedHandler: serieClicked });
        }

        _view.renderChart(_latestData);
        this.view = _view;
    };

    this.clearSelected = function() {
        /// <summary>
        ///   Unselects all in the chart points.
        /// </summary>    
        _view.clearSelected();
    };

    this.getSelected = function() {
        /// <summary>
        ///   Gets data about the first selected point. JSON object {range, value, serieName}
        /// </summary>
        return _view.getSelected();
    };

    return this;
};
Silobreaker.Chart.ChartController.DefaultSettings = { chartModel: {}, chartSettings: {}, guiReference: '' };



/*
 Highcharts JS v2.1.0 (2010-11-23)

 (c) 2009-2010 Torstein H?nsi

 License: www.highcharts.com/license
*/
(function(){function na(a,c){a||(a={});for(var b in c)a[b]=c[b];return a}function oa(a,c){return parseInt(a,c||10)}function Gb(a){return typeof a=="string"}function Hb(a){return typeof a=="object"}function bc(a){return typeof a=="number"}function wc(a,c){for(var b=a.length;b--;)if(a[b]==c){a.splice(b,1);break}}function M(a){return a!==Ma&&a!==null}function xa(a,c,b){var d,e;if(Gb(c))if(M(b))a.setAttribute(c,b);else{if(a&&a.getAttribute)e=a.getAttribute(c)}else if(M(c)&&Hb(c))for(d in c)a.setAttribute(d,
c[d]);return e}function mc(a){if(!a||a.constructor!=Array)a=[a];return a}function y(){var a=arguments,c,b;for(c=0;c<a.length;c++){b=a[c];if(M(b))return b}}function Vd(a){var c="",b;for(b in a)c+=Ad(b)+":"+a[b]+";";return c}function Xa(a,c){if(Zc)if(c&&c.opacity!==Ma)c.filter="alpha(opacity="+c.opacity*100+")";na(a.style,c)}function fb(a,c,b,d,e){a=Ca.createElement(a);c&&na(a,c);e&&Xa(a,{padding:0,border:mb,margin:0});b&&Xa(a,b);d&&d.appendChild(a);return a}function Ib(a,c){xc=y(a,c.animation)}function Bd(){var a=
Na.global.useUTC;yc=a?Date.UTC:function(c,b,d,e,f,g){return(new Date(c,b,y(d,1),y(e,0),y(f,0),y(g,0))).getTime()};$c=a?"getUTCMinutes":"getMinutes";ad=a?"getUTCHours":"getHours";bd=a?"getUTCDay":"getDay";nc=a?"getUTCDate":"getDate";zc=a?"getUTCMonth":"getMonth";Ac=a?"getUTCFullYear":"getFullYear";Cd=a?"setUTCMinutes":"setMinutes";Dd=a?"setUTCHours":"setHours";cd=a?"setUTCDate":"setDate";Ed=a?"setUTCMonth":"setMonth";Fd=a?"setUTCFullYear":"setFullYear"}function Bc(a){Cc||(Cc=fb(Jb));a&&Cc.appendChild(a);
Cc.innerHTML=""}function vb(a,c){var b=function(){};b.prototype=new a;na(b.prototype,c);return b}function Gd(a,c,b,d){var e=Na.lang;a=a;var f=isNaN(c=$a(c))?2:c;c=b===undefined?e.decimalPoint:b;d=d===undefined?e.thousandsSep:d;e=a<0?"-":"";b=oa(a=$a(+a||0).toFixed(f))+"";var g=(g=b.length)>3?g%3:0;return e+(g?b.substr(0,g)+d:"")+b.substr(g).replace(/(\d{3})(?=\d)/g,"$1"+d)+(f?c+$a(a-b).toFixed(f).slice(2):"")}function Dc(){}function Hd(a,c){function b(l,h){function x(m,q){this.pos=m;this.minor=q;
this.isNew=true;q||this.addLabel()}function w(m){if(m){this.options=m;this.id=m.id}return this}function N(){var m=[],q=[],r;Oa=v=null;S=[];t(ya,function(o){r=false;t(["xAxis","yAxis"],function(da){if(o.isCartesian&&(da=="xAxis"&&ha||da=="yAxis"&&!ha)&&(o.options[da]==h.index||o.options[da]===Ma&&h.index===0)){o[da]=s;S.push(o);r=true}});if(!o.visible&&u.ignoreHiddenSeries)r=false;if(r){var V,W,G,B,ea;if(!ha){V=o.options.stacking;Ec=V=="percent";if(V){B=o.type+y(o.options.stack,"");ea="-"+B;o.stackKey=
B;W=m[B]||[];m[B]=W;G=q[ea]||[];q[ea]=G}if(Ec){Oa=0;v=99}}if(o.isCartesian){t(o.data,function(da){var C=da.x,ra=da.y,R=ra<0,X=R?G:W;R=R?ea:B;if(Oa===null)Oa=v=da[H];if(ha)if(C>v)v=C;else{if(C<Oa)Oa=C}else if(M(ra)){if(V)X[C]=M(X[C])?X[C]+ra:ra;da=X?X[C]:ra;if(!Ec)if(da>v)v=da;else if(da<Oa)Oa=da;if(V){aa[R]||(aa[R]={});aa[R][C]={total:da,cum:da}}}});if(/(area|column|bar)/.test(o.type)&&!ha)if(Oa>=0){Oa=0;Id=true}else if(v<0){v=0;Jd=true}}}})}function fa(m,q){var r;Kb=q?1:Pa.pow(10,Lb(Pa.log(m)/Pa.LN10));
r=m/Kb;if(!q){q=[1,2,2.5,5,10];if(h.allowDecimals===false)if(Kb==1)q=[1,2,5,10];else if(Kb<=0.1)q=[1/Kb]}for(var o=0;o<q.length;o++){m=q[o];if(r<=(q[o]+(q[o+1]||q[o]))/2)break}m*=Kb;return m}function A(m){var q=(Kb<1?T(1/Kb):1)*10;return T(m*q)/q}function Ta(){var m,q,r,o,V=h.tickInterval,W=h.tickPixelInterval;m=h.maxZoom||(ha?ab(l.smallestInterval*5,v-Oa):null);D=L?za:pa;if(Mb){r=l[ha?"xAxis":"yAxis"][h.linkedTo];o=r.getExtremes();I=y(o.min,o.dataMin);P=y(o.max,o.dataMax)}else{I=y(va,h.min,Oa);P=
y(Qa,h.max,v)}if(P-I<m){o=(m-P+I)/2;I=Aa(I-o,y(h.min,I-o),Oa);P=ab(I+m,y(h.max,I+m),v)}if(!gb&&!Ec&&!Mb&&M(I)&&M(P)){m=P-I||1;if(!M(h.min)&&!M(va)&&Vb&&(Oa<0||!Id))I-=m*Vb;if(!M(h.max)&&!M(Qa)&&Kd&&(v>0||!Jd))P+=m*Kd}Ua=I==P?1:Mb&&!V&&W==r.options.tickPixelInterval?r.tickInterval:y(V,gb?1:(P-I)*W/D);if(!J&&!M(h.tickInterval))s.tickInterval=Ua=fa(Ua);Fc=h.minorTickInterval==="auto"&&Ua?Ua/5:h.minorTickInterval;if(J){ka=[];V=Na.global.useUTC;var G=1E3/nb,B=6E4/nb,ea=36E5/nb;W=864E5/nb;m=6048E5/nb;o=
2592E6/nb;var da=31556952E3/nb,C=[["second",G,[1,2,5,10,15,30]],["minute",B,[1,2,5,10,15,30]],["hour",ea,[1,2,3,4,6,8,12]],["day",W,[1,2]],["week",m,[1,2]],["month",o,[1,2,3,4,6]],["year",da,null]],ra=C[6],R=ra[1],X=ra[2];for(r=0;r<C.length;r++){ra=C[r];R=ra[1];X=ra[2];if(C[r+1])if(Ua<=(R*X[X.length-1]+C[r+1][1])/2)break}if(R==da&&Ua<5*R)X=[1,2,5];C=fa(Ua/R,X);X=new Date(I*nb);X.setMilliseconds(0);if(R>=G)X.setSeconds(R>=B?0:C*Lb(X.getSeconds()/C));if(R>=B)X[Cd](R>=ea?0:C*Lb(X[$c]()/C));if(R>=ea)X[Dd](R>=
W?0:C*Lb(X[ad]()/C));if(R>=W)X[cd](R>=o?1:C*Lb(X[nc]()/C));if(R>=o){X[Ed](R>=da?0:C*Lb(X[zc]()/C));q=X[Ac]()}if(R>=da){q-=q%C;X[Fd](q)}R==m&&X[cd](X[nc]()-X[bd]()+h.startOfWeek);r=1;q=X[Ac]();G=X.getTime()/nb;B=X[zc]();for(ea=X[nc]();G<P&&r<za;){ka.push(G);if(R==da)G=yc(q+r*C,0)/nb;else if(R==o)G=yc(q,B+r*C)/nb;else if(!V&&(R==W||R==m))G=yc(q,B,ea+r*C*(R==W?1:7));else G+=R*C;r++}ka.push(G);Gc=h.dateTimeLabelFormats[ra[0]]}else{r=Lb(I/Ua)*Ua;q=dd(P/Ua)*Ua;ka=[];for(r=A(r);r<=q;){ka.push(r);r=A(r+Ua)}}if(!Mb){if(gb||
ha&&l.hasColumn){q=(gb?1:Ua)*0.5;I-=q;P+=q}q=ka[0];r=ka[ka.length-1];if(h.startOnTick)I=q;else I>q&&ka.shift();if(h.endOnTick)P=r;else P<r&&ka.pop();Nb||(Nb={x:0,y:0});if(!J&&ka.length>Nb[H])Nb[H]=ka.length}}function Da(){var m,q;hb=I;cc=P;N();Ta();ba=E;E=D/(P-I||1);if(!ha)for(m in aa)for(q in aa[m])aa[m][q].cum=aa[m][q].total;if(!s.isDirty)s.isDirty=I!=hb||P!=cc}function sa(m){m=(new w(m)).render();Ob.push(m);return m}function Ya(){var m=h.title,q=h.alternateGridColor,r=h.lineWidth,o,V,W=l.hasRendered,
G=W&&M(hb)&&!isNaN(hb);o=S.length&&M(I)&&M(P);D=L?za:pa;E=D/(P-I||1);ta=L?U:ob;if(o||Mb){if(Fc&&!gb)for(o=I+(ka[0]-I)%Fc;o<=P;o+=Fc){Wb[o]||(Wb[o]=new x(o,true));G&&Wb[o].isNew&&Wb[o].render(null,true);Wb[o].isActive=true;Wb[o].render()}t(ka,function(B,ea){if(!Mb||B>=I&&B<=P){G&&pb[B].isNew&&pb[B].render(ea,true);pb[B].isActive=true;pb[B].render(ea)}});q&&t(ka,function(B,ea){if(ea%2===0&&B<P){dc[B]||(dc[B]=new w);dc[B].options={from:B,to:ka[ea+1]!==Ma?ka[ea+1]:P,color:q};dc[B].render();dc[B].isActive=
true}});W||t((h.plotLines||[]).concat(h.plotBands||[]),function(B){Ob.push((new w(B)).render())})}t([pb,Wb,dc],function(B){for(var ea in B)if(B[ea].isActive)B[ea].isActive=false;else{B[ea].destroy();delete B[ea]}});if(r){o=U+(Ja?za:0)+Q;V=Ka-ob-(Ja?pa:0)+Q;o=Y.crispLine([Va,L?U:o,L?V:Z,Ba,L?Ra-yb:o,L?V:Ka-ob],r);if(Ea)Ea.animate({d:o});else Ea=Y.path(o).attr({stroke:h.lineColor,"stroke-width":r,zIndex:7}).add()}if(s.axisTitle){o=L?U:Z;r=oa(m.style.fontSize||12);o={low:o+(L?0:D),middle:o+D/2,high:o+
(L?D:0)}[m.align];r=(L?Z+pa:U)+(L?1:-1)*(Ja?-1:1)*ed+(F==2?r:0);s.axisTitle[W?"animate":"attr"]({x:L?o:r+(Ja?za:0)+Q+(m.x||0),y:L?r-(Ja?pa:0)+Q:o+(m.y||0)})}s.isDirty=false}function Ga(m){for(var q=0;q<Ob.length;q++)Ob[q].id==m&&Ob[q].destroy()}var ha=h.isX,Ja=h.opposite,L=Fa?!ha:ha,F=L?Ja?0:2:Ja?1:3,aa={};h=ua(ha?Hc:fd,[Wd,Xd,Ld,Yd][F],h);var s=this,J=h.type=="datetime",Q=h.offset||0,H=ha?"x":"y",D,E,ba,ta=L?U:ob,la,qa,cb,zb,Ea,Oa,v,S,va,Qa,P=null,I=null,hb,cc,Vb=h.minPadding,Kd=h.maxPadding,Mb=
M(h.linkedTo),Id,Jd,Ec,Md=h.events,gd,Ob=[],Ua,Fc,Kb,ka,pb={},Wb={},dc={},ec,fc,ed,Gc,gb=h.categories,Zd=h.labels.formatter||function(){var m=this.value;return Gc?Ic(Gc,m):Ua%1E6===0?m/1E6+"M":Ua%1E3===0?m/1E3+"k":!gb&&m>=1E3?Gd(m,0):m},Jc=L&&h.labels.staggerLines,Xb=h.reversed,Yb=gb&&h.tickmarkPlacement=="between"?0.5:0;x.prototype={addLabel:function(){var m=this.pos,q=h.labels,r=!(m==I&&!y(h.showFirstLabel,1)||m==P&&!y(h.showLastLabel,0)),o=this.label;m=Zd.call({isFirst:m==ka[0],isLast:m==ka[ka.length-
1],dateTimeLabelFormat:Gc,value:gb&&gb[m]?gb[m]:m});if(o===Ma)this.label=M(m)&&r&&q.enabled?Y.text(m,0,0).attr({align:q.align,rotation:q.rotation}).css(q.style).add(cb):null;else o&&o.attr({text:m})},getLabelSize:function(){var m=this.label;return m?(this.labelBBox=m.getBBox())[L?"height":"width"]:0},render:function(m,q){var r=!this.minor,o=this.label,V=this.pos,W=h.labels,G=this.gridLine,B=r?h.gridLineWidth:h.minorGridLineWidth,ea=r?h.gridLineColor:h.minorGridLineColor,da=r?h.gridLineDashStyle:h.minorGridLineDashStyle,
C=this.mark,ra=r?h.tickLength:h.minorTickLength,R=r?h.tickWidth:h.minorTickWidth||0,X=r?h.tickColor:h.minorTickColor,oc=r?h.tickPosition:h.minorTickPosition;r=W.step;var qb=q&&Kc||Ka,Pb;Pb=L?la(V+Yb,null,null,q)+ta:U+Q+(Ja?(q&&hd||Ra)-yb-U:0);qb=L?qb-ob+Q-(Ja?pa:0):qb-la(V+Yb,null,null,q)-ta;if(B){V=qa(V+Yb,B,q);if(G===Ma){G={stroke:ea,"stroke-width":B};if(da)G.dashstyle=da;this.gridLine=G=B?Y.path(V).attr(G).add(zb):null}G&&V&&G.animate({d:V})}if(R){if(oc=="inside")ra=-ra;if(Ja)ra=-ra;B=Y.crispLine([Va,
Pb,qb,Ba,Pb+(L?0:-ra),qb+(L?ra:0)],R);if(C)C.animate({d:B});else this.mark=Y.path(B).attr({stroke:X,"stroke-width":R}).add(cb)}if(o){Pb=Pb+W.x-(Yb&&L?Yb*E*(Xb?-1:1):0);qb=qb+W.y-(Yb&&!L?Yb*E*(Xb?1:-1):0);if(Jc)qb+=m%Jc*16;if(r)o[m%r?"hide":"show"]();o[this.isNew?"attr":"animate"]({x:Pb,y:qb})}this.isNew=false},destroy:function(){for(var m in this)this[m]&&this[m].destroy&&this[m].destroy()}};w.prototype={render:function(){var m=this,q=m.options,r=q.label,o=m.label,V=q.width,W=q.to,G,B=q.from,ea=q.dashStyle,
da=m.svgElem,C=[],ra,R,X=q.color;R=q.zIndex;var oc=q.events;if(V){C=qa(q.value,V);q={stroke:X,"stroke-width":V};if(ea)q.dashstyle=ea}else if(M(B)&&M(W)){B=Aa(B,I);W=ab(W,P);G=qa(W);if((C=qa(B))&&G)C.push(G[4],G[5],G[1],G[2]);else C=null;q={fill:X}}else return;if(M(R))q.zIndex=R;if(da)if(C)da.animate({d:C},null,da.onGetPath);else{da.hide();da.onGetPath=function(){da.show()}}else if(C&&C.length){m.svgElem=da=Y.path(C).attr(q).add();if(oc){ea=function(qb){da.on(qb,function(Pb){oc[qb].apply(m,[Pb])})};
for(ra in oc)ea(ra)}}if(r&&M(r.text)&&C&&C.length&&za>0&&pa>0){r=ua({align:L&&G&&"center",x:L?!G&&4:10,verticalAlign:!L&&G&&"middle",y:L?G?16:10:G?6:-4,rotation:L&&!G&&90},r);if(!o)m.label=o=Y.text(r.text,0,0).attr({align:r.textAlign||r.align,rotation:r.rotation,zIndex:R}).css(r.style).add();G=[C[1],C[4],C[6]||C[1]];C=[C[2],C[5],C[7]||C[2]];ra=ab.apply(Pa,G);R=ab.apply(Pa,C);o.align(r,false,{x:ra,y:R,width:Aa.apply(Pa,G)-ra,height:Aa.apply(Pa,C)-R});o.show()}else o&&o.hide();return m},destroy:function(){for(var m in this){this[m]&&
this[m].destroy&&this[m].destroy();delete this[m]}wc(Ob,this)}};la=function(m,q,r,o){var V=1,W=0,G=o?ba:E;o=o?hb:I;G||(G=E);if(r){V*=-1;W=D}if(Xb){V*=-1;W-=V*D}if(q){if(Xb)m=D-m;m=m/G+o}else m=V*(m-o)*G+W;return m};qa=function(m,q,r){var o,V,W;m=la(m,null,null,r);var G=r&&Kc||Ka,B=r&&hd||Ra,ea;r=V=T(m+ta);o=W=T(G-m-ta);if(isNaN(m))ea=true;else if(L){o=Z;W=G-ob;if(r<U||r>U+za)ea=true}else{r=U;V=B-yb;if(o<Z||o>Z+pa)ea=true}return ea?null:Y.crispLine([Va,r,o,Ba,V,W],q||0)};if(Fa&&ha&&Xb===Ma)Xb=true;
na(s,{addPlotBand:sa,addPlotLine:sa,adjustTickAmount:function(){if(!J&&!gb&&!Mb){var m=ec,q=ka.length;ec=Nb[H];if(q<ec){for(;ka.length<ec;)ka.push(A(ka[ka.length-1]+Ua));E*=(q-1)/(ec-1);P=ka[ka.length-1]}if(M(m)&&ec!=m)s.isDirty=true}},categories:gb,getExtremes:function(){return{min:I,max:P,dataMin:Oa,dataMax:v}},getPlotLinePath:qa,getThreshold:function(m){if(I>m)m=I;else if(P<m)m=P;return la(m,0,1)},isXAxis:ha,options:h,plotLinesAndBands:Ob,getOffset:function(){var m=S.length&&M(I)&&M(P),q=0,r=0,
o=h.title,V=h.labels,W=[-1,1,1,-1][F];if(!cb){cb=Y.g("axis").attr({zIndex:7}).add();zb=Y.g("grid").attr({zIndex:1}).add()}fc=0;if(m||Mb){t(ka,function(B){if(pb[B])pb[B].addLabel();else pb[B]=new x(B);if(F===0||F==2||{1:"left",3:"right"}[F]==V.align)fc=Aa(pb[B].getLabelSize(),fc)});if(Jc)fc+=(Jc-1)*16}else for(var G in pb){pb[G].destroy();delete pb[G]}if(o&&o.text){if(!s.axisTitle)s.axisTitle=Y.text(o.text,0,0).attr({zIndex:7,rotation:o.rotation||0,align:o.textAlign||{low:"left",middle:"center",high:"right"}[o.align]}).css(o.style).add();
q=s.axisTitle.getBBox()[L?"height":"width"];r=y(o.margin,L?5:10)}Q=W*(h.offset||Qb[F]);ed=fc+(F!=2&&fc&&W*h.labels[L?"y":"x"])+r;Qb[F]=Aa(Qb[F],ed+q+W*Q)},render:Ya,setCategories:function(m,q){s.categories=gb=m;t(S,function(r){r.translate();r.setTooltipPoints(true)});s.isDirty=true;y(q,true)&&l.redraw()},setExtremes:function(m,q,r,o){Ib(o,l);r=y(r,true);Ha(s,"setExtremes",{min:m,max:q},function(){va=m;Qa=q;r&&l.redraw()})},setScale:Da,setTickPositions:Ta,translate:la,redraw:function(){gc.resetTracker&&
gc.resetTracker();Ya();t(Ob,function(m){m.render()});t(S,function(m){m.isDirty=true})},removePlotBand:Ga,removePlotLine:Ga,reversed:Xb,stacks:aa});for(gd in Md)La(s,gd,Md[gd]);Da()}function d(){var l={};return{add:function(h,x,w,N){if(!l[h]){x=Y.text(x,0,0).css(a.toolbar.itemStyle).align({align:"right",x:-yb-20,y:Z+30}).on("click",N).attr({align:"right",zIndex:20}).add();l[h]=x}},remove:function(h){Bc(l[h].element);l[h]=null}}}function e(l){function h(){var H=this.points||mc(this.point),D=H[0].series.xAxis,
E=this.x;D=D&&D.options.type=="datetime";var ba=Gb(E)||D,ta,la;la=ba?['<span style="font-size: 10px">',D?Ic("%A, %b %e, %Y",E):E,"</span><br/>"]:[];t(H,function(qa){ta=qa.series;la.push('<span style="color:'+ta.color+'">',qa.name||ta.name,"</span>: ",!ba?"<b>x = "+(qa.name||qa.x)+",</b> ":"","<b>",!ba?"y = ":"",qa.y,"</b><br/>")});return la.join("")}function x(H,D){F=ha?H:(2*F+H)/3;aa=ha?D:(aa+D)/2;s.translate(F,aa);id=$a(H-F)>1||$a(D-aa)>1?function(){x(H,D)}:null}function w(){if(!ha){var H=p.hoverPoints;
s.hide();t(Ta,function(D){D.hide()});H&&t(H,function(D){D.setState()});p.hoverPoints=null;ha=true}}var N,fa=l.borderWidth,A=l.crosshairs,Ta=[],Da=l.style,sa=l.shared,Ya=oa(Da.padding),Ga=fa+Ya,ha=true,Ja,L,F=0,aa=0;Da.padding=0;var s=Y.g("tooltip").attr({zIndex:8}).add(),J=Y.rect(Ga,Ga,0,0,l.borderRadius,fa).attr({fill:l.backgroundColor,"stroke-width":fa}).add(s).shadow(l.shadow),Q=Y.text("",Ya+Ga,oa(Da.fontSize)+Ya+Ga).attr({zIndex:1}).css(Da).add(s);s.hide();return{shared:sa,refresh:function(H){var D,
E,ba,ta=0,la={},qa=[];ba=H.tooltipPos;D=l.formatter||h;la=p.hoverPoints;var cb=function(Ea){return{series:Ea.series,point:Ea,x:Ea.category,y:Ea.y,percentage:Ea.percentage,total:Ea.total||Ea.stackTotal}};if(sa){la&&t(la,function(Ea){Ea.setState()});p.hoverPoints=H;t(H,function(Ea){Ea.setState(wb);ta+=Ea.plotY;qa.push(cb(Ea))});E=H[0].plotX;ta=T(ta)/H.length;la={x:H[0].category};la.points=qa;H=H[0]}else la=cb(H);la=D.call(la);N=H.series;E=sa?E:H.plotX;ta=sa?ta:H.plotY;D=T(ba?ba[0]:Fa?za-ta:E);E=T(ba?
ba[1]:Fa?pa-E:ta);ba=!H.series.isCartesian||hc(D,E);if(la===false||!ba)w();else{if(ha){s.show();ha=false}Q.attr({text:la});ba=Q.getBBox();Ja=ba.width;L=ba.height;J.attr({width:Ja+2*Ya,height:L+2*Ya,stroke:l.borderColor||H.color||N.color||"#606060"});D=D-Ja+U-25;E=E-L+Z+10;if(D<7){D=7;E-=30}if(E<5)E=5;else if(E+L>Ka)E=Ka-L-5;x(T(D-Ga),T(E-Ga))}if(A){A=mc(A);E=A.length;for(var zb;E--;)if(A[E]&&(zb=H.series[E?"yAxis":"xAxis"])){D=zb.getPlotLinePath(H[E?"y":"x"],1);if(Ta[E])Ta[E].attr({d:D,visibility:Ab});
else{ba={"stroke-width":A[E].width||1,stroke:A[E].color||"#C0C0C0",zIndex:2};if(A[E].dashStyle)ba.dashstyle=A[E].dashStyle;Ta[E]=Y.path(D).attr(ba).add()}}}},hide:w}}function f(l,h){function x(F){var aa;F=F||rb.event;if(!F.target)F.target=F.srcElement;aa=F.touches?F.touches.item(0):F;if(F.type!="mousemove"||rb.opera){for(var s=wa,J={left:s.offsetLeft,top:s.offsetTop};s=s.offsetParent;){J.left+=s.offsetLeft;J.top+=s.offsetTop;if(s!=Ca.body&&s!=Ca.documentElement){J.left-=s.scrollLeft;J.top-=s.scrollTop}}pc=
J}if(Zc){F.chartX=F.x;F.chartY=F.y}else if(aa.layerX===Ma){F.chartX=aa.pageX-pc.left;F.chartY=aa.pageY-pc.top}else{F.chartX=F.layerX;F.chartY=F.layerY}return F}function w(F){var aa={xAxis:[],yAxis:[]};t(Wa,function(s){var J=s.translate,Q=s.isXAxis;aa[Q?"xAxis":"yAxis"].push({axis:s,value:J((Fa?!Q:Q)?F.chartX-U:pa-F.chartY+Z,true)})});return aa}function N(){var F=l.hoverSeries,aa=l.hoverPoint;aa&&aa.onMouseOut();F&&F.onMouseOut();qc&&qc.hide();jd=null}function fa(){if(sa){var F={xAxis:[],yAxis:[]},
aa=sa.getBBox(),s=aa.x-U,J=aa.y-Z;if(Da){t(Wa,function(Q){var H=Q.translate,D=Q.isXAxis,E=Fa?!D:D,ba=H(E?s:pa-J-aa.height,true);H=H(E?s+aa.width:pa-J,true);F[D?"xAxis":"yAxis"].push({axis:Q,min:ab(ba,H),max:Aa(ba,H)})});Ha(l,"selection",F,kd)}sa=sa.destroy()}l.mouseIsDown=ld=Da=false;Bb(Ca,Eb?"touchend":"mouseup",fa)}var A,Ta,Da,sa,Ya=u.zoomType,Ga=/x/.test(Ya),ha=/y/.test(Ya),Ja=Ga&&!Fa||ha&&Fa,L=ha&&!Fa||Ga&&Fa;Lc=function(){if(Mc){Mc.translate(U,Z);Fa&&Mc.attr({width:l.plotWidth,height:l.plotHeight}).invert()}else l.trackerGroup=
Mc=Y.g("tracker").attr({zIndex:9}).add()};Lc();if(h.enabled)l.tooltip=qc=e(h);(function(){var F=true;wa.onmousedown=function(s){s=x(s);l.mouseIsDown=ld=true;A=s.chartX;Ta=s.chartY;La(Ca,Eb?"touchend":"mouseup",fa)};var aa=function(s){if(!(s&&s.touches&&s.touches.length>1)){s=x(s);if(!Eb)s.returnValue=false;var J=s.chartX,Q=s.chartY,H=!hc(J-U,Q-Z);if(Eb&&s.type=="touchstart")if(xa(s.target,"isTracker"))l.runTrackerClick||s.preventDefault();else!$d&&!H&&s.preventDefault();if(H){F||N();if(J<U)J=U;else if(J>
U+za)J=U+za;if(Q<Z)Q=Z;else if(Q>Z+pa)Q=Z+pa}if(ld&&s.type!="touchstart"){if(Da=Math.sqrt(Math.pow(A-J,2)+Math.pow(Ta-Q,2))>10){if(ic&&(Ga||ha)&&hc(A-U,Ta-Z))sa||(sa=Y.rect(U,Z,Ja?1:za,L?1:pa,0).attr({fill:"rgba(69,114,167,0.25)",zIndex:7}).add());if(sa&&Ja){J=J-A;sa.attr({width:$a(J),x:(J>0?0:J)+A})}if(sa&&L){Q=Q-Ta;sa.attr({height:$a(Q),y:(Q>0?0:Q)+Ta})}}}else if(!H){var D;Q=l.hoverPoint;J=l.hoverSeries;var E,ba,ta=Ra,la=Fa?s.chartY:s.chartX-U;if(qc&&h.shared){D=[];E=ya.length;for(ba=0;ba<E;ba++)if(ya[ba].visible&&
ya[ba].tooltipPoints.length){s=ya[ba].tooltipPoints[la];s._dist=$a(la-s.plotX);ta=ab(ta,s._dist);D.push(s)}for(E=D.length;E--;)D[E]._dist>ta&&D.splice(E,1);if(D.length&&D[0].plotX!=jd){qc.refresh(D);jd=D[0].plotX}}if(J&&J.tracker)(s=J.tooltipPoints[la])&&s!=Q&&s.onMouseOver()}return(F=H)||!ic}};wa.onmousemove=aa;La(wa,"mouseleave",N);wa.ontouchstart=function(s){if(Ga||ha)wa.onmousedown(s);aa(s)};wa.ontouchmove=aa;wa.ontouchend=function(){Da&&N()};wa.onclick=function(s){var J=l.hoverPoint;s=x(s);s.cancelBubble=
true;if(!Da)if(J&&xa(s.target,"isTracker")){var Q=J.plotX,H=J.plotY;na(J,{pageX:pc.left+U+(Fa?za-H:Q),pageY:pc.top+Z+(Fa?pa-Q:H)});Ha(J.series,"click",na(s,{point:J}));J.firePointEvent("click",s)}else{na(s,w(s));hc(s.chartX-U,s.chartY-Z)&&Ha(l,"click",s)}Da=false}})();Nd=setInterval(function(){id&&id()},32);na(this,{zoomX:Ga,zoomY:ha,resetTracker:N})}function g(l){var h=l.type||u.type||u.defaultSeriesType,x=sb[h],w=p.hasRendered;if(w)if(Fa&&h=="column")x=sb.bar;else if(!Fa&&h=="bar")x=sb.column;h=
new x;h.init(p,l);if(!w&&h.inverted)Fa=true;if(h.isCartesian)ic=h.isCartesian;ya.push(h);return h}function i(){u.alignTicks!==false&&t(Wa,function(l){l.adjustTickAmount()});Nb=null}function j(l){var h=p.isDirtyLegend,x,w=p.isDirtyBox,N=ya.length,fa=N;for(Ib(l,p);fa--;){l=ya[fa];if(l.isDirty&&l.options.stacking){x=true;break}}if(x)for(fa=N;fa--;){l=ya[fa];if(l.options.stacking)l.isDirty=true}t(ya,function(A){if(A.isDirty){A.cleanData();A.getSegments();if(A.options.legendType=="point")h=true}});if(h&&
md.renderLegend){md.renderLegend();p.isDirtyLegend=false}if(ic){if(!Nc){Nb=null;t(Wa,function(A){A.setScale()})}i();rc();t(Wa,function(A){if(A.isDirty||w){A.redraw();w=true}})}if(w){nd();Lc()}t(ya,function(A){A.isDirty&&A.visible&&A.redraw()});gc&&gc.resetTracker&&gc.resetTracker();Ha(p,"redraw")}function k(){var l=a.xAxis||{},h=a.yAxis||{},x;l=mc(l);t(l,function(w,N){w.index=N;w.isX=true});h=mc(h);t(h,function(w,N){w.index=N});Wa=l.concat(h);p.xAxis=[];p.yAxis=[];Wa=jc(Wa,function(w){x=new b(p,w);
p[x.isXAxis?"xAxis":"yAxis"].push(x);return x});i()}function n(l,h){kc=ua(a.title,l);sc=ua(a.subtitle,h);t([["title",l,kc],["subtitle",h,sc]],function(x){var w=x[0],N=p[w],fa=x[1];x=x[2];if(N&&fa){N.destroy();N=null}if(x&&x.text&&!N)p[w]=Y.text(x.text,0,0).attr({align:x.align,"class":"highcharts-"+w,zIndex:1}).css(x.style).add().align(x,false,tc)})}function z(){ib=u.renderTo;Od=Zb+od++;if(Gb(ib))ib=Ca.getElementById(ib);ib.innerHTML="";if(!ib.offsetWidth){Rb=ib.cloneNode(0);Xa(Rb,{position:lc,top:"-9999px",
display:""});Ca.body.appendChild(Rb)}Oc=(Rb||ib).offsetWidth;uc=(Rb||ib).offsetHeight;p.chartWidth=Ra=u.width||Oc||600;p.chartHeight=Ka=u.height||(uc>19?uc:400);p.container=wa=fb(Jb,{className:"highcharts-container"+(u.className?" "+u.className:""),id:Od},na({position:Pd,overflow:Cb,width:Ra+bb,height:Ka+bb,textAlign:"left"},u.style),Rb||ib);p.renderer=Y=u.renderer=="SVG"?new Pc(wa,Ra,Ka):new Qd(wa,Ra,Ka);var l;if(/Gecko/.test(Qc)){l=function(){Xa(wa,{left:0,top:0});var h=wa.getBoundingClientRect();
Xa(wa,{left:-h.left%1+bb,top:-h.top%1+bb})};l();La(rb,"resize",l);La(p,"destroy",function(){Bb(rb,"resize",l)})}}function K(){function l(){var x=u.width||ib.offsetWidth,w=u.height||ib.offsetHeight;if(x&&w){if(x!=Oc||w!=uc){clearTimeout(h);h=setTimeout(function(){pd(x,w,false)},100)}Oc=x;uc=w}}var h;La(window,"resize",l);La(p,"destroy",function(){Bb(window,"resize",l)})}function ia(){var l=a.labels,h=a.credits,x;n();md=p.legend=new ae(p);rc();t(Wa,function(w){w.setTickPositions(true)});i();rc();nd();
ic&&t(Wa,function(w){w.render()});if(!p.seriesGroup)p.seriesGroup=Y.g("series-group").attr({zIndex:3}).add();t(ya,function(w){w.translate();w.setTooltipPoints();w.render()});l.items&&t(l.items,function(){var w=na(l.style,this.style),N=oa(w.left)+U,fa=oa(w.top)+Z+12;delete w.left;delete w.top;Y.text(this.html,N,fa).attr({zIndex:2}).css(w).add()});if(!p.toolbar)p.toolbar=d(p);if(h.enabled&&!p.credits){x=h.href;Y.text(h.text,0,0).on("click",function(){if(x)location.href=x}).attr({align:h.position.align,
zIndex:8}).css(h.style).add().align(h.position)}Lc();p.hasRendered=true;if(Rb){ib.appendChild(wa);Bc(Rb)}}function $(){var l=ya.length,h=wa.parentNode;Ha(p,"destroy");Bb(rb,"unload",$);Bb(p);for(t(Wa,function(x){Bb(x)});l--;)ya[l].destroy();wa.innerHTML="";Bb(wa);h&&h.removeChild(wa);wa=null;Y.alignedObjects=null;clearInterval(Nd);for(l in p)delete p[l]}function ga(){if(!Rc&&Ca.readyState!="complete")Ca.attachEvent("onreadystatechange",function(){Ca.detachEvent("onreadystatechange",ga);ga()});else{z();
qd();rd();t(a.series||[],function(l){g(l)});p.inverted=Fa=y(Fa,a.chart.inverted);k();p.render=ia;p.tracker=gc=new f(p,a.tooltip);ia();Ha(p,"load");c&&c.apply(p,[p]);t(p.callbacks,function(l){l.apply(p,[p])})}}Hc=ua(Hc,Na.xAxis);fd=ua(fd,Na.yAxis);Na.xAxis=Na.yAxis=null;a=ua(Na,a);var u=a.chart,O=u.margin;O=Hb(O)?O:[O,O,O,O];var ja=y(u.marginTop,O[0]),Sa=y(u.marginRight,O[1]),ca=y(u.marginBottom,O[2]),ma=y(u.marginLeft,O[3]),Za=u.spacingTop,jb=u.spacingRight,sd=u.spacingBottom,Sc=u.spacingLeft,tc,
kc,sc,Z,yb,ob,U,Qb,ib,Rb,wa,Od,Oc,uc,Ra,Ka,hd,Kc,td,ud,vd,wd,p=this,$d=(O=u.events)&&!!O.click,xd,hc,qc,ld,$b,Rd,yd,pa,za,gc,Mc,Lc,md,Sb,Tb,pc,ic=u.showAxes,Nc=0,Wa=[],Nb,ya=[],Fa,Y,id,Nd,jd,nd,rc,qd,rd,pd,kd,Sd,ae=function(l){function h(v,S){var va=v.legendItem,Qa=v.legendLine,P=v.legendSymbol,I=L.color,hb=S?A.itemStyle.color:I;I=S?v.color:I;va&&va.css({fill:hb});Qa&&Qa.attr({stroke:I});P&&P.attr({stroke:I,fill:I})}function x(v,S,va){var Qa=v.legendItem,P=v.legendLine,I=v.legendSymbol;v=v.checkbox;
Qa&&Qa.attr({x:S,y:va});P&&P.translate(S,va-4);I&&I.attr({x:S+I.xOff,y:va+I.yOff});if(v){v.x=S;v.y=va}}function w(){t(Ya,function(v){var S=v.checkbox;S&&Xa(S,{left:qa.attr("translateX")+v.legendItemWidth+S.x-40+bb,top:qa.attr("translateY")+S.y-11+bb})})}function N(v){var S,va,Qa,P,I,hb=v.legendItem;P=v.series||v;if(!hb){I=/^(bar|pie|area|column)$/.test(P.type);v.legendItem=hb=Y.text(A.labelFormatter.call(v),0,0).css(v.visible?ha:L).on("mouseover",function(){v.setState(wb);hb.css(Ja)}).on("mouseout",
function(){hb.css(v.visible?ha:L);v.setState()}).on("click",function(){var Vb=function(){v.setVisible()};v.firePointEvent?v.firePointEvent("legendItemClick",null,Vb):Ha(v,"legendItemClick",null,Vb)}).attr({zIndex:2}).add(qa);if(!I&&v.options&&v.options.lineWidth){var cc=v.options;P={"stroke-width":cc.lineWidth,zIndex:2};if(cc.dashStyle)P.dashstyle=cc.dashStyle;v.legendLine=Y.path([Va,-Da-sa,0,Ba,-sa,0]).attr(P).add(qa)}if(I)S=Y.rect(va=-Da-sa,Qa=-11,Da,12,2).attr({"stroke-width":0,zIndex:3}).add(qa);
else if(v.options&&v.options.marker&&v.options.marker.enabled)S=Y.symbol(v.symbol,va=-Da/2-sa,Qa=-4,v.options.marker.radius).attr(v.pointAttr[db]).attr({zIndex:3}).add(qa);if(S){S.xOff=va;S.yOff=Qa}v.legendSymbol=S;h(v,v.visible);if(v.options&&v.options.showCheckbox){v.checkbox=fb("input",{type:"checkbox",checked:v.selected,defaultChecked:v.selected},A.itemCheckboxStyle,wa);La(v.checkbox,"click",function(Vb){Ha(v,"checkboxClick",{checked:Vb.target.checked},function(){v.select()})})}}x(v,Q,H);S=hb.getBBox();
D=H;E=S.height;v.legendItemWidth=S=A.itemWidth||Da+sa+S.width+aa;if(Ta){Q+=S;cb=zb||Aa(Q-J,cb);if(Q-J+S>(zb||Ra-2*F-J)){Q=J;H+=E}}else{H+=E;cb=zb||Aa(S,cb)}Ya.push(v)}function fa(){Q=J;H=s;D=cb=0;Ya=[];qa||(qa=Y.g("legend").attr({zIndex:7}).add());Oa&&Ea.reverse();t(Ea,function(Qa){if(Qa.options.showInLegend)t(Qa.options.legendType=="point"?Qa.data:[Qa],N)});Oa&&Ea.reverse();Sb=zb||cb;Tb=D-s+E;if(ta||la){Sb+=2*F;Tb+=2*F;if(ba)Sb>0&&Tb>0&&ba.animate({width:Sb,height:Tb});else ba=Y.rect(0,0,Sb,Tb,A.borderRadius,
ta||0).attr({stroke:A.borderColor,"stroke-width":ta||0,fill:la||mb}).add(qa).shadow(A.shadow);ba[Ya.length?"show":"hide"]()}for(var v=["left","right","top","bottom"],S,va=4;va--;){S=v[va];if(Ga[S]&&Ga[S]!="auto"){A[va<2?"align":"verticalAlign"]=S;A[va<2?"x":"y"]=oa(Ga[S])*(va%2?-1:1)}}qa.align(na(A,{width:Sb,height:Tb}),true,tc);Nc||w()}var A=l.options.legend;if(A.enabled){var Ta=A.layout=="horizontal",Da=A.symbolWidth,sa=A.symbolPadding,Ya,Ga=A.style,ha=A.itemStyle,Ja=A.itemHoverStyle,L=A.itemHiddenStyle,
F=oa(Ga.padding),aa=20,s=18,J=4+F+Da+sa,Q,H,D,E=0,ba,ta=A.borderWidth,la=A.backgroundColor,qa,cb,zb=A.width,Ea=l.series,Oa=A.reversed;fa();La(l,"endResize",w);return{colorizeItem:h,destroyItem:function(v){var S=v.checkbox;t(["legendItem","legendLine","legendSymbol"],function(va){v[va]&&v[va].destroy()});S&&Bc(v.checkbox)},renderLegend:fa}}};hc=function(l,h){return l>=0&&l<=za&&h>=0&&h<=pa};Sd=function(){Ha(p,"selection",{resetSelection:true},kd);p.toolbar.remove("zoom")};kd=function(l){var h=Na.lang,
x=p.pointCount<100;p.toolbar.add("zoom",h.resetZoom,h.resetZoomTitle,Sd);!l||l.resetSelection?t(Wa,function(w){w.setExtremes(null,null,false,x)}):t(l.xAxis.concat(l.yAxis),function(w){var N=w.axis;if(p.tracker[N.isXAxis?"zoomX":"zoomY"])N.setExtremes(w.min,w.max,false,x)});j()};rc=function(){var l=a.legend,h=y(l.margin,10),x=l.x,w=l.y,N=l.align,fa=l.verticalAlign,A;qd();if((p.title||p.subtitle)&&!M(ja))if(A=Aa(p.title&&!kc.floating&&!kc.verticalAlign&&kc.y||0,p.subtitle&&!sc.floating&&!sc.verticalAlign&&
sc.y||0))Z=Aa(Z,A+y(kc.margin,15)+Za);if(l.enabled&&!l.floating)if(N=="right")M(Sa)||(yb=Aa(yb,Sb-x+h+jb));else if(N=="left")M(ma)||(U=Aa(U,Sb+x+h+Sc));else if(fa=="top")M(ja)||(Z=Aa(Z,Tb+w+h+Za));else if(fa=="bottom")M(ca)||(ob=Aa(ob,Tb-w+h+sd));ic&&t(Wa,function(Ta){Ta.getOffset()});M(ma)||(U+=Qb[3]);M(ja)||(Z+=Qb[0]);M(ca)||(ob+=Qb[2]);M(Sa)||(yb+=Qb[1]);rd()};pd=function(l,h,x){var w=p.title,N=p.subtitle;Nc+=1;Ib(x,p);Kc=Ka;hd=Ra;Ra=T(l);Ka=T(h);Xa(wa,{width:Ra+bb,height:Ka+bb});Y.setSize(Ra,
Ka);za=Ra-U-yb;pa=Ka-Z-ob;Nb=null;t(Wa,function(fa){fa.isDirty=true;fa.setScale()});t(ya,function(fa){fa.isDirty=true});p.isDirtyLegend=true;p.isDirtyBox=true;rc();w&&w.align(null,null,tc);N&&N.align(null,null,tc);j();Kc=null;Ha(p,"resize");setTimeout(function(){Ha(p,"endResize",null,function(){Nc-=1})},xc&&xc.duration||500)};rd=function(){p.plotLeft=U=T(U);p.plotTop=Z=T(Z);p.plotWidth=za=T(Ra-U-yb);p.plotHeight=pa=T(Ka-Z-ob);p.plotSizeX=Fa?pa:za;p.plotSizeY=Fa?za:pa;tc={x:Sc,y:Za,width:Ra-Sc-jb,
height:Ka-Za-sd}};qd=function(){Z=y(ja,Za);yb=y(Sa,jb);ob=y(ca,sd);U=y(ma,Sc);Qb=[0,0,0,0]};nd=function(){var l=u.borderWidth||0,h=u.backgroundColor,x=u.plotBackgroundColor,w=u.plotBackgroundImage,N,fa={x:U,y:Z,width:za,height:pa};N=2*l+(u.shadow?8:0);if(l||h)if(td)td.animate({width:Ra-N,height:Ka-N});else td=Y.rect(N/2,N/2,Ra-N,Ka-N,u.borderRadius,l).attr({stroke:u.borderColor,"stroke-width":l,fill:h||mb}).add().shadow(u.shadow);if(x)if(ud)ud.animate(fa);else ud=Y.rect(U,Z,za,pa,0).attr({fill:x}).add().shadow(u.plotShadow);
if(w)if(vd)vd.animate(fa);else vd=Y.image(w,U,Z,za,pa).add();if(u.plotBorderWidth)if(wd)wd.animate(fa);else wd=Y.rect(U,Z,za,pa,0,u.plotBorderWidth).attr({stroke:u.plotBorderColor,"stroke-width":u.plotBorderWidth,zIndex:4}).add();p.isDirtyBox=false};Tc=Fb=0;La(rb,"unload",$);u.reflow!==false&&La(p,"load",K);if(O)for(xd in O)La(p,xd,O[xd]);p.options=a;p.series=ya;p.addSeries=function(l,h,x){var w;if(l){Ib(x,p);h=y(h,true);Ha(p,"addSeries",{options:l},function(){w=g(l);w.isDirty=true;p.isDirtyLegend=
true;h&&p.redraw()})}return w};p.animation=y(u.animation,true);p.destroy=$;p.get=function(l){var h,x,w;for(h=0;h<Wa.length;h++)if(Wa[h].options.id==l)return Wa[h];for(h=0;h<ya.length;h++)if(ya[h].options.id==l)return ya[h];for(h=0;h<ya.length;h++){w=ya[h].data;for(x=0;x<w.length;x++)if(w[x].id==l)return w[x]}return null};p.getSelectedPoints=function(){var l=[];t(ya,function(h){l=l.concat(zd(h.data,function(x){return x.selected}))});return l};p.getSelectedSeries=function(){return zd(ya,function(l){return l.selected})};
p.hideLoading=function(){Uc($b,{opacity:0},{duration:a.loading.hideDuration,complete:function(){Xa($b,{display:mb})}});yd=false};p.isInsidePlot=hc;p.redraw=j;p.setSize=pd;p.setTitle=n;p.showLoading=function(l){var h=a.loading;if(!$b){$b=fb(Jb,{className:"highcharts-loading"},na(h.style,{left:U+bb,top:Z+bb,width:za+bb,height:pa+bb,zIndex:10,display:mb}),wa);Rd=fb("span",null,h.labelStyle,$b)}Rd.innerHTML=l||a.lang.loading;if(!yd){Xa($b,{opacity:0,display:""});Uc($b,{opacity:h.style.opacity},{duration:h.showDuration});
yd=true}};p.pointCount=0;ga()}var Ca=document,rb=window,Pa=Math,T=Pa.round,Lb=Pa.floor,dd=Pa.ceil,Aa=Pa.max,ab=Pa.min,$a=Pa.abs,tb=Pa.cos,xb=Pa.sin,Ub=Pa.PI,Td=Ub*2/360,Qc=navigator.userAgent,Zc=/msie/i.test(Qc)&&!rb.opera,Vc=Ca.documentMode==8,be=/AppleWebKit/.test(Qc),Rc=rb.SVGAngle||Ca.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1"),Eb="ontouchstart"in Ca.documentElement,Fb,Tc,ce={},od=0,nb=1,Cc,Na,Ic,xc,Wc,Ma,Jb="div",lc="absolute",Pd="relative",Cb="hidden",
Zb="highcharts-",Ab="visible",bb="px",mb="none",Va="M",Ba="L",Ud="rgba(192,192,192,"+(Rc?1.0E-6:0.0020)+")",db="",wb="hover",yc,$c,ad,bd,nc,zc,Ac,Cd,Dd,cd,Ed,Fd,eb=rb.HighchartsAdapter,Db=eb||{},t=Db.each,zd=Db.grep,jc=Db.map,ua=Db.merge,Ad=Db.hyphenate,La=Db.addEvent,Bb=Db.removeEvent,Ha=Db.fireEvent,Uc=Db.animate,Xc=Db.stop,sb={};eb&&eb.init&&eb.init();if(!eb&&rb.jQuery){var kb=jQuery;t=function(a,c){for(var b=0,d=a.length;b<d;b++)if(c.call(a[b],a[b],b,a)===false)return b};zd=kb.grep;jc=function(a,
c){for(var b=[],d=0,e=a.length;d<e;d++)b[d]=c.call(a[d],a[d],d,a);return b};ua=function(){var a=arguments;return kb.extend(true,null,a[0],a[1],a[2],a[3])};Ad=function(a){return a.replace(/([A-Z])/g,function(c,b){return"-"+b.toLowerCase()})};La=function(a,c,b){kb(a).bind(c,b)};Bb=function(a,c,b){var d=Ca.removeEventListener?"removeEventListener":"detachEvent";if(Ca[d]&&!a[d])a[d]=function(){};kb(a).unbind(c,b)};Ha=function(a,c,b,d){var e=kb.Event(c),f="detached"+c;na(e,b);if(a[c]){a[f]=a[c];a[c]=null}kb(a).trigger(e);
if(a[f]){a[c]=a[f];a[f]=null}d&&!e.isDefaultPrevented()&&d(e)};Uc=function(a,c,b){var d=kb(a);if(c.d){a.toD=c.d;c.d=1}d.stop();d.animate(c,b)};Xc=function(a){kb(a).stop()};kb.extend(kb.easing,{easeOutQuad:function(a,c,b,d,e){return-d*(c/=e)*(c-2)+b}});var de=jQuery.fx.step._default,ee=jQuery.fx.prototype.cur;kb.fx.step._default=function(a){var c=a.elem;c.attr?c.attr(a.prop,a.now):de.apply(this,arguments)};kb.fx.step.d=function(a){var c=a.elem;if(!a.started){var b=Wc.init(c,c.d,c.toD);a.start=b[0];
a.end=b[1];a.started=true}c.attr("d",Wc.step(a.start,a.end,a.pos,c.toD))};kb.fx.prototype.cur=function(){var a=this.elem;return a.attr?a.attr(this.prop):ee.apply(this,arguments)}}Wc={init:function(a,c,b){c=c||"";var d=a.shift,e=c.indexOf("C")>-1,f=e?7:3,g;c=c.split(" ");b=[].concat(b);var i,j,k=function(n){for(g=n.length;g--;)n[g]==Va&&n.splice(g+1,0,n[g+1],n[g+2],n[g+1],n[g+2])};if(e){k(c);k(b)}if(a.isArea){i=c.splice(c.length-6,6);j=b.splice(b.length-6,6)}if(d){b=[].concat(b).splice(0,f).concat(b);
a.shift=false}for(a=b.length;c.length<a;){d=[].concat(c).splice(c.length-f,f);if(e){d[f-6]=d[f-2];d[f-5]=d[f-1]}c=c.concat(d)}if(i){c=c.concat(i);b=b.concat(j)}return[c,b]},step:function(a,c,b,d){var e=[],f=a.length;if(b==1)e=d;else if(f==c.length&&b<1)for(;f--;){d=parseFloat(a[f]);e[f]=isNaN(d)?a[f]:b*parseFloat(c[f]-d)+d}else e=c;return e}};eb={enabled:true,align:"center",x:0,y:15,style:{color:"#666",fontSize:"11px"}};Na={colors:["#4572A7","#AA4643","#89A54E","#80699B","#3D96AE","#DB843D","#92A8CD",
"#A47D7C","#B5CA92"],symbols:["circle","diamond","square","triangle","triangle-down"],lang:{loading:"Loading...",months:["January","February","March","April","May","June","July","August","September","October","November","December"],weekdays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],decimalPoint:".",resetZoom:"Reset zoom",resetZoomTitle:"Reset zoom level 1:1",thousandsSep:","},global:{useUTC:true},chart:{borderColor:"#4572A7",borderRadius:5,defaultSeriesType:"line",ignoreHiddenSeries:true,
spacingTop:10,spacingRight:10,spacingBottom:15,spacingLeft:10,style:{fontFamily:'"Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif',fontSize:"12px"},backgroundColor:"#FFFFFF",plotBorderColor:"#C0C0C0"},title:{text:"Chart title",align:"center",y:15,style:{color:"#3E576F",fontSize:"16px"}},subtitle:{text:"",align:"center",y:30,style:{color:"#6D869F"}},plotOptions:{line:{allowPointSelect:false,showCheckbox:false,animation:{duration:1E3},events:{},lineWidth:2,shadow:true,marker:{enabled:true,
lineWidth:0,radius:4,lineColor:"#FFFFFF",states:{hover:{},select:{fillColor:"#FFFFFF",lineColor:"#000000",lineWidth:2}}},point:{events:{}},dataLabels:ua(eb,{enabled:false,y:-6,formatter:function(){return this.y}}),showInLegend:true,states:{hover:{marker:{}},select:{marker:{}}},stickyTracking:true}},labels:{style:{position:lc,color:"#3E576F"}},legend:{enabled:true,align:"center",layout:"horizontal",labelFormatter:function(){return this.name},borderWidth:1,borderColor:"#909090",borderRadius:5,shadow:false,
style:{padding:"5px"},itemStyle:{cursor:"pointer",color:"#3E576F"},itemHoverStyle:{cursor:"pointer",color:"#000000"},itemHiddenStyle:{color:"#C0C0C0"},itemCheckboxStyle:{position:lc,width:"13px",height:"13px"},symbolWidth:16,symbolPadding:5,verticalAlign:"bottom",x:0,y:0},loading:{hideDuration:100,labelStyle:{fontWeight:"bold",position:Pd,top:"1em"},showDuration:100,style:{position:lc,backgroundColor:"white",opacity:0.5,textAlign:"center"}},tooltip:{enabled:true,backgroundColor:"rgba(255, 255, 255, .85)",
borderWidth:2,borderRadius:5,shadow:true,snap:Eb?25:10,style:{color:"#333333",fontSize:"12px",padding:"5px",whiteSpace:"nowrap"}},toolbar:{itemStyle:{color:"#4572A7",cursor:"pointer"}},credits:{enabled:true,text:"Highcharts.com",href:"http://www.highcharts.com",position:{align:"right",x:-10,verticalAlign:"bottom",y:-5},style:{cursor:"pointer",color:"#909090",fontSize:"10px"}}};var Hc={dateTimeLabelFormats:{second:"%H:%M:%S",minute:"%H:%M",hour:"%H:%M",day:"%e. %b",week:"%e. %b",month:"%b '%y",year:"%Y"},
endOnTick:false,gridLineColor:"#C0C0C0",labels:eb,lineColor:"#C0D0E0",lineWidth:1,max:null,min:null,minPadding:0.01,maxPadding:0.01,minorGridLineColor:"#E0E0E0",minorGridLineWidth:1,minorTickColor:"#A0A0A0",minorTickLength:2,minorTickPosition:"outside",startOfWeek:1,startOnTick:false,tickColor:"#C0D0E0",tickLength:5,tickmarkPlacement:"between",tickPixelInterval:100,tickPosition:"outside",tickWidth:1,title:{align:"middle",style:{color:"#6D869F",fontWeight:"bold"}},type:"linear"},fd=ua(Hc,{endOnTick:true,
gridLineWidth:1,tickPixelInterval:72,showLastLabel:true,labels:{align:"right",x:-8,y:3},lineWidth:0,maxPadding:0.05,minPadding:0.05,startOnTick:true,tickWidth:0,title:{rotation:270,text:"Y-values"}}),Yd={labels:{align:"right",x:-8,y:3},title:{rotation:270}},Xd={labels:{align:"left",x:8,y:3},title:{rotation:90}},Ld={labels:{align:"center",x:0,y:14},title:{rotation:0}},Wd=ua(Ld,{labels:{y:-5}}),ub=Na.plotOptions;eb=ub.line;ub.spline=ua(eb);ub.scatter=ua(eb,{lineWidth:0,states:{hover:{lineWidth:0}}});
ub.area=ua(eb,{});ub.areaspline=ua(ub.area);ub.column=ua(eb,{borderColor:"#FFFFFF",borderWidth:1,borderRadius:0,groupPadding:0.2,marker:null,pointPadding:0.1,minPointLength:0,states:{hover:{brightness:0.1,shadow:false},select:{color:"#C0C0C0",borderColor:"#000000",shadow:false}}});ub.bar=ua(ub.column,{dataLabels:{align:"left",x:5,y:0}});ub.pie=ua(eb,{borderColor:"#FFFFFF",borderWidth:1,center:["50%","50%"],colorByPoint:true,dataLabels:{distance:30,enabled:true,formatter:function(){return this.point.name},
y:5},legendType:"point",marker:null,size:"75%",showInLegend:false,slicedOffset:10,states:{hover:{brightness:0.1,shadow:false}}});Bd();var ac=function(a){var c=[],b;(function(d){if(b=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]?(?:\.[0-9]+)?)\s*\)/.exec(d))c=[oa(b[1]),oa(b[2]),oa(b[3]),parseFloat(b[4],10)];else if(b=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(d))c=[oa(b[1],16),oa(b[2],16),oa(b[3],16),1]})(a);return{get:function(d){return c&&!isNaN(c[0])?d==
"rgb"?"rgb("+c[0]+","+c[1]+","+c[2]+")":d=="a"?c[3]:"rgba("+c.join(",")+")":a},brighten:function(d){if(bc(d)&&d!==0){var e;for(e=0;e<3;e++){c[e]+=oa(d*255);if(c[e]<0)c[e]=0;if(c[e]>255)c[e]=255}}return this},setOpacity:function(d){c[3]=d;return this}}};Ic=function(a,c,b){function d(K){return K.toString().replace(/^([0-9])$/,"0$1")}if(!M(c)||isNaN(c))return"Invalid date";a=y(a,"%Y-%m-%d %H:%M:%S");c=new Date(c*nb);var e=c[ad](),f=c[bd](),g=c[nc](),i=c[zc](),j=c[Ac](),k=Na.lang,n=k.weekdays;k=k.months;
c={a:n[f].substr(0,3),A:n[f],d:d(g),e:g,b:k[i].substr(0,3),B:k[i],m:d(i+1),y:j.toString().substr(2,2),Y:j,H:d(e),I:d(e%12||12),l:e%12||12,M:d(c[$c]()),p:e<12?"AM":"PM",P:e<12?"am":"pm",S:d(c.getSeconds())};for(var z in c)a=a.replace("%"+z,c[z]);return b?a.substr(0,1).toUpperCase()+a.substr(1):a};Dc.prototype={init:function(a,c){this.element=Ca.createElementNS("http://www.w3.org/2000/svg",c);this.renderer=a},animate:function(a,c,b){if(c=y(c,xc,true)){c=ua(c);if(b)c.complete=b;Uc(this,a,c)}else{this.attr(a);
b&&b()}},attr:function(a,c){var b,d,e,f,g=this.element,i=g.nodeName,j=this.renderer,k,n=this.shadows,z,K=this;if(Gb(a)&&M(c)){b=a;a={};a[b]=c}if(Gb(a)){b=a;if(i=="circle")b={x:"cx",y:"cy"}[b]||b;else if(b=="strokeWidth")b="stroke-width";K=xa(g,b)||this[b]||0;if(b!="d"&&b!="visibility")K=parseFloat(K)}else for(b in a){k=false;d=a[b];if(b=="d"){if(d&&d.join)d=d.join(" ");if(/(NaN| {2}|^$)/.test(d))d="M 0 0";this.d=d}else if(b=="x"&&i=="text"){for(e=0;e<g.childNodes.length;e++){f=g.childNodes[e];xa(f,
"x")==xa(g,"x")&&xa(f,"x",d)}if(this.rotation)xa(g,"transform","rotate("+this.rotation+" "+d+" "+oa(a.y||xa(g,"y"))+")")}else if(b=="fill")d=j.color(d,g,b);else if(i=="circle"&&(b=="x"||b=="y"))b={x:"cx",y:"cy"}[b]||b;else if(b=="translateX"||b=="translateY"||b=="rotation"){this[b]=d;this.updateTransform();k=true}else if(b=="stroke")d=j.color(d,g,b);else if(b=="dashstyle"){b="stroke-dasharray";if(d){d=d.toLowerCase().replace("shortdashdotdot","3,1,1,1,1,1,").replace("shortdashdot","3,1,1,1").replace("shortdot",
"1,1,").replace("shortdash","3,1,").replace("longdash","8,3,").replace(/dot/g,"1,3,").replace("dash","4,3,").replace(/,$/,"").split(",");for(e=d.length;e--;)d[e]=oa(d[e])*a["stroke-width"];d=d.join(",")}}else if(b=="isTracker")this[b]=d;else if(b=="width")d=oa(d);else if(b=="align"){b="text-anchor";d={left:"start",center:"middle",right:"end"}[d]}if(b=="strokeWidth")b="stroke-width";if(be&&b=="stroke-width"&&d===0)d=1.0E-6;if(this.symbolName&&/^(x|y|r|start|end|innerR)/.test(b)){if(!z){this.symbolAttr(a);
z=true}k=true}if(n&&/^(width|height|visibility|x|y|d)$/.test(b))for(e=n.length;e--;)xa(n[e],b,d);if(b=="text")j.buildText(g,d);else k||xa(g,b,d)}return K},symbolAttr:function(a){this.x=y(a.x,this.x);this.y=parseFloat(y(a.y,this.y));this.r=y(a.r,this.r);this.start=y(a.start,this.start);this.end=y(a.end,this.end);this.width=y(a.width,this.width);this.height=parseFloat(y(a.height,this.height));this.innerR=y(a.innerR,this.innerR);this.attr({d:this.renderer.symbols[this.symbolName](this.x,this.y,this.r,
{start:this.start,end:this.end,width:this.width,height:this.height,innerR:this.innerR})})},clip:function(a){return this.attr("clip-path","url("+this.renderer.url+"#"+a.id+")")},css:function(a){if(a&&a.color)a.fill=a.color;a=na(this.styles,a);this.attr({style:Vd(a)});this.styles=a;return this},on:function(a,c){var b=c;if(Eb&&a=="click"){a="touchstart";b=function(d){d.preventDefault();c()}}this.element["on"+a]=b;return this},translate:function(a,c){return this.attr({translateX:a,translateY:c})},invert:function(){this.inverted=
true;this.updateTransform();return this},updateTransform:function(){var a=this.translateX||0,c=this.translateY||0,b=this.inverted,d=this.rotation,e=[];if(b){a+=this.attr("width");c+=this.attr("height")}if(a||c)e.push("translate("+a+","+c+")");if(b)e.push("rotate(90) scale(-1,1)");else d&&e.push("rotate("+d+" "+this.x+" "+this.y+")");e.length&&xa(this.element,"transform",e.join(" "))},toFront:function(){var a=this.element;a.parentNode.appendChild(a);return this},align:function(a,c,b){if(a){this.alignOptions=
a;this.alignByTranslate=c;b||this.renderer.alignedObjects.push(this)}else{a=this.alignOptions;c=this.alignByTranslate}b=y(b,this.renderer);var d=a.align,e=a.verticalAlign,f=(b.x||0)+(a.x||0),g=(b.y||0)+(a.y||0),i={};if(/^(right|center)$/.test(d))f+=(b.width-(a.width||0))/{right:1,center:2}[d];i[c?"translateX":"x"]=f;if(/^(bottom|middle)$/.test(e))g+=(b.height-(a.height||0))/({bottom:1,middle:2}[e]||1);i[c?"translateY":"y"]=g;this[this.placed?"animate":"attr"](i);this.placed=true;return this},getBBox:function(){var a,
c,b,d=this.rotation,e=d*Td;try{a=na({},this.element.getBBox())}catch(f){a={width:0,height:0}}c=a.width;b=a.height;if(d){a.width=$a(b*xb(e))+$a(c*tb(e));a.height=$a(b*tb(e))+$a(c*xb(e))}return a},show:function(){return this.attr({visibility:Ab})},hide:function(){return this.attr({visibility:Cb})},add:function(a){var c=this.renderer,b=a||c;c=b.element||c.box;var d=c.childNodes,e=this.element,f=xa(e,"zIndex"),g;this.parentInverted=a&&a.inverted;if(f){b.handleZ=true;f=oa(f)}if(b.handleZ)for(g=0;g<d.length;g++){a=
d[g];b=xa(a,"zIndex");if(a!=e&&(oa(b)>f||!M(f)&&M(b))){c.insertBefore(e,a);return this}}c.appendChild(e);return this},destroy:function(){var a=this.element||{},c=this.shadows,b=a.parentNode,d;a.onclick=a.onmouseout=a.onmouseover=a.onmousemove=null;Xc(this);b&&b.removeChild(a);c&&t(c,function(e){(b=e.parentNode)&&b.removeChild(e)});wc(this.renderer.alignedObjects,this);for(d in this)delete this[d];return null},empty:function(){for(var a=this.element,c=a.childNodes,b=c.length;b--;)a.removeChild(c[b])},
shadow:function(a){var c=[],b,d=this.element,e=this.parentInverted?"(-1,-1)":"(1,1)";if(a){for(a=1;a<=3;a++){b=d.cloneNode(0);xa(b,{isShadow:"true",stroke:"rgb(0, 0, 0)","stroke-opacity":0.05*a,"stroke-width":7-2*a,transform:"translate"+e,fill:mb});d.parentNode.insertBefore(b,d);c.push(b)}this.shadows=c}return this}};var Pc=function(){this.init.apply(this,arguments)};Pc.prototype={init:function(a,c,b){var d=location,e;this.Element=Dc;e=this.createElement("svg").attr({xmlns:"http://www.w3.org/2000/svg",
version:"1.1"});a.appendChild(e.element);this.box=e.element;this.boxWrapper=e;this.alignedObjects=[];this.url=Zc?"":d.href.replace(/#.*?$/,"");this.defs=this.createElement("defs").add();this.setSize(c,b,false)},createElement:function(a){var c=new this.Element;c.init(this,a);return c},buildText:function(a,c){for(var b=c.toString().replace(/<(b|strong)>/g,'<span style="font-weight:bold">').replace(/<(i|em)>/g,'<span style="font-style:italic">').replace(/<a/g,"<span").replace(/<\/(b|strong|i|em|a)>/g,
"</span>").split(/<br[^>]?>/g),d=a.childNodes,e=/style="([^"]+)"/,f=/href="([^"]+)"/,g=xa(a,"x"),i,j=d.length;j--;)a.removeChild(d[j]);t(b,function(k,n){var z,K=0,ia;k=k.replace(/<span/g,"|||<span").replace(/<\/span>/g,"</span>|||");z=k.split("|||");t(z,function($){if($!==""||z.length==1){var ga={},u=Ca.createElementNS("http://www.w3.org/2000/svg","tspan");e.test($)&&xa(u,"style",$.match(e)[1].replace(/(;| |^)color([ :])/,"$1fill$2"));if(f.test($)){xa(u,"onclick",'location.href="'+$.match(f)[1]+'"');
Xa(u,{cursor:"pointer"})}$=$.replace(/<(.|\n)*?>/g,"");u.appendChild(Ca.createTextNode($||" "));if(K)ga.dx=3;else ga.x=g;if(!K){if(n){ia=oa(window.getComputedStyle(i,null).getPropertyValue("line-height"));if(isNaN(ia))ia=i.offsetHeight||18;xa(u,"dy",ia)}i=u}xa(u,ga);a.appendChild(u);K++}})})},crispLine:function(a,c){if(a[1]==a[4])a[1]=a[4]=T(a[1])+c%2/2;if(a[2]==a[5])a[2]=a[5]=T(a[2])+c%2/2;return a},path:function(a){return this.createElement("path").attr({d:a,fill:mb})},circle:function(a,c,b){a=
Hb(a)?a:{x:a,y:c,r:b};return this.createElement("circle").attr(a)},arc:function(a,c,b,d,e,f){if(Hb(a)){c=a.y;b=a.r;d=a.innerR;e=a.start;f=a.end;a=a.x}return this.symbol("arc",a||0,c||0,b||0,{innerR:d||0,start:e||0,end:f||0})},rect:function(a,c,b,d,e,f){if(arguments.length>1){var g=(f||0)%2/2;a=T(a||0)+g;c=T(c||0)+g;b=T((b||0)-2*g);d=T((d||0)-2*g)}g=Hb(a)?a:{x:a,y:c,width:Aa(b,0),height:Aa(d,0)};return this.createElement("rect").attr(na(g,{rx:e||g.r,ry:e||g.r,fill:mb}))},setSize:function(a,c,b){var d=
this.alignedObjects,e=d.length;this.width=a;this.height=c;for(this.boxWrapper[y(b,true)?"animate":"attr"]({width:a,height:c});e--;)d[e].align()},g:function(a){return this.createElement("g").attr(M(a)&&{"class":Zb+a})},image:function(a,c,b,d,e){var f={preserveAspectRatio:mb};arguments.length>1&&na(f,{x:c,y:b,width:d,height:e});f=this.createElement("image").attr(f);f.element.setAttributeNS("http://www.w3.org/1999/xlink","href",a);return f},symbol:function(a,c,b,d,e){var f,g=this.symbols[a];g=g&&g(c,
b,d,e);var i=/^url\((.*?)\)$/;if(g){f=this.path(g);na(f,{symbolName:a,x:c,y:b,r:d});e&&na(f,e)}else if(i.test(a)){a=a.match(i)[1];f=this.image(a).attr({x:c,y:b});fb("img",{onload:function(){var j=ce[this.src]||[this.width,this.height];f.attr({width:j[0],height:j[1]}).translate(-T(j[0]/2),-T(j[1]/2))},src:a})}else f=this.circle(c,b,d);return f},symbols:{square:function(a,c,b){b=0.707*b;return[Va,a-b,c-b,Ba,a+b,c-b,a+b,c+b,a-b,c+b,"Z"]},triangle:function(a,c,b){return[Va,a,c-1.33*b,Ba,a+b,c+0.67*b,
a-b,c+0.67*b,"Z"]},"triangle-down":function(a,c,b){return[Va,a,c+1.33*b,Ba,a-b,c-0.67*b,a+b,c-0.67*b,"Z"]},diamond:function(a,c,b){return[Va,a,c-b,Ba,a+b,c,a,c+b,a-b,c,"Z"]},arc:function(a,c,b,d){var e=d.start,f=d.end-1.0E-6,g=d.innerR,i=tb(e),j=xb(e),k=tb(f);f=xb(f);d=d.end-e<Ub?0:1;return[Va,a+b*i,c+b*j,"A",b,b,0,d,1,a+b*k,c+b*f,Ba,a+g*k,c+g*f,"A",g,g,0,d,0,a+g*i,c+g*j,"Z"]}},clipRect:function(a,c,b,d){var e=Zb+od++,f=this.createElement("clipPath").attr({id:e}).add(this.defs);a=this.rect(a,c,b,
d,0).add(f);a.id=e;return a},color:function(a,c,b){var d,e=/^rgba/;if(a&&a.linearGradient){var f=this;c=a.linearGradient;b=Zb+od++;var g,i,j;g=f.createElement("linearGradient").attr({id:b,gradientUnits:"userSpaceOnUse",x1:c[0],y1:c[1],x2:c[2],y2:c[3]}).add(f.defs);t(a.stops,function(k){if(e.test(k[1])){d=ac(k[1]);i=d.get("rgb");j=d.get("a")}else{i=k[1];j=1}f.createElement("stop").attr({offset:k[0],"stop-color":i,"stop-opacity":j}).add(g)});return"url("+this.url+"#"+b+")"}else if(e.test(a)){d=ac(a);
xa(c,b+"-opacity",d.get("a"));return d.get("rgb")}else return a},text:function(a,c,b){var d=Na.chart.style;c=T(y(c,0));b=T(y(b,0));a=this.createElement("text").attr({x:c,y:b,text:a}).css({"font-family":d.fontFamily,"font-size":d.fontSize});a.x=c;a.y=b;return a}};var Ia;if(!Rc){var fe=vb(Dc,{init:function(a,c){var b=["<",c,' filled="f" stroked="f"'],d=["position: ",lc,";"];if(c=="shape"||c==Jb)d.push("left:0;top:0;width:10px;height:10px;");if(Vc)d.push("visibility: ",c==Jb?Cb:Ab);b.push(' style="',
d.join(""),'"/>');if(c){b=c==Jb||c=="span"||c=="img"?b.join(""):a.prepVML(b);this.element=fb(b)}this.renderer=a},add:function(a){var c=this.renderer,b=this.element,d=c.box;d=a?a.element||a:d;a&&a.inverted&&c.invertChild(b,d);d.appendChild(b);this.added=true;this.alignOnAdd&&this.updateTransform();return this},attr:function(a,c){var b,d,e,f=this.element||{},g=f.style,i=f.nodeName,j=this.renderer,k=this.symbolName,n,z,K=this.shadows,ia=this;if(Gb(a)&&M(c)){b=a;a={};a[b]=c}if(Gb(a)){b=a;ia=b=="strokeWidth"||
b=="stroke-width"?this.strokeweight:this[b]}else for(b in a){d=a[b];n=false;if(k&&/^(x|y|r|start|end|width|height|innerR)/.test(b)){if(!z){this.symbolAttr(a);z=true}n=true}else if(b=="d"){d=d||[];this.d=d.join(" ");e=d.length;for(n=[];e--;)n[e]=bc(d[e])?T(d[e]*10)-5:d[e]=="Z"?"x":d[e];d=n.join(" ")||"x";f.path=d;if(K)for(e=K.length;e--;)K[e].path=d;n=true}else if(b=="zIndex"||b=="visibility"){if(Vc&&b=="visibility"&&i=="DIV"){n=f.childNodes;for(e=n.length;e--;)Xa(n[e],{visibility:d});if(d==Ab)d=null}if(d)g[b]=
d;n=true}else if(/^(width|height)$/.test(b)){if(this.updateClipping){this[b]=d;this.updateClipping()}else g[b]=d;n=true}else if(/^(x|y)$/.test(b)){this[b]=d;if(f.tagName=="SPAN")this.updateTransform();else g[{x:"left",y:"top"}[b]]=d}else if(b=="class")f.className=d;else if(b=="stroke"){d=j.color(d,f,b);b="strokecolor"}else if(b=="stroke-width"||b=="strokeWidth"){f.stroked=d?true:false;b="strokeweight";this[b]=d;if(bc(d))d+=bb}else if(b=="dashstyle"){(f.getElementsByTagName("stroke")[0]||fb(j.prepVML(["<stroke/>"]),
null,null,f))[b]=d||"solid";this.dashstyle=d;n=true}else if(b=="fill")if(i=="SPAN")g.color=d;else{f.filled=d!=mb?true:false;d=j.color(d,f,b);b="fillcolor"}else if(b=="translateX"||b=="translateY"||b=="rotation"||b=="align"){if(b=="align")b="textAlign";this[b]=d;this.updateTransform();n=true}else if(b=="text"){f.innerHTML=d;n=true}if(K&&b=="visibility")for(e=K.length;e--;)K[e].style[b]=d;if(!n)if(Vc)f[b]=d;else xa(f,b,d)}return ia},clip:function(a){var c=a.members,b=c.length;c.push(this);this.destroyClip=
function(){c.splice(b,1)};return this.css(a.getCSS(this.inverted))},css:function(a){Xa(this.element,a);return this},destroy:function(){this.destroyClip&&this.destroyClip();Dc.prototype.destroy.apply(this)},empty:function(){for(var a=this.element.childNodes,c=a.length,b;c--;){b=a[c];b.parentNode.removeChild(b)}},getBBox:function(){var a=this.element;if(a.nodeName=="text")a.style.position=lc;return{x:a.offsetLeft,y:a.offsetTop,width:a.offsetWidth,height:a.offsetHeight}},on:function(a,c){this.element["on"+
a]=function(){var b=rb.event;b.target=b.srcElement;c(b)};return this},updateTransform:function(){if(this.added){var a=this,c=a.element,b=a.translateX||0,d=a.translateY||0,e=a.x||0,f=a.y||0,g=a.rotation||0,i=g*Td,j=tb(i);i=xb(i);var k=a.textAlign||"left",n={right:1,center:2}[k],z=k&&k!="left";if(b||d)a.css({marginLeft:b,marginTop:d});a.inverted&&t(c.childNodes,function(K){a.renderer.invertChild(K,c)});if(c.tagName=="SPAN"){Xa(c,{filter:g?["progid:DXImageTransform.Microsoft.Matrix(M11=",j,", M12=",
-i,", M21=",i,", M22=",j,", sizingMethod='auto expand')"].join(""):mb});b=c.offsetWidth;d=c.offsetHeight;g=T(oa(c.style.fontSize||12)*1.2);e+=b*ab(j,0)+ab(i,0)*g;f+=d*ab(i,0)-Aa(j,0)*g;if(z){e-=b/n*j;f-=d/n*i}Xa(c,{textAlign:k,left:e,top:f})}}else this.alignOnAdd=true},shadow:function(a){var c=[],b=this.element,d=this.renderer,e,f=b.style,g,i=b.path;if(""+b.path==="")i="x";if(a){for(a=1;a<=3;a++){g=['<shape isShadow="true" strokeweight="',7-2*a,'" filled="false" path="',i,'" coordsize="100,100" style="',
b.style.cssText,'" />'];e=fb(d.prepVML(g),null,{left:oa(f.left)+1,top:oa(f.top)+1});g=['<stroke color="black" opacity="',0.05*a,'"/>'];fb(d.prepVML(g),null,null,e);b.parentNode.insertBefore(e,b);c.push(e)}this.shadows=c}return this}});Ia=function(){this.init.apply(this,arguments)};Ia.prototype=ua(Pc.prototype,{isIE8:Qc.indexOf("MSIE 8.0")>-1,init:function(a,c,b){var d;this.Element=fe;this.alignedObjects=[];d=this.createElement(Jb);a.appendChild(d.element);this.box=d.element;this.boxWrapper=d;this.setSize(c,
b,false);if(!Ca.namespaces.hcv){Ca.namespaces.add("hcv","urn:schemas-microsoft-com:vml");Ca.createStyleSheet().cssText="hcv\\:fill, hcv\\:path, hcv\\:shape, hcv\\:stroke{ behavior:url(#default#VML); display: inline-block; } "}},clipRect:function(a,c,b,d){var e=this.createElement();return na(e,{members:[],left:a,top:c,width:b,height:d,getCSS:function(f){var g=this.top,i=this.left,j=i+this.width,k=g+this.height;g={clip:"rect("+T(f?i:g)+"px,"+T(f?k:j)+"px,"+T(f?j:k)+"px,"+T(f?g:i)+"px)"};!f&&Vc&&na(g,
{width:j+bb,height:k+bb});return g},updateClipping:function(){t(e.members,function(f){f.css(e.getCSS(f.inverted))})}})},color:function(a,c,b){var d,e=/^rgba/;if(a&&a.linearGradient){var f,g,i=a.linearGradient,j,k,n,z;t(a.stops,function(K,ia){if(e.test(K[1])){d=ac(K[1]);f=d.get("rgb");g=d.get("a")}else{f=K[1];g=1}if(ia){n=f;z=g}else{j=f;k=g}});a=90-Pa.atan((i[3]-i[1])/(i[2]-i[0]))*180/Ub;b=["<",b,' colors="0% ',j,",100% ",n,'" angle="',a,'" opacity="',z,'" o:opacity2="',k,'" type="gradient" focus="100%" />'];
fb(this.prepVML(b),null,null,c)}else if(e.test(a)&&c.tagName!="IMG"){d=ac(a);b=["<",b,' opacity="',d.get("a"),'"/>'];fb(this.prepVML(b),null,null,c);return d.get("rgb")}else return a},prepVML:function(a){var c=this.isIE8;a=a.join("");if(c){a=a.replace("/>",' xmlns="urn:schemas-microsoft-com:vml" />');a=a.indexOf('style="')==-1?a.replace("/>",' style="display:inline-block;behavior:url(#default#VML);" />'):a.replace('style="','style="display:inline-block;behavior:url(#default#VML);')}else a=a.replace("<",
"<hcv:");return a},text:function(a,c,b){var d=Na.chart.style;return this.createElement("span").attr({text:a,x:T(c),y:T(b)}).css({whiteSpace:"nowrap",fontFamily:d.fontFamily,fontSize:d.fontSize})},path:function(a){return this.createElement("shape").attr({coordsize:"100 100",d:a})},circle:function(a,c,b){return this.path(this.symbols.circle(a,c,b))},g:function(a){var c;if(a)c={className:Zb+a,"class":Zb+a};return this.createElement(Jb).attr(c)},image:function(a,c,b,d,e){var f=this.createElement("img").attr({src:a});
arguments.length>1&&f.css({left:c,top:b,width:d,height:e});return f},rect:function(a,c,b,d,e,f){if(arguments.length>1){var g=(f||0)%2/2;a=T(a||0)+g;c=T(c||0)+g;b=T((b||0)-2*g);d=T((d||0)-2*g)}if(Hb(a)){c=a.y;b=a.width;d=a.height;e=a.r;a=a.x}return this.symbol("rect",a||0,c||0,e||0,{width:b||0,height:d||0})},invertChild:function(a,c){var b=c.style;Xa(a,{flip:"x",left:oa(b.width)-10,top:oa(b.height)-10,rotation:-90})},symbols:{arc:function(a,c,b,d){var e=d.start,f=d.end,g=tb(e),i=xb(e),j=tb(f),k=xb(f);
d=d.innerR;if(f-e===0)return["x"];else if(f-e==2*Ub)j=-0.07/b;return["wa",a-b,c-b,a+b,c+b,a+b*g,c+b*i,a+b*j,c+b*k,"at",a-d,c-d,a+d,c+d,a+d*j,c+d*k,a+d*g,c+d*i,"x","e"]},circle:function(a,c,b){return["wa",a-b,c-b,a+b,c+b,a+b,c,a+b,c,"e"]},rect:function(a,c,b,d){var e=d.width;d=d.height;var f=a+e,g=c+d;b=ab(b,e,d);return[Va,a+b,c,Ba,f-b,c,"wa",f-2*b,c,f,c+2*b,f-b,c,f,c+b,Ba,f,g-b,"wa",f-2*b,g-2*b,f,g,f,g-b,f-b,g,Ba,a+b,g,"wa",a,g-2*b,a+2*b,g,a+b,g,a,g-b,Ba,a,c+b,"wa",a,c,a+2*b,c+2*b,a,c+b,a+b,c,"x",
"e"]}}})}var Qd=Rc?Pc:Ia;Hd.prototype.callbacks=[];var vc=function(){};vc.prototype={init:function(a,c){var b;this.series=a;this.applyOptions(c);this.pointAttr={};if(a.options.colorByPoint){b=a.chart.options.colors;if(!this.options)this.options={};this.color=this.options.color=this.color||b[Fb++];if(Fb>=b.length)Fb=0}a.chart.pointCount++;return this},applyOptions:function(a){var c=this.series;this.config=a;if(bc(a)||a===null)this.y=a;else if(Hb(a)&&!bc(a.length)){na(this,a);this.options=a}else if(Gb(a[0])){this.name=
a[0];this.y=a[1]}else if(bc(a[0])){this.x=a[0];this.y=a[1]}if(this.x===Ma)this.x=c.autoIncrement()},destroy:function(){var a=this,c=a.series,b;c.chart.pointCount--;a==c.chart.hoverPoint&&a.onMouseOut();c.chart.hoverPoints=null;Bb(a);t(["graphic","tracker","group","dataLabel","connector"],function(d){a[d]&&a[d].destroy()});a.legendItem&&a.series.chart.legend.destroyItem(a);for(b in a)a[b]=null},select:function(a,c){var b=this,d=b.series.chart;b.selected=a=y(a,!b.selected);b.firePointEvent(a?"select":
"unselect");b.setState(a&&"select");c||t(d.getSelectedPoints(),function(e){if(e.selected&&e!=b){e.selected=false;e.setState(db);e.firePointEvent("unselect")}})},onMouseOver:function(){var a=this.series.chart,c=a.tooltip,b=a.hoverPoint;b&&b!=this&&b.onMouseOut();this.firePointEvent("mouseOver");c&&!c.shared&&c.refresh(this);this.setState(wb);a.hoverPoint=this},onMouseOut:function(){this.firePointEvent("mouseOut");this.setState();this.series.chart.hoverPoint=null},update:function(a,c,b){var d=this,
e=d.series,f=e.chart;Ib(b,f);c=y(c,true);d.firePointEvent("update",{options:a},function(){d.applyOptions(a);e.isDirty=true;c&&f.redraw()})},remove:function(a,c){var b=this,d=b.series,e=d.chart,f=d.data;Ib(c,e);a=y(a,true);b.firePointEvent("remove",null,function(){wc(f,b);b.destroy();d.isDirty=true;a&&e.redraw()})},firePointEvent:function(a,c,b){var d=this,e=this.series.options;if(e.point.events[a]||d.options&&d.options.events&&d.options.events[a])this.importEvents();if(a=="click"&&e.allowPointSelect)b=
function(f){d.select(null,f.ctrlKey||f.metaKey||f.shiftKey)};Ha(this,a,c,b)},importEvents:function(){if(!this.hasImportedEvents){var a=ua(this.series.options.point,this.options).events,c;this.events=a;for(c in a)La(this,c,a[c]);this.hasImportedEvents=true}},setState:function(a){var c=this.series,b=c.options.states,d=ub[c.type].marker&&c.options.marker,e=d&&!d.enabled,f=(d=d&&d.states[a])&&d.enabled===false,g=c.stateMarkerGraphic,i=c.chart,j=this.pointAttr;a||(a=db);if(!(a==this.state||this.selected&&
a!="select"||b[a]&&b[a].enabled===false||a&&(f||e&&!d.enabled))){if(this.graphic)this.graphic.attr(j[a]);else{if(a){if(!g)c.stateMarkerGraphic=g=i.renderer.circle(0,0,j[a].r).attr(j[a]).add(c.group);g.translate(this.plotX,this.plotY)}if(g)g[a?"show":"hide"]()}this.state=a}}};var lb=function(){};lb.prototype={isCartesian:true,type:"line",pointClass:vc,pointAttrToOptions:{stroke:"lineColor","stroke-width":"lineWidth",fill:"fillColor",r:"radius"},init:function(a,c){var b,d;d=a.series.length;this.chart=
a;c=this.setOptions(c);na(this,{index:d,options:c,name:c.name||"Series "+(d+1),state:db,pointAttr:{},visible:c.visible!==false,selected:c.selected===true});d=c.events;for(b in d)La(this,b,d[b]);if(d&&d.click||c.point&&c.point.events&&c.point.events.click||c.allowPointSelect)a.runTrackerClick=true;this.getColor();this.getSymbol();this.setData(c.data,false)},autoIncrement:function(){var a=this.options,c=this.xIncrement;c=y(c,a.pointStart,0);this.pointInterval=y(this.pointInterval,a.pointInterval,1);
this.xIncrement=c+this.pointInterval;return c},cleanData:function(){var a=this.chart,c=this.data,b,d,e=a.smallestInterval,f,g;c.sort(function(i,j){return i.x-j.x});for(g=c.length-1;g>=0;g--)c[g-1]&&c[g-1].x==c[g].x&&c.splice(g-1,1);for(g=c.length-1;g>=0;g--)if(c[g-1]){f=c[g].x-c[g-1].x;if(d===Ma||f<d){d=f;b=g}}if(e===Ma||d<e)a.smallestInterval=d;this.closestPoints=b},getSegments:function(){var a=-1,c=[],b=this.data;t(b,function(d,e){if(d.y===null){e>a+1&&c.push(b.slice(a+1,e));a=e}else e==b.length-
1&&c.push(b.slice(a+1,e+1))});this.segments=c},setOptions:function(a){var c=this.chart.options.plotOptions;return ua(c[this.type],c.series,a)},getColor:function(){var a=this.chart.options.colors;this.color=this.options.color||a[Fb++]||"#0000ff";if(Fb>=a.length)Fb=0},getSymbol:function(){var a=this.chart.options.symbols;this.symbol=this.options.marker.symbol||a[Tc++];if(Tc>=a.length)Tc=0},addPoint:function(a,c,b,d){var e=this.data,f=this.graph,g=this.area,i=this.chart;a=(new this.pointClass).init(this,
a);Ib(d,i);if(f&&b)f.shift=b;if(g){g.shift=b;g.isArea=true}c=y(c,true);e.push(a);b&&e[0].remove(false);this.isDirty=true;c&&i.redraw()},setData:function(a,c){var b=this,d=b.data,e=b.initialColor,f=b.chart,g=d&&d.length||0;b.xIncrement=null;if(M(e))Fb=e;for(a=jc(mc(a||[]),function(i){return(new b.pointClass).init(b,i)});g--;)d[g].destroy();b.data=a;b.cleanData();b.getSegments();b.isDirty=true;f.isDirtyBox=true;y(c,true)&&f.redraw(false)},remove:function(a,c){var b=this,d=b.chart;a=y(a,true);if(!b.isRemoving){b.isRemoving=
true;Ha(b,"remove",null,function(){b.destroy();d.isDirtyLegend=d.isDirtyBox=true;a&&d.redraw(c)})}b.isRemoving=false},translate:function(){for(var a=this.chart,c=this.options.stacking,b=this.xAxis.categories,d=this.yAxis,e=this.data,f=e.length;f--;){var g=e[f],i=g.x,j=g.y,k;k=d.stacks[(j<0?"-":"")+this.stackKey];g.plotX=this.xAxis.translate(i);if(c&&this.visible&&k[i]){k=k[i];i=k.total;k.cum=k=k.cum-j;j=k+j;if(c=="percent"){k=i?k*100/i:0;j=i?j*100/i:0}g.percentage=i?g.y*100/i:0;g.stackTotal=i;g.yBottom=
d.translate(k,0,1)}if(j!==null)g.plotY=d.translate(j,0,1);g.clientX=a.inverted?a.plotHeight-g.plotX:g.plotX;g.category=b&&b[g.x]!==Ma?b[g.x]:g.x}},setTooltipPoints:function(a){var c=this.chart,b=c.inverted,d=[],e=T((b?c.plotTop:c.plotLeft)+c.plotSizeX),f,g,i=[];if(a)this.tooltipPoints=null;t(this.segments,function(j){d=d.concat(j)});if(this.xAxis&&this.xAxis.reversed)d=d.reverse();t(d,function(j,k){f=d[k-1]?d[k-1].high+1:0;for(g=j.high=d[k+1]?Lb((j.plotX+(d[k+1]?d[k+1].plotX:e))/2):e;f<=g;)i[b?e-
f++:f++]=j});this.tooltipPoints=i},onMouseOver:function(){var a=this.chart,c=a.hoverSeries;if(!(!Eb&&a.mouseIsDown)){c&&c!=this&&c.onMouseOut();this.options.events.mouseOver&&Ha(this,"mouseOver");this.tracker&&this.tracker.toFront();this.setState(wb);a.hoverSeries=this}},onMouseOut:function(){var a=this.options,c=this.chart,b=c.tooltip,d=c.hoverPoint;d&&d.onMouseOut();this&&a.events.mouseOut&&Ha(this,"mouseOut");b&&!a.stickyTracking&&b.hide();this.setState();c.hoverSeries=null},animate:function(a){var c=
this.chart,b=this.clipRect,d=this.options.animation;if(d&&!Hb(d))d={};if(a){if(!b.isAnimating){b.attr("width",0);b.isAnimating=true}}else{b.animate({width:c.plotSizeX},d&&na(d,{complete:function(){b.isAnimating=false}}));this.animate=null}},drawPoints:function(){var a,c=this.data,b=this.chart,d,e,f,g,i,j;if(this.options.marker.enabled)for(f=c.length;f--;){g=c[f];d=g.plotX;e=g.plotY;j=g.graphic;if(e!==Ma&&!isNaN(e)){a=g.pointAttr[g.selected?"select":db];i=a.r;if(j)j.animate({x:d,y:e,r:i});else g.graphic=
b.renderer.symbol(y(g.marker&&g.marker.symbol,this.symbol),d,e,i).attr(a).add(this.group)}}},convertAttribs:function(a,c,b,d){var e=this.pointAttrToOptions,f,g,i={};a=a||{};c=c||{};b=b||{};d=d||{};for(f in e){g=e[f];i[f]=y(a[g],c[f],b[f],d[f])}return i},getAttribs:function(){var a=this,c=ub[a.type].marker?a.options.marker:a.options,b=c.states,d=b[wb],e,f={},g=a.color,i=a.data,j=[],k,n=a.pointAttrToOptions;if(a.options.marker){f={stroke:g,fill:g};d.radius=d.radius||c.radius+2;d.lineWidth=d.lineWidth||
c.lineWidth+1}else{f={fill:g};d.color=d.color||ac(d.color||g).brighten(d.brightness).get()}j[db]=a.convertAttribs(c,f);t([wb,"select"],function(K){j[K]=a.convertAttribs(b[K],j[db])});a.pointAttr=j;for(f=i.length;f--;){g=i[f];if((c=g.options&&g.options.marker||g.options)&&c.enabled===false)c.radius=0;e=false;if(g.options)for(var z in n)if(M(c[n[z]]))e=true;if(e){k=[];b=c.states||{};e=b[wb]=b[wb]||{};if(!a.options.marker)e.color=ac(e.color||g.options.color).brighten(e.brightness||d.brightness).get();
k[db]=a.convertAttribs(c,j[db]);k[wb]=a.convertAttribs(b[wb],j[wb],k[db]);k.select=a.convertAttribs(b.select,j.select,k[db])}else k=j;g.pointAttr=k}},destroy:function(){var a=this,c=a.chart,b=a.clipRect,d;Bb(a);a.legendItem&&a.chart.legend.destroyItem(a);t(a.data,function(e){e.destroy()});t(["area","graph","dataLabelsGroup","group","tracker"],function(e){a[e]&&a[e].destroy()});b&&b!=a.chart.clipRect&&b.destroy();if(c.hoverSeries==a)c.hoverSeries=null;wc(c.series,a);for(d in a)delete a[d]},drawDataLabels:function(){if(this.options.dataLabels.enabled){var a=
this,c,b,d=a.data,e=a.options.dataLabels,f,g=a.dataLabelsGroup,i=a.chart,j=i.inverted,k=a.type,n;if(!g)g=a.dataLabelsGroup=i.renderer.g(Zb+"data-labels").attr({visibility:a.visible?Ab:Cb,zIndex:5}).translate(i.plotLeft,i.plotTop).add();n=e.color;if(n=="auto")n=null;e.style.color=y(n,a.color);t(d,function(z){var K=y(z.barX,z.plotX,-999),ia=y(z.plotY,-999),$=z.dataLabel,ga=e.align;f=e.formatter.call({x:z.x,y:z.y,series:a,point:z,percentage:z.percentage,total:z.total||z.stackTotal});c=(j?i.plotWidth-
ia:K)+e.x;b=(j?i.plotHeight-K:ia)+e.y;if(k=="column")c+={center:z.barW/2,right:z.barW}[ga]||0;if($)$.animate({x:c,y:b});else if(f)z.dataLabel=i.renderer.text(f,c,b).attr({align:ga,rotation:e.rotation,zIndex:1}).css(e.style).add(g)})}},drawGraph:function(){var a=this,c=a.options,b=a.graph,d=[],e,f=a.area,g=a.group,i=c.lineColor||a.color,j=c.lineWidth,k=c.dashStyle,n,z=a.chart.renderer,K=a.yAxis.getThreshold(c.threshold||0),ia=/^area/.test(a.type),$=[],ga=[];t(a.segments,function(u){if(u.length>1){n=
[];t(u,function(ca,ma){if(a.getPointSpline)n.push.apply(n,a.getPointSpline(u,ca,ma));else{n.push(ma?Ba:Va);ma&&c.step&&n.push(ca.plotX,u[ma-1].plotY);n.push(ca.plotX,ca.plotY)}});d=d.concat(n);if(ia){var O=[],ja,Sa=n.length;for(ja=0;ja<Sa;ja++)O.push(n[ja]);if(c.stacking&&a.type!="areaspline")for(ja=u.length-1;ja>=0;ja--)O.push(u[ja].plotX,u[ja].yBottom);else O.push(Ba,u[u.length-1].plotX,K,Ba,u[0].plotX,K);ga=ga.concat(O)}}else $.push(u[0])});a.graphPath=d;a.singlePoints=$;if(ia){e=y(c.fillColor,
ac(a.color).setOpacity(c.fillOpacity||0.75).get());if(f)f.animate({d:ga});else a.area=a.chart.renderer.path(ga).attr({fill:e}).add(g)}if(b)b.animate({d:d});else if(j){b={stroke:i,"stroke-width":j};if(k)b.dashstyle=k;a.graph=z.path(d).attr(b).add(g).shadow(c.shadow)}},render:function(){var a=this.chart,c,b,d=this.options,e=d.animation&&this.animate;b=a.renderer;if(!this.clipRect){this.clipRect=!a.hasRendered&&a.clipRect?a.clipRect:b.clipRect(0,0,a.plotSizeX,a.plotSizeY);if(!a.clipRect)a.clipRect=this.clipRect}if(!this.group){c=
this.group=b.g("series");if(a.inverted){b=function(){c.attr({width:a.plotWidth,height:a.plotHeight}).invert()};b();La(a,"resize",b)}c.clip(this.clipRect).attr({visibility:this.visible?Ab:Cb,zIndex:d.zIndex}).translate(a.plotLeft,a.plotTop).add(a.seriesGroup)}this.drawDataLabels();e&&this.animate(true);this.getAttribs();this.drawGraph&&this.drawGraph();this.drawPoints();this.options.enableMouseTracking!==false&&this.drawTracker();e&&this.animate();this.isDirty=false},redraw:function(){var a=this.chart,
c=this.clipRect,b=this.group;if(c){Xc(c);c.animate({width:a.plotSizeX,height:a.plotSizeY})}b&&b.animate({translateX:a.plotLeft,translateY:a.plotTop});this.translate();this.setTooltipPoints(true);this.render()},setState:function(a){var c=this.options,b=this.graph,d=c.states;c=c.lineWidth;a=a||db;if(this.state!=a){this.state=a;if(!(d[a]&&d[a].enabled===false)){if(a)c=d[a].lineWidth||c+1;if(b&&!b.dashstyle)b.attr({"stroke-width":c},a?0:500)}}},setVisible:function(a,c){var b=this.chart,d=this.legendItem,
e=this.group,f=this.tracker,g=this.dataLabelsGroup,i,j=this.data,k=b.options.chart.ignoreHiddenSeries;i=this.visible;i=(this.visible=a=a===Ma?!i:a)?"show":"hide";e&&e[i]();if(f)f[i]();else for(e=j.length;e--;){f=j[e];f.tracker&&f.tracker[i]()}g&&g[i]();d&&b.legend.colorizeItem(this,a);this.isDirty=true;this.options.stacking&&t(b.series,function(n){if(n.options.stacking&&n.visible)n.isDirty=true});if(k)b.isDirtyBox=true;c!==false&&b.redraw();Ha(this,i)},show:function(){this.setVisible(true)},hide:function(){this.setVisible(false)},
select:function(a){this.selected=a=a===Ma?!this.selected:a;if(this.checkbox)this.checkbox.checked=a;Ha(this,a?"select":"unselect")},drawTracker:function(){var a=this,c=a.options,b=[].concat(a.graphPath),d=b.length,e=a.chart,f=e.options.tooltip.snap,g=a.tracker,i=c.cursor;i=i&&{cursor:i};var j=a.singlePoints,k;if(d)for(k=d+1;k--;){b[k]==Va&&b.splice(k+1,0,b[k+1]-f,b[k+2],Ba);if(k&&b[k]==Va||k==d)b.splice(k,0,Ba,b[k-2]+f,b[k-1])}for(k=0;k<j.length;k++){d=j[k];b.push(Va,d.plotX-f,d.plotY,Ba,d.plotX+
f,d.plotY)}if(g)g.attr({d:b});else a.tracker=e.renderer.path(b).attr({isTracker:true,stroke:Ud,fill:mb,"stroke-width":c.lineWidth+2*f,visibility:a.visible?Ab:Cb,zIndex:1}).on(Eb?"touchstart":"mouseover",function(){e.hoverSeries!=a&&a.onMouseOver()}).on("mouseout",function(){c.stickyTracking||a.onMouseOut()}).css(i).add(e.trackerGroup)}};Ia=vb(lb);sb.line=Ia;Ia=vb(lb,{type:"area"});sb.area=Ia;Ia=vb(lb,{type:"spline",getPointSpline:function(a,c,b){var d=c.plotX,e=c.plotY,f=a[b-1],g=a[b+1],i,j,k,n;if(b&&
b<a.length-1){a=f.plotY;k=g.plotX;g=g.plotY;var z;i=(1.5*d+f.plotX)/2.5;j=(1.5*e+a)/2.5;k=(1.5*d+k)/2.5;n=(1.5*e+g)/2.5;z=(n-j)*(k-d)/(k-i)+e-n;j+=z;n+=z;if(j>a&&j>e){j=Aa(a,e);n=2*e-j}else if(j<a&&j<e){j=ab(a,e);n=2*e-j}if(n>g&&n>e){n=Aa(g,e);j=2*e-n}else if(n<g&&n<e){n=ab(g,e);j=2*e-n}c.rightContX=k;c.rightContY=n}if(b){c=["C",f.rightContX||f.plotX,f.rightContY||f.plotY,i||d,j||e,d,e];f.rightContX=f.rightContY=null}else c=[Va,d,e];return c}});sb.spline=Ia;Ia=vb(Ia,{type:"areaspline"});sb.areaspline=
Ia;var Yc=vb(lb,{type:"column",pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color",r:"borderRadius"},init:function(){lb.prototype.init.apply(this,arguments);var a=this,c=a.chart;c.hasColumn=true;c.hasRendered&&t(c.series,function(b){if(b.type==a.type)b.isDirty=true})},translate:function(){var a=this,c=a.chart,b=0,d=a.xAxis.reversed,e=a.xAxis.categories,f={},g,i;lb.prototype.translate.apply(a);t(c.series,function(O){if(O.type==a.type){if(O.options.stacking){g=O.stackKey;
if(f[g]===Ma)f[g]=b++;i=f[g]}else i=b++;O.columnIndex=i}});var j=a.options,k=a.data,n=a.closestPoints;c=$a(k[1]?k[n].plotX-k[n-1].plotX:c.plotSizeX/(e?e.length:1));e=c*j.groupPadding;n=(c-2*e)/b;var z=j.pointWidth,K=M(z)?(n-z)/2:n*j.pointPadding,ia=y(z,n-2*K),$=K+(e+((d?b-a.columnIndex:a.columnIndex)||0)*n-c/2)*(d?-1:1),ga=a.yAxis.getThreshold(j.threshold||0),u=y(j.minPointLength,5);t(k,function(O){var ja=O.plotY,Sa=O.yBottom||ga,ca=O.plotX+$,ma=dd(ab(ja,Sa)),Za=dd(Aa(ja,Sa)-ma),jb;if($a(Za)<u){if(u){Za=
u;ma=$a(ma-ga)>u?Sa-u:ga-(ja<=ga?u:0)}jb=ma-3}na(O,{barX:ca,barY:ma,barW:ia,barH:Za});O.shapeType="rect";O.shapeArgs={x:ca,y:ma,width:ia,height:Za,r:j.borderRadius};O.trackerArgs=M(jb)&&ua(O.shapeArgs,{height:Aa(6,Za+3),y:jb})})},getSymbol:function(){},drawGraph:function(){},drawPoints:function(){var a=this,c=a.options,b=a.chart.renderer,d,e;t(a.data,function(f){var g=f.plotY;if(g!==Ma&&!isNaN(g)){d=f.graphic;e=f.shapeArgs;if(d){Xc(d);d.animate(e)}else f.graphic=b[f.shapeType](e).attr(f.pointAttr[f.selected?
"select":db]).add(a.group).shadow(c.shadow)}})},drawTracker:function(){var a=this,c=a.chart,b=c.renderer,d,e,f=+new Date,g=a.options.cursor,i=g&&{cursor:g},j;t(a.data,function(k){e=k.tracker;d=k.trackerArgs||k.shapeArgs;if(k.y!==null)if(e)e.attr(d);else k.tracker=b[k.shapeType](d).attr({isTracker:f,fill:Ud,visibility:a.visible?Ab:Cb,zIndex:1}).on(Eb?"touchstart":"mouseover",function(n){j=n.relatedTarget||n.fromElement;c.hoverSeries!=a&&xa(j,"isTracker")!=f&&a.onMouseOver();k.onMouseOver()}).on("mouseout",
function(n){if(!a.options.stickyTracking){j=n.relatedTarget||n.toElement;xa(j,"isTracker")!=f&&a.onMouseOut()}}).css(i).add(c.trackerGroup)})},animate:function(a){var c=this,b=c.data;if(!a){t(b,function(d){var e=d.graphic;if(e){e.attr({height:0,y:c.yAxis.translate(0,0,1)});e.animate({height:d.barH,y:d.barY},c.options.animation)}});c.animate=null}},remove:function(){var a=this,c=a.chart;c.hasRendered&&t(c.series,function(b){if(b.type==a.type)b.isDirty=true});lb.prototype.remove.apply(a,arguments)}});
sb.column=Yc;Ia=vb(Yc,{type:"bar",init:function(a){a.inverted=this.inverted=true;Yc.prototype.init.apply(this,arguments)}});sb.bar=Ia;Ia=vb(lb,{type:"scatter",translate:function(){var a=this;lb.prototype.translate.apply(a);t(a.data,function(c){c.shapeType="circle";c.shapeArgs={x:c.plotX,y:c.plotY,r:a.chart.options.tooltip.snap}})},drawTracker:function(){var a=this,c=a.options.cursor,b=c&&{cursor:c},d;t(a.data,function(e){(d=e.graphic)&&d.attr({isTracker:true}).on("mouseover",function(){a.onMouseOver();
e.onMouseOver()}).on("mouseout",function(){a.options.stickyTracking||a.onMouseOut()}).css(b)})},cleanData:function(){}});sb.scatter=Ia;Ia=vb(vc,{init:function(){vc.prototype.init.apply(this,arguments);var a=this,c;na(a,{visible:a.visible!==false,name:y(a.name,"Slice")});c=function(){a.slice()};La(a,"select",c);La(a,"unselect",c);return a},setVisible:function(a){var c=this.series.chart,b=this.tracker,d=this.dataLabel,e=this.connector,f;f=(this.visible=a=a===Ma?!this.visible:a)?"show":"hide";this.group[f]();
b&&b[f]();d&&d[f]();e&&e[f]();this.legendItem&&c.legend.colorizeItem(this,a)},slice:function(a,c,b){var d=this.series.chart,e=this.slicedTranslation;Ib(b,d);y(c,true);a=this.sliced=M(a)?a:!this.sliced;this.group.animate({translateX:a?e[0]:d.plotLeft,translateY:a?e[1]:d.plotTop})}});Ia=vb(lb,{type:"pie",isCartesian:false,pointClass:Ia,pointAttrToOptions:{stroke:"borderColor","stroke-width":"borderWidth",fill:"color"},getColor:function(){this.initialColor=Fb},animate:function(){var a=this;t(a.data,
function(c){var b=c.graphic;c=c.shapeArgs;var d=-Ub/2;if(b){b.attr({r:0,start:d,end:d});b.animate({r:c.r,start:c.start,end:c.end},a.options.animation)}});a.animate=null},translate:function(){var a=0,c=-0.25,b=this.options,d=b.slicedOffset,e=d+b.borderWidth,f=b.center,g=this.chart,i=g.plotWidth,j=g.plotHeight,k,n,z,K=this.data,ia=2*Ub,$,ga=ab(i,j),u,O,ja,Sa=b.dataLabels.distance;f.push(b.size,b.innerSize||0);f=jc(f,function(ca,ma){return(u=/%$/.test(ca))?[i,j,ga,ga][ma]*oa(ca)/100:ca});this.getX=function(ca,
ma){z=Pa.asin((ca-f[1])/(f[2]/2+Sa));return f[0]+(ma?-1:1)*tb(z)*(f[2]/2+Sa)};this.center=f;t(K,function(ca){a+=ca.y});t(K,function(ca){$=a?ca.y/a:0;k=c*ia;c+=$;n=c*ia;ca.shapeType="arc";ca.shapeArgs={x:f[0],y:f[1],r:f[2]/2,innerR:f[3]/2,start:k,end:n};z=(n+k)/2;ca.slicedTranslation=jc([tb(z)*d+g.plotLeft,xb(z)*d+g.plotTop],T);O=tb(z)*f[2]/2;ja=xb(z)*f[2]/2;ca.tooltipPos=[f[0]+O*0.7,f[1]+ja*0.7];ca.labelPos=[f[0]+O+tb(z)*Sa,f[1]+ja+xb(z)*Sa,f[0]+O+tb(z)*e,f[1]+ja+xb(z)*e,f[0]+O,f[1]+ja,Sa<0?"center":
z<ia/4?"left":"right",z];ca.percentage=$*100;ca.total=a});this.setTooltipPoints()},render:function(){this.getAttribs();this.drawPoints();this.options.enableMouseTracking!==false&&this.drawTracker();this.drawDataLabels();this.options.animation&&this.animate&&this.animate();this.isDirty=false},drawPoints:function(){var a=this.chart,c=a.renderer,b,d,e;t(this.data,function(f){d=f.graphic;e=f.shapeArgs;if(!f.group){b=f.sliced?f.slicedTranslation:[a.plotLeft,a.plotTop];f.group=c.g("point").attr({zIndex:5}).add().translate(b[0],
b[1])}if(d)d.animate(e);else f.graphic=c.arc(e).attr(f.pointAttr[db]).add(f.group);f.visible===false&&f.setVisible(false)})},drawDataLabels:function(){var a=this.data,c,b=this.chart,d=this.options.dataLabels,e=y(d.connectorPadding,10),f=y(d.connectorWidth,1),g,i,j=d.distance>0,k,n,z=this.center[1],K=[[],[],[],[]],ia,$,ga,u,O,ja,Sa,ca=4,ma;lb.prototype.drawDataLabels.apply(this);t(a,function(Za){var jb=Za.labelPos[7];K[jb<0?0:jb<Ub/2?1:jb<Ub?2:3].push(Za)});K[1].reverse();K[3].reverse();for(Sa=function(Za,
jb){return Za.y>jb.y};ca--;){a=0;c=[].concat(K[ca]);c.sort(Sa);for(ma=c.length;ma--;)c[ma].rank=ma;for(u=0;u<2;u++){n=(ja=ca%3)?9999:-9999;O=ja?-1:1;for(ma=0;ma<K[ca].length;ma++){c=K[ca][ma];if(g=c.dataLabel){i=c.labelPos;ga=Ab;ia=i[0];$=i[1];k||(k=g&&g.getBBox().height);if(j)if(u&&c.rank<a)ga=Cb;else if(!ja&&$<n+k||ja&&$>n-k){$=n+O*k;ia=this.getX($,ca>1);if(!ja&&$+k>z||ja&&$-k<z)if(u)ga=Cb;else a++}if(c.visible===false)ga=Cb;if(ga==Ab)n=$;if(u){g.attr({visibility:ga,align:i[6]})[g.moved?"animate":
"attr"]({x:ia+d.x+({left:e,right:-e}[i[6]]||0),y:$+d.y});g.moved=true;if(j&&f){g=c.connector;i=[Va,ia+(i[6]=="left"?5:-5),$,Ba,ia,$,Ba,i[2],i[3],Ba,i[4],i[5]];if(g){g.animate({d:i});g.attr("visibility",ga)}else c.connector=g=this.chart.renderer.path(i).attr({"stroke-width":f,stroke:d.connectorColor||"#606060",visibility:ga,zIndex:3}).translate(b.plotLeft,b.plotTop).add()}}}}}}},drawTracker:Yc.prototype.drawTracker,getSymbol:function(){}});sb.pie=Ia;rb.Highcharts={Chart:Hd,dateFormat:Ic,pathAnim:Wc,
getOptions:function(){return Na},numberFormat:Gd,Point:vc,Renderer:Qd,seriesTypes:sb,setOptions:function(a){Na=ua(Na,a);Bd();return Na},Series:lb,addEvent:La,createElement:fb,discardElement:Bc,css:Xa,each:t,extend:na,map:jc,merge:ua,pick:y,extendClass:vb}})();
/// <reference path="Models.js" />

Silobreaker = window.Silobreaker || {};
Silobreaker.Chart = window.Silobreaker.Chart || {};

Silobreaker.SplitWizard = function(params) {
    /// <summary>
    ///     Creates a new instance of a Silobreaker.SplitWizard
    ///     showing a wizard for splitting up a query.
    /// </summary>
    /// <param name="params">
    ///     Parameters for the view. Should contain:
    ///     guiReference: "#mySplitWizard" where to render the wizard
    ///     query: the base query to split up
    ///     splitContextChanged: a delegate that's invoked when the split context has been created function(splitContext)
    /// </param>


    var _params = params;
    var _self = this;
    this.params = _params;

    Silobreaker.Strings.add('en', {
        "query": "Query",
        "baseQuery": "Enter a query to display a Time Series. Use wizard for advanced queries.",
        "manualFilteredSplit": "Split Query 1 above into manually filtered Time Series.",
        "manualSplit": "Add additional queries for multiple Time Series",
        "assistedSplit": "Split Query 1 above into preset Time Series",
        "ok": "Create Time Series",
        "cancel": "cancel"
    });
    Silobreaker.Strings.add('sv', {
        "query": "Sökuttryck",
        "baseQuery": "Skriv in ett sökuttryck för att visa en tidsserie.",
        "manualFilteredSplit": "Dela upp Sökuttryck 1 ovan i egna filtrerade tidsserier",
        "manualSplit": "Lägg till fler sökbegrepp för multipla tidsserier",
        "assistedSplit": "Dela upp Sökuttryck 1 ovan i förvalda tidsserier",
        "ok": "Skapa tidsserie",
        "cancel": "avbryt"
    });

    var _activeTab = 0;

    _splitContextViews = [
        { label: Silobreaker.Strings.getTranslation('manualSplit'), splitContextView: new Silobreaker.ManualSplitContextView() },
        { label: Silobreaker.Strings.getTranslation('assistedSplit'), splitContextView: new Silobreaker.AssistedSplitContextView() },
        { label: Silobreaker.Strings.getTranslation('manualFilteredSplit'), splitContextView: new Silobreaker.ManualFilteredSplitContextView() }
        ];

    this.splitContextViews = _splitContextViews;
    this.id = 'Silobreaker.SplitWizard';

    updateViewFromModel = function() {
        var primarySearch;

        if (_params.model.getPrimarySearch()) {
            primarySearch = _params.model.getPrimarySearch();
        }

        // Depending of model type, initialize the correct tab
        if (_params.model.constructor == Silobreaker.SplitModels.ManualSplitModel) {
            if (!_params.model.getSearchContext()) {
                _splitContextViews[0].splitContextView.setModel(_params.model);
                _activeTab = 0;
            } else if (primarySearch && primarySearch != '') {
                _splitContextViews[2].splitContextView.setModel(_params.model);
                _activeTab = 2;
            }
        } else if (_params.model.constructor == Silobreaker.SplitModels.AutoItemSplitModel && primarySearch && primarySearch != '') {
            _splitContextViews[1].splitContextView.setModel(_params.model);
            _activeTab = 1;
        }

        // Preset first text box to the models primary search when available
        if (primarySearch) {
            _params.query = primarySearch;
        }
    };

    if (params.model) {
        updateViewFromModel();
    }

    this.setModel = function(model) {
        _params.model = model;
        updateViewFromModel();
    };

    this.getActiveTab = function() {
        return _activeTab;
    };

    this.initialize = function(element) {
        _self.params.guiReference = element;
        _self.render();
    }

    this.render = function() {
        var splitWizard = jQuery('<div class="SB splitWizard"></div>');
        var escapedQuery = _self.params.query.replace(/\"/g, '&quot;');
        var baseQuery = jQuery('<div class="baseQuery queryInput"><div class="description">' + Silobreaker.Strings.getTranslation('baseQuery') + '</div>' + Silobreaker.Strings.getTranslation('query') + ' 1<input type="text" class="query" value="' + escapedQuery + '"></input></div>');
        var tabs = jQuery('<div class="accordion"></div>');

        splitWizard.append(baseQuery);
        splitWizard.append(tabs);

        for (var i = 0; i < _splitContextViews.length; i++) {
            var newTab = jQuery('<h3><a href="#">' + _splitContextViews[i].label + '</a></h3>');
            tabs.append(newTab);
            _splitContextViews[i].splitContextView.render(tabs, "tabContent tabContent-" + i);
        }

        var okCancel = jQuery('<div class="okcancel"></div>');
        var cancelButton = jQuery('<input type="button" value="' + Silobreaker.Strings.getTranslation('cancel') + '"/>');
        var okButton = jQuery('<input type="button" value="' + Silobreaker.Strings.getTranslation('ok') + '"/>');

        okButton.click(function() {
            var clickedTab = jQuery(_self.params.guiReference).find('.accordion').accordion('option', 'active');
            if (clickedTab instanceof jQuery) {
                clickedTab = jQuery(_self.params.guiReference).find('.accordion .tabContent').index(clickedTab)
            }
            var baseQuery = jQuery(_self.params.guiReference).find('.baseQuery input').val();
            var splitContext = _self.splitContextViews[clickedTab].splitContextView.getSplitContext(baseQuery);
            if (jQuery.isFunction(_self.params.splitContextChanged)) {
                _self.params.splitContextChanged(splitContext);

            }
        });
        okCancel.append(okButton);
        /*okCancel.append(cancelButton);*/

        splitWizard.append(okCancel);


        jQuery(splitWizard).keydown(function(event) { if (event.keyCode == 13) { event.preventDefault(); return false; } });
        jQuery(_params.guiReference).append(splitWizard);
        jQuery(_params.guiReference).append('<div style="clear:both"></div>');

        tabs.accordion({ clearStyle: true, active: _activeTab });
        //tabs.accordion("activate", _activeTab);

    }

    //this.render();

};

Silobreaker.ManualSplitContextView = function(model) {

    var _element;
    this.element = _element;
    var _self = this;
    this.model = model;

    Silobreaker.Strings.add('en', { "manualSplitDescription": "Add additional queries for multiple Time Series.", "query": "Query" });
    Silobreaker.Strings.add('sv', { "manualSplitDescription": "Lägg till fler sökbegrepp för multipla tidsserier.", "query": "Sökuttryck" });

    this.setModel = function(model) {
        _self.model = model;
    };

    this.render = function(guiReference, cssClass) {

        var newElement = jQuery('<div class="splitContext manualSplitContext ' + cssClass + '"></div>');

        for (var i = 0; i < 3; i++) {
            var content = '';

            if (_self.model && _self.model.getSearchStrings()[i + 1]) {
                content = _self.model.getSearchStrings()[i + 1].replace(/\"/g, '&quot;');
            }

            var s = '<div class="queryInput">' + Silobreaker.Strings.getTranslation('query') + ' ' + (i + 2) + '<input class="query" type="text" value="' + content + '"></input></div>';
            newElement.append(s);
        }

        guiReference.append(newElement);
        _self.element = newElement;
    };

    this.getSplitContext = function(mainSearch) {
        var queries = [];

        if (mainSearch && mainSearch.length > 0) {
            queries.push(mainSearch);
        };

        _self.element.find(".query").each(function() {
            var value = jQuery(this).val();
            if (value.length > 0) {
                queries.push(value);
            }
        });

        return new Silobreaker.SplitModels.ManualSplitModel(queries);
    };

};

Silobreaker.ManualFilteredSplitContextView = function(model) {

    var _element;
    this.element = _element;
    var _self = this;
    this.model = model;

    Silobreaker.Strings.add('en', { "serie": "Filter" });
    Silobreaker.Strings.add('sv', { "serie": "Filter" });

    this.setModel = function(model) {
        _self.model = model;
    };


    this.render = function(guiReference, cssClass) {

        var newElement = jQuery('<div class="splitContext manualFilteredSplitContext ' + cssClass + '"></div>');

        for (var i = 0; i < 3; i++) {
            var content = '';

            if (_self.model && _self.model.getSearchStrings()[i]) {
                content = _self.model.getSearchStrings()[i].replace(/\"/g, '&quot;');
            }

            var s = '<div class="queryInput">' + Silobreaker.Strings.getTranslation('serie') + ' ' + (i + 1) + '<input class="query" type="text" value="' + content + '"></input></div>';
            newElement.append(s);
        }

        guiReference.append(newElement);
        _self.element = newElement;
    };

    this.getSplitContext = function(mainSearch) {
        var queries = [];

        _self.element.find(".query").each(function() {
            var value = jQuery(this).val();
            if (value.length > 0) {
                queries.push(value);
            }
        });

        return new Silobreaker.SplitModels.ManualSplitModel(queries, mainSearch);
    };

};


Silobreaker.AssistedSplitContextView = function(model) {

    var _element;
    this.element = _element;
    this.model = model;
    var _self = this;

    Silobreaker.Strings.add('en', {
        "assistedSplitDescription": "Select how you would like to split the data.",
        "byDocumentType": "By Document Type",
        "byPublication": "By Publication",
        "bySourceCountry": "By Source Country",
        "numberOfSplits": "Select number of series"
    });
    Silobreaker.Strings.add('sv', {
        "assistedSplitDescription": "Välj hur du vill dela upp din data .",
        "byDocumentType": "Per dokumenttyp",
        "byPublication": "Per publikation",
        "bySourceCountry": "Per publikationsland",
        "numberOfSplits": "Välj antal serier"
    });

    this.setModel = function(model) {
        _self.model = model;
    };


    this.render = function(guiReference, cssClass) {

        var splitTypes = ['docType', 'publication', 'sourceCountry'];
        var splitNames = ['byDocumentType', 'byPublication', 'bySourceCountry'];
        var numberOfSplitOptions = [2, 3, 4, 5, 10];

        var selectedSplitType = 'docType';
        var numberOfSplits = 2;
        if (_self.model) {
            selectedSplitType = _self.model.getSplitType();
            numberOfSplits = _self.model.getNumberOfSplits();
        }

        var newElement = jQuery('<div class="splitContext assistedSplitContext ' + cssClass + '"></div>');
        for (var i = 0; i < splitTypes.length; i++) {
            var checked = (selectedSplitType == splitTypes[i] ? 'checked="checked"' : '');
            var radioElement = jQuery('<div><input type="radio" name="splitType" value="' + splitTypes[i] + '"/>' + Silobreaker.Strings.getTranslation(splitNames[i]) + '</div>');
            if (selectedSplitType == splitTypes[i]) {
                radioElement.find('input').attr("checked", true);
            }
            newElement.append(radioElement);
        }

        var options = '';
        for (var i = 0; i < numberOfSplitOptions.length; i++) {
            var selected = (numberOfSplits == numberOfSplitOptions[i] ? 'selected' : '');
            options += '<option ' + selected + '>' + numberOfSplitOptions[i] + '</option>'
        }

        newElement.append('<div class="noSplits">' + Silobreaker.Strings.getTranslation('numberOfSplits') + ': <select class="noSplits">' + options + '</select></div>');

        guiReference.append(newElement);
        _self.element = newElement;
    };

    this.getSplitContext = function(mainSearch) {
        var checkedElement = _self.element.find('input[name="splitType"]:checked');
        var noSplits = _self.element.find('option:selected').val();
        var splitType = jQuery(checkedElement).val();
        return new Silobreaker.SplitModels.AutoItemSplitModel(mainSearch, splitType, noSplits);
    };

};

Silobreaker.SplitWizard.prototype.defaultCss = '.SB.splitWizard{    overflow: auto;    background-color:white;    border: 1px solid gray;    }.SB.splitWizard .baseQuery{    padding:10px;      border-bottom: 1px solid gray;}.SB.splitWizard .queryInput{    font-size:12px;}.SB.splitWizard input[type=text]{       /*width:300px;*/       margin-left:5px;}.SB.splitWizard .ui-accordion{    margin-top:10px;    padding-left:15px;    padding-right:15px;}.SB.splitWizard .ui-accordion-content{    /*border: 1px solid #AAA;*/    padding:5px;}.SB.splitWizard h3{        font-size:14px;    font-weight:normal;    margin:0px;    padding:0px;}.SB.splitWizard h3 a{    text-decoration:none;      color:#606060; }.SB.splitWizard h3.ui-state-active a{    text-decoration:none;      color:#303030; }.SB.splitWizard .ui-accordion-header{    border-bottom: 1px solid lightGrey;}.SB.splitWizard .ui-accordion-header.ui-state-active{    border-bottom: 1px solid lightGrey;    }.SB.splitWizard .ui-state-active .ui-icon {        }.SB.splitWizard .ui-icon{    background-image: url(http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/images/ui-icons_454545_256x240.png);    height: 16px;    width: 16px;    float:left;    background-repeat: no-repeat;    display: block;    overflow: hidden;        margin-top: 2px;}.SB.splitWizard .ui-icon-triangle-1-s {    background-position: -64px -16px;}.SB.splitWizard .ui-icon-triangle-1-e {    background-position: -32px -16px;}.SB.splitWizard .description{    font-size:14px;    margin-bottom:10px;}.SB.splitWizard .okcancel{                float:right;    margin:10px;    font-size:14px;    }.SB.splitWizard .tabs ul li.selected {    background-color:white;}.SB.splitWizard .splitContext .description{    padding: 5px 5px 5px 5px;}.SB.splitWizard .assistedSplitContext .noSplits{    margin-top:10px;}.SB.splitWizard .assistedSplitContext .listEntities select{    font-size:80%;}';
Silobreaker.EntitySummary.prototype.htmlTemplate = '<div class="SB widget entitySummary" style="width:400px;">    <div style="display:none;">        <div class="contentTemplate">        <!--data-->            <div>                                                    <div>                    <table>                        <tr>                            <td rowspan="3">                                <!--Images-->                                <img @#ImageSrc@ style="margin:18px 10px 0px 0px; vertical-align:top" width="@Width@" height="@Height@"/ >                                <!--Images-->                                </td>                        </tr>                                                <tr>                           <td>                               <div class="centered"><a itemref="@Id@"><span class="entityName">@Description@</span></a><span class="entityType"> (@LocalizedType@)</span></div>                           </td>                        </tr>                        <tr>                            <td>                                <div class="propertyList">                                <!--TextFields-->                                <div><b>@Key@:</b> @Value@</div>                                <!--TextFields-->                                <!--ItemFields-->                                <div><b>@Key@:</b> <!--Value--><a itemref="@Id@">@Description@</a><!--Value--></div>                                <!--ItemFields-->                                                    </div>                            </td>                            </tr>                    </table>                </div>                             <!--Evidence-->                <div class="inContext">                    <div class="heading">In Context</div>                    <div class="evidenceText">@#HtmlSnippet@</div>                    <div class="link"><!--SnippetSource--><a itemref="@Id@">@Description@</a> <span class="publication"><nobr>[@Publisher@ - @PrettyPublicationDate@]</nobr></span><!--SnippetSource--></div>                </div>                <!--Evidence-->                   <div style="clear:both;">                    <div class="listHeading">Lastest stories</div>                    <div class="relatedDocuments"></div>                </div>                        </div>        <!--data-->         </div>    </div>    <div class="content"><div class="loading">Loading...</div></div></div>';
Silobreaker.EntitySummary.prototype.defaultCss = '.SB.entitySummary{    background-color: #F8F8FF;	line-height:normal;}.SB.entitySummary img{    padding: 5px 5px 5px 5px;    }.SB.entitySummary .entityName{    font-weight:bold;    font-size:14px;  }.SB.entitySummary .propertyList{    line-height:1.5;    float:left;}.SB.entitySummary .listHeading{        font-size:12px;    border-bottom:solid 1px silver;    margin-top: 12px;}.SB.entitySummary .publication{	text-align: right;    color:Gray;    font-size: .8em;}.SB.entitySummary .header{    text-align:center;    margin-bottom:6px;}/* Set background color of doucment list */.SB.entitySummary .SB.documents{    background-color:#F8F8FF;  }';
Silobreaker.Documents.prototype.htmlTemplate = '<div class="SB widget documents" style="min-height: 30px;">    <div style="display:none;">        <div class="contentTemplate">            <!--data-->                    <!--Items-->                    <div class="document"><a itemref="@Id@" @#SourceUrlRef@>@Description@</a>                    <span class="publication"><nobr>[@Publisher@ - @PrettyPublicationDate@]</nobr></span>                    <p class="teaser">@Teaser@</p></div>                    <!--Items-->            <!--data-->        </div>    </div>    <div class="content"></div></div>';
Silobreaker.Documents.prototype.defaultCss = '.SB.documents{		border: none;    padding: 0px 5px 5px 5px;}.SB.documents .document{    margin-bottom:6px;    line-height:1;}.SB.documents .teaser{    margin: 3px 5px 5px 5px;    color: #606060;    }.SB.documents .publication{	text-align: right;    color:Gray;    font-size: .8em;}.SB.documents .pagination b{    color:#B06000;    font-size:110%;}';
Silobreaker.Evidence.prototype.htmlTemplate = '<div class="SB widget evidence">    <div style="display:none;">        <div class="contentTemplate">        <!--data-->            <div class="heading">Documents indicating a relationship between @node1@ and @node2@ in context @context@.</div>            <!--Evidence-->            <div class="inContext">                <div class="heading">In Context</div>                <div class="evidenceText">@#HtmlSnippet@</div>                <div class="link"><!--SnippetSource--></nobr><a itemref="@Id@">@Description@</a> <span class="publication"><nobr>[@Publisher@ - @PrettyPublicationDate@]</nobr></span><!--SnippetSource--></div>            </div>                            <!--Evidence-->        <!--data-->        </div>    </div>    <div class="content"><div class="loading">Loading...</div></div>     <div class="evidenceDocuments"></div>    <div class="searchFurther"><a class="searchFurtherAnchor">Search further</a></div></div>';
Silobreaker.Evidence.prototype.defaultCss = '.SB.evidence{	background-color: #F8F8FF;	padding: 5px 5px 5px 5px;	width: 400px;	border: solid 1px #707070;}.SB.evidence .inContext{    margin-top:10px;    margin-bottom:10px;}.SB.evidence .searchFurther{	padding-top: 1em;	text-align: right;}.SB.evidence .publication{	text-align: right;    color:Gray;    font-size: .8em;}';
Silobreaker.InFocus.prototype.htmlTemplate = '<div class="SB widget inFocus">    <div style="display:none;">        <div class="contentTemplate">            <!--data-->            <div class="typeList">                   <div class="icon @TypeClass@"></div>                             <div class="entities">                                        <!--Items-->                    <span class="entity"><a itemref="@id@"><nobr>@Description@</nobr></a><span class="separator">,</span></span>                    <!--Items-->                    <a class="showMore" data="@Type@">[more]</a>                </div>            </div>                        <!--data-->        </div>    </div>    <div class="content"><div class="loading">Loading...</div></div></div>';
Silobreaker.InFocus.prototype.defaultCss = '.SB.inFocus{    overflow:auto;}.SB.inFocus .typeList{    clear:both;}.SB.inFocus .icon{    margin: 3px 3px 3px 3px;}.SB.inFocus .showMore{    color:Gray;    font-size:80%;    cursor:pointer;    }.SB.inFocus .entities{	margin-top:5px;       line-height: 140%;        margin-left:30px;    }';
Silobreaker.Network.prototype.htmlTemplate = '<div class="SB widget network">    <div class="content">        <div class="networkDiv">        </div>    </div></div>';
Silobreaker.Network.prototype.defaultCss = '.SB.widget.network{	    background-color:#f7fafb;}.SB .networkIcon{    background-position:0 -751px;}.SB.network .content{    clear:both;}.SB.network.widget .content{		padding: 0px 0px 0px 0px;}.SB.widget.entitySummary .content{    padding: 5px;}.SB.widget.documents .content, .SB.widget.evidence .content{		border: none;}';
Silobreaker.TopStories.prototype.htmlTemplate = '<div class="SB widget topstories">    <div style="display:none;">        <div class="contentTemplate">            <!--data-->                <div class="story story@StoryGroup@">                    <div class="discreet">First Reported @PrettyFirstReported@ - Updated @PrettyLastUpdated@ - @NoDocuments@ documents</div>                    <div class="floatLeft"><!--Images--><img class="image" @#ImageSrc@ /><div class="imageText">@Description@</div><!--Images--></div>                     <div class="headline"><a itemref="@Id@" target="_blank" @#SourceUrlRef@>@Description@</a></div>                    <div class="teaser">@#HtmlSnippet@ <span class="publication"><nobr><a itemref="@Id@" target="_blank" @#SourceUrlRef@>[@Publisher@ - @PrettyPublicationDate@]</a></nobr></span>                    </div>                      <div class="entities" context="itemref:@Id@"><span class="discreet">Entities:</span><!--RelatedEntities--> <a itemref="@Id@">@Description@</a><!--RelatedEntities--></div>                </div>                               <!--data-->                    </div>    </div>    <div class="content"><div class="loading">Loading...</div></div></div>';
Silobreaker.TopStories.prototype.defaultCss = '.SB.topstories{    overflow:auto;}.SB.topstories .content{    padding:5px 5px 5px 5px;}.SB.topstories .image{    margin:5px 10px 5px 5px;}.SB.topstories .imageText{    width:80px;    text-align:center;    font-size: 85%;    color: #606060;    padding-right: 5px;}.SB.topstories .headline{	    font-size:1.2em;	font-weight:bold;	color:#303030;	margin-bottom:5px;    margin-top:5px;}.SB.topstories .story{    margin-bottom:18px;}.SB.topstories .teaser{    margin-bottom:6px;}.SB.topstories .story0{    font-size:120%;}.SB.topstories .story1, .SB.topstories .story2, .SB.topstories .story3, .SB.topstories .story4{    width: 45%;        float:left;}.SB.topstories .story2, .SB.topstories .story4{    padding-left:2%;}.SB.topstories .story0, .SB.topstories .story1, .SB.topstories .story3{    clear:left;    }';
Silobreaker.defaultCss = '/* *************************** *//* General CSS for all widgets *//* *************************** */.SB {    font-size: 8.25pt;    font-family: Tahoma;    line-height: normal;        background-color: #ffffff;    color:#333333;}.SB.siloLink{    font-size:8px;    float:left;    margin-top:-12px;    margin-left:3px;    color:gray;    text-decoration:none}.SB img{    border-style:none;    padding:0px 0px 0px 0px;    margin:0px 0px 0px 0px;}.SB .centered{    text-align:center;}.SB .floatLeft{    float:left;}.SB A{    cursor:pointer;    text-decoration: none;    color: #404080;}.SB A:hover{    color:#E2904E;    text-decoration:underline;}.SB .heading{	font-size:13px;	font-weight:bold;	color:#303030;}.SB.widget{	    padding:0px;    border: solid 1px #A0A0C0;    position: static;}.SB.widget .content{		padding: 5px 5px 5px 5px;	position: static;}.SB .header{    color:Gray;    min-height:22px;    border-bottom: solid 1px #A0A0C0;    background: url("http://api.silobreaker.com/Content/bluegradient.png") 0 0;}.SB .header img{    border:0px;    float:right;    margin-top:1px;    margin-right:3px;}.SB .header .infotext{    padding: 4px 0px 5px 10px;}.SB .header .helptext{     position:absolute;      width:250px;      background-color:#ffffff;      padding:5px;      border:solid 1px #ed6934;}.SB .header .helptext .title{    font-size:1.2em;     font-weight:bold;        margin-bottom:10px;}.SB .header .helptext .close{    float:right;    cursor:pointer;    margin-top:5px;    margin-left:5px;}.SB .footer{    height:17px;    clear:both;        border:0px;    padding: 3px 0px 3px 0px;}.SB .footer img{    border:0px;    height:15px;    margin-right:3px;    float:right;}.SB .loading{    color: #A0A0C0;    text-align:center;}.SB .discreet{    color: #606060;    font-size:90%;   }.SB.widget tr td{    vertical-align:middle;    padding:0px !important;}/**************//* In Context *//**************/.SB .inContext{        background-color:white;    border:solid 1px #404040;    margin-left:10%;    margin-right:10%;    margin-top:6px;    clear:both;}.SB .inContext .heading{	font-size:11px;	font-weight:bold;	border-bottom:solid 1px #404040;	padding:3px 3px 3px 6px;}.SB .inContext .link{	/*margin-top:2px;*/	text-align:right;	padding:1px 6px 3px 1px;}.SB .inContext .evidenceText {padding:6px;}/**********************//* Small Entity Icons *//**********************/.SB .icon{    background: transparent url("http://www.silobreaker.com/Images/icons_s_7.png") no-repeat scroll 0 0;        width:17px;    height:17px;    float: left;}.SB .Person{    background-position: 0px -852px;}.SB .Company{    background-position: 0px -515px;}.SB .Organization{    background-position: 0px -805px;}.SB .Keyphrase{    background-position: 0px -705px;}.SB .City{    background-position: 0px -468px;}.SB .Country{    background-position: 0px -560px;}.SB .SportsTeam {     background-position: 0 -1380px; } .SB .MusicBand {     background-position: 0 -1350px; }.SB .Product{     background-position: 0 -1408px; }';
Silobreaker.Tabs.prototype.htmlTemplate = '<div style="display:none;">    <div class="contentTemplate"><!--data--><span class="tab @#cssClass@">@title@</span><!--data--></div></div><div class="tabs content"></div>';
Silobreaker.TabDocuments.prototype.htmlTemplate = '<div class="SB widget tabDocuments">    <div class="tabsPlaceholder"></div>    <div class="documentsPlaceholder"></div></div>';
Silobreaker.TabDocuments.prototype.defaultCss = '.SB.widget.tabDocuments .content{		padding: 0px 0px 0px 0px;		}.tabs .contentTemplate{            border-bottom:1px solid #606060;    margin:0px 0px 10px 0px;    padding: 0px 5px 0px 5px;    background-color:#F0F0F0;  }.SB span.tab{	            margin:5px 3px -1px 0px;    padding:2px 5px 0px 5px;    display: inline-block; 	    cursor:pointer;        border:1px solid #606060;	border-bottom-color:gray;	font-size:120%;					    white-space:nowrap;  	background-image: url("http://www.silobreaker.com/Images/grd_s_1.png");	background-position: 0px -43px;}.SB span.selected {    background-position: 0px -154px;        border-bottom-color: #e5caa3;    }';
Silobreaker.MetaSearch.prototype.htmlTemplate = '<div class="SB widget metaSearch">    <div style="display:none;">        <div class="contentTemplate">            <!--data-->                    <!--Items-->                    <div class="msRow">                    <div class="msIcon @CssClass@" title="@Provider@"></div><div class="msEntry"><div class="msContent">@#Content@</div>                    <div class="msLinks"><!--RelatedLinks--><div><a href="@HRef@" title="@Alt@" target="_blank">@Name@</a><div>@Description@</div></div><!--RelatedLinks--></div>                    <div class="msInfo"><span class="msUpdated">@#PrettyUpdatedDate@</span> from <span class="msAuthor">@#author@</span> via <span class="msProvider">@Provider@</span></div></div>                                       </div>                    <!--Items-->            <!--data-->        </div>    </div>        <div class="msSettings">autorefresh:<input type="checkbox" class="msRefresh" title="auto refresh"/></div>    <div class="content"><div class="loading">Loading...</div></div>    <div class="msError"></div></div>';
Silobreaker.MetaSearch.prototype.defaultCss = '.SB.metaSearch{    overflow:auto;    font-size:11px;     font-family:Verdana;   }.SB.metaSearch .content{    height:500px;    overflow:auto;}.SB.metaSearch .error{    color:Red;    font-size:8px;    margin-left:5px;    padding-top:2px;    text-align:center;}.SB.metaSearch .msRow{    border-bottom: solid 1px #D0D0D0;    padding-bottom: 6px;    padding-top: 6px;        }.SB.metaSearch .msEntry{    overflow:hidden;}.SB.metaSearch .msIcon.msGoogleBuzz{    background-position: 0 -1950px;}.SB.metaSearch .msIcon.msGoogleBlogSearch{    background-position: 0 -1870px;}.SB.metaSearch .msIcon.msTwitter{    background-position: 0 -1740px;}.SB.metaSearch .msIcon.msTwitter{    background-position: 0 -1740px;}.SB.metaSearch .msIcon.msFacebook{    background-position: 0 -1836px;}.SB.metaSearch .msIcon{    background-image: url(http://sbstatic.com/Images/icons_s_11.png);	    background-repeat: no-repeat;	width: 24px;	height: 24px;	float:left;	margin: 5px 5px 5px 5px;	}.SB.metaSearch .msLinks{    padding-left:15px;    padding-top:5px;        }.SB.metaSearch .msInfo{	    padding-top:6px;    color:Gray;        font-style:italic;}.SB.metaSearch .msUpdate{    border-bottom:1px solid silver;    color:silver;    font-style:italic;    font-weight:bold;    text-align:center;    	}.SB.metaSearch .msSettings{	    font-size:9px;    border-bottom:solid 1px silver;    text-align:right;    background-color:#F0F0F0;    font-style:italic;    color:Gray;}.SB.metaSearch .msSettings input{    vertical-align:middle;	}.SB.metaSearch .title{    font-weight:bold;    margin-bottom:5px;    color:Black;}';
Silobreaker.DocumentVolume.prototype.defaultCss = '.SB.documentVolume .showHideDocs{    float:right;    margin:4px;}.SB.documentVolume .documentArea{    clear:both;}.SB.documentVolume .queryfilter{    background-color:#FFFFC0;    border:1px solid #E0E0E0;    padding: 0px 4px 0px 4px;    color:Black;    margin:3px;    padding:3px;}.SB.documentVolume .queryfilter{    background-color:#FFFFC0;    border:1px solid #E0E0E0;    overflow:auto;}.SB.documentVolume .clearQuery{    display:none;    float:right;    cursor:pointer;}.SB.documentVolume .SB.documents{    border:none;}';
if (typeof(Sys) != 'undefined' && typeof(Sys.Application) != 'undefined') {Sys.Application.notifyScriptLoaded();}


