(function($){$.fn.ajaxSubmit=function(options){if(!this.length){log('ajaxSubmit: skipping submit process - no element selected');return this;}
if(typeof options=='function')
options={success:options};var url=$.trim(this.attr('action'));if(url){url=(url.match(/^([^#]+)/)||[])[1];}
url=url||window.location.href||''
options=$.extend({url:url,type:this.attr('method')||'GET'},options||{});var veto={};this.trigger('form-pre-serialize',[this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');return this;}
if(options.beforeSerialize&&options.beforeSerialize(this,options)===false){log('ajaxSubmit: submit aborted via beforeSerialize callback');return this;}
var a=this.formToArray(options.semantic);if(options.data){options.extraData=options.data;for(var n in options.data){if(options.data[n]instanceof Array){for(var k in options.data[n])
a.push({name:n,value:options.data[n][k]});}
else
a.push({name:n,value:options.data[n]});}}
if(options.beforeSubmit&&options.beforeSubmit(a,this,options)===false){log('ajaxSubmit: submit aborted via beforeSubmit callback');return this;}
this.trigger('form-submit-validate',[a,this,options,veto]);if(veto.veto){log('ajaxSubmit: submit vetoed via form-submit-validate trigger');return this;}
var q=$.param(a);if(options.type.toUpperCase()=='GET'){options.url+=(options.url.indexOf('?')>=0?'&':'?')+q;options.data=null;}
else
options.data=q;var $form=this,callbacks=[];if(options.resetForm)callbacks.push(function(){$form.resetForm();});if(options.clearForm)callbacks.push(function(){$form.clearForm();});if(!options.dataType&&options.target){var oldSuccess=options.success||function(){};callbacks.push(function(data){$(options.target).html(data).each(oldSuccess,arguments);});}
else if(options.success)
callbacks.push(options.success);options.success=function(data,status){for(var i=0,max=callbacks.length;i<max;i++)
callbacks[i].apply(options,[data,status,$form]);};var files=$('input:file',this).fieldValue();var found=false;for(var j=0;j<files.length;j++)
if(files[j])
found=true;var multipart=false;if(options.iframe||found||multipart){if(options.closeKeepAlive)
$.get(options.closeKeepAlive,fileUpload);else
fileUpload();}
else
$.ajax(options);this.trigger('form-submit-notify',[this,options]);return this;function fileUpload(){var form=$form[0];if($(':input[name=submit]',form).length){alert('Error: Form elements must not be named "submit".');return;}
var opts=$.extend({},$.ajaxSettings,options);var s=$.extend(true,{},$.extend(true,{},$.ajaxSettings),opts);var id='jqFormIO'+(new Date().getTime());var $io=$('<iframe id="'+id+'" name="'+id+'" src="about:blank" />');var io=$io[0];$io.css({position:'absolute',top:'-1000px',left:'-1000px'});var xhr={aborted:0,responseText:null,responseXML:null,status:0,statusText:'n/a',getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;$io.attr('src','about:blank');}};var g=opts.global;if(g&&!$.active++)$.event.trigger("ajaxStart");if(g)$.event.trigger("ajaxSend",[xhr,opts]);if(s.beforeSend&&s.beforeSend(xhr,s)===false){s.global&&$.active--;return;}
if(xhr.aborted)
return;var cbInvoked=0;var timedOut=0;var sub=form.clk;if(sub){var n=sub.name;if(n&&!sub.disabled){options.extraData=options.extraData||{};options.extraData[n]=sub.value;if(sub.type=="image"){options.extraData[name+'.x']=form.clk_x;options.extraData[name+'.y']=form.clk_y;}}}
setTimeout(function(){var t=$form.attr('target'),a=$form.attr('action');form.setAttribute('target',id);if(form.getAttribute('method')!='POST')
form.setAttribute('method','POST');if(form.getAttribute('action')!=opts.url)
form.setAttribute('action',opts.url);if(!options.skipEncodingOverride){$form.attr({encoding:'multipart/form-data',enctype:'multipart/form-data'});}
if(opts.timeout)
setTimeout(function(){timedOut=true;cb();},opts.timeout);var extraInputs=[];try{if(options.extraData)
for(var n in options.extraData)
extraInputs.push($('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />').appendTo(form)[0]);$io.appendTo('body');io.attachEvent?io.attachEvent('onload',cb):io.addEventListener('load',cb,false);form.submit();}
finally{form.setAttribute('action',a);t?form.setAttribute('target',t):$form.removeAttr('target');$(extraInputs).remove();}},10);var nullCheckFlag=0;function cb(){if(cbInvoked++)return;io.detachEvent?io.detachEvent('onload',cb):io.removeEventListener('load',cb,false);var ok=true;try{if(timedOut)throw'timeout';var data,doc;doc=io.contentWindow?io.contentWindow.document:io.contentDocument?io.contentDocument:io.document;if((doc.body==null||doc.body.innerHTML=='')&&!nullCheckFlag){nullCheckFlag=1;cbInvoked--;setTimeout(cb,100);return;}
xhr.responseText=doc.body?doc.body.innerHTML:null;xhr.responseXML=doc.XMLDocument?doc.XMLDocument:doc;xhr.getResponseHeader=function(header){var headers={'content-type':opts.dataType};return headers[header];};if(opts.dataType=='json'||opts.dataType=='script'){var ta=doc.getElementsByTagName('textarea')[0];xhr.responseText=ta?ta.value:xhr.responseText;}
else if(opts.dataType=='xml'&&!xhr.responseXML&&xhr.responseText!=null){xhr.responseXML=toXml(xhr.responseText);}
data=$.httpData(xhr,opts.dataType);}
catch(e){ok=false;$.handleError(opts,xhr,'error',e);}
if(ok){opts.success(data,'success');if(g)$.event.trigger("ajaxSuccess",[xhr,opts]);}
if(g)$.event.trigger("ajaxComplete",[xhr,opts]);if(g&&!--$.active)$.event.trigger("ajaxStop");if(opts.complete)opts.complete(xhr,ok?'success':'error');setTimeout(function(){$io.remove();xhr.responseXML=null;},100);};function toXml(s,doc){if(window.ActiveXObject){doc=new ActiveXObject('Microsoft.XMLDOM');doc.async='false';doc.loadXML(s);}
else
doc=(new DOMParser()).parseFromString(s,'text/xml');return(doc&&doc.documentElement&&doc.documentElement.tagName!='parsererror')?doc:null;};};};$.fn.ajaxForm=function(options){return this.ajaxFormUnbind().bind('submit.form-plugin',function(){$(this).ajaxSubmit(options);return false;}).each(function(){$(":submit,input:image",this).bind('click.form-plugin',function(e){var form=this.form;form.clk=this;if(this.type=='image'){if(e.offsetX!=undefined){form.clk_x=e.offsetX;form.clk_y=e.offsetY;}else if(typeof $.fn.offset=='function'){var offset=$(this).offset();form.clk_x=e.pageX-offset.left;form.clk_y=e.pageY-offset.top;}else{form.clk_x=e.pageX-this.offsetLeft;form.clk_y=e.pageY-this.offsetTop;}}
setTimeout(function(){form.clk=form.clk_x=form.clk_y=null;},10);});});};$.fn.ajaxFormUnbind=function(){this.unbind('submit.form-plugin');return this.each(function(){$(":submit,input:image",this).unbind('click.form-plugin');});};$.fn.formToArray=function(semantic){var a=[];if(this.length==0)return a;var form=this[0];var els=semantic?form.getElementsByTagName('*'):form.elements;if(!els)return a;for(var i=0,max=els.length;i<max;i++){var el=els[i];var n=el.name;if(!n)continue;if(semantic&&form.clk&&el.type=="image"){if(!el.disabled&&form.clk==el){a.push({name:n,value:$(el).val()});a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}
continue;}
var v=$.fieldValue(el,true);if(v&&v.constructor==Array){for(var j=0,jmax=v.length;j<jmax;j++)
a.push({name:n,value:v[j]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:n,value:v});}
if(!semantic&&form.clk){var $input=$(form.clk),input=$input[0],n=input.name;if(n&&!input.disabled&&input.type=='image'){a.push({name:n,value:$input.val()});a.push({name:n+'.x',value:form.clk_x},{name:n+'.y',value:form.clk_y});}}
return a;};$.fn.formSerialize=function(semantic){return $.param(this.formToArray(semantic));};$.fn.fieldSerialize=function(successful){var a=[];this.each(function(){var n=this.name;if(!n)return;var v=$.fieldValue(this,successful);if(v&&v.constructor==Array){for(var i=0,max=v.length;i<max;i++)
a.push({name:n,value:v[i]});}
else if(v!==null&&typeof v!='undefined')
a.push({name:this.name,value:v});});return $.param(a);};$.fn.fieldValue=function(successful){for(var val=[],i=0,max=this.length;i<max;i++){var el=this[i];var v=$.fieldValue(el,successful);if(v===null||typeof v=='undefined'||(v.constructor==Array&&!v.length))
continue;v.constructor==Array?$.merge(val,v):val.push(v);}
return val;};$.fieldValue=function(el,successful){var n=el.name,t=el.type,tag=el.tagName.toLowerCase();if(typeof successful=='undefined')successful=true;if(successful&&(!n||el.disabled||t=='reset'||t=='button'||(t=='checkbox'||t=='radio')&&!el.checked||(t=='submit'||t=='image')&&el.form&&el.form.clk!=el||tag=='select'&&el.selectedIndex==-1))
return null;if(tag=='select'){var index=el.selectedIndex;if(index<0)return null;var a=[],ops=el.options;var one=(t=='select-one');var max=(one?index+1:ops.length);for(var i=(one?index:0);i<max;i++){var op=ops[i];if(op.selected){var v=op.value;if(!v)
v=(op.attributes&&op.attributes['value']&&!(op.attributes['value'].specified))?op.text:op.value;if(one)return v;a.push(v);}}
return a;}
return el.value;};$.fn.clearForm=function(){return this.each(function(){$('input,select,textarea',this).clearFields();});};$.fn.clearFields=$.fn.clearInputs=function(){return this.each(function(){var t=this.type,tag=this.tagName.toLowerCase();if(t=='text'||t=='password'||tag=='textarea')
this.value='';else if(t=='checkbox'||t=='radio')
this.checked=false;else if(tag=='select')
this.selectedIndex=-1;});};$.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=='function'||(typeof this.reset=='object'&&!this.reset.nodeType))
this.reset();});};$.fn.enable=function(b){if(b==undefined)b=true;return this.each(function(){this.disabled=!b;});};$.fn.selected=function(select){if(select==undefined)select=true;return this.each(function(){var t=this.type;if(t=='checkbox'||t=='radio')
this.checked=select;else if(this.tagName.toLowerCase()=='option'){var $sel=$(this).parent('select');if(select&&$sel[0]&&$sel[0].type=='select-one'){$sel.find('option').selected(false);}
this.selected=select;}});};function log(){if($.fn.ajaxSubmit.debug&&window.console&&window.console.log)
window.console.log('[jquery.form] '+Array.prototype.join.call(arguments,''));};})(jQuery);

/* auto complete */
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}(';(3($){$.2e.1u({19:3(b,d){5 c=W b=="1B";d=$.1u({},$.M.1T,{Y:c?b:P,y:c?P:b,1J:c?$.M.1T.1J:10,X:d&&!d.1D?10:48},d);d.1y=d.1y||3(a){6 a};d.1v=d.1v||d.1R;6 A.I(3(){1M $.M(A,d)})},L:3(a){6 A.11("L",a)},1k:3(a){6 A.14("1k",[a])},2b:3(){6 A.14("2b")},28:3(a){6 A.14("28",[a])},24:3(){6 A.14("24")}});$.M=3(o,r){5 t={2Y:38,2S:40,2N:46,2I:9,2E:13,2B:27,2x:3I,2v:33,2p:34,2n:8};5 u=$(o).3r("19","3o").Q(r.2Q);5 p;5 m="";5 n=$.M.3c(r);5 s=0;5 k;5 h={1F:C};5 l=$.M.32(r,o,1Z,h);5 j;$.1Y.2X&&$(o.2U).11("45.19",3(){4(j){j=C;6 C}});u.11(($.1Y.2X?"43":"42")+".19",3(a){s=1;k=a.2M;3V(a.2M){O t.2Y:a.1d();4(l.N()){l.30()}w{12(0,D)}R;O t.2S:a.1d();4(l.N()){l.2D()}w{12(0,D)}R;O t.2v:a.1d();4(l.N()){l.2C()}w{12(0,D)}R;O t.2p:a.1d();4(l.N()){l.2A()}w{12(0,D)}R;O r.17&&$.1c(r.S)==","&&t.2x:O t.2I:O t.2E:4(1Z()){a.1d();j=D;6 C}R;O t.2B:l.Z();R;3J:1P(p);p=1O(12,r.1J);R}}).2t(3(){s++}).3E(3(){s=0;4(!h.1F){2r()}}).2q(3(){4(s++>1&&!l.N()){12(0,D)}}).11("1k",3(){5 c=(1r.7>1)?1r[1]:P;3 1N(q,a){5 b;4(a&&a.7){16(5 i=0;i<a.7;i++){4(a[i].L.J()==q.J()){b=a[i];R}}}4(W c=="3")c(b);w u.14("L",b&&[b.y,b.F])}$.I(15(u.K()),3(i,a){21(a,1N,1N)})}).11("2b",3(){n.1o()}).11("28",3(){$.1u(r,1r[1]);4("y"2h 1r[1])n.1e()}).11("24",3(){l.1p();u.1p();$(o.2U).1p(".19")});3 1Z(){5 e=l.2g();4(!e)6 C;5 v=e.L;m=v;4(r.17){5 b=15(u.K());4(b.7>1){5 f=r.S.7;5 c=$(o).18().1I;5 d,1H=0;$.I(b,3(i,a){1H+=a.7;4(c<=1H){d=i;6 C}1H+=f});b[d]=v;v=b.3f(r.S)}v+=r.S}u.K(v);1l();u.14("L",[e.y,e.F]);6 D}3 12(b,c){4(k==t.2N){l.Z();6}5 a=u.K();4(!c&&a==m)6;m=a;a=1m(a);4(a.7>=r.29){u.Q(r.26);4(!r.1s)a=a.J();21(a,3a,1l)}w{1q();l.Z()}};3 15(b){4(!b)6[""];4(!r.17)6[$.1c(b)];6 $.4h(b.23(r.S),3(a){6 $.1c(b).7?$.1c(a):P})}3 1m(a){4(!r.17)6 a;5 c=15(a);4(c.7==1)6 c[0];5 b=$(o).18().1I;4(b==a.7){c=15(a)}w{c=15(a.22(a.37(b),""))}6 c[c.7-1]}3 1G(q,a){4(r.1G&&(1m(u.K()).J()==q.J())&&k!=t.2n){u.K(u.K()+a.37(1m(m).7));$(o).18(m.7,m.7+a.7)}};3 2r(){1P(p);p=1O(1l,4g)};3 1l(){5 c=l.N();l.Z();1P(p);1q();4(r.36){u.1k(3(a){4(!a){4(r.17){5 b=15(u.K()).1n(0,-1);u.K(b.3f(r.S)+(b.7?r.S:""))}w{u.K("");u.14("L",P)}}})}};3 3a(q,a){4(a&&a.7&&s){1q();l.35(a,q);1G(q,a[0].F);l.20()}w{1l()}};3 21(f,d,g){4(!r.1s)f=f.J();5 e=n.31(f);4(e&&e.7){d(f,e)}w 4((W r.Y=="1B")&&(r.Y.7>0)){5 c={4f:+1M 4e()};$.I(r.2Z,3(a,b){c[a]=W b=="3"?b():b});$.4d({4c:"4b",4a:"19"+o.49,2V:r.2V,Y:r.Y,y:$.1u({q:1m(f),47:r.X},c),44:3(a){5 b=r.1A&&r.1A(a)||1A(a);n.1i(f,b);d(f,b)}})}w{l.2T();g(f)}};3 1A(c){5 d=[];5 b=c.23("\\n");16(5 i=0;i<b.7;i++){5 a=$.1c(b[i]);4(a){a=a.23("|");d[d.7]={y:a,F:a[0],L:r.1z&&r.1z(a,a[0])||a[0]}}}6 d};3 1q(){u.1h(r.26)}};$.M.1T={2Q:"41",2P:"3Z",26:"3Y",29:1,1J:3W,1s:C,1f:D,1w:C,1g:10,X:3U,36:C,2Z:{},1X:D,1R:3(a){6 a[0]},1v:P,1G:C,E:0,17:C,S:", ",1y:3(b,a){6 b.22(1M 3T("(?![^&;]+;)(?!<[^<>]*)("+a.22(/([\\^\\$\\(\\)\\[\\]\\{\\}\\*\\.\\+\\?\\|\\\\])/2K,"\\\\$1")+")(?![^<>]*>)(?![^&;]+;)","2K"),"<2J>$1</2J>")},1D:D,1E:3S};$.M.3c=3(g){5 h={};5 j=0;3 1f(s,a){4(!g.1s)s=s.J();5 i=s.2H(a);4(g.1w=="3R"){i=s.J().1k("\\\\b"+a.J())}4(i==-1)6 C;6 i==0||g.1w};3 1i(q,a){4(j>g.1g){1o()}4(!h[q]){j++}h[q]=a}3 1e(){4(!g.y)6 C;5 f={},2G=0;4(!g.Y)g.1g=1;f[""]=[];16(5 i=0,2F=g.y.7;i<2F;i++){5 c=g.y[i];c=(W c=="1B")?[c]:c;5 d=g.1v(c,i+1,g.y.7);4(d===C)1V;5 e=d.3Q(0).J();4(!f[e])f[e]=[];5 b={F:d,y:c,L:g.1z&&g.1z(c)||d};f[e].1U(b);4(2G++<g.X){f[""].1U(b)}};$.I(f,3(i,a){g.1g++;1i(i,a)})}1O(1e,25);3 1o(){h={};j=0}6{1o:1o,1i:1i,1e:1e,31:3(q){4(!g.1g||!j)6 P;4(!g.Y&&g.1w){5 a=[];16(5 k 2h h){4(k.7>0){5 c=h[k];$.I(c,3(i,x){4(1f(x.F,q)){a.1U(x)}})}}6 a}w 4(h[q]){6 h[q]}w 4(g.1f){16(5 i=q.7-1;i>=g.29;i--){5 c=h[q.3O(0,i)];4(c){5 a=[];$.I(c,3(i,x){4(1f(x.F,q)){a[a.7]=x}});6 a}}}6 P}}};$.M.32=3(e,g,f,k){5 h={H:"3N"};5 j,z=-1,y,1t="",1S=D,G,B;3 2y(){4(!1S)6;G=$("<3M/>").Z().Q(e.2P).T("3L","3K").1Q(1K.2w);B=$("<3H/>").1Q(G).3G(3(a){4(U(a).2u&&U(a).2u.3F()==\'2s\'){z=$("1L",B).1h(h.H).3D(U(a));$(U(a)).Q(h.H)}}).2q(3(a){$(U(a)).Q(h.H);f();g.2t();6 C}).3C(3(){k.1F=D}).3B(3(){k.1F=C});4(e.E>0)G.T("E",e.E);1S=C}3 U(a){5 b=a.U;3A(b&&b.3z!="2s")b=b.3y;4(!b)6[];6 b}3 V(b){j.1n(z,z+1).1h(h.H);2o(b);5 a=j.1n(z,z+1).Q(h.H);4(e.1D){5 c=0;j.1n(0,z).I(3(){c+=A.1a});4((c+a[0].1a-B.1b())>B[0].3x){B.1b(c+a[0].1a-B.3w())}w 4(c<B.1b()){B.1b(c)}}};3 2o(a){z+=a;4(z<0){z=j.1j()-1}w 4(z>=j.1j()){z=0}}3 2m(a){6 e.X&&e.X<a?e.X:a}3 2l(){B.2z();5 b=2m(y.7);16(5 i=0;i<b;i++){4(!y[i])1V;5 a=e.1R(y[i].y,i+1,b,y[i].F,1t);4(a===C)1V;5 c=$("<1L/>").3v(e.1y(a,1t)).Q(i%2==0?"3u":"3P").1Q(B)[0];$.y(c,"2k",y[i])}j=B.3t("1L");4(e.1X){j.1n(0,1).Q(h.H);z=0}4($.2e.2W)B.2W()}6{35:3(d,q){2y();y=d;1t=q;2l()},2D:3(){V(1)},30:3(){V(-1)},2C:3(){4(z!=0&&z-8<0){V(-z)}w{V(-8)}},2A:3(){4(z!=j.1j()-1&&z+8>j.1j()){V(j.1j()-1-z)}w{V(8)}},Z:3(){G&&G.Z();j&&j.1h(h.H);z=-1},N:3(){6 G&&G.3s(":N")},3q:3(){6 A.N()&&(j.2j("."+h.H)[0]||e.1X&&j[0])},20:3(){5 a=$(g).3p();G.T({E:W e.E=="1B"||e.E>0?e.E:$(g).E(),2i:a.2i+g.1a,1W:a.1W}).20();4(e.1D){B.1b(0);B.T({2L:e.1E,3n:\'3X\'});4($.1Y.3m&&W 1K.2w.3l.2L==="1x"){5 c=0;j.I(3(){c+=A.1a});5 b=c>e.1E;B.T(\'3k\',b?e.1E:c);4(!b){j.E(B.E()-2R(j.T("2O-1W"))-2R(j.T("2O-3j")))}}}},2g:3(){5 a=j&&j.2j("."+h.H).1h(h.H);6 a&&a.7&&$.y(a[0],"2k")},2T:3(){B&&B.2z()},1p:3(){G&&G.3i()}}};$.2e.18=3(b,f){4(b!==1x){6 A.I(3(){4(A.2d){5 a=A.2d();4(f===1x||b==f){a.4n("2c",b);a.3h()}w{a.4m(D);a.4l("2c",b);a.4k("2c",f);a.3h()}}w 4(A.3g){A.3g(b,f)}w 4(A.1C){A.1C=b;A.3e=f}})}5 c=A[0];4(c.2d){5 e=1K.18.4j(),3d=c.F,2a="<->",2f=e.3b.7;e.3b=2a;5 d=c.F.2H(2a);c.F=3d;A.18(d,d+2f);6{1I:d,39:d+2f}}w 4(c.1C!==1x){6{1I:c.1C,39:c.3e}}}})(4i);',62,272,'|||function|if|var|return|length|||||||||||||||||||||||||else||data|active|this|list|false|true|width|value|element|ACTIVE|each|toLowerCase|val|result|Autocompleter|visible|case|null|addClass|break|multipleSeparator|css|target|moveSelect|typeof|max|url|hide||bind|onChange||trigger|trimWords|for|multiple|selection|autocomplete|offsetHeight|scrollTop|trim|preventDefault|populate|matchSubset|cacheLength|removeClass|add|size|search|hideResultsNow|lastWord|slice|flush|unbind|stopLoading|arguments|matchCase|term|extend|formatMatch|matchContains|undefined|highlight|formatResult|parse|string|selectionStart|scroll|scrollHeight|mouseDownOnSelect|autoFill|progress|start|delay|document|li|new|findValueCallback|setTimeout|clearTimeout|appendTo|formatItem|needsInit|defaults|push|continue|left|selectFirst|browser|selectCurrent|show|request|replace|split|unautocomplete||loadingClass||setOptions|minChars|teststring|flushCache|character|createTextRange|fn|textLength|selected|in|top|filter|ac_data|fillList|limitNumberOfItems|BACKSPACE|movePosition|PAGEDOWN|click|hideResults|LI|focus|nodeName|PAGEUP|body|COMMA|init|empty|pageDown|ESC|pageUp|next|RETURN|ol|nullData|indexOf|TAB|strong|gi|maxHeight|keyCode|DEL|padding|resultsClass|inputClass|parseInt|DOWN|emptyList|form|dataType|bgiframe|opera|UP|extraParams|prev|load|Select|||display|mustMatch|substring||end|receiveData|text|Cache|orig|selectionEnd|join|setSelectionRange|select|remove|right|height|style|msie|overflow|off|offset|current|attr|is|find|ac_even|html|innerHeight|clientHeight|parentNode|tagName|while|mouseup|mousedown|index|blur|toUpperCase|mouseover|ul|188|default|absolute|position|div|ac_over|substr|ac_odd|charAt|word|180|RegExp|100|switch|400|auto|ac_loading|ac_results||ac_input|keydown|keypress|success|submit||limit|150|name|port|abort|mode|ajax|Date|timestamp|200|map|jQuery|createRange|moveEnd|moveStart|collapse|move'.split('|'),0,{}))

/* flash */
;(function(){var $$;$$=jQuery.fn.flash=function(htmlOptions,pluginOptions,replace,update){var block=replace||$$.replace;pluginOptions=$$.copy($$.pluginOptions,pluginOptions);if(!$$.hasFlash(pluginOptions.version)){if(pluginOptions.expressInstall&&$$.hasFlash(6,0,65)){var expressInstallOptions={flashvars:{MMredirectURL:location,MMplayerType:'PlugIn',MMdoctitle:jQuery('title').text()}};}else if(pluginOptions.update){block=update||$$.update;}else{return this;}}
htmlOptions=$$.copy($$.htmlOptions,expressInstallOptions,htmlOptions);return this.each(function(){block.call(this,$$.copy(htmlOptions));});};$$.copy=function(){var options={},flashvars={};for(var i=0;i<arguments.length;i++){var arg=arguments[i];if(arg==undefined)continue;jQuery.extend(options,arg);if(arg.flashvars==undefined)continue;jQuery.extend(flashvars,arg.flashvars);}
options.flashvars=flashvars;return options;};$$.hasFlash=function(){if(/hasFlash\=true/.test(location))return true;if(/hasFlash\=false/.test(location))return false;var pv=$$.hasFlash.playerVersion().match(/\d+/g);var rv=String([arguments[0],arguments[1],arguments[2]]).match(/\d+/g)||String($$.pluginOptions.version).match(/\d+/g);for(var i=0;i<3;i++){pv[i]=parseInt(pv[i]||0);rv[i]=parseInt(rv[i]||0);if(pv[i]<rv[i])return false;if(pv[i]>rv[i])return true;}
return true;};$$.hasFlash.playerVersion=function(){try{try{var axo=new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');try{axo.AllowScriptAccess='always';}
catch(e){return'6,0,0';}}catch(e){}
return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g,',').match(/^,?(.+),?$/)[1];}catch(e){try{if(navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin){return(navigator.plugins["Shockwave Flash 2.0"]||navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g,",").match(/^,?(.+),?$/)[1];}}catch(e){}}
return'0,0,0';};$$.htmlOptions={height:240,flashvars:{},pluginspage:'http://www.adobe.com/go/getflashplayer',src:'#',type:'application/x-shockwave-flash',width:320};$$.pluginOptions={expressInstall:false,update:true,version:'6.0.65'};$$.replace=function(htmlOptions){this.innerHTML='<div class="alt">'+this.innerHTML+'</div>';jQuery(this).addClass('flash-replaced').prepend($$.transform(htmlOptions));};$$.update=function(htmlOptions){var url=String(location).split('?');url.splice(1,0,'?hasFlash=true&');url=url.join('');var msg='<p>This content requires the Flash Player. <a href="http://www.adobe.com/go/getflashplayer">Download Flash Player</a>. Already have Flash Player? <a href="'+url+'">Click here.</a></p>';this.innerHTML='<span class="alt">'+this.innerHTML+'</span>';jQuery(this).addClass('flash-update').prepend(msg);};function toAttributeString(){var s='';for(var key in this)
if(typeof this[key]!='function')
s+=key+'="'+this[key]+'" ';return s;};function toFlashvarsString(){var s='';for(var key in this)
if(typeof this[key]!='function')
s+=key+'='+encodeURIComponent(this[key])+'&';return s.replace(/&$/,'');};$$.transform=function(htmlOptions){htmlOptions.toString=toAttributeString;if(htmlOptions.flashvars)htmlOptions.flashvars.toString=toFlashvarsString;return'<embed '+String(htmlOptions)+'/>';};if(window.attachEvent){window.attachEvent("onbeforeunload",function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};});}})();

