 

(function(b){var m,u,x,g,D,i,z,A,B,p=0,e={},q=[],n=0,c={},j=[],E=null,s=new Image,G=/\.(jpg|gif|png|bmp|jpeg)(.*)?$/i,S=/[^\.]\.(swf)\s*$/i,H,I=1,k,l,h=false,y=b.extend(b("<div/>")[0],{prop:0}),v=0,O=!b.support.opacity&&!window.XMLHttpRequest,J=function(){u.hide();s.onerror=s.onload=null;E&&E.abort();m.empty()},P=function(){b.fancybox('<p id="fancybox_error">The requested content cannot be loaded.<br />Please try again later.</p>',{scrolling:"no",padding:20,transitionIn:"none",transitionOut:"none"})},
K=function(){return[b(window).width(),b(window).height(),b(document).scrollLeft(),b(document).scrollTop()]},T=function(){var a=K(),d={},f=c.margin,o=c.autoScale,t=(20+f)*2,w=(20+f)*2,r=c.padding*2;if(c.width.toString().indexOf("%")>-1){d.width=a[0]*parseFloat(c.width)/100-40;o=false}else d.width=c.width+r;if(c.height.toString().indexOf("%")>-1){d.height=a[1]*parseFloat(c.height)/100-40;o=false}else d.height=c.height+r;if(o&&(d.width>a[0]-t||d.height>a[1]-w))if(e.type=="image"||e.type=="swf"){t+=r;
w+=r;o=Math.min(Math.min(a[0]-t,c.width)/c.width,Math.min(a[1]-w,c.height)/c.height);d.width=Math.round(o*(d.width-r))+r;d.height=Math.round(o*(d.height-r))+r}else{d.width=Math.min(d.width,a[0]-t);d.height=Math.min(d.height,a[1]-w)}d.top=a[3]+(a[1]-(d.height+40))*0.5;d.left=a[2]+(a[0]-(d.width+40))*0.5;if(c.autoScale===false){d.top=Math.max(a[3]+f,d.top);d.left=Math.max(a[2]+f,d.left)}return d},U=function(a){if(a&&a.length)switch(c.titlePosition){case "inside":return a;case "over":return'<span id="fancybox-title-over">'+
a+"</span>";default:return'<span id="fancybox-title-wrap"><span id="fancybox-title-left"></span><span id="fancybox-title-main">'+a+'</span><span id="fancybox-title-right"></span></span>'}return false},V=function(){var a=c.title,d=l.width-c.padding*2,f="fancybox-title-"+c.titlePosition;b("#fancybox-title").remove();v=0;if(c.titleShow!==false){a=b.isFunction(c.titleFormat)?c.titleFormat(a,j,n,c):U(a);if(!(!a||a==="")){b('<div id="fancybox-title" class="'+f+'" />').css({width:d,paddingLeft:c.padding,
paddingRight:c.padding}).html(a).appendTo("body");switch(c.titlePosition){case "inside":v=b("#fancybox-title").outerHeight(true)-c.padding;l.height+=v;break;case "over":b("#fancybox-title").css("bottom",c.padding);break;default:b("#fancybox-title").css("bottom",b("#fancybox-title").outerHeight(true)*-1);break}b("#fancybox-title").appendTo(D).hide()}}},W=function(){b(document).unbind("keydown.fb").bind("keydown.fb",function(a){if(a.keyCode==27&&c.enableEscapeButton){a.preventDefault();b.fancybox.close()}else if(a.keyCode==
37){a.preventDefault();b.fancybox.prev()}else if(a.keyCode==39){a.preventDefault();b.fancybox.next()}});if(b.fn.mousewheel){g.unbind("mousewheel.fb");j.length>1&&g.bind("mousewheel.fb",function(a,d){a.preventDefault();h||d===0||(d>0?b.fancybox.prev():b.fancybox.next())})}if(c.showNavArrows){if(c.cyclic&&j.length>1||n!==0)A.show();if(c.cyclic&&j.length>1||n!=j.length-1)B.show()}},X=function(){var a,d;if(j.length-1>n){a=j[n+1].href;if(typeof a!=="undefined"&&a.match(G)){d=new Image;d.src=a}}if(n>0){a=
j[n-1].href;if(typeof a!=="undefined"&&a.match(G)){d=new Image;d.src=a}}},L=function(){i.css("overflow",c.scrolling=="auto"?c.type=="image"||c.type=="iframe"||c.type=="swf"?"hidden":"auto":c.scrolling=="yes"?"auto":"visible");if(!b.support.opacity){i.get(0).style.removeAttribute("filter");g.get(0).style.removeAttribute("filter")}b("#fancybox-title").show();c.hideOnContentClick&&i.one("click",b.fancybox.close);c.hideOnOverlayClick&&x.one("click",b.fancybox.close);c.showCloseButton&&z.show();W();b(window).bind("resize.fb",
b.fancybox.center);c.centerOnScroll?b(window).bind("scroll.fb",b.fancybox.center):b(window).unbind("scroll.fb");b.isFunction(c.onComplete)&&c.onComplete(j,n,c);h=false;X()},M=function(a){var d=Math.round(k.width+(l.width-k.width)*a),f=Math.round(k.height+(l.height-k.height)*a),o=Math.round(k.top+(l.top-k.top)*a),t=Math.round(k.left+(l.left-k.left)*a);g.css({width:d+"px",height:f+"px",top:o+"px",left:t+"px"});d=Math.max(d-c.padding*2,0);f=Math.max(f-(c.padding*2+v*a),0);i.css({width:d+"px",height:f+
"px"});if(typeof l.opacity!=="undefined")g.css("opacity",a<0.5?0.5:a)},Y=function(a){var d=a.offset();d.top+=parseFloat(a.css("paddingTop"))||0;d.left+=parseFloat(a.css("paddingLeft"))||0;d.top+=parseFloat(a.css("border-top-width"))||0;d.left+=parseFloat(a.css("border-left-width"))||0;d.width=a.width();d.height=a.height();return d},Q=function(){var a=e.orig?b(e.orig):false,d={};if(a&&a.length){a=Y(a);d={width:a.width+c.padding*2,height:a.height+c.padding*2,top:a.top-c.padding-20,left:a.left-c.padding-
20}}else{a=K();d={width:1,height:1,top:a[3]+a[1]*0.5,left:a[2]+a[0]*0.5}}return d},N=function(){u.hide();if(g.is(":visible")&&b.isFunction(c.onCleanup))if(c.onCleanup(j,n,c)===false){b.event.trigger("fancybox-cancel");h=false;return}j=q;n=p;c=e;i.get(0).scrollTop=0;i.get(0).scrollLeft=0;if(c.overlayShow){O&&b("select:not(#fancybox-tmp select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one("fancybox-cleanup",function(){this.style.visibility="inherit"});
x.css({"background-color":c.overlayColor,opacity:c.overlayOpacity}).unbind().show()}l=T();V();if(g.is(":visible")){b(z.add(A).add(B)).hide();var a=g.position(),d;k={top:a.top,left:a.left,width:g.width(),height:g.height()};d=k.width==l.width&&k.height==l.height;i.fadeOut(c.changeFade,function(){var f=function(){i.html(m.contents()).fadeIn(c.changeFade,L)};b.event.trigger("fancybox-change");i.empty().css("overflow","hidden");if(d){i.css({top:c.padding,left:c.padding,width:Math.max(l.width-c.padding*
2,1),height:Math.max(l.height-c.padding*2-v,1)});f()}else{i.css({top:c.padding,left:c.padding,width:Math.max(k.width-c.padding*2,1),height:Math.max(k.height-c.padding*2,1)});y.prop=0;b(y).animate({prop:1},{duration:c.changeSpeed,easing:c.easingChange,step:M,complete:f})}})}else{g.css("opacity",1);if(c.transitionIn=="elastic"){k=Q();i.css({top:c.padding,left:c.padding,width:Math.max(k.width-c.padding*2,1),height:Math.max(k.height-c.padding*2,1)}).html(m.contents());g.css(k).show();if(c.opacity)l.opacity=
0;y.prop=0;b(y).animate({prop:1},{duration:c.speedIn,easing:c.easingIn,step:M,complete:L})}else{i.css({top:c.padding,left:c.padding,width:Math.max(l.width-c.padding*2,1),height:Math.max(l.height-c.padding*2-v,1)}).html(m.contents());g.css(l).fadeIn(c.transitionIn=="none"?0:c.speedIn,L)}}},F=function(){m.width(e.width);m.height(e.height);if(e.width=="auto")e.width=m.width();if(e.height=="auto")e.height=m.height();N()},Z=function(){h=true;e.width=s.width;e.height=s.height;b("<img />").attr({id:"fancybox-img",
src:s.src,alt:e.title}).appendTo(m);N()},C=function(){J();var a=q[p],d,f,o,t,w;e=b.extend({},b.fn.fancybox.defaults,typeof b(a).data("fancybox")=="undefined"?e:b(a).data("fancybox"));o=a.title||b(a).title||e.title||"";if(a.nodeName&&!e.orig)e.orig=b(a).children("img:first").length?b(a).children("img:first"):b(a);if(o===""&&e.orig)o=e.orig.attr("alt");d=a.nodeName&&/^(?:javascript|#)/i.test(a.href)?e.href||null:e.href||a.href||null;if(e.type){f=e.type;if(!d)d=e.content}else if(e.content)f="html";else if(d)if(d.match(G))f=
"image";else if(d.match(S))f="swf";else if(b(a).hasClass("iframe"))f="iframe";else if(d.match(/#/)){a=d.substr(d.indexOf("#"));f=b(a).length>0?"inline":"ajax"}else f="ajax";else f="inline";e.type=f;e.href=d;e.title=o;if(e.autoDimensions&&e.type!=="iframe"&&e.type!=="swf"){e.width="auto";e.height="auto"}if(e.modal){e.overlayShow=true;e.hideOnOverlayClick=false;e.hideOnContentClick=false;e.enableEscapeButton=false;e.showCloseButton=false}if(b.isFunction(e.onStart))if(e.onStart(q,p,e)===false){h=false;
return}m.css("padding",20+e.padding+e.margin);b(".fancybox-inline-tmp").unbind("fancybox-cancel").bind("fancybox-change",function(){b(this).replaceWith(i.children())});switch(f){case "html":m.html(e.content);F();break;case "inline":b('<div class="fancybox-inline-tmp" />').hide().insertBefore(b(a)).bind("fancybox-cleanup",function(){b(this).replaceWith(i.children())}).bind("fancybox-cancel",function(){b(this).replaceWith(m.children())});b(a).appendTo(m);F();break;case "image":h=false;b.fancybox.showActivity();
s=new Image;s.onerror=function(){P()};s.onload=function(){s.onerror=null;s.onload=null;Z()};s.src=d;break;case "swf":t='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+e.width+'" height="'+e.height+'"><param name="movie" value="'+d+'"></param>';w="";b.each(e.swf,function(r,R){t+='<param name="'+r+'" value="'+R+'"></param>';w+=" "+r+'="'+R+'"'});t+='<embed src="'+d+'" type="application/x-shockwave-flash" width="'+e.width+'" height="'+e.height+'"'+w+"></embed></object>";m.html(t);
F();break;case "ajax":a=d.split("#",2);f=e.ajax.data||{};if(a.length>1){d=a[0];if(typeof f=="string")f+="&selector="+a[1];else f.selector=a[1]}h=false;b.fancybox.showActivity();E=b.ajax(b.extend(e.ajax,{url:d,data:f,error:P,success:function(r){if(E.status==200){m.html(r);F()}}}));break;case "iframe":b('<iframe id="fancybox-frame" name="fancybox-frame'+(new Date).getTime()+'" frameborder="0" hspace="0" scrolling="'+e.scrolling+'" src="'+e.href+'"></iframe>').appendTo(m);N();break}},$=function(){if(u.is(":visible")){b("div",
u).css("top",I*-40+"px");I=(I+1)%12}else clearInterval(H)},aa=function(){if(!b("#fancybox-wrap").length){b("body").append(m=b('<div id="fancybox-tmp"></div>'),u=b('<div id="fancybox-loading"><div></div></div>'),x=b('<div id="fancybox-overlay"></div>'),g=b('<div id="fancybox-wrap"></div>'));if(!b.support.opacity){g.addClass("fancybox-ie");u.addClass("fancybox-ie")}D=b('<div id="fancybox-outer"></div>').append('<div class="fancy-bg" id="fancy-bg-n"></div><div class="fancy-bg" id="fancy-bg-ne"></div><div class="fancy-bg" id="fancy-bg-e"></div><div class="fancy-bg" id="fancy-bg-se"></div><div class="fancy-bg" id="fancy-bg-s"></div><div class="fancy-bg" id="fancy-bg-sw"></div><div class="fancy-bg" id="fancy-bg-w"></div><div class="fancy-bg" id="fancy-bg-nw"></div>').appendTo(g);
D.append(i=b('<div id="fancybox-inner"></div>'),z=b('<a id="fancybox-close"></a>'),A=b('<a href="javascript:;" id="fancybox-left"><span class="fancy-ico" id="fancybox-left-ico"></span></a>'),B=b('<a href="javascript:;" id="fancybox-right"><span class="fancy-ico" id="fancybox-right-ico"></span></a>'));z.click(b.fancybox.close);u.click(b.fancybox.cancel);A.click(function(a){a.preventDefault();b.fancybox.prev()});B.click(function(a){a.preventDefault();b.fancybox.next()});if(O){x.get(0).style.setExpression("height",
"document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px'");u.get(0).style.setExpression("top","(-20 + (document.documentElement.clientHeight ? document.documentElement.clientHeight/2 : document.body.clientHeight/2 ) + ( ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop )) + 'px'");D.prepend('<iframe id="fancybox-hide-sel-frame" src="javascript:\'\';" scrolling="no" frameborder="0" ></iframe>')}}};
b.fn.fancybox=function(a){b(this).data("fancybox",b.extend({},a,b.metadata?b(this).metadata():{})).unbind("click.fb").bind("click.fb",function(d){d.preventDefault();if(!h){h=true;b(this).blur();q=[];p=0;d=b(this).attr("rel")||"";if(!d||d==""||d==="nofollow")q.push(this);else{q=b("a[rel="+d+"], area[rel="+d+"]");p=q.index(this)}C();return false}});return this};b.fancybox=function(a,d){if(!h){h=true;d=typeof d!=="undefined"?d:{};q=[];p=d.index||0;if(b.isArray(a)){for(var f=0,o=a.length;f<o;f++)if(typeof a[f]==
"object")b(a[f]).data("fancybox",b.extend({},d,a[f]));else a[f]=b({}).data("fancybox",b.extend({content:a[f]},d));q=jQuery.merge(q,a)}else{if(typeof a=="object")b(a).data("fancybox",b.extend({},d,a));else a=b({}).data("fancybox",b.extend({content:a},d));q.push(a)}if(p>q.length||p<0)p=0;C()}};b.fancybox.showActivity=function(){clearInterval(H);u.show();H=setInterval($,66)};b.fancybox.hideActivity=function(){u.hide()};b.fancybox.next=function(){return b.fancybox.pos(n+1)};b.fancybox.prev=function(){return b.fancybox.pos(n-
1)};b.fancybox.pos=function(a){if(!h){a=parseInt(a,10);if(a>-1&&j.length>a){p=a;C()}if(c.cyclic&&j.length>1&&a<0){p=j.length-1;C()}if(c.cyclic&&j.length>1&&a>=j.length){p=0;C()}}};b.fancybox.cancel=function(){if(!h){h=true;b.event.trigger("fancybox-cancel");J();e&&b.isFunction(e.onCancel)&&e.onCancel(q,p,e);h=false}};b.fancybox.close=function(){function a(){x.fadeOut("fast");g.hide();b.event.trigger("fancybox-cleanup");i.empty();b.isFunction(c.onClosed)&&c.onClosed(j,n,c);j=e=[];n=p=0;c=e={};h=false}
if(!(h||g.is(":hidden"))){h=true;if(c&&b.isFunction(c.onCleanup))if(c.onCleanup(j,n,c)===false){h=false;return}J();b(z.add(A).add(B)).hide();b("#fancybox-title").remove();g.add(i).add(x).unbind();b(window).unbind("resize.fb scroll.fb");b(document).unbind("keydown.fb");i.css("overflow","hidden");if(c.transitionOut=="elastic"){k=Q();var d=g.position();l={top:d.top,left:d.left,width:g.width(),height:g.height()};if(c.opacity)l.opacity=1;y.prop=1;b(y).animate({prop:0},{duration:c.speedOut,easing:c.easingOut,
step:M,complete:a})}else g.fadeOut(c.transitionOut=="none"?0:c.speedOut,a)}};b.fancybox.resize=function(){var a,d;if(!(h||g.is(":hidden"))){h=true;a=i.wrapInner("<div style='overflow:auto'></div>").children();d=a.height();g.css({height:d+c.padding*2+v});i.css({height:d});a.replaceWith(a.children());b.fancybox.center()}};b.fancybox.center=function(){h=true;var a=K(),d=c.margin,f={};f.top=a[3]+(a[1]-(g.height()-v+40))*0.5;f.left=a[2]+(a[0]-(g.width()+40))*0.5;f.top=Math.max(a[3]+d,f.top);f.left=Math.max(a[2]+
d,f.left);g.css(f);h=false};b.fn.fancybox.defaults={padding:10,margin:20,opacity:false,modal:false,cyclic:false,scrolling:"auto",width:560,height:340,autoScale:true,autoDimensions:true,centerOnScroll:false,ajax:{},swf:{wmode:"transparent"},hideOnOverlayClick:true,hideOnContentClick:false,overlayShow:true,overlayOpacity:0.3,overlayColor:"#666",titleShow:true,titlePosition:"outside",titleFormat:null,transitionIn:"fade",transitionOut:"fade",speedIn:300,speedOut:300,changeSpeed:300,changeFade:"fast",
easingIn:"swing",easingOut:"swing",showCloseButton:true,showNavArrows:true,enableEscapeButton:true,onStart:null,onCancel:null,onComplete:null,onCleanup:null,onClosed:null};b(document).ready(function(){aa()})})(jQuery);
 

(function(b){function d(a){var f=[].slice.call(arguments,1),e=0;a=b.event.fix(a||window.event);a.type="mousewheel";if(a.wheelDelta)e=a.wheelDelta/120;if(a.detail)e=-a.detail/3;f.unshift(a,e);return b.event.handle.apply(this,f)}var c=["DOMMouseScroll","mousewheel"];b.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],d,false);else this.onmousewheel=d},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],
d,false);else this.onmousewheel=null}};b.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);
 

 
eval(function(p,a,c,k,e,r){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)r[e(c)]=k[c]||e(c);k=[function(e){return r[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('h.i[\'1a\']=h.i[\'z\'];h.O(h.i,{y:\'D\',z:9(x,t,b,c,d){6 h.i[h.i.y](x,t,b,c,d)},17:9(x,t,b,c,d){6 c*(t/=d)*t+b},D:9(x,t,b,c,d){6-c*(t/=d)*(t-2)+b},13:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t+b;6-c/2*((--t)*(t-2)-1)+b},X:9(x,t,b,c,d){6 c*(t/=d)*t*t+b},U:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t+1)+b},R:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t+b;6 c/2*((t-=2)*t*t+2)+b},N:9(x,t,b,c,d){6 c*(t/=d)*t*t*t+b},M:9(x,t,b,c,d){6-c*((t=t/d-1)*t*t*t-1)+b},L:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t+b;6-c/2*((t-=2)*t*t*t-2)+b},K:9(x,t,b,c,d){6 c*(t/=d)*t*t*t*t+b},J:9(x,t,b,c,d){6 c*((t=t/d-1)*t*t*t*t+1)+b},I:9(x,t,b,c,d){e((t/=d/2)<1)6 c/2*t*t*t*t*t+b;6 c/2*((t-=2)*t*t*t*t+2)+b},G:9(x,t,b,c,d){6-c*8.C(t/d*(8.g/2))+c+b},15:9(x,t,b,c,d){6 c*8.n(t/d*(8.g/2))+b},12:9(x,t,b,c,d){6-c/2*(8.C(8.g*t/d)-1)+b},Z:9(x,t,b,c,d){6(t==0)?b:c*8.j(2,10*(t/d-1))+b},Y:9(x,t,b,c,d){6(t==d)?b+c:c*(-8.j(2,-10*t/d)+1)+b},W:9(x,t,b,c,d){e(t==0)6 b;e(t==d)6 b+c;e((t/=d/2)<1)6 c/2*8.j(2,10*(t-1))+b;6 c/2*(-8.j(2,-10*--t)+2)+b},V:9(x,t,b,c,d){6-c*(8.o(1-(t/=d)*t)-1)+b},S:9(x,t,b,c,d){6 c*8.o(1-(t=t/d-1)*t)+b},Q:9(x,t,b,c,d){e((t/=d/2)<1)6-c/2*(8.o(1-t*t)-1)+b;6 c/2*(8.o(1-(t-=2)*t)+1)+b},P:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6-(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b},H:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d)==1)6 b+c;e(!p)p=d*.3;e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);6 a*8.j(2,-10*t)*8.n((t*d-s)*(2*8.g)/p)+c+b},T:9(x,t,b,c,d){f s=1.l;f p=0;f a=c;e(t==0)6 b;e((t/=d/2)==2)6 b+c;e(!p)p=d*(.3*1.5);e(a<8.w(c)){a=c;f s=p/4}m f s=p/(2*8.g)*8.r(c/a);e(t<1)6-.5*(a*8.j(2,10*(t-=1))*8.n((t*d-s)*(2*8.g)/p))+b;6 a*8.j(2,-10*(t-=1))*8.n((t*d-s)*(2*8.g)/p)*.5+c+b},F:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*(t/=d)*t*((s+1)*t-s)+b},E:9(x,t,b,c,d,s){e(s==u)s=1.l;6 c*((t=t/d-1)*t*((s+1)*t+s)+1)+b},16:9(x,t,b,c,d,s){e(s==u)s=1.l;e((t/=d/2)<1)6 c/2*(t*t*(((s*=(1.B))+1)*t-s))+b;6 c/2*((t-=2)*t*(((s*=(1.B))+1)*t+s)+2)+b},A:9(x,t,b,c,d){6 c-h.i.v(x,d-t,0,c,d)+b},v:9(x,t,b,c,d){e((t/=d)<(1/2.k)){6 c*(7.q*t*t)+b}m e(t<(2/2.k)){6 c*(7.q*(t-=(1.5/2.k))*t+.k)+b}m e(t<(2.5/2.k)){6 c*(7.q*(t-=(2.14/2.k))*t+.11)+b}m{6 c*(7.q*(t-=(2.18/2.k))*t+.19)+b}},1b:9(x,t,b,c,d){e(t<d/2)6 h.i.A(x,t*2,0,c,d)*.5+b;6 h.i.v(x,t*2-d,0,c,d)*.5+c*.5+b}});',62,74,'||||||return||Math|function|||||if|var|PI|jQuery|easing|pow|75|70158|else|sin|sqrt||5625|asin|||undefined|easeOutBounce|abs||def|swing|easeInBounce|525|cos|easeOutQuad|easeOutBack|easeInBack|easeInSine|easeOutElastic|easeInOutQuint|easeOutQuint|easeInQuint|easeInOutQuart|easeOutQuart|easeInQuart|extend|easeInElastic|easeInOutCirc|easeInOutCubic|easeOutCirc|easeInOutElastic|easeOutCubic|easeInCirc|easeInOutExpo|easeInCubic|easeOutExpo|easeInExpo||9375|easeInOutSine|easeInOutQuad|25|easeOutSine|easeInOutBack|easeInQuad|625|984375|jswing|easeInOutBounce'.split('|'),0,{}))

 

function MessagesO() {
	var messageBoard;
	var messageIsUp;	
	var messageHandler;

	this.init = function() {
		messageBoard=$('<div id="message_board"/>')
			.appendTo($(document.body));
		messageIsUp=true;
	}

	this.post = function(text) {
		if (!text || text=="")
			return;
		if (messageHandler)
			clearTimeout(messageHandler);
		if (messageIsUp) {
			messageIsUp=true;
			messageBoard.stop(true)
				.animate({ 'top':'20px' },200);
		}		
		messageBoard.empty()
			.append(text);
		messageHandler=setTimeout(hideMessage,4000); 
	}
	
	var hideMessage = function(messageDiv) {
		messageIsUp=true;
		messageBoard.animate({ 'top':'-40px' },700);
	}
	
}

function PersonO(thedata) {
	var data=thedata;
	
	var sprite_35_size=16;
	var sprite_120_size=8;

	this.getData = function() {
		return data;
	}

	this.getSpriteIcon=function() {
		if (data.sprite_id==null)
			return "url(/img/pic_nophoto_35.jpg) no-repeat top left";
		var sprite_i = Math.floor((data.sprite_id-1)/(sprite_35_size*sprite_35_size))+1;
		var inner_i = (data.sprite_id-1)%(sprite_35_size*sprite_35_size);
		var left = (inner_i%sprite_35_size)*35;
		var top = Math.floor(inner_i/sprite_35_size)*35;
		return "url(/img/sprite/sprite_"+sprite_i+"_35.jpg) no-repeat -"+left+"px -"+top+"px";
	}

	this.getSpriteBigIcon=function() {
		if (data.sprite_id==null)
			return "url(/img/pic_nophoto_120.jpg) no-repeat top left";
		var sprite_i = Math.floor((data.sprite_id-1)/(sprite_120_size*sprite_120_size))+1;
		var inner_i = (data.sprite_id-1)%(sprite_120_size*sprite_120_size);
		var left = (inner_i%sprite_120_size)*120;
		var top = Math.floor(inner_i/sprite_120_size)*120;
		return "url(/img/sprite/sprite_"+sprite_i+"_120.jpg) no-repeat -"+left+"px -"+top+"px";
	}

	this.getSpriteBigImage=function(size,style) {
		if (data.sprite_id==null)
			return '<div style="overflow:hidden;width:'+size+'px;height:'+size+'px;'+style+'">'+
				'<img src="/img/pic_nophoto_120.jpg" style="float:none;'+
				'left:-'+left+'px;top:-'+top+'px;width:'+size+'px;"/></div>';
		var sprite_i = Math.floor((data.sprite_id-1)/(sprite_120_size*sprite_120_size))+1;
		var inner_i = (data.sprite_id-1)%(sprite_120_size*sprite_120_size);
		var left = (inner_i%sprite_120_size)*size;
		var top = Math.floor(inner_i/sprite_120_size)*size;
		return '<div style="overflow:hidden;width:'+size+'px;height:'+size+'px;'+style+'">'+
			'<img src="/img/sprite/sprite_'+sprite_i+'_120.jpg" style="float:none;'+
			'position:relative;left:-'+left+'px;top:-'+top+'px;'+
			'width:'+(size*sprite_120_size)+'px;"/></div>';
	}

	this.getIcon=function() {
		return hashToImageURLs(data.snimka).s;
	}

	this.getBigIcon=function() {
		return hashToImageURLs(data.snimka).m;
	}

	this.getVeryBigIcon=function() {
		return hashToImageURLs(data.snimka).l;
	}

	this.getBigImages=function() {
		var temp=new Array();
		$.each(data.photos,function(i,photo) {
			var tempim = hashToImageURLs(photo.hash);
			temp.push({ 'urlsmall':tempim.m, 'url':tempim.l, 'comment':photo.comentar });
		});
		return temp;
	}

	var hashToImageURLs = function(hash) {
		return {"s":"img/pic_"+hash+"_35.jpg", "m":"img/pic_"+hash+"_120.jpg",  "l":"img/pic_"+hash+".jpg" };
	}

	this.getLocation = function() {
		var temp = data.mqsto.split(",");
		return { 'lat':temp[0], 'lng':temp[1] };
	}
}

function PeopleO() {
	var peoplelist=new Array();
	var listeners=new Array();

	this.load = function() {
		$.getJSON('/data/data_short.json?'+Math.floor(Math.random()*10000), parseHora);
	}

	var parseHora = function(data) {
		if (peoplelist!=null && peoplelist.length>0)
			peoplelist=new Array();
		callListeners('removed');

		if ($.isArray(data.hora))
			for (i=0;i<data.hora.length;i++)
				peoplelist.push(new PersonO(data.hora[i]));
		callListeners('loaded');
	}

	this.getFullList = function() {
		return peoplelist;
	}

	this.getListSize = function() {
		return peoplelist.length;
	}

	this.isLoaded = function() {
		return peoplelist!=null && peoplelist.length>0;
	}

	 
	this.addListener = function(type,method,id) {
		if (!listeners[type])
			listeners[type]=new Array();
		var found=false;
		$.each(listeners[type], function(i,tuple) {
			if (tuple.id==id)
				found=true;
		});
		if (!found)
			listeners[type].push({'id':id, 'method':method });
	}
	var callListeners = function(type) {
		if (listeners[type] && listeners[type].length>0)
			$.each(listeners[type], function (i,tuple) {
				if (tuple!=null)
					tuple.method(peoplelist);
			});
	}
	this.removeListener = function(type,id) {
		if (listeners[type] && listeners[type])
			$.each(listeners[type], function(i,tuple) {
				if (tuple.id==id)
					listeners[type][i]=null;
			});
	}
}

function MarkerManagerO(themap) {
	var map=themap;
	var markers=new Array();
	var fullinfoholder;
	var fullinfoactivator;
	var blockDialogsAtStartup=false;
	var people;
	var messages;
	var heatmap;
	var listeners=new Array();  
	
	var currentFilter=false;
	var clusterer;
	var peopleList;

	var animateMarkers=false;
	var animateMarkers_list;
	var animateMarkers_active;	
	var animateMarkers_speed=500;

	var markers_newperiod=30.5*3;


	this.init = function(thepeople, themessages, theheatmap) {
		GEvent.addListener(map,'zoomend',function() {
			$("img[id^='mtgt_unnamed']").each(function(i,o) {
				$(o).css({left:$(o).position().left+9, top:$(o).position().top+9});
			});
		});

		messages=themessages;
		people=thepeople;
		people.addListener("loaded",startupMarkers,"markerman_startupMarkers");
		heatmap=theheatmap;

		GEvent.addListener(map, "dragstart", function() {
			map.closeInfoWindow();
		});
		if (getURLPerson()!="")
			blockDialogsAtStartup=true;
	}

	var startupMarkers=function(list) {
		animateMarkers=false;
		peopleList=list;
		sortPeopleList();
		if (!heatmap.getBlockRegularMapDisplay()) {
			placeMarkers();
			displayPersonProfileAtStart();
		}
	};

	this.filterMarkers = function(hashs) {
		var hashsSerialize=false;
		if (hashs && hashs.length>0) {
			var hashsSerialize=hashs.sort().join("|");
			if (currentFilter==hashsSerialize)
				return;
		}

		clearMarkers();
		if (hashsSerialize===false)
			peopleList=people.getFullList();
		else {
			peopleList=new Array();
			$.each(people.getFullList(), function(i,person) {
				if (hashs.indexOf(person.getData().hash)>-1)
					peopleList.push(person);
			});
		}
		
		sortPeopleList();
		placeMarkers();	
		currentFilter=hashsSerialize;
	}
	
	this.toggleAnimateMarkers = function() {
		var oldanimateMarkers=animateMarkers;
		clearMarkers();
		animateMarkers=!oldanimateMarkers;
		placeMarkers();	
	}

	var sortPeopleList = function() {
		peopleList.sort(function(a,b) {
			var a1=(new Date(a.getData().vreme)).getTime();
			var b1=(new Date(b.getData().vreme)).getTime();
			if (isNaN(b1) || !b.getData().vreme)
				return 1;
			if (isNaN(a1) || !a.getData().vreme)
				return -1;
			return a1<b1?1:-1;
		});
	}

	var placeMarkers=function() {
		clusterer = new MarkerClusterer(map,[], {	
			gridSize:40, 
			maxZoom:12,
			styles:[
				{width:53, height:53, opt_textColor:'white', url:'img/design/shadow_l1.png'},
				{width:53, height:53, opt_textColor:'white', url:'img/design/shadow_l2.png'},
				{width:53, height:53, opt_textColor:'white', url:'img/design/shadow_l3.png'}
			]			
		});

		if (animateMarkers) {
			animateMarkers_list=new Array();
			$.each(peopleList,function(i,person) {
				var marker=createMarker(person);
				animateMarkers_list.push(marker);
			});
			animateMarkers_list.reverse();
			animateMarkers_active=setInterval(placeAnimateMarkers,animateMarkers_speed);
			callListeners("animation_started");
		} else {
			$.each(peopleList,function(i,person) {
				var marker=createMarker(person);
				markers.push(marker);
			});

			clusterer.addMarkers(markers);
		}
	}

	this.redrawMap = function() {
		placeMarkers();
	}

	var placeAnimateMarkers = function() {
		if (animateMarkers && animateMarkers_active && animateMarkers_list.length==0) {
			clearAnimate();
		} else {
			var marker=animateMarkers_list.shift();
			markers.push(marker);
			clusterer.clearMarkers();
			clusterer.addMarkers(markers);
			messages.post(marker.person.getData().vreme);
		}
	}
	
	var clearMarkers=function() {
		if (clusterer)
			clusterer.clearMarkers();	
		clearAnimate()
		delete markers;
		markers=new Array();
	}

	this.cleanMap=function() {
		clearMarkers();
	}

	var clearAnimate=function() {
		if (animateMarkers_active) {
			animateMarkers=false;
			clearInterval(animateMarkers_active);
			animateMarkers_active=false;
			delete animateMarkers_list;
			callListeners("animation_stopped");
		}
	}

	var createMarker = function(person) {
		var faceIcon = new GIcon();
		faceIcon.image="http://maps.gstatic.com/intl/en_ALL/mapfiles/transparent.png";
		faceIcon.iconSize=new GSize(53,53);
		faceIcon.iconAnchor = new GPoint(19, 49);
		faceIcon.infoWindowAnchor = new GPoint(26, 10);

		var date=new Date(person.getData().vreme);
		var diff=(new Date()-date)/1000/60/60/24;

		var aperson=person;
		aperson.latlng=GLatLng.fromUrlValue(person.getData().mqsto);
		marker=new MyMarker(person.latlng, { 
			icon:faceIcon,
			"map":map, 
			title:person.getData().ime,
			lipsva: {background:person.getSpriteIcon(), iconSize:new GSize(35,35), isnew: diff<markers_newperiod }
		});
		GEvent.addListener(marker, "click", function() { this.openInfoWindow(this.shortInfo); } );
		GEvent.addListener(marker, "dblclick", function() { showFullInfo(person) });

		marker.person=aperson;
		person.marker=marker;

		var code=$('<div class="infowindow" title="Покажи цялата информация" title="Отвори целият профил"><img src="/img/design/transparent.gif" alt="'+aperson.getData().ime+'" title="'+aperson.getData().ime+'" style="width:120px; height:120px;background:'+aperson.getSpriteBigIcon()+';"/>'+
				'<a href="javascript:;">'+aperson.getData().ime+'</a><br/>'+
				'<i>Липсва от:</i> '+aperson.getData().vreme+'<br/>'+
				'<i>Последно видян/а:</i> '+aperson.getData().mqstoT+'<br/>'+
				'<br/><a href="javascript:;" style="font-size:80%;float:right;">Пълна информация &#187;</a>'+
				'</div>').click(function() { showFullInfo(aperson) });
		marker.shortInfo = code.get(0);

		return marker;
	}
	
	this.centerMarkerForPerson = function(person) {
		map.setCenter(person.latlng,13);
		person.marker.openInfoWindow(person.marker.shortInfo);
	}

	var showFullInfo = function(person) {
		if (!person) 
			return;
		newWindow = window.open("/staticpage.php?person="+person.getData().hash, '_blank');
		newWindow.focus();
	}
	
	this.isPersonFocus = function() {
		return getURLPerson()!="";
	}

	var getURLPerson = function () {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regex = new RegExp("[\\?&]person=([^&#]*)");
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return results[1];
	}

	var displayPersonProfileAtStart = function() {
		var personHash=getURLPerson();
		if (personHash && personHash!="")
			for (i=0;i<markers.length;i++)
				if (markers[i].person.getData().hash==personHash) {
					var marker=markers[i];
					map.setCenter(marker.getLatLng(),13);
					marker.openInfoWindow(marker.shortInfo);
					return;
				}
	}

	this.getBlockDialogsAtStartup = function() {
		return blockDialogsAtStartup;
	}

 
	this.addListener = function(type,method,id) {
		if (!listeners[type])
			listeners[type]=new Array();
		var found=false;
		$.each(listeners[type], function(i,tuple) {
			if (tuple.id==id)
				found=true;
		});
		if (!found)
			listeners[type].push({'id':id, 'method':method });
	}
	var callListeners = function(type) {
		if (listeners[type] && listeners[type].length>0)
			$.each(listeners[type], function (i,tuple) {
				if (tuple!=null)
					tuple.method();
			});
	}
	this.removeListener = function(type,id) {
		if (listeners[type] && listeners[type])
			$.each(listeners[type], function(i,tuple) {
				if (tuple.id==id)
					listeners[type][i]=null;
			});
	}
}

function ListO(themap) {
	var map=themap;
	var people;
	var listeners=new Array();
	var orderedlist=new Array();
	var forcesynch=false;

	var order="timeAsc";  

	this.init=function(thepeople) {
		people=thepeople;
		people.addListener("loaded",reorder,"list_reorder");
		GEvent.addListener(map,'moveend',reorder);
	}

	this.reorderTo = function(location, callback) {
		reorder({"center":location});
		if (callback)
			callback(orderedlist);
	}
	this.forceReorder = function() {
		reorder();
	}

	var reorder=function(args) {
		if (forcesynch) 
			return;

		var center=args?args['center']:false;			
		if (!center || !(center instanceof GLatLng))
			center=map.getCenter();


		var old_orderedlist=orderedlist;
		orderedlist = new Array();
		$.each(people.getFullList(),function(i, person) {
			var distance=Math.round(parseInt(center.distanceFrom(person.latlng)));
			orderedlist.push({'distance':distance, 'person':person});
		});

		forcesynch=true;
		if (order=="near")
			reorderDistance(center);
		else
		if (order=='timeAsc' || order=='timeDesc')
			reorderTime();

		var changes="none";
		if (!old_orderedlist || old_orderedlist.length==0)
			changes="reordered"
		else
		for (i=0;i<old_orderedlist.length;i++)
			if (old_orderedlist[i].person!=orderedlist[i].person) {
				changes="reordered";
				break
			} else
			if (old_orderedlist[i].distance!=orderedlist[i].person)
				changes="data";

		forcesynch=false;

		if (changes=="reordered")
			callListeners('updated');
		else
		if (changes=="data")	
			callListeners('updatedDistance');		
	}

	var reorderDistance = function(center) {
		orderedlist.sort(function(a,b) {
			return a.distance<b.distance?-1:1;
		});
	}

	var reorderTime = function() {
		var asc = (order=="timeAsc")?-1:1;
		orderedlist.sort(function(a,b) {
			var a1=(new Date(a.person.getData().vreme)).getTime();
			var b1=(new Date(b.person.getData().vreme)).getTime();
			if (isNaN(b1) || !b.person.getData().vreme)
				return 1;
			if (isNaN(a1) || !a.person.getData().vreme)
				return -1;
			return (a1<b1?-1:1)*asc;
		});
	}

	var reorder1=function(center) {
		if (forcesynch) 
			return;
		forcesynch=true;
		if (!center || !(center instanceof GLatLng))
			center=map.getCenter();
		orderedlist = new Array();
		$.each(people.getFullList(),function(i, person) {
			var distance=Math.round(parseInt(center.distanceFrom(person.latlng)));
			orderedlist.push({'distance':distance, 'person':person});
		});

		if (order=="near")
			orderedlist.sort(function(a,b) {
				return a.distance<b.distance?-1:1;
			});
		else {
			var asc = (order=="timeAsc")?-1:1;
			orderedlist.sort(function(a,b) {
			var a1=(new Date(a.person.getData().vreme)).getTime();
			var b1=(new Date(b.person.getData().vreme)).getTime();
			if (isNaN(b1) || !b.person.getData().vreme)
				return 1;
			if (isNaN(a1) || !a.person.getData().vreme)
				return -1;
			return (a1<b1?-1:1)*asc;
		});
		}
		forcesynch=false;
		callListeners('updated');		
	}

	this.getOrderType = function() {
		return order;
	}

	this.setOrderType = function(theorder) {
		order=theorder;
		reorder();
	}

	this.getNearest = function() {
		return orderedlist[0];
	}

	this.getNearestThree = function() {
		return orderedlist.slice(0,3);
	}
	this.getNearestTen = function() {
		return orderedlist.slice(0,9);
	}
	
	this.getList = function() {
		return orderedlist;
	}

	
	 
	this.addListener = function(type,method,id) {
		if (!listeners[type])
			listeners[type]=new Array();
		var found=false;
		$.each(listeners[type], function(i,tuple) {
			if (tuple.id==id)
				found=true;
		});
		if (!found)
			listeners[type].push({'id':id, 'method':method });
	}
	var callListeners = function(type) {
		if (listeners[type] && listeners[type].length>0)
			$.each(listeners[type], function (i,tuple) {
				if (tuple!=null)
					tuple.method(orderedlist);
			});
	}
	this.removeListener = function(type,id) {
		if (listeners[type] && listeners[type])
			$.each(listeners[type], function(i,tuple) {
				if (tuple.id==id)
					listeners[type][i]=null;
			});
	}
}

function PositionerO(themap) {
	var min_reposition_distance=20000;

	var map=themap;
	var bulgaria_center = new google.maps.LatLng(42.593533,25.202637);
	var bulgaria_bounds=new GLatLngBounds(new google.maps.LatLng(41.529142,22.593384), new google.maps.LatLng(43.826601,28.141479));
	var bulgaria_boundsOut=new GLatLngBounds(new google.maps.LatLng(41.219986,22.373657), new google.maps.LatLng(44.186143,28.701782));
	var clientpos;
	var cities=false;
	var people;
	var markerman;

	var askforcitiesafter=false;
	var selectcitiesform;

	this.init = function(thepeople, themarkerman) {
		markerman=themarkerman;
		people=thepeople;
		loadCities();
		clientpos=getClientPosition();
		if (getInitCity()=="" && clientpos!==false) {
			if (bulgaria_boundsOut.containsLatLng(clientpos)) {
				map.setCenter(clientpos, 13);
				people.addListener("loaded",reposition,"positions_reposition");
			} else
				positionBulgaria();
		} else {
			positionBulgaria();
			if (!markerman.getBlockDialogsAtStartup()) {
				if (cities)
					askCity();
				else
					askforcitiesafter=true;				
			}
		}
	}

	var reposition = function(orderedlist) {
		if (!orderedlist)
			return;


		people.removeListener("loaded","positions_reposition");
		
		if (orderedlist[0].distance>min_reposition_distance) {
			map.setCenter(clientpos instanceof GLatLngBounds?clientpos.getCenter():clientpos, 12);
			return;
		}
		var bounds = clientpos instanceof GLatLngBounds?clientpos:new GLatLngBounds(clientpos,clientpos);
		for (i=0;i<3 && i<orderedlist.length;i++)
			if (orderedlist[i].distance<min_reposition_distance)
				bounds.extend(orderedlist[i].person.latlng);
		var zoomlevel = map.getBoundsZoomLevel(bounds);
		if (zoomlevel<15 && zoomlevel>6)
			map.setCenter(bounds.getCenter(), zoomlevel);
		else
			map.setCenter(clientpos instanceof GLatLngBounds?clientpos.getCenter():clientpos, 12);
	}

	var getClientPosition = function() {
		if (google.loader.ClientLocation)
			return new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);

		return false;
	}

	var askCity = function() {
		if (getInitCity()=="" || !positionCity(getInitCity()))
				selectcitiesform.click();
	}
	
	var positionBulgaria = function() {
		clientpos=bulgaria_center;
		map.setCenter(bulgaria_center, markerman.isPersonFocus()?13:map.getBoundsZoomLevel(bulgaria_bounds));
	}

	var loadCities = function() {
		$.getJSON('app/cities.json', handleCities);
	}
	
	var handleCities = function(thecities) {
		cities=thecities;
		
		var code=$('<div style="display:none;" align="center" id="selectcityform"><b>Изберете град</b><br/></div>');
		code.append($('<a href="javascript:;">Цяла България</a>').click(function() { 
			$.fancybox.close(); 
			positionBulgaria();
		}));

		var tablecode=$('<table/>');
		for (j=0;j<3;j++) {
			var trcode=$('<tr/>');
			for (i=0;i<3;i++) {
				trcode.append($('<td><a href="javascript:;">'+cities[j*3+i][0]+'</a></td>').attr({'boundsw':cities[j*3+i][1],'boundne':cities[j*3+i][2]?cities[j*3+i][2]:cities[j*3+i][1]}).click(function() { 
					$.fancybox.close(); 
					clientpos=new GLatLngBounds(GLatLng.fromUrlValue($(this).attr('boundsw')),
									GLatLng.fromUrlValue($(this).attr('boundne'))); 
					map.setCenter(clientpos.getCenter() , map.getBoundsZoomLevel(clientpos)>16?14:map.getBoundsZoomLevel(clientpos));
				}));
			}
			tablecode.append(trcode);
		}
		code.append(tablecode);

		var selectcode=$('<select>');
		$('<option disabled selected>или изберете близък град</option>').appendTo(selectcode);
		for (i=9;i<cities.length;i++) {
			$('<option value="'+cities[i][0]+'">'+cities[i][0]+'</option>').attr({'boundsw':cities[i][1],'boundne':cities[i][2]?cities[i][2]:cities[i][1]}).appendTo(selectcode);
		}
		selectcode.change(function() { 
			if (this.selectedIndex==0)
				return;
			$.fancybox.close(); 
			clientpos=new GLatLngBounds(GLatLng.fromUrlValue($(this).children(":selected").attr('boundsw')),
							GLatLng.fromUrlValue($(this).children(":selected").attr('boundne'))); 
			map.setCenter(clientpos.getCenter() , map.getBoundsZoomLevel(clientpos)>16?14:map.getBoundsZoomLevel(clientpos));

		});
		code.append(selectcode);
		code.appendTo('body');

		selectcitiesform=$('<a href="#selectcityform">Изберете град</a>').fancybox({
			'scrolling': 'no',
			'titleShow': false,
			'onStart': function() {	 
				map.disableScrollWheelZoom();  
				$('#selectcityform').show().children("select").children(":disabled").attr('selected',true); 
			},
			'onCleanup': function() { 
				map.enableScrollWheelZoom(); 
				$('#selectcityform').hide(); 
			}
		}).appendTo('#logopanel');

		if (askforcitiesafter) {
			askforcitiesafter=false;
			askCity();
		}
			
	}

	var positionCity = function(city) {
		if (cities)
			for (i=0;i<cities.length;i++) 
				if (cities[i][0].toLowerCase()==city.toLowerCase()) {
					clientpos=new GLatLngBounds(GLatLng.fromUrlValue(cities[i][1]),
						GLatLng.fromUrlValue(cities[i][2]?cities[i][2]:cities[i][1])); 
					var zoom = getInitCityZoom();
					if (zoom==-1)
						zoom = map.getBoundsZoomLevel(clientpos)>16?14:map.getBoundsZoomLevel(clientpos);
					map.setCenter(clientpos.getCenter() , zoom);
					return true;
				}
		return false;
	}

	var getInitCity = function () {
		var regex = new RegExp("[\\?&]city=([^&#]*)");
		var results = regex.exec( window.location.href );
		if( results == null )
			return "";
		else
			return decodeURI(results[1]);
	}

	var getInitCityZoom = function () {
		var regex = new RegExp("[\\?&]z=([^&#]*)");
		var results = regex.exec( window.location.href );
		if( results == null)
			return -1;
		else {
			var zoom = parseInt(decodeURI(results[1]));
			if (isNaN(zoom) || zoom<4 || zoom>16)
				return -1;
			else
				return parseInt(decodeURI(results[1]));
		}
	}

}

function SidePanelO(themap) {
	var map=themap;
	var holder;
	var markerman;
	var people;
	var messages;
	var geocoder;	
	
	var searchPanel;

	var translit={
		"щ":["sht","st"],
		"ж":["j","zh"],
		"ц":["tz", "ts"],
		"ч":["ch","4"],
		"ш":["sh","6"],
		"ю":["yu","yo"],
		"я":["ya","q"],

		"а":["a"],
		"б":["b"],
		"в":["v","w"],
		"г":["g"],
		"д":["d"],
		"е":["e"],
		"з":["z"],
		"и":["i"],
		"й":[],
		"к":["k"],
		"л":["l"],
		"м":["m"],
		"н":["n"],
		"о":["o"],
		"п":["p"],
		"р":["r"],
		"с":["s"],
		"т":["t"],
		"у":["u"],
		"ф":["f"],
		"х":["h"],
		"ъ":["y"],
		"ь":[]
	}

	this.init = function(thepeople, themarkerman, themessages) {
		markerman=themarkerman;
		people=thepeople;
		messages=themessages;

		holder=$('#people_list').empty();
		holder.parent().scrollTop(0);
		$('<a href="javascript:;">Затвори всички раздели</a>')
			.click(closeAllGroups)
			.appendTo(holder);
	
		holder.append(" | ");
	
		var animateButton = $('<a href="javascript:;">Анимирай</a>')
			.click(markerman.toggleAnimateMarkers)
			.appendTo(holder);	
		markerman.addListener("animation_stopped",function() {
			animateButton.empty().append("Анимирай");
		},"animatebutton_stopped");
		markerman.addListener("animation_started",function() {
			animateButton.empty().append("Спри");
		},"animatebutton_sterted");


		$('<form action="javascript:;" autocomplete="off" id="sidepanel_searchform"/>')
			.append($('<input type="text" name="term"  autocomplete="off"/>')
					.focus(function() {
						searchPanel.show();
					})
					.blur(function() {
						searchPanel.hide();
					}))
			.append('<input type="submit" value="Търси"/>')
			.submit(doSearch)
			.wrapAll('<div/>')
			.parent().appendTo(holder);
	
		searchPanel=$('<div id="searchpanel_holder">'+
			'<div/>"'+
			'</div>')
			.append("aaa")
			.appendTo(document.body);

		people.addListener("loaded",updateList,"sidepanel_update");

	
		
		$('#sidepanel').css('height',$('#maintable').height()-180);
		geocoder = new GClientGeocoder();
	}

	var updateMarkers = function() {
		var list=new Array();
		holder.children("div")
			.filter(function() {
				return $(this).data("expanded");
			})
			.children(".sidepanel_people:not(:hidden)")
			.children()
			.each(function(i, person) {
				list.push($(person).data("hash"));
			});

		var text, year0, year1;
		if (list.length>0) {
			$.each(people.getFullList(), function(i,person) {
				if (person.getData().hash==list[0])
					year1=new Date((person.getData().vreme)).getFullYear();
				if (person.getData().hash==list[list.length-1])
					year0=new Date((person.getData().vreme)).getFullYear();
			})
			if (year0==year1)
				text="Изчезнали през "+year0;
			else
				text="Изчезнали между "+year0;
			text+=" - "+list.length+" от "+people.getListSize();
		} else
			text="Всички изчезнали - "+people.getListSize();
		messages.post(text);
		
		
		markerman.filterMarkers(list);
	}

	var doSearch = function() {
		var term = $('form input[name="term"]').attr('value');
		closeAllGroups();

		var panel=$('<div/>').data("expanded",true);
		var searchTitle=$('<div class="sidepanel_title">'+
					'<div></div>'+
					'<div class="toggleSwitch">затвори </div>'+
					'Търсене на "'+term+'"'+
					' - <i></i>'+
					'</div>')			
			.click(function () { toggleGroup(panel); updateMarkers(); } )
			.mouseover(function() {$(this).children(".toggleSwitch").show();})
			.mouseout(function() {$(this).children(".toggleSwitch").hide();})
			.appendTo(panel);

		 
		geocoder.getLocations(term+" България", function(response) { doSearch_showGoogle(response, panel) } );	

		 
		term=term.toLowerCase();
		var term_translit = translitTerm(term);
		term=term.split(" ").concat(term_translit.split(" "));
		var peopleTemp=sortPeople(people.getFullList());
		var peopleDiv=$('<div class="sidepanel_people"/>')
			.appendTo(panel);
		var count=0;
		$.each(peopleTemp, function(i,person) {
			var searchData=person.getData().ime+" "+
				person.getData().opisanie+" "+
				person.getData().informaciq+" "+ 
				person.getData().vreme+" "+
				person.getData().mqstoT;
			for (i=0;i<term.length;i++)
				if (searchData.toLowerCase().indexOf(term[i])>-1) {
					createPersonSidepanel(person).appendTo(peopleDiv);
					count++;
					break;
				}	
		});
		panel.insertAfter(holder.children("div:first"));
		searchTitle.children("i").html(count);

		updateMarkers();

		return false;
	}

	var doSearch_showGoogle = function(response, panel) {
		if (!response || response.Status.code != 200) {
			return;
		}
	
		var len=response.Placemark.length>5?5:response.Placemark.length;
		panel.children(":first").children('i').html(parseInt(panel.children(":first").children('i').html())+len);
		var div=$('<div class="sidepanel_place">'+
					'<img src="/img/design/google_maps_icon.png"/>'+
					'<i>Места:</i> '+
					'</div>');
		for (i=0;i<len;i++) {
			var place=response.Placemark[i];
				var text=place.address.replace(", Bulgaria","");
				var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				$('<a href="javascript:;">'+text+'</a><br/>')
				.data("point",point)
				.click(function() { map.setCenter($(this).data("point"), 13); })
				.appendTo(div);
		}
		div.append('<div style="clear:both; line-height:1px;"/>')
			.insertBefore(panel.children(".sidepanel_people").children(":first"));
	}
	
	var updateList = function(peopleData) {
		var grouped = groupPeople(peopleData);

		$.each(grouped, function(i, group) {
			var isFirst = group.title=="последните 3 месеца";
			var panel=$('<div/>').data("expanded",group.title=="последните 3 месеца");
			$('<div class="sidepanel_title">'+
					'<div></div>'+
					'<div class="toggleSwitch">'+(isFirst?'затвори':'отвори')+'</div>'+
					'През '+group.title+
					'</div>')
				.click(function () { toggleGroup(panel); updateMarkers(); } )
				.mouseover(function() {$(this).children(".toggleSwitch").show();})
				.mouseout(function() {$(this).children(".toggleSwitch").hide();})
				.appendTo(panel);
			var peopleDiv=$('<div class="sidepanel_people"/>')
				.css("display", isFirst?'block':'none')
				.appendTo(panel);
			var numberDiv=$('<div class="sidepanel_number">'+
					'<div class="number">'+group.people.length+'</div>'+
					'</div>')
				.css("display", isFirst?'none':'block')
				.click(function () { toggleGroup(panel); updateMarkers(); } )
				.mouseover(function() {$(this).siblings(":first").children(".toggleSwitch").show();})
				.mouseout(function() {$(this).siblings(":first").children(".toggleSwitch").hide();})
				.appendTo(panel);
			$.each(group.people, function(i, person) {
				var code=createPersonSidepanel(person);
				code.appendTo(peopleDiv);
				if (numberDiv.children().size()<7)
					numberDiv.append('<img src="/img/design/transparent.gif" style="background:'+person.getSpriteIcon()+';"/>');
			});
			numberDiv.append('<img src="/img/design/cover1.png" class="cover"/>');
			panel.appendTo(holder);
		});
	}

	var createPersonSidepanel = function(person) {
		return $('<div class="sidepanel_person">'+
				person.getSpriteBigImage(50, "float:right")+
				person.getData().ime+'<br/>'+
				'<i>Липсва от:</i> '+person.getData().vreme+'<br/>'+
				(person.getData().mqstoT?'<i>Последно видян:</i> '+person.getData().mqstoT+'<br/>':'')+
				'</div>')
			.data("hash",person.getData().hash)
			.click(function() { markerman.centerMarkerForPerson(person); });
	}
		
	var closeAllGroups = function() {
		holder.children("div").each(function(i,panel) {
			if ($(panel).data("expanded"))
				toggleGroup($(panel));
		});
	}

	var toggleGroup = function(panel) { 
		expanded=panel.data("expanded");
		panel.data("expanded",!expanded);
		panel.children(":first").children(".toggleSwitch").html(!expanded?'затвори':'отвори');
		if (panel.children(".sidepanel_number")) {
			if (!expanded)		
				panel.children(".sidepanel_number").hide();
			else
				panel.children(".sidepanel_number").show();
		}
		if (panel.children(".sidepanel_people")) {
			if (!expanded)		
				panel.children(".sidepanel_people").fadeIn();
			else
				panel.children(".sidepanel_people").fadeOut();
		}
	}

	 

	var groupPeople = function(peopleData) {
		peopleData=sortPeople(peopleData);

		var last3months = new Array();
		var yearwise = new Array();
		$.each(peopleData, function(i, person) {
			var date=new Date(person.getData().vreme);
			var year=date.getFullYear();
			var diff=(new Date()-date)/1000/60/60/24;
			if (diff<92)
				last3months.push(person);
			else {
				if (!yearwise[year])
					yearwise[year]=new Array();
				yearwise[year].push(person);
			}
		});		

		var temp = new Array();
		$.each(yearwise, function(year, peopleData) {
			if (peopleData)
				temp.push(peopleData);
		});
		while (temp.length>5) {
			var minsize=-1;
			var minsizei;
			for (i=0;i<temp.length-2;i++) {
				newsize=temp[i].length+temp[i+1].length;
				if (minsize>newsize || minsize==-1) {
					minsize=newsize;
					minsizei=i;
				}
			}
			var temp1=new Array();
			for (i=0;i<temp.length;i++) {
				if (i!=minsizei)
					temp1.push(temp[i]);
				else {	
					temp1.push(temp[i+1].concat(temp[i]));
					i++;
				}		
			}
			temp=temp1;
		}
	
		var result=new Array();

		$.each(temp, function(i, people) {
			var year1=(new Date(people[0].getData().vreme)).getFullYear();
			var year0=(new Date(people[people.length-1].getData().vreme)).getFullYear();
			result.push({"title":year0==year1?year0:'периода '+year0+" - "+year1, "people":people});
		});
		result[result.length-1].title="остатъка на "+result[result.length-1].title;
		result.push({"title":"последните 3 месеца", "people":last3months})
		result.reverse();
		return result;
	}

	var sortPeople = function(peopleData) {
		var peopleSorted = peopleData;
		peopleSorted.sort(function(a,b) {
			var a1=(new Date(a.getData().vreme)).getTime();
			var b1=(new Date(b.getData().vreme)).getTime();
			if (isNaN(b1))
				return 1;
			if (isNaN(a1))
				return -1;
			return a1<b1;
		});
		return peopleSorted;
	}	
	
	var translitTerm = function(term) {
		$.each(translit, function(cyr,lat) {
			if (lat.length>0)
				term=term.replace(new RegExp(lat.join("|"),'gi'),cyr);
		});
		return term;
	}

}

function HeatMapO(themap) {
	var map=themap;
	var markerman;
	var people;
	var messages;
	var tilemap;
	var heatOverlay;
	var disabled;

	var blockRegularMapDisplay=false;

	this.init = function(themarkerman, themessages, thepeople) {
		markerman=themarkerman;
		messages=themessages;
		people=thepeople;
		tilemap=false;
		heatOverlay=false;
		disabled=true;
		
		placeButton();

		if (getURLHeat()) {
			blockRegularMapDisplay=true;
			setTimeout(actionButton,2000);
		}
	}

		
	var display = function() {
		disabled=false;
		if (!tilemap)
			$.getJSON("heatmap/tiles/tiles.json", function(data) {
				tilemap=data;
				display_inner();
			});
		else
			display_inner();	
	}

	var remove = function() {
		disabled=true;
		map.removeOverlay(heatOverlay);
		$('#doheatmap-temp').remove();
		$('#people_list').show();
		markerman.redrawMap();
	}

	var display_inner = function(){
		if (disabled)
			return;

		markerman.cleanMap(); 
		$('#people_list').hide();

		if (getURLHeat())
			$('<div id="doheatmap-temp" style="text-align:center;font-weight:bold;font-size:120%;margin-top:50px;"><a href="http://lipsva.com">Покажи нормалния<br/>изглед със снимки</a></div>')
			.appendTo($('#people_list').parent());
		else
			$('<div id="doheatmap-temp" style="text-align:center;font-weight:bold;font-size:120%;margin-top:50px;"><a href="javascript:;">Покажи нормалния<br/>изглед със снимки</a></div>')
			.click(actionButton).appendTo($('#people_list').parent());

		if (!heatOverlay) {
			var layer = new GTileLayer(new GCopyrightCollection("(CC)"), null, null, {isPng: true, opacity:1.0});
			layer.getTileUrl =function(coord, zoom) {
				if (tilemap && tilemap[zoom-1])					
					for (i=0;i<tilemap[zoom-1].length;i++)
						if (tilemap[zoom-1][i]==coord.x+"_"+coord.y) 
							return 'heatmap/tiles/'+zoom+'/'+tilemap[zoom-1][i]+'.png';
				return 'heatmap/tiles/empty.png';
			};
			heatOverlay = new GTileLayerOverlay(layer);
		}
		map.addOverlay(heatOverlay);
	}

	var placeButton = function() {
		$('<a href="javascript:;" id="doheatmap">Честота на изчезване</a>')
		.click(actionButton).appendTo('#logopanel');
		$('#logopanel').append(' | ');
	}

	var actionButton = function() {
		var button = $("#doheatmap");	
		if (button.html()=="Честота на изчезване") {
			button.html("Нормален изглед");
			display();
		} else {
			button.html("Честота на изчезване");
			remove();
		}
	}

	this.getBlockRegularMapDisplay = function() {
		return blockRegularMapDisplay;
	}

	var getURLHeat = function () {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regex = new RegExp("[\\?&]heat([^&#]*)");
		var results = regex.exec( window.location.href );
		return results != null;
	}
}

function initialize() {


	if (!GBrowserIsCompatible()) return;

	var map;
	if (($.browser.msie && jQuery.browser.version<'8.0') || $.browser.opera) {
		 
		$('#map_canvas').css({'width':$('body').width()-300,'height':$('body').height()});
	}
	map = new GMap2(document.getElementById("map_canvas"), { mapTypes:[G_NORMAL_MAP, G_HYBRID_MAP, G_SATELLITE_MAP ]});
	map.enableScrollWheelZoom();

	map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());

	var messages = new MessagesO();
	var positioner = new PositionerO(map);
	var people = new PeopleO();
	var markerman = new MarkerManagerO(map);
	var list = new ListO(map);
	var sidepanel = new SidePanelO(map);
	var heatmap = new HeatMapO(map);

	messages.init();
	markerman.init(people, messages, heatmap);
	list.init(people);
	positioner.init(people,markerman);
	heatmap.init(markerman, messages, people); 
	sidepanel.init(people,markerman, messages); 
	people.load();


 
}