var TINY_MCE = false;
var TINY_TIMER = 0;
var ADMIN = false;

var Loader = (function() {
    var smallLoader;
return {
    init: function() {
	smallLoader = $('#small-loading-indicator');
    },
    sShow: function() {
	smallLoader.show();
    },
    sHide: function() {
	smallLoader.hide();
    }
}
})();

function initTiny() {
    if (TINY_MCE && $('#add-banner-description_parent').size() < 1) {
	jQuery.ajaxSettings.cache = true;
	$('#add-banner-description').tinymce({
	    script_url: '/tiny/tiny_mce.js',
	    theme: 'advanced',
	    theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,formatselect", /* ,fontsizeselect */
	    theme_advanced_buttons2: "bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,image,cleanup,help,code,|,insertdate,inserttime,preview",
	    theme_advanced_buttons3: "hr,removeformat,visualaid,|,sub,sup,|,charmap,iespell,media,advhr,|,fullscreen",
	    theme_advanced_toolbar_location: "top",
	    theme_advanced_toolbar_align: "left",
	    theme_advanced_resizing: true,
	    theme_advanced_statusbar_location: "bottom",
	    plugins: "safari,pagebreak,style,layer,table,advhr,advimage,advlink,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
	    content_css: "/css/commons.css"
	});
	jQuery.ajaxSettings.cache = false;
	clearTimeout(TINY_TIMER);
    } else {
	TINY_TIMER = setTimeout(initTiny, 1500);
    }
}

var Auth = (function() {
    function getAuthForm() {
	return '<div id="auth"><form action="/auth.html" method="POST">\
	    <p><label for="auth-mail">Логин:&nbsp;</label><input type="text" name="users_email" id="auth-mail"><input type="hidden" name="do" value="log_in"></p>\
	    <p><label for="auth-password">Пароль:&nbsp;</label><input type="password" name="users_password" id="auth-password"></p>\
	    <p id="auth-message">&nbsp;</p><p class="tac"><input type="submit" value="Войти"></p>\
	</form></div>';
    }
    
    function getConsole() {
	var index = (location.hash.match('\/index')) ? ' class="index"' : '';
	return '<div id="console"' + index + '>\
	    <ul class="container">\
		<li><a href="#/banner" id="add-banner">&nbsp;</a></li>\
		<li><a href="#/banner?banner_id=' + $('#banner_id').val() + '" id="edit-banner">&nbsp;</a></li>\
		<li><a href="#" id="remove-banner">&nbsp;</a></li>\
		<li><a href="/auth.html?do=log_out" id="exit">&nbsp;</a></li>\
	    </ul><i class="right">&nbsp;</i>\
	</div>';
    }
    
    function initAuthRequest() {
	var authTimer = 0;
	$('#footer form').ajaxForm({
	    type: 'POST', dataType: 'json',
	    beforeSubmit: function() {
		Loader.sShow();
		var isValid = true;
		if ($.trim($('#auth-mail').val()) != '' && $.trim($('#auth-password').val()) != '') {
		    $('#auth-message').html('Отправка отзыва...').css('color', '#666').show();
		} else {
		    isValid = false;
		    $('#auth-message').html('Введите логин и пароль').css('color', '#f00').show();
		}
		return isValid;
	    },
	    success: function(data, status) {
		Loader.sHide();
		if (status == 'success' && data.code == 200) {
		    $('#auth-message').html('Авторизация завершена').css('color', '#090').show();
		    Comment.showDelButtons();
		    if ($('#console').size() == 0) $(document.body || document.documentElement).append(getConsole());
		    ADMIN = true;
		    getTinyScripts();
		    authTimer = setTimeout(function() {
			$('#auth-message').fadeOut();
			$('#auth').hide();
		    }, 3000);
		}
	    }
	});
    }
    function initDeleteBanner() {
        $('#remove-banner').click(function() {
	    if ($('#console').size() > 0 && $('#console').hasClass('index')) {
		var bannerId = $('#banner_id').val();
		$.getJSON('/main.json', 'do=delete&banner_id=' + bannerId, function(data, status) {
		    if (status == 'success') {
                        var cacheData = Cache.getCacheData();
                        if (cacheData.first && cacheData.first == $('#banner_id').val()) {
                            if (cacheData.first == cacheData.last) {
                                BannerProvider.setBanner(null);
                            } else {
                                if (cacheData.newer[0]) {
                                    location.hash = location.hash.replace(/banner_id=\d*/, 'banner_id=' + cacheData.newer[0].banner.banner_id).replace(/&dir=(newer|older)/, '');
                                    console.log(location.hash);
                                    FullAJAX.changeHash(location.hash.substr(1));
                                    BannerProvider.setBanner(cacheData.newer[0]);
                                } else {
                                    location.hash = '#/index?banner_id=';
                                }
                                Cache.clearCache();
                                Cache.get();
                            }
                        } else {
                            if (cacheData.older[0]) {
                                location.hash = location.hash.replace(/banner_id=\d*/, 'banner_id=' + cacheData.older[0].banner.banner_id).replace(/&dir=(newer|older)/, '');
                                console.log(location.hash);
                                FullAJAX.changeHash(location.hash.substr(1));
                                BannerProvider.setBanner(cacheData.older[0]);
                            } else {
                                location.hash = '#/index?banner_id=';
                            }
                            Cache.clearCache();
                            Cache.get();
                        }			
		    }
		});
	    }
	    return false;
	});
    }
    function initEditBanner() {
        $('#edit-banner').click(function() {
	    if ($('#console').size() > 0 && $('#console').hasClass('index')) {
		var bannerId = $('#banner_id').val();
		location.hash = '/banner?do=edit&banner_id=' + bannerId;
	    }
	    return false;
	});
    }
    function initConsole() {
	initDeleteBanner();
	initEditBanner();
    }
    function initAuth() {
	$('#footer p span').bind('click', function() {
	    if ($('#auth').size() == 0) $('#footer').append(getAuthForm());
	    initAuthRequest();
	    var isVisible = $('#auth').css('display') == 'block';
	    (isVisible) ? $('#auth').hide() : $('#auth').show();
	});
    }
    function buildSuggestData(aMass, data) {
	for (var i = 0; i < data.length; i++) aMass[i] = data[i][0];
    }
    function getTinyScripts() {
	$.getScript('/tiny/jquery.tinymce.js', function() {
	    TINY_MCE = true;
	    initTiny();
	});

    }
    function checkAuth() {
	$.getJSON('/main.json', 'do=auth', function(data, status) {
	    if (status == 'success') {
		if (data && data.rights != 'nobody') {
		    ADMIN = true;
		    Auth.printConsole();
		    Auth.getSuggest();
		    Comment.showDelButtons();
		    getTinyScripts();
		} 
	    }
	});
    }
return {
    init: function() {
	initAuth();
	checkAuth();
    },
    printConsole: function() {
	if ($('#console').size() == 0) $(document.body || document.documentElement).append(getConsole());
	initConsole();
    },
    destroyAuthForm: function() {
	$('#footer p span').unbind();
    },
    getSuggest: function() {
	$.getJSON('/main.json', 'do=tags&tags=1&agency_id=&brand_id=&category_id=', function(data, status) {
	    if (status == 'success') {
		for (var name in data) buildSuggestData(window[name.toUpperCase()], data[name]);
		BannerProvider.initSuggest();
	    }
	});
    }
}
})();

function initColor(idColor, idGallery, idInputColor) {
    $('#' + idColor + ' ul li').click(function() {
	$('#' + idGallery)[0].className = this.className;
	if (idInputColor) $('#' + idInputColor).val(this.className);
        return false;
    });
}

var Filter = (function() {
    var oFilter = null;
    var oButton = null;
    var oDo = null;
    var oFields = null;
    var oRecord = {};

    function saveSelectedData() {
	oFields.each( function() {
	    oRecord[this.id] = this.value;
	});
    }
    function printSelectedData() {
	oFields.each( function() {
	    if (this.tagName.toLowerCase() == 'select') {
		var selectedValue = $(this).find('option[value=' + oRecord[this.id] + ']');
		if (selectedValue.size() > 0) selectedValue.attr('selected', 'selected');
	    }
	});
    }
    function fillField(obj, data) {
	if (obj && data) {
	    var aObj = [ '<option value="">все</option>' ];
	    for (var i = 0; i < data.length; i++) aObj[i+1] = '<option value="' + data[i][1] + '">' + data[i][0] + '</option>';
	    obj.html(aObj.join(''));
	}
    }
    function printFields(data) {
	oFields.each(function() {
	    try { fillField($(this), data[this.id]); } catch(err) {}
	});
    }
    function _fillField(obj, data) {
	if (obj && data) {
	    var aObj = [ '<option vaue="">все</option>' ];
	    for (var i = 0; i < data.length; i++) aObj[i+1] = '<option value="' + data[i].tag_id + '">' + data[i].tag_title + '</option>';
	    obj.html(aObj.join(''));
	}
    }
    function _printFields(data) {
	oFields.each(function() {
	    try { _fillField($(this), data[this.id]); } catch(err) {}
	});
    }
    function getFields() {
	saveSelectedData();
	oDo.val('tags');
	oFilter.ajaxSubmit({
	    type: 'GET', dataType: 'json',
	    beforeSubmit: function() {
		Loader.sShow();
		oFields.add(oButton).attr('disabled', 'disabled');
	    },
	    success: function(data, status) {
		Loader.sHide();
		oFields.add(oButton).attr('disabled', '');
		oDo.val('search');
		oFields.each( function() {
		    try { fillField($(this), data[this.id]); } catch(err) {}
		});
		printSelectedData();
	    }
	});
    }
    function initGetFields() {
	oFields.bind('change',getFields);	
    }
    function clear() {
	oFields.add(oButton).attr('disabled', '');
	oFields.filter('select').find('option:first').attr('selected', 'selected');
	oFields.filter('input').not('non-change').val('');
    }
return {
    init: function() {
	oFilter = $('#filter form');
	oButton = oFilter.find('input[type=submit]');
	$('#filter-show-all').click(function() {
	    clear();
	});
	oDo = oFilter.find('input[name=do]');
	oFields = oFilter.find('select, input[type=text], input[type=hidden]');
	initGetFields();
	clear();
    },
    printFields: function(data) {
	_printFields(data);
    },
    getFields: function() {
	getFields();
    }
}
})();

function checkFlash(sPath) {
    var obj = $('#' + sPath +  ' img');
    if (obj.attr('src').match('.swf')) {
	var path = obj.attr('src');
	if (path == '/banners/2158173121114891.swf') { //banner GT
		$('#' + sPath).html('<iframe width="1108" height="802" frameborder="0" src="http://www.smartnewsolutions.ru/festival/cannes/gt5/"></iframe>');
		return;
	}
	
	var dimantion = obj[0].className.split('|');
	$('#' + sPath).html('');
	$('#' + sPath).flash({
	    src: path,
	    wmode: 'opaque',
	    width: dimantion[0] || 0,
	    height: dimantion[1] || 0
	});
    }
}

var Cache = (function() {
    var nCurNumber, nLastNumber, nFirstNumber;
    nCurNumber = nLastNumber = nFirstNumber = -1;
    var nLuft = null;
    var dir = null;
    var oLast = {
	id: 0,
	banner: null
    };
    var oFirst = {
	id: 0,
	banner: null
    };
    var oNext = {
	type: 'newer',
	counter: 0,
	current: 0
    };
    var oPrevious = {
	type: 'older',
	counter: 0,
	current: 0
    };
    var aId = [];
    var oCache = {
	newer: [],
	older: [],
	current: null
    };
    function getCurrent(id) {
	id = id || '';
	$.getJSON('/main.json', 'do=banner&banner_id=' + id, function(data, status) {
	    if (status == 'success' && data.banner && data.banner.banner_id) {
		oCache.current = data.banner;
	    }
	});
    }
    function changeButton() {
	(oCache.newer.length == 0) ? $('#next').hide() : $('#next').show();
	(oCache.older.length == 0) ? $('#previous').hide() : $('#previous').show();
    }
    function get(obj) {
	obj.counter = oCache[obj.type].length;
	obj.current = (obj.counter > 0 && oCache[obj.type][obj.counter - 1]) ?  oCache[obj.type][obj.counter - 1].banner.banner_id : obj.current;
	var isBoundary = (obj.current == nLastNumber && obj.type == 'newer') || (obj.current == nFirstNumber && obj.type == 'older');
	if (!isBoundary) {
	    $.getJSON('/main.json', 'do=banner&banner_id=' + obj.current + '&dir=' + obj.type, function(data, status) {
		if (status == 'success' && data.banner && data.banner.banner_id) {
		    oCache[obj.type][obj.counter] = {};
		    oCache[obj.type][obj.counter++].banner = data.banner;
		    obj.current = data.banner.banner_id;			
		    if (obj.counter < nLuft) get(obj);
		} else {
		    if (obj.type == 'newer') {
			nLastNumber = obj.current;
			oLast.id = obj.current;
			oLast.banner = data.banner;
		    } else {
			nFirstNumber = obj.current;
			oFirst.id = obj.current;
			oFirst.banner = data.banner;
		    }
		}
	    });
	}
	changeButton();
    }
    function reset(obj) {
	obj.count = 0;
	obj.current = nCurNumber;
    }
    function getCache(obj) {
	reset(obj);
	get(obj);
    }
    function clearCache() {
	oNext = {
	    type: 'newer',
	    counter: 0,
	    current: 0
	};
	oPrevious = {
	    type: 'older',
	    counter: 0,
	    current: 0
	};
        oCache.newer.length = oCache.older.length = 0;
	oCache.newer = [];
        oCache.older = [];
	oCache.current = null;
    }
    function checkDir(id, dir) {
	var hit = false;
	var bannerId;
	for (var i = 0; i < oCache[dir].length; i++) {
	    try {
		bannerId = oCache[dir][i].banner.banner_id;
		if (bannerId == id) {
		    hit = true;
		    return {
			hit: true,
			data: oCache[dir][i].banner,
			index: i,
			direction: dir,
			boundary: bannerId == nLastNumber || bannerId == nFirstNumber || (oCache[dir].length - 1) == i
		    }
		}
	    } catch(err) {
		alert('error');
		return { hit: false, data: null, index: null, direction: dir, boundary: null };
	    }; 
	}
	return { hit: false, data: null, index: null, direction: dir, boundary: null };
    }
    function check(id, dir) {
	var isHit;
	if (dir) {
	    isHit = checkDir(id, dir);
	} else {
	    var hitNewer = checkDir(id, 'newer');
	    var hitOlder = checkDir(id, 'older');
	    var nCurId = (oCache.current) ? oCache.current.banner_id : nCurNumber;
	    if (hitNewer.hit) {
		isHit = hitNewer;
	    } else if (hitOlder.hit) {
		isHit = hitOlder;
	    } else if (id == nCurId) {
		isHit = { hit: true, data: oCache.current, index: null, direction: null, boundary: false };
	    } else {
		isHit = { hit: false, data: null, index: null, direction: null, boundary: null };
	    }
	}
	return isHit;
    }
    function getItem(id, dir) {
	dir = dir || null;
	var item = check(id, dir);
	if (!item.hit) item = check(id);
	if (item.hit) {
	    var other = (item.direction == 'newer') ? 'older' : 'newer';
	    oCache[other].unshift({ banner: oCache.current });
	    for (var i = 0; i < item.index; i++) oCache[other].unshift(oCache[item.direction].shift());
	    oCache.current = oCache[item.direction].shift().banner;
	    nCurNumber = oCache.current.banner_id;
	    if (item.boundary) oCache[item.direction] = [];
	    (item.direction == 'newer') ? getCache(oNext) : getCache(oPrevious);
	    return oCache;
	}
	return false;
    }
return {
    setLastNumber: function() {
	if (arguments.length > 0) $('#last_banner_id').val(arguments[0]);
	nLastNumber = $('#last_banner_id').val();
    },
    setCurrentNumber: function(id) {
	nCurNumber = id || $('#banner_id').val();
    },
    init: function(_nLuft) {
	/*nLastNumber =*/ nCurNumber = $('#banner_id').val();
	nLuft = _nLuft;
    },
    getLast: function() {
	$.getJSON('/main.json', 'do=banner&banner_id=', function(data, status) {
	    nLastNumber = oLast.id = data.banner.banner_id;
	    oLast.banner = data.banner;
	});
    },
    getFirst: function() {
	$.getJSON('/main.json', 'do=banner&first=1', function(data, status) {
	    nFirstNumber = oFirst.id = data.banner.banner_id;
	    oFirst.banner = data.banner;
	});
    },
    getNeighbourId: function(id, dir) {
	var result = check(id);
	var neighbourId = null;
	if (result.hit) { 
	    if (result.index != null && result.index >= 0) {
		neighbourId = (oCache[result.direction][result.index - 1]) ? oCache[result.direction][result.index - 1].banner.banner_id : null;
	    } else {
		neighbourId = (oCache[dir].length> 0) ? oCache[dir][0].banner.banner_id : null;
	    }
	}
	return neighbourId;
    },
    get: function() {
	if (!oCache.current) getCurrent($('#banner_id').val());
	if (nCurNumber != nLastNumber) getCache(oNext);
	if (nCurNumber != nFirstNumber) getCache(oPrevious);
    },
    getItem: function(id, dir) {
	return getItem(id, dir);
    },
    check: function(id, dir) {
	return check(id, dir);
    },
    setCurrent: function(banner) {
	oCache.current = banner;
    },
    test: function() {
	console.dir(oCache);
    },
    getCacheData: function() {
	return {
	    newer: oCache.newer,
	    older: oCache.older,
	    current: oCache.current,
	    last: nLastNumber,
	    first: nFirstNumber
	};
    },
    clearCache: function() {
	clearCache();
    }
}
})();

var BannerProvider = (function() {
    var _oThis = this;
    var timer = 0;
    var ratingTimer = 0;
    function initEditScore() {
	function changeScore() {
	    $(this).val($(this).val().replace(new RegExp(/[^0-9\.,]/g), ''));
	    var score = $('#rating-plus-add input').val() - $('#rating-minus-add input').val();
	    if (score > 0) score = '+' + score;
	    $('#rating-score-add').html(score);
	}
	$('#rating-plus-add input, #rating-minus-add input').bind('keyup', changeScore).bind('keydown', changeScore).bind('blur', changeScore);
    }
    function setBannerRating(bd) {
	$('#rating-score').html((bd.banner_raiting - 0 == 0 || bd.banner_raiting - 0 < 0) ? bd.banner_raiting : '+' + bd.banner_raiting);
	$('#rating-plus').html('<i></i>' + bd.banner_raiting_plus);
	$('#rating-minus').html('<i></i>' + bd.banner_raiting_minus);	
    }
    function setBanner(data, comments) {
        clearTimeout(ratingTimer);
        $('#rating-message').hide();
	function setField(jqPath, data, key, editionalText) {
	    var temp = [];
	    for (var i = 0; i < data.length; i++) temp[i] = '<a href="#/search?' + key + '=' + data[i].tag_id + '">' + data[i].tag_title + '</a>';
	    $(jqPath).html(editionalText + temp.join(', '));
	}
	function clearComments() {
	    $('#comment-items').html('<p>Пока никто не оставил комментарии к этому баннеру.</p>');
	}
	if (data && data.banner && data.banner.banner_id) {
	    Filter.printFields(data);
	    var bd = data.banner;
	    setField('#name h2', bd.brand_loop, 'brand_id', '');
	    $('#name h3').html(bd.banner_title);
	    $('#name .date').html(bd.banner_date_norm);
	    setField('#name .agency', bd.agency_loop, 'agency_id', 'Выполнено: ');
	    setField('#description .category', bd.category_loop, 'category_id', 'Категории: ');
	    setField('#description .tags', bd.tag_loop, 'tag_id', '');
	    setBannerRating(bd);
	    setFile(bd);
	    $('#banner_id').val(bd.banner_id);
            if (ADMIN) $('#edit-banner').attr('href', '#/banner?do=edit&banner_id=' + bd.banner_id);
	    $('#text-content').html(bd.banner_comment);
	    $('#gallery')[0].className = bd.banner_bg_color;
	    $('#other-content').hide();
	    $('#index').show();
	    (arguments.length == 1 || !comments) ? clearComments() : Comment.getComments();
	    Cache.setCurrentNumber(bd.banner_id);
	    Cache.get();
	    return bd.banner_id;
	} else {
	    setBanner({
		banner: {
		    brand_loop: [],
		    banner_date_norm: '',
		    banner_file: '/default.jpg',
		    banner_width: 250,
		    tag_loop: [],
		    agency_loop: [],
		    category_loop: [],
		    banner_protect: 0,
		    banner_comment: '',
		    banner_raiting_minus: 0,
		    banner_raiting_plus: 0,
		    banner_bg_color: 'white',
		    banner_title: 'Баннер не найден',
		    banner_raiting: 0,
		    banner_height: 200,
		    banner_id: $('#banner_id').val()
		}
	    });
	    return false;
	}
    }
    function setForm(data) {
	function setField(jqPath, data) {
	    var temp = [];
	    for (var i = 0; i < data.length; i++) temp[i] = data[i].tag_title;
	    $(jqPath).val(temp.join(', '));
	}
	function clearComments() {
	    $('#comment-items').html('<p>Пока никто не оставил комментарии к этому баннеру.</p>');
	}
	data = data.banner;
        setField('#add-banner-brand', data.brand_loop);
	$('#add-banner-name').val(data.banner_title);
	setField('#add-banner-agency', data.agency_loop);
	setField('#add-banner-categories', data.category_loop);
	setField('#add-banner-tags', data.tag_loop);
	$('#rating-score-add').html((data.banner_raiting - 0 == 0 || data.banner_raiting - 0 < 0) ? data.banner_raiting : '+' + data.banner_raiting);
	$('#rating-plus-add input').val(data.banner_raiting_plus);
	$('#rating-minus-add input').val(data.banner_raiting_minus);	
	setFile(data, true);
	$('#add-banner-file-upload-hidden').val(data.banner_file);
	$('#add-banner-width').val(data.banner_width);
	$('#add-banner-height').val(data.banner_height);
	$('#banner_id-add').val(data.banner_id);
	$('#add-banner-description').val(data.banner_comment);
	$('#add-banner-bg-color').val($('#gallery-add')[0].className = data.banner_bg_color);
	try { $('#add-banner-description').val(tinyMCE.getInstanceById('add-banner-description').getContent()); } catch(err) {}
	return data.banner_id;
    }
    
    function formReset(){
	function clearValidation() {
	    $('#add-banner-form input[type=text], #add-banner-form textarea, #add-banner-description_tbl, #add-banner-input').removeClass('invalid').removeClass('valid');
	    $('#add-banner-description_tbl').css('border', 'none').css({ 'border-left': 'solid 1px #ccc', 'border-right': 'solid 1px #ccc' });
	}
	$('#add-banner-bg-color').val($('#gallery-add')[0].className = 'white');
	$('#rating-score-add').html('0');
	clearValidation();
	$('#add-banner-file-upload-hidden').val('');
	$('#banner-add').html('');
	$('#add-banner-message').hide();
	try { tinyMCE.getInstanceById('add-banner-description').setContent(''); } catch(err) {}
	$('#add-banner-form').resetForm();
    }
    
    function initSendForm() {
	var oThis = this;
	this.setStatusInvalid = function(oField) {
	    $(oField).addClass('invalid');
	    if (oField.id == 'add-banner-description') $('#add-banner-description_tbl').addClass('invalid').css('border', 'solid 1px #f00');
	    if (oField.id == 'add-banner-file-upload-hidden') $('#add-banner-input').addClass('invalid');
	    return false;
	}
	this.setStatusValid = function(oField) {
	    $(oField).addClass('valid');
	    if (oField.id == 'add-banner-description') $('#add-banner-description_tbl').addClass('valid').css('border', 'solid 1px #090');
	    if (oField.id == 'add-banner-file-upload-hidden') $('#add-banner-input').removeClass('invalid');
	}
	this.validation = function() {
	    var isValid = true;
	    $('#add-banner-form').find('input[type=text], input[type=hidden], textarea').each(function() {
		if (!$(this).hasClass('additional')) {
		    var isFieldInvalid = $.trim($(this).val()) == '';
		    (isFieldInvalid) ? isValid = oThis.setStatusInvalid(this) : oThis.setStatusValid(this);
		}
	    });
	    return isValid;
	}
	this.printMessage = function(type, text) {
	    var _isValid = null;
	    switch (type) {
		case 'before':
		    _isValid = oThis.validation();
		    if (_isValid) {
			$('#add-banner-message').removeClass().addClass('wait').html('Добавление баннера...').show();
			$('#add-banner-form').find('input[type=submit]').attr('disabled', 'disabled');
		    } else $('#add-banner-message').removeClass().addClass('error').html('Заполнены не все обязательные поля.').show();
		    break;
		case 'error':
		    clearTimeout(timer);
		    $('#add-banner-form').find('input[type=submit]').attr('disabled', '');
		    $('#add-banner-message').removeClass().addClass('error').html(text).show();
		    break;
		case 'success':
		    $('#add-banner-message').removeClass().addClass('success').html('Баннер добавлен.').show();
		    $('#add-banner-form').find('input[type=submit]').attr('disabled', '');
		    timer = setTimeout(function() { $('#add-banner-message').fadeOut(); }, 7000);
	    }
	    return _isValid || false;
	}
	$('#add-banner-form input[type=submit]').bind('click', function() {
	    if ($('#add-banner-description').size() > 0) $('#add-banner-description').val(tinyMCE.getInstanceById('add-banner-description').getContent());
	});
	$('#add-banner-form').ajaxForm({
	    type: 'POST', dataType: 'json',
	    beforeSubmit: function() {
		Loader.sShow();
		return oThis.printMessage('before');
	    },
	    error: function(XHR) {
		Loader.sHide();
		oThis.printMessage('error', XHR.responseText);
	    },
	    success: function(data, status) {
		Loader.sHide();
		if (status == 'success' && data.code == '200') {
		    oThis.printMessage('success');
		    formReset();
		    if (data.data.banner) {
			Cache.setLastNumber(data.data.banner.banner_id);
                        Cache.clearCache();
                        Cache.setCurrent(data.data.banner);
                        location.hash = '#/index?banner_id=' + data.data.banner.banner_id;
		    } else {
			oThis.printMessage('error', data.error)
		    }
		} else oThis.printMessage('error', data.error);
	    }
	});
    }
    function setFile(data, addKey) {
	var additional = (addKey) ? '-add' : '';
	var path = data.path || data.banner_file;
	var extention = path.split('.');
	extention = extention[extention.length - 1].toLowerCase();
	$('#banner' + additional).html('');
	if (extention != 'jpg' && extention != 'jpeg' && extention != 'gif' && extention != 'png' && extention != 'bmp' && extention != 'swf') {
	    oMessage.html('Не верное разрешение файла!').removeClass().addClass('error').show();
	} else {
	    var isFlash = extention == 'swf';
	    if (isFlash) {
			if (data.banner_id != 103) {
				$('#banner' + additional).flash({ src: path, wmode: 'opaque', width: data.banner_width, height: data.banner_height });
			}
			else {
				$('#banner' + additional).html('<iframe width="1108" height="802" frameborder="0" src="http://www.smartnewsolutions.ru/festival/cannes/gt5/"></iframe>');
			}
	    } else {
		$('#banner' + additional).html('<img src="' + path + '" alt="">');
	    }
	}
    }
    function initAjaxFileUpload() {
	var oMessage = $('#gallery-add p.message');
	var ENCTYPE = 'multipart/form-data';
	$('#add-banner-file-upload').bind('change', function() {
	    $('#add-banner-form').attr('enctype', ENCTYPE).find('input[name=do]').val('upload');
	    $('#add-banner-form').ajaxSubmit({
		type: 'POST', dataType: 'json',
		beforeSubmit: function() {
		    Loader.sShow();
		    oMessage.html('Загрузка изображения...').removeClass().addClass('wait').show();
		    $('#add-banner-form').find('input[type=submit]').attr('disabled', 'disabled');
		},
		success: function(data, status) {
		    Loader.sHide();
		    oMessage.html('Изображение загружено...').removeClass().addClass('success').show();
		    timer = setTimeout(function() { oMessage.fadeOut(); }, 3000);
		    $('#add-banner-form').attr('enctype', '').find('input[name=do]').val('set_banner');
		    $('#add-banner-form').find('input[type=submit]').attr('disabled', '');
		    if (status == 'success' && data.code == 200) {
			$('#add-banner-input').css('border', 'none');
			setFile(data.data, true);
			$('#add-banner-width').val(data.data.banner_width);
			$('#add-banner-height').val(data.data.banner_height);
			$('#add-banner-file-upload-hidden').val(data.data.path);
			$('#add-banner-file-upload').val('');			
		    } else {
			oMessage.html(data.error).removeClass().addClass('error').show();
		    }
		}
	    });
	});
    }
    function initSuggest() {
	$('#add-banner-tags').attr('autocomplete', 'off').autocomplete(TAGS, { multiple: true, autoFill: true });
	$('#add-banner-brand').attr('autocomplete', 'off').autocomplete(BRANDS, { multiple: true, autoFill: true });
	$('#add-banner-agency').attr('autocomplete', 'off').autocomplete(AGENCIES, { multiple: true, autoFill: true });
	$('#add-banner-categories').attr('autocomplete', 'off').autocomplete(CATEGORIES, { multiple: true, autoFill: true });
    }
    function getNeighbourBanner(param) {
	var data = Cache.getCacheData();
	//var bannerId = $('#banner_id').val();
	var result = location.hash.match(/banner_id=(\d*)/i);
	var bannerId = (result && result[1]) ? result[1] : $('#banner_id').val();
	var isBoundary = (param == 'newer' && bannerId == data.last) || (param == 'older' && bannerId == data.first);
	if (!isBoundary) {
	    //nextId = (data[param][0]) ? data[param][0].banner.banner_id : null;
	    var nextId = Cache.getNeighbourId(bannerId, param);
	    if (nextId) {
		setBanner({ banner: Cache.getItem(nextId, param).current }, true);
	    } else {
		Loader.sShow();
		$.getJSON('/main.json', 'do=banner&dir=' + param + '&banner_id=' + bannerId, function(data, status) {
		    Loader.sHide();
		    if (status == 'success') setBanner(data, true);
		});
	    }
	} else {
	    alert('Там кажется нет баннера...');
	}
    }
    function getBanner(bannerId, type) {
	var isShow = arguments.length == 1 || !type;
	var data = Cache.getCacheData();
	if (data.current && (data.newer.length > 0 || data.older.length > 0)) {
	    bannerId = (bannerId && bannerId != '') ? bannerId : data.last;
	    var isHit = Cache.check(bannerId);
	    var isCache = isHit.hit || bannerId == Cache.getCacheData().current.banner_id;
	    var oBanner = (isShow && bannerId != Cache.getCacheData().current.banner_id) ? { banner: Cache.getItem(bannerId).current } : { banner: data.current };
	    (isShow) ? setBanner(oBanner, true) : setForm(oBanner);
	} else {
	    Loader.sShow();
	    $.getJSON('/main.json', 'do=banner&banner_id=' + bannerId, function(data, status) {
		Loader.sHide();
		if (status == 'success') {
		    (isShow) ? setBanner(data, true) : setForm(data);
		}
	    });
	}	
    }
    function initNavigation() {
	$('#previous, #next').click(function() {
	    var direction = (this.id == 'next') ? 'newer' : 'older';
	    var sHash = location.hash; 
	    if (sHash.split('?').length <= 1) sHash += '?';
	    sHash = (sHash.match('banner_id=')) ? sHash.replace(/banner_id=\d*/gi, 'banner_id=' + $('#banner_id').val()) : sHash + '&banner_id=' + $('#banner_id').val();
	    sHash = (sHash.match('dir=')) ? sHash.replace(/dir=(newer|older)/gi, 'dir=' + direction) : sHash + '&dir=' + direction;
	    location.hash = sHash.replace('?&', '?').replace(/&comment_id=\d*|comment_id=\d*&/i, '');
	    return false;
	});
    }
    function initRating() {
	var oMessage = $('#rating-message');
	ratingTimer = 0;
	function changeScore(obj, delta, editional, abs) {
	    abs = abs || false;
	    var sScore = obj.html().replace(/\D/gi, '') - 0 + delta;
	    if (sScore > 0 && !abs) sScore = '+' + sScore;
	    if (abs) sScore = Math.abs(sScore - 0);
	    editional = editional || '';
	    obj.html(editional + sScore);
	}
	$('#rating-plus, #rating-minus').click(function() {
	    var oObj = $(this);
	    var sBannerId = $('#banner_id').val();
	    var sVote = (this.id == 'rating-minus') ? -1 : 1;
	    clearTimeout(ratingTimer);
	    oMessage.html('Отправка голоса...').removeClass().addClass('wait').show();
	    Loader.sShow();
	    $.getJSON('/main.json', 'do=vote&banner_id=' + sBannerId + '&vote=' + sVote, function(data, status) {
		Loader.sHide();
		if (data && data.code) {
		    if (data.code == 200) {
			changeScore($('#rating-score'), sVote);
			changeScore(oObj, 1, '<i></i>', true);
			oMessage.html('Голос учтен. Спасибо!').removeClass().addClass('success').show();
			ratingTimer = setTimeout(function() { oMessage.hide(); }, 7000);
		    } else {
			clearTimeout(ratingTimer);
			oMessage.html(data.error).removeClass().addClass('error').show();
		    }
		}
	    });
	    return false; 
	});
    }
    function refreshRating() {
	Loader.sShow();
	$.getJSON('/main.json', 'do=banner&banner_id=' + $('#banner_id').val(), function(data, status) {
	    Loader.sHide();
	    if (status == 'success') setBannerRating(data.banner);
	});
    }

return {
    init: function() {
	initColor('color', 'gallery');
	initNavigation();
	initRating();
	Comment.init();
	if (location.hash.match('index')) {
	    var isId = location.hash.match(/banner_id=(\d*)/);
	    if (!location.hash.match(/newer|older/gi) && (!isId || isId[1] == '')) {
		Cache.get();
		Comment.getComments();
	    }
	    if (location.hash.substr(2) == 'index') refreshRating();
	}
    },
    loadPage: function(HTML, currentPage) {
	$('#index, #other-content > *').hide();
	if ($('#add-banner-form').size() == 0) {
	    $('#other-content').append(HTML);
	    FullAJAX.addHashedPage('banner');
	    initColor('color-add', 'gallery-add', 'add-banner-bg-color');
	    initTiny();
	    initSuggest();
	    initEditScore();
	    initSendForm();
	    initAjaxFileUpload();
	}
	if (currentPage.extraObj && currentPage.extraObj['do'] && currentPage.extraObj['do'] == 'edit') {
	    getBanner(currentPage.extraObj.banner_id, true);
	} else {
	    formReset();
	}
	$('#other-content').show();
	$('#add-banner-form').show();
    },
    initSuggest: function() {
	initSuggest();
    },
    getNeighbourBanner: function(param) {
	getNeighbourBanner(param);
    },
    getBanner: function(bannerId) {
	getBanner(bannerId);
    },
    setBanner: function(banner) {
        setBanner(banner, true);
    }
}
})();

var Comment = (function() {
    var JUMPING_FORM = null;
    var COMMENT_ID = null;
    function getCommentForm(g) {
	return '<div id="comment-form-jump" class="comment-form"><form action="/main.json" method="POST"><p><input type="hidden" name="do" value="add_comment"><input type="hidden" name="banner_id" value=""><input type="hidden" name="comment_id"><label for="comment-text-jump">Комментарий:</label><textarea id="comment-text-jump" name="comment_text" rows="5" cols="50"></textarea></p><p><label for="comment-name-jump">Имя:</label><input type="text" id="comment-name-jump" name="comment_nick"></p><p id="comment-message-jump">&nbsp;</p><p class="button"><input type="submit" value="Написать"></p></form></div>';
    }
    function initSendComment() {
	var oMessage = $('#comment-message-jump');
	var oForm = $('#comment-form-jump form');
	var sendCommentTimer = 0;
	var oBannerId = oForm.find('input[name=banner_id]');
	oForm.find('input[type=submit]').click(function() {
	    oBannerId.val($('#banner_id').val());
	});
	oForm.ajaxForm({
	    type: 'POST', dataType: 'json',
	    beforeSubmit: function() {
		Loader.sShow();
		clearTimeout(sendCommentTimer);
		var isValid = true;
		oForm.find('input[type=text], textarea').each(function() {
		    if ($.trim($(this).val()) == '') isValid = false; 
		});
		if (isValid) {
		    oMessage.html('Отправка комментария...').removeClass().addClass('wait').show();
		    oBannerId.attr('disabled', 'disabled');
		} else oMessage.html('Заполните все поля').removeClass().addClass('error').show();
		return isValid;
	    },
	    error: function(XHR) {
		Loader.sHide();
		clearTimeout(sendCommentTimer);
		oMessage.html(XHR.responseText).removeClass().addClass('error').show();
		oBannerId.attr('disabled', '');
	    },
	    success: function(data, status) {
		Loader.sHide();
		if (status == 'success') {
		    oMessage.html('Комментарий отправлен. Спасибо!').removeClass().addClass('success').show();
		    sendCommentTimer = setTimeout(function() { oMessage.hide() }, 7000);
		    oBannerId.attr('disabled', '');
		    var currentTime = new Date();
		    var sMonth = currentTime.getMonth() + 1;
		    sMonth = (sMonth < 10) ? '0' + sMonth : sMonth;
		    var sDate = currentTime.getDate() + '.' + sMonth + '.' + currentTime.getFullYear() + ', ' + currentTime.getHours() + ':' + currentTime.getMinutes();
		    var oComment = {
			banner_id: $('#banner_id').val(),
			comment_date_norm: sDate,
			comment_id: data.data.comment_id,
			comment_text: $('#comment-text-jump').val(),
			comment_nick: $('#comment-name-jump').val(), 
			comment_raiting: '0'
		    };
		    var isDownMod = $('#comments').children(':last').hasClass('comment-form');
		    if (isDownMod) {
			printComment(oComment);
		    } else {
			printComment(oComment, $('#comment-form-jump').parent());
			oMessage.hide();
		    }
		}
	    }
	});
    }
    function getTextComment(oItem) {
	var bannerId = $('#banner_id').val();
	var sName = (oItem.comment_nick && oItem.comment_nick != '' && oItem.comment_deleted != '1') ? '★ ' + oItem.comment_nick : '★';
	var sText = (oItem.comment_deleted == '1') ? 'Комментарий удален' : oItem.comment_text;
	var sButtonDel = (ADMIN && oItem.comment_deleted != '1') ? '<span class="comment-delete" comment_id="' + oItem.comment_id + '"><a class="del">Удалить</a></span>' : '';
	return '<li><p class="title"><strong class="name">' + sName + '</strong><span class="date">' + oItem.comment_date_norm + '</span><a href="#/index?banner_id=' + bannerId + '&comment_id=' + oItem.comment_id + '" class="anchor">#</a>' + sButtonDel + '</p><div class="comment"><p>' + sText.replace(/\r\n|\r|\n/g, '<br>') + '</p></div><p class="send"><a comment_id=' + oItem.comment_id + '>Ответить</a></p></li>';
    }
    function printComments(data) {
	var bannerId = $('#banner_id').val();	
	function printItem(oItem, oParent) {
	    $(getTextComment(oItem)).appendTo(oParent).find('p.send a').click(showJumpingForm).end().find('span.comment-delete').click(deleteComment);
	}
	function getTextBranch() {
	    return '<ul></lu>';
	}
	function printAll(oParent, aItems) {
	    for (var i = 0; i < aItems.length; i++) {
		printItem(aItems[i], oParent);
		if (aItems[i].tree) printAll(oParent.find('li:last'), aItems[i].tree);
	    }
	}
	if (data.length > 0) { 
	    $('#comment-items').html('<ul></ul>');
	    printAll($('#comment-items').find('ul'), data);
	} else $('#comment-items').html('<p>Пока никто не оставил комментарии к этому баннеру.</p>');
	initJumpingForm();
    }
    function deleteComment(e) {
	var oThis = $(this);
	var oComment = oThis.parent().parent(); 
	e = (e) ? e.target : event.srcElement;
	if (e.className == 'del') {
	    oThis.html('<span class="yes">Да</span> / <span class="no">Нет</span>');
	} else if (e.className == 'yes') {
	    $(this).after('<span class="wait">Удаление комментария...</span>');
	    Loader.sShow();
	    $.getJSON('/main.json', 'do=delete_comment&comment_id=' + $(this).attr('comment_id'), function(data, status) {
		Loader.sHide();
		if (status == 'success' && data.code == 200) {
		    oComment.find('.name:first').html('★').end().find('div.comment:first').html('<p>Комментарий удален</p>');
		    oThis.next().add(oComment.find('span.comment-delete:first')).remove().empty();
		} else {
		    oThis.next().html('<span class="error">Произошла ошибка: ' + data.error + '</span>');
		}
	    });
	} else if (e.className == 'no') {
	    oThis.html('<a class="del">Удалить</a>');
	}
	return false;
    }
    function goToComment(id) {
	var oCommentAhchor = $('#comment-items li span[comment_id=' + id + ']');
	if (oCommentAhchor.size() > 0) {
	    window.scrollTo(0, oCommentAhchor.parent().offset().top);
	    oCommentAhchor.parent().next().css('background-color', '#e8f4fe');
	} else {
	    window.scrollTo(0, $('#comment-items').offset().top);
	}
    }
    function printComment(oItem, oParent) {
	var root = oParent || $('#comment-items > ul');
	if (root.size() < 1) {
	    $('#comment-items').html('<ul></ul>');
	    root = $('#comment-items > ul');
	}
	$(getTextComment(oItem)).appendTo(root).find('p.send a').click(showJumpingForm).end().find('span.comment-delete').click(deleteComment);
	$('#comment-form-jump').hide();
    }
    function getComments() {
	var oMessage = $('#comment-items');
	$.ajax({
	    url: '/main.json', data: { 'do': 'comments', 'banner_id': $('#banner_id').val() }, type: 'POST', dataType: 'json',
	    beforeSubmit: function() {
		Loader.sShow();
		oMessage.html('Загрузка комментариев...').removeClass().addClass('wait');
	    },
	    error: function(XHR) {
		Loader.sHide();
		oMessage.html(XHR.responseText).removeClass().addClass('error');
	    },
	    success: function(data, status) {
		Loader.sHide();
		if (status == 'success') {
		    printComments(data);
		    var isComment = FullAJAX.hash().match(/comment_id=(\d*)/i);
		    if (isComment) goToComment(isComment[1]);
		}
	    }
	});
    }
    function initGeneralForm() {
	$('#comments').append(getCommentForm());
	initSendComment();
    }
    function initJumpingForm() {
	if ($('#comment-form-jump').size() == 0) $('#comments').append(getCommentForm(true));
	$('#comment-form-jump').hide();
	initSendComment(true);
	COMMENT_ID = $('#comment-form-jump').find('input[name=comment_id]');
    }
    function showJumpingForm() {
	var isDownMod = $(this).parent()[0].tagName.toLowerCase() == 'h2';
	var isHasForm = (isDownMod && $(this).parent().next().hasClass('comment-form')) || $(this).parent().next().hasClass('comment-form');
	if (isHasForm) {
	    ($('#comment-form-jump').css('display') == 'none') ? $('#comment-form-jump').show() : $('#comment-form-jump').hide();
	} else {
	    $('#comment-form-jump').find('form').resetForm();
	    $(this).parent().after($('#comment-form-jump').show());
	}
	($(this).parent()[0].tagName.toLowerCase() == 'h2') ? COMMENT_ID.val('') : COMMENT_ID.val($(this).attr('comment_id'));
    }
return {
    init: function() {
	$('#comments h2 a.add-comment').unbind().bind('click', showJumpingForm);
	initJumpingForm();
    },
    getComments: function() {
	$('#comment-items').html('<p class="wait">Загрузка комментариев...</p>');
	getComments();
    },
    showDelButtons: function() {
	$('#comment-items span.comment-delete').show();
    }
}
})();

var TAGS = [];
var BRANDS = [];
var AGENCIES = [];
var CATEGORIES = [];
var START_FLAG = true;

var Unicode = {
    '&sup2;': '\u00B2',
    '&sup3;': '\u00B3',
    '&nbsp;': '\u0020',
    '&quot;': '\u0022',
    '&lt;': '\u003C',
    '&gt;': '\u003E',
    '&deg;': '\u00B0'
}

function JSONHtml() {
    this.JSON = null;
}

JSONHtml.prototype.createNamedElement = function (sTagName, sName) {
    var oElement = null;
    try {
	    oElement = document.createElement('<'+sTagName+' name="'+sName+'">');
    } catch (e) {}
    if (!oElement || oElement.nodeName != sTagName.toUpperCase()) {
	    oElement = document.createElement(sTagName);
	    oElement.setAttribute('name', sName);
    }
    return oElement;
}

JSONHtml.prototype.setAttributes = function (oElement, oAttributes) {
    for (var name in oAttributes) {
	var sName = (name.toLowerCase() == 'class' || name.toLowerCase() == 'classname') ? 'class' : name;
	if (document.all && sName == 'class' && !browser.isIE8) {
	    oElement.setAttribute('className', oAttributes[name]);
	}
	oElement.setAttribute(sName, oAttributes[name]);
	if (document.all && name.toLowerCase() == 'colspan') oElement.colSpan = oAttributes[name];
    }
    return oElement;
}

JSONHtml.prototype.createElement = function (sTagName, oAttributes) {
    var oElement = null;
    if (arguments.length > 0) {
	if (sTagName && sTagName.toLowerCase() == 'input' && oAttributes && oAttributes.name) {
	    oElement = this.createNamedElement(sTagName, oAttributes.name);
	} else {
	    oElement = document.createElement(sTagName);
	    if (oAttributes && oAttributes.name) oElement.setAttribute('name', oAttributes.name);
	}
	if (arguments[1]) {
	    if (oAttributes.name) delete oAttributes.name;
	    this.setAttributes(oElement, oAttributes);
	}
	return oElement;
    } else {
	throw new Error('JSONHtml: неправильный вызов функции createElement. Недостаточно параметров!');
    }
}

JSONHtml.prototype.createHTML = function (JSON) {
    if (JSON) { 
	var oElement = null;
	oThis = this;
	if (typeof JSON == 'object') { 
	    if (JSON.length) {
		oElement = document.createDocumentFragment();
		for (var i = 0; i < JSON.length; i++) {
		    var oChild = this.createHTML(JSON[i]);
		    if (oChild) oElement.appendChild(oChild);
		}
	    } else {
		try {
		    if (JSON.tag && JSON.tag.toLowerCase() != 'html') {
			oElement = this.createElement(JSON.tag, (JSON.attributes) ? JSON.attributes : null);
			if (JSON.children) oElement.appendChild(oThis.createHTML(JSON.children));
		    } else {
			oElement = $(JSON.children)[0];
		    }
		} catch (err) {}
	    }
	} else if (typeof JSON == 'string' || typeof JSON == 'number') {
	    if (typeof JSON == 'string') {
		for (var code in Unicode) {
		    var pattern = new RegExp(code, 'gi');
		    JSON = JSON.replace(pattern, Unicode[code]);
		}
	    }
	    oElement = document.createTextNode(JSON);
	}
        return oElement;
    }
}

function Listing(oListing, nLuft) {
    this.oListing = $(oListing);
    this.nPages = this.nCurrent = 1;
    this.nLuft = (nLuft) ? nLuft - 0 : 4;;
    this.init(nLuft);
}

Listing.prototype.init = function (oListing, nLuft) {
    this.oListing = $(oListing);
    this.nLuft = (nLuft) ? nLuft - 0 : 4;
    this.nRdots = this.nLdotes = this.nRcount = this.nLcount = this.nLfirst = this.nLlast = 0;
    this.htmlMaker = new JSONHtml();
}

Listing.prototype.ListingArchitect = function () {
    var rdots, ldots, rcount, lcount;
    this.nPages-=0;
    this.nCurrent-=0;
    rdots = ldots = true;
    rcount = lcount = this.nLuft;
    if (lcount + rcount + 1 >= this.nPages) {
	rcount = this.nPages - this.nCurrent;
	lcount = this.nCurrent - 1;
	rdots = ldots = false;
    } else {
	if (lcount >= (this.nCurrent - 1)) {
	    ldots = false;
	    lcount = this.nCurrent - 1;
	    rcount = 2 * this.nLuft - lcount;
	}
	if (lcount == (this.nCurrent-2)) {
	    ldots = false;
	    lcount += 1;
	}
	if ((rcount + this.nCurrent) >= this.nPages) {
	    rcount = this.nPages - this.nCurrent;
	    lcount = 2 * this.nLuft-rcount;
	    rdots = false;
	}
	if ((rcount + this.nCurrent) == (this.nPages - 1)) {
	    rcount += 1;
	    rdots = false;
	}
    }
    this.nLcount = lcount;
    this.nLdots = ldots;
    this.nRcount = rcount;
    this.nRdots = rdots;
}

Listing.prototype.ListingConstructor = function () {
    var JSON = new Array();
    var number = this.nLfirst = this.nCurrent - this.nLcount;
    if (this.nLdots) {
	var obj = {
	    tag: 'LI',
	    children: { tag: 'A', children: '...' },
	    attributes: { v: this.nLfirst - 1 }
	}
	JSON.push(obj);
    }
    for (var i = 0; i < (this.nLcount + this.nRcount + 1); i++) {
	var obj = {
	    tag: 'LI',
	    children: { tag: 'A', children: number + '' },
	    attributes: { v: (number++) + '' }
	}
	if ((number - 1) == this.nCurrent) obj.attributes.className = 'cur';
	JSON.push(obj);
    }
    if (this.nRdots) {
	var obj = {
	    tag: 'LI',
	    children: { tag: 'A', children: '...' },
	    attributes: { v: number + '' }
	}
	JSON.push(obj);
    }
    this.nLlast = number-1;
    var span = this.oListing[0].getElementsByTagName('SPAN');
    var ht = this.htmlMaker.createHTML({ tag: 'UL',  children: JSON });
    this.oListing[0].replaceChild(ht, this.oListing[0].getElementsByTagName('UL')[0]);
    span[0].className = span[1].className = 'disabled';
    if (this.nLfirst < this.nCurrent) span[0].className = 'enabled';
    if (this.nLlast != this.nCurrent) span[1].className = 'enabled';
}

Listing.prototype.makeListing = function () {
    var arg = arguments;
    if (arg[0]) this.nCount = arg[0];
    if (arg[1]) this.nPages = (arg[1] == 0 || arg[1] == '') ? 1 : arg[1];
    if (arg[2]) this.nCurrent = arg[2];
    this.ListingArchitect();
    this.ListingConstructor();
}

Listing.prototype.listner = function (oButton, nCurPage) {
    function getNextPageNumber(obj, current) {
	var nNewPage = nCurPage;
	var isButtonDown = obj[0].tagName.toLowerCase() == 'li';
	if (!isButtonDown) {
	    nNewPage  = (obj.attr('title') == 'next') ? nCurPage + 1 : nCurPage - 1;
	} else {
	    nNewPage  = obj.attr('v') - 0;
	}
	if (nNewPage < 1) nNewPage = 1; else if (nNewPage > this.nPages) nNewPage = this.nPages;
	return nNewPage;
    }
    this.nCurrent = nCurPage;
    var nNextPage = getNextPageNumber(oButton.parent(), this.nCurrent);
    var isChange = this.nCurrent != nNextPage;
    var parentTagName = oButton.parent()[0].tagName.toLowerCase();
    if (isChange) {
	if (parentTagName == 'li') oButton.css('background-color', '#dedede');
	    else if (parentTagName == 'span') oButton.parent().addClass('disabled');
        this.nCurrent = nNextPage;
    }
    return { isChange: isChange, nextPage: nNextPage };
}

var TablePage = (function() {
    var oTable, oFilter, oSubmit, oCount, oListing, oPageNumber;
    function initSearchForm() {
	oFilter.bind('submit', function() {
	    oPageNumber.val(1);
	    location.hash = '#/search?' + oFilter.serialize().replace('do=search&', '');
	    return false;
	});
    }
    function clearFilter() {
	oFilter.resetForm();
    }
    function fillFilterFromHash(hash) {
	clearFilter();
	for (var name in hash) if (name != 'do' && hash[name]) oFilter.find('[name=' + name + ']').val(hash[name]);
	Filter.getFields();
    }
    function printWait() {
	oSubmit.attr('disabled', 'disabled');
	oTable.html('<tr><td colspan="4"><p class="wait">Получение даных...</p></td></tr>');
    }
    function getData(link) {
	printWait();
	Loader.sShow();
	$.getJSON('/main.json?do=search', link.replace('do=serach&', ''), function(data, status) {
	    Loader.sHide();
	    oSubmit.attr('disabled', '');
	    if (status == 'success') buildTable(data);
	});
    }
    function getTextString(oItem) {
	function setField(data) {
	    var temp = [];
	    for (var i = 0; i < data.length; i++) temp[i] = data[i].tag_title;
	    return temp.join(', ');
	}
	var sLink = '<a href="#/index?banner_id=' + oItem.banner_id + '">';
	var sBrands = setField(oItem.brand_loop);
	var sAgencies = setField(oItem.agency_loop);
	var sCategories = setField(oItem.category_loop);
	var score = oItem.banner_raiting_plus - oItem.banner_raiting_minus;
	var plus = (oItem.banner_raiting_plus > 0) ? '+' + oItem.banner_raiting_plus : 0;
	var minus = (oItem.banner_raiting_minus > 0) ? '&minus;' + oItem.banner_raiting_minus : 0;
	return '<tr><td><p>' + sLink + sBrands + ' :: ' + oItem.banner_title + '</a><br><span class="date">' + oItem.banner_date_norm + '</span></p></td><td><p>' + sLink + sAgencies + '</a></p></td><td><p>' + sLink + sCategories+ '</a></p></td><td><p class="button"><span class="score">' + score + '</span> (<span class="plus">' + plus + '</span>, <span class="minus">' + minus + '</span>)</p></td></tr>';
    }
    function buildTable(data) {
	oListing.makeListing(10, data.total_pages, data.page);
	oCount.html(data.total_elements);
	oTable.html('');
	if (data.banner_loop.length > 0) {
	    for (var i = 0; i < data.banner_loop.length; i++) {
		oTable.append(getTextString(data.banner_loop[i]));
	    }
	} else oTable.html('<tr><td colspan><p>По вашему запросу ничего не найдено.</p></td></tr>');
	initListingListner();
    }
    function initListingListner() {
	oListing.oListing.find('a').unbind('click');
	oListing.oListing.find('a').bind('click', function() {
	    if (!$(this).parent().hasClass('disabled')) {
		var data = oListing.listner($(this), oPageNumber.val() - 0);
		if (data.isChange) {
		    oPageNumber.val(data.nextPage);
		    getData(oFilter.serialize());
		}
	    }
	    return false;
	});
    }
return {
    init: function() {
	oFilter = $('#filter form');
	oSubmit = oFilter.find('input[type=submit]');
	oPageNumber = oFilter.find('input[name=page]');
	initSearchForm();
	oListing = new Listing(null, 4);
    },
    loadPage: function(HTML, oCurPage) {
	$('#index, #other-content > *').hide();
	if ($('#search-result').size() == 0) {
	    $('#other-content').append(HTML);
	    FullAJAX.addHashedPage('search');
	    oTable = $('#search-result table tbody');
	    oCount = $('#serach-count span');
	    oListing = new Listing($('#listing')[0], 4);
	    oListing.init($('#listing')[0], 4);
	}
	$('#other-content, #search-result').show();
	fillFilterFromHash(oCurPage.extraObj);
	getData(oCurPage.extra);
    }
}
})();

var PagesSettings = (function() {
    var links = {
        link_default: '/index.html',
        hash_default: '#/index?banner_id=',
        simple_url: '/templates/<%page%>.html'
    };
    var indexPageElements = [ '#banner-title', '#gallery', '#description', '#comments' ];
return {
    index: {
        type: 'static',
        url_data: '/postavshiki.json?do=search',
        rus: 'Баннеры',
	firstFlag: true,
	obj: {
	    loadPage: function(oHTML, oPage) {
		$('#console').addClass('index');
		$('#other-content').hide();
		$('#index').show();
		if (oPage.extraObj.dir) {
		    BannerProvider.getNeighbourBanner(oPage.extraObj.dir);
		} else {
		    BannerProvider.getBanner(oPage.extraObj.banner_id);
		}
		Comment.init();
	    }   
	},
	initPage: function() {
	    
	}
    },
    search: {
        type: 'static',
        url_data: '/main.json?do=search',
        rus: 'Баннеры - поиск',
	initPage: function() {
	    
	}
    },
    banner: {
        type: 'static',
        rus: 'Баннеры - добавление',
        initForm: function(oCurPage) {
        },
        typeForm: function() {            
        }
    },
    pages: {
	type: 'static',
        url_data: '/postavshiki.json?do=search',
        rus: 'Баннеры - поиск',
	initPage: function() {
	    
	},
	obj: {
	    loadPage: function(HTML, curPage) {
		$('#index, #other-content > *').hide();
		$('#other-content .page').html(HTML);		
		$('#other-content, #other-content .page').show();
	    }
	}
    },
    links: links    
}})();

var Core = (function(oPagesSettings, FullAJAX) {
    var oThis = this;
    var _PageProvider = FullAJAX;
    var _PagesSettings = oPagesSettings;
    var _AHAH = FullAJAX;
    var oIndex, oSearch, oForm;
    var fProviderList = false;
    var oProviderList = [];
    var oProviderHtml = null;
    var fFirst = true;
    
    this.initSystems = function() {
	$('#links .s1 a').click(function() {
	    this.href = 'http://www.digg.com/submit?phase=2&url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '"') + '&bodytext=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '" для ' + $('#name h2').text());
	});
        $('#links .s2 a').click(function() {
            this.href = 'http://www.delicious.com/post?url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '"') + '&notes=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '" для ' + $('#name h2').text());
	});
        $('#links .s3 a').click(function() {
	    this.href = 'http://www.facebook.com/share.php?u=' + encodeURIComponent(location.href) + '&t=' + encodeURIComponent('Баннер "'+ $('#name h3').text());
	});
        $('#links .s4 a').click(function() {
	    this.href = 'http://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(location.href) + '&title=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '"') + '&source=' + encodeURIComponent('Bannerblog.ru') + '&summary=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '" для ' + $('#name h2').text()); 
	});
        $('#links .s5 a').click(function() {
	    this.href = 'http://www.google.com/bookmarks/mark?op=edit&bkmk=' + encodeURIComponent(location.href)+ '&title=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '"') + '&annotation=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '" для ' + $('#name h2').text()) + '&labels=' + encodeURIComponent($('#description .category').text().replace('Категории: ', ''));
	});
        $('#links .s6 a').click(function() {
	    this.href = 'http://twitter.com/home?status=' + encodeURIComponent('Баннер "' + $('#name h3').text() + '" для ' + $('#name h2').text() + ', http://bannerblog.ru/#/index?banner_id=' + $('#banner_id').val());
	});
    }
    this.writeLinks = function() {
        for (var name in _PagesSettings)
            if (name != 'links' && _PagesSettings[name].url_tpl) _PagesSettings.links[name] = _PagesSettings[name].url_tpl;
    }
    this.initSearch = function() {
	TablePage.init();
        _PagesSettings.search.obj = TablePage;
    }
    this.initSendBanner = function() {
        _PagesSettings.banner.obj = BannerProvider;
    }
    this.initSearch();
    this.initSendBanner();
return {
    init: function () {
	Cache.init(5);
	Cache.setLastNumber();
	var result;
	var bannerId = (result = location.hash.match(/banner_id=(\d+)/i)) ? result[1] : false;
	if (fFirst && bannerId && location.hash.match(/newer|older/gi)) {
	    $('#banner_id').val(bannerId);
	    fFirst = false;
	};
	oThis.writeLinks();
	oThis.initSystems();
        _AHAH.init(_PagesSettings);
	Auth.init();
	BannerProvider.init();
	Filter.init();

	checkFlash('banner');
    },
    watchFrameHash: function (hash) {
	FullAJAX.watchFrameHash(hash);
    }
}
})(PagesSettings, FullAJAX);

$(document).ready(function() {
    Loader.init();
    Core.init();
});
