var Prototype={Version:"1.6.0.3",Browser:{IE:!!(window.attachEvent&&navigator.userAgent.indexOf("Opera")===-1),Opera:navigator.userAgent.indexOf("Opera")>-1,WebKit:navigator.userAgent.indexOf("AppleWebKit/")>-1,Gecko:navigator.userAgent.indexOf("Gecko")>-1&&navigator.userAgent.indexOf("KHTML")===-1,MobileSafari:!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)},BrowserFeatures:{XPath:!!document.evaluate,SelectorsAPI:!!document.querySelector,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:document.createElement("div")["__proto__"]&&document.createElement("div")["__proto__"]!==document.createElement("form")["__proto__"]},ScriptFragment:"<script[^>]*>([\\S\\s]*?)<\/script>",JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(a){return a}};if(Prototype.Browser.MobileSafari){Prototype.BrowserFeatures.SpecificElementExtensions=false}var Class={create:function(){var e=null,d=$A(arguments);if(Object.isFunction(d[0])){e=d.shift()}function a(){this.initialize.apply(this,arguments)}Object.extend(a,Class.Methods);a.superclass=e;a.subclasses=[];if(e){var b=function(){};b.prototype=e.prototype;a.prototype=new b;e.subclasses.push(a)}for(var c=0;c<d.length;c++){a.addMethods(d[c])}if(!a.prototype.initialize){a.prototype.initialize=Prototype.emptyFunction}a.prototype.constructor=a;return a}};Class.Methods={addMethods:function(g){var c=this.superclass&&this.superclass.prototype;var b=Object.keys(g);if(!Object.keys({toString:true}).length){b.push("toString","valueOf")}for(var a=0,d=b.length;a<d;a++){var f=b[a],e=g[f];if(c&&Object.isFunction(e)&&e.argumentNames().first()=="$super"){var h=e;e=(function(i){return function(){return c[i].apply(this,arguments)}})(f).wrap(h);e.valueOf=h.valueOf.bind(h);e.toString=h.toString.bind(h)}this.prototype[f]=e}return this}};var Abstract={};Object.extend=function(a,c){for(var b in c){a[b]=c[b]}return a};Object.extend(Object,{inspect:function(a){try{if(Object.isUndefined(a)){return"undefined"}if(a===null){return"null"}return a.inspect?a.inspect():String(a)}catch(b){if(b instanceof RangeError){return"..."}throw b}},toJSON:function(a){var c=typeof a;switch(c){case"undefined":case"function":case"unknown":return;case"boolean":return a.toString()}if(a===null){return"null"}if(a.toJSON){return a.toJSON()}if(Object.isElement(a)){return}var b=[];for(var e in a){var d=Object.toJSON(a[e]);if(!Object.isUndefined(d)){b.push(e.toJSON()+": "+d)}}return"{"+b.join(", ")+"}"},toQueryString:function(a){return $H(a).toQueryString()},toHTML:function(a){return a&&a.toHTML?a.toHTML():String.interpret(a)},keys:function(a){var b=[];for(var c in a){b.push(c)}return b},values:function(b){var a=[];for(var c in b){a.push(b[c])}return a},clone:function(a){return Object.extend({},a)},isElement:function(a){return !!(a&&a.nodeType==1)},isArray:function(a){return a!=null&&typeof a=="object"&&"splice" in a&&"join" in a},isHash:function(a){return a instanceof Hash},isFunction:function(a){return typeof a=="function"},isString:function(a){return typeof a=="string"},isNumber:function(a){return typeof a=="number"},isUndefined:function(a){return typeof a=="undefined"}});Object.extend(Function.prototype,{argumentNames:function(){var a=this.toString().match(/^[\s\(]*function[^(]*\(([^\)]*)\)/)[1].replace(/\s+/g,"").split(",");return a.length==1&&!a[0]?[]:a},bind:function(){if(arguments.length<2&&Object.isUndefined(arguments[0])){return this}var a=this,c=$A(arguments),b=c.shift();return function(){return a.apply(b,c.concat($A(arguments)))}},bindAsEventListener:function(){var a=this,c=$A(arguments),b=c.shift();return function(d){return a.apply(b,[d||window.event].concat(c))}},curry:function(){if(!arguments.length){return this}var a=this,b=$A(arguments);return function(){return a.apply(this,b.concat($A(arguments)))}},delay:function(){var a=this,b=$A(arguments),c=b.shift()*1000;return window.setTimeout(function(){return a.apply(a,b)},c)},defer:function(){var a=[0.01].concat($A(arguments));return this.delay.apply(this,a)},wrap:function(b){var a=this;return function(){return b.apply(this,[a.bind(this)].concat($A(arguments)))}},methodize:function(){if(this._methodized){return this._methodized}var a=this;return this._methodized=function(){return a.apply(null,[this].concat($A(arguments)))}}});Date.prototype.toJSON=function(){return'"'+this.getUTCFullYear()+"-"+(this.getUTCMonth()+1).toPaddedString(2)+"-"+this.getUTCDate().toPaddedString(2)+"T"+this.getUTCHours().toPaddedString(2)+":"+this.getUTCMinutes().toPaddedString(2)+":"+this.getUTCSeconds().toPaddedString(2)+'Z"'};var Try={these:function(){var c;for(var b=0,d=arguments.length;b<d;b++){var a=arguments[b];try{c=a();break}catch(f){}}return c}};RegExp.prototype.match=RegExp.prototype.test;RegExp.escape=function(a){return String(a).replace(/([.*+?^=!:${}()|[\]\/\\])/g,"\\$1")};var PeriodicalExecuter=Class.create({initialize:function(b,a){this.callback=b;this.frequency=a;this.currentlyExecuting=false;this.registerCallback()},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1000)},execute:function(){this.callback(this)},stop:function(){if(!this.timer){return}clearInterval(this.timer);this.timer=null},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.execute()}finally{this.currentlyExecuting=false}}}});Object.extend(String,{interpret:function(a){return a==null?"":String(a)},specialChar:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r","\\":"\\\\"}});Object.extend(String.prototype,{gsub:function(e,c){var a="",d=this,b;c=arguments.callee.prepareReplacement(c);while(d.length>0){if(b=d.match(e)){a+=d.slice(0,b.index);a+=String.interpret(c(b));d=d.slice(b.index+b[0].length)}else{a+=d,d=""}}return a},sub:function(c,a,b){a=this.gsub.prepareReplacement(a);b=Object.isUndefined(b)?1:b;return this.gsub(c,function(d){if(--b<0){return d[0]}return a(d)})},scan:function(b,a){this.gsub(b,a);return String(this)},truncate:function(b,a){b=b||30;a=Object.isUndefined(a)?"...":a;return this.length>b?this.slice(0,b-a.length)+a:String(this)},strip:function(){return this.replace(/^\s+/,"").replace(/\s+$/,"")},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,"")},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,"img"),"")},extractScripts:function(){var b=new RegExp(Prototype.ScriptFragment,"img");var a=new RegExp(Prototype.ScriptFragment,"im");return(this.match(b)||[]).map(function(c){return(c.match(a)||["",""])[1]})},evalScripts:function(){return this.extractScripts().map(function(script){return eval(script)})},escapeHTML:function(){var a=arguments.callee;a.text.data=this;return a.div.innerHTML},unescapeHTML:function(){var a=new Element("div");a.innerHTML=this.stripTags();return a.childNodes[0]?(a.childNodes.length>1?$A(a.childNodes).inject("",function(b,c){return b+c.nodeValue}):a.childNodes[0].nodeValue):""},toQueryParams:function(b){var a=this.strip().match(/([^?#]*)(#.*)?$/);if(!a){return{}}return a[1].split(b||"&").inject({},function(e,f){if((f=f.split("="))[0]){var c=decodeURIComponent(f.shift());var d=f.length>1?f.join("="):f[0];if(d!=undefined){d=decodeURIComponent(d)}if(c in e){if(!Object.isArray(e[c])){e[c]=[e[c]]}e[c].push(d)}else{e[c]=d}}return e})},toArray:function(){return this.split("")},succ:function(){return this.slice(0,this.length-1)+String.fromCharCode(this.charCodeAt(this.length-1)+1)},times:function(a){return a<1?"":new Array(a+1).join(this)},camelize:function(){var d=this.split("-"),a=d.length;if(a==1){return d[0]}var c=this.charAt(0)=="-"?d[0].charAt(0).toUpperCase()+d[0].substring(1):d[0];for(var b=1;b<a;b++){c+=d[b].charAt(0).toUpperCase()+d[b].substring(1)}return c},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase()},underscore:function(){return this.gsub(/::/,"/").gsub(/([A-Z]+)([A-Z][a-z])/,"#{1}_#{2}").gsub(/([a-z\d])([A-Z])/,"#{1}_#{2}").gsub(/-/,"_").toLowerCase()},dasherize:function(){return this.gsub(/_/,"-")},inspect:function(b){var a=this.gsub(/[\x00-\x1f\\]/,function(c){var d=String.specialChar[c[0]];return d?d:"\\u00"+c[0].charCodeAt().toPaddedString(2,16)});if(b){return'"'+a.replace(/"/g,'\\"')+'"'}return"'"+a.replace(/'/g,"\\'")+"'"},toJSON:function(){return this.inspect(true)},unfilterJSON:function(a){return this.sub(a||Prototype.JSONFilter,"#{1}")},isJSON:function(){var a=this;if(a.blank()){return false}a=this.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,"");return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(a)},evalJSON:function(sanitize){var json=this.unfilterJSON();try{if(!sanitize||json.isJSON()){return eval("("+json+")")}}catch(e){}throw new SyntaxError("Badly formed JSON string: "+this.inspect())},include:function(a){return this.indexOf(a)>-1},startsWith:function(a){return this.indexOf(a)===0},endsWith:function(a){var b=this.length-a.length;return b>=0&&this.lastIndexOf(a)===b},empty:function(){return this==""},blank:function(){return/^\s*$/.test(this)},interpolate:function(a,b){return new Template(this,b).evaluate(a)}});if(Prototype.Browser.WebKit||Prototype.Browser.IE){Object.extend(String.prototype,{escapeHTML:function(){return this.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")},unescapeHTML:function(){return this.stripTags().replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")}})}String.prototype.gsub.prepareReplacement=function(b){if(Object.isFunction(b)){return b}var a=new Template(b);return function(c){return a.evaluate(c)}};String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement("div"),text:document.createTextNode("")});String.prototype.escapeHTML.div.appendChild(String.prototype.escapeHTML.text);var Template=Class.create({initialize:function(a,b){this.template=a.toString();this.pattern=b||Template.Pattern},evaluate:function(a){if(Object.isFunction(a.toTemplateReplacements)){a=a.toTemplateReplacements()}return this.template.gsub(this.pattern,function(d){if(a==null){return""}var f=d[1]||"";if(f=="\\"){return d[2]}var b=a,g=d[3];var e=/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;d=e.exec(g);if(d==null){return f}while(d!=null){var c=d[1].startsWith("[")?d[2].gsub("\\\\]","]"):d[1];b=b[c];if(null==b||""==d[3]){break}g=g.substring("["==d[3]?d[1].length:d[0].length);d=e.exec(g)}return f+String.interpret(b)})}});Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;var $break={};var Enumerable={each:function(c,b){var a=0;try{this._each(function(e){c.call(b,e,a++)})}catch(d){if(d!=$break){throw d}}return this},eachSlice:function(d,c,b){var a=-d,e=[],f=this.toArray();if(d<1){return f}while((a+=d)<f.length){e.push(f.slice(a,a+d))}return e.collect(c,b)},all:function(c,b){c=c||Prototype.K;var a=true;this.each(function(e,d){a=a&&!!c.call(b,e,d);if(!a){throw $break}});return a},any:function(c,b){c=c||Prototype.K;var a=false;this.each(function(e,d){if(a=!!c.call(b,e,d)){throw $break}});return a},collect:function(c,b){c=c||Prototype.K;var a=[];this.each(function(e,d){a.push(c.call(b,e,d))});return a},detect:function(c,b){var a;this.each(function(e,d){if(c.call(b,e,d)){a=e;throw $break}});return a},findAll:function(c,b){var a=[];this.each(function(e,d){if(c.call(b,e,d)){a.push(e)}});return a},grep:function(d,c,b){c=c||Prototype.K;var a=[];if(Object.isString(d)){d=new RegExp(d)}this.each(function(f,e){if(d.match(f)){a.push(c.call(b,f,e))}});return a},include:function(a){if(Object.isFunction(this.indexOf)){if(this.indexOf(a)!=-1){return true}}var b=false;this.each(function(c){if(c==a){b=true;throw $break}});return b},inGroupsOf:function(b,a){a=Object.isUndefined(a)?null:a;return this.eachSlice(b,function(c){while(c.length<b){c.push(a)}return c})},inject:function(a,c,b){this.each(function(e,d){a=c.call(b,a,e,d)});return a},invoke:function(b){var a=$A(arguments).slice(1);return this.map(function(c){return c[b].apply(c,a)})},max:function(c,b){c=c||Prototype.K;var a;this.each(function(e,d){e=c.call(b,e,d);if(a==null||e>=a){a=e}});return a},min:function(c,b){c=c||Prototype.K;var a;this.each(function(e,d){e=c.call(b,e,d);if(a==null||e<a){a=e}});return a},partition:function(d,b){d=d||Prototype.K;var c=[],a=[];this.each(function(f,e){(d.call(b,f,e)?c:a).push(f)});return[c,a]},pluck:function(b){var a=[];this.each(function(c){a.push(c[b])});return a},reject:function(c,b){var a=[];this.each(function(e,d){if(!c.call(b,e,d)){a.push(e)}});return a},sortBy:function(b,a){return this.map(function(d,c){return{value:d,criteria:b.call(a,d,c)}}).sort(function(f,e){var d=f.criteria,c=e.criteria;return d<c?-1:d>c?1:0}).pluck("value")},toArray:function(){return this.map()},zip:function(){var b=Prototype.K,a=$A(arguments);if(Object.isFunction(a.last())){b=a.pop()}var c=[this].concat(a).map($A);return this.map(function(e,d){return b(c.pluck(d))})},size:function(){return this.toArray().length},inspect:function(){return"#<Enumerable:"+this.toArray().inspect()+">"}};Object.extend(Enumerable,{map:Enumerable.collect,find:Enumerable.detect,select:Enumerable.findAll,filter:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray,every:Enumerable.all,some:Enumerable.any});function $A(c){if(!c){return[]}if(c.toArray){return c.toArray()}var b=c.length||0,a=new Array(b);while(b--){a[b]=c[b]}return a}if(Prototype.Browser.WebKit){$A=function(c){if(!c){return[]}if(!(typeof c==="function"&&typeof c.length==="number"&&typeof c.item==="function")&&c.toArray){return c.toArray()}var b=c.length||0,a=new Array(b);while(b--){a[b]=c[b]}return a}}Array.from=$A;Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse){Array.prototype._reverse=Array.prototype.reverse}Object.extend(Array.prototype,{_each:function(b){for(var a=0,c=this.length;a<c;a++){b(this[a])}},clear:function(){this.length=0;return this},first:function(){return this[0]},last:function(){return this[this.length-1]},compact:function(){return this.select(function(a){return a!=null})},flatten:function(){return this.inject([],function(b,a){return b.concat(Object.isArray(a)?a.flatten():[a])})},without:function(){var a=$A(arguments);return this.select(function(b){return !a.include(b)})},reverse:function(a){return(a!==false?this:this.toArray())._reverse()},reduce:function(){return this.length>1?this:this[0]},uniq:function(a){return this.inject([],function(d,c,b){if(0==b||(a?d.last()!=c:!d.include(c))){d.push(c)}return d})},intersect:function(a){return this.uniq().findAll(function(b){return a.detect(function(c){return b===c})})},clone:function(){return[].concat(this)},size:function(){return this.length},inspect:function(){return"["+this.map(Object.inspect).join(", ")+"]"},toJSON:function(){var a=[];this.each(function(b){var c=Object.toJSON(b);if(!Object.isUndefined(c)){a.push(c)}});return"["+a.join(", ")+"]"}});if(Object.isFunction(Array.prototype.forEach)){Array.prototype._each=Array.prototype.forEach}if(!Array.prototype.indexOf){Array.prototype.indexOf=function(c,a){a||(a=0);var b=this.length;if(a<0){a=b+a}for(;a<b;a++){if(this[a]===c){return a}}return -1}}if(!Array.prototype.lastIndexOf){Array.prototype.lastIndexOf=function(b,a){a=isNaN(a)?this.length:(a<0?this.length+a:a)+1;var c=this.slice(0,a).reverse().indexOf(b);return(c<0)?c:a-c-1}}Array.prototype.toArray=Array.prototype.clone;function $w(a){if(!Object.isString(a)){return[]}a=a.strip();return a?a.split(/\s+/):[]}if(Prototype.Browser.Opera){Array.prototype.concat=function(){var e=[];for(var b=0,c=this.length;b<c;b++){e.push(this[b])}for(var b=0,c=arguments.length;b<c;b++){if(Object.isArray(arguments[b])){for(var a=0,d=arguments[b].length;a<d;a++){e.push(arguments[b][a])}}else{e.push(arguments[b])}}return e}}Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16)},succ:function(){return this+1},times:function(b,a){$R(0,this,true).each(b,a);return this},toPaddedString:function(c,b){var a=this.toString(b||10);return"0".times(c-a.length)+a},toJSON:function(){return isFinite(this)?this.toString():"null"}});$w("abs round ceil floor").each(function(a){Number.prototype[a]=Math[a].methodize()});function $H(a){return new Hash(a)}var Hash=Class.create(Enumerable,(function(){function a(b,c){if(Object.isUndefined(c)){return b}return b+"="+encodeURIComponent(String.interpret(c))}return{initialize:function(b){this._object=Object.isHash(b)?b.toObject():Object.clone(b)},_each:function(c){for(var b in this._object){var d=this._object[b],e=[b,d];e.key=b;e.value=d;c(e)}},set:function(b,c){return this._object[b]=c},get:function(b){if(this._object[b]!==Object.prototype[b]){return this._object[b]}},unset:function(b){var c=this._object[b];delete this._object[b];return c},toObject:function(){return Object.clone(this._object)},keys:function(){return this.pluck("key")},values:function(){return this.pluck("value")},index:function(c){var b=this.detect(function(d){return d.value===c});return b&&b.key},merge:function(b){return this.clone().update(b)},update:function(b){return new Hash(b).inject(this,function(c,d){c.set(d.key,d.value);return c})},toQueryString:function(){return this.inject([],function(d,e){var c=encodeURIComponent(e.key),b=e.value;if(b&&typeof b=="object"){if(Object.isArray(b)){return d.concat(b.map(a.curry(c)))}}else{d.push(a(c,b))}return d}).join("&")},inspect:function(){return"#<Hash:{"+this.map(function(b){return b.map(Object.inspect).join(": ")}).join(", ")+"}>"},toJSON:function(){return Object.toJSON(this.toObject())},clone:function(){return new Hash(this)}}})());Hash.prototype.toTemplateReplacements=Hash.prototype.toObject;Hash.from=$H;var ObjectRange=Class.create(Enumerable,{initialize:function(c,a,b){this.start=c;this.end=a;this.exclusive=b},_each:function(a){var b=this.start;while(this.include(b)){a(b);b=b.succ()}},include:function(a){if(a<this.start){return false}if(this.exclusive){return a<this.end}return a<=this.end}});var $R=function(c,a,b){return new ObjectRange(c,a,b)};var Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest()},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")})||false},activeRequestCount:0};Ajax.Responders={responders:[],_each:function(a){this.responders._each(a)},register:function(a){if(!this.include(a)){this.responders.push(a)}},unregister:function(a){this.responders=this.responders.without(a)},dispatch:function(d,b,c,a){this.each(function(f){if(Object.isFunction(f[d])){try{f[d].apply(f,[b,c,a])}catch(g){}}})}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++},onComplete:function(){Ajax.activeRequestCount--}});Ajax.Base=Class.create({initialize:function(a){this.options={method:"post",asynchronous:true,contentType:"application/x-www-form-urlencoded",encoding:"UTF-8",parameters:"",evalJSON:true,evalJS:true};Object.extend(this.options,a||{});this.options.method=this.options.method.toLowerCase();if(Object.isString(this.options.parameters)){this.options.parameters=this.options.parameters.toQueryParams()}else{if(Object.isHash(this.options.parameters)){this.options.parameters=this.options.parameters.toObject()}}}});Ajax.Request=Class.create(Ajax.Base,{_complete:false,initialize:function($super,b,a){$super(a);this.transport=Ajax.getTransport();this.request(b)},request:function(b){this.url=b;this.method=this.options.method;var d=Object.clone(this.options.parameters);if(!["get","post"].include(this.method)){d._method=this.method;this.method="post"}this.parameters=d;if(d=Object.toQueryString(d)){if(this.method=="get"){this.url+=(this.url.include("?")?"&":"?")+d}else{if(/Konqueror|Safari|KHTML/.test(navigator.userAgent)){d+="&_="}}}try{var a=new Ajax.Response(this);if(this.options.onCreate){this.options.onCreate(a)}Ajax.Responders.dispatch("onCreate",this,a);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous){this.respondToReadyState.bind(this).defer(1)}this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=="post"?(this.options.postBody||d):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType){this.onStateChange()}}catch(c){this.dispatchException(c)}},onStateChange:function(){var a=this.transport.readyState;if(a>1&&!((a==4)&&this._complete)){this.respondToReadyState(this.transport.readyState)}},setRequestHeaders:function(){var e={"X-Requested-With":"XMLHttpRequest","X-Prototype-Version":Prototype.Version,Accept:"text/javascript, text/html, application/xml, text/xml, */*"};if(this.method=="post"){e["Content-type"]=this.options.contentType+(this.options.encoding?"; charset="+this.options.encoding:"");if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005){e.Connection="close"}}if(typeof this.options.requestHeaders=="object"){var c=this.options.requestHeaders;if(Object.isFunction(c.push)){for(var b=0,d=c.length;b<d;b+=2){e[c[b]]=c[b+1]}}else{$H(c).each(function(f){e[f.key]=f.value})}}for(var a in e){this.transport.setRequestHeader(a,e[a])}},success:function(){var a=this.getStatus();return !a||(a>=200&&a<300)},getStatus:function(){try{return this.transport.status||0}catch(a){return 0}},respondToReadyState:function(a){var c=Ajax.Request.Events[a],b=new Ajax.Response(this);if(c=="Complete"){try{this._complete=true;(this.options["on"+b.status]||this.options["on"+(this.success()?"Success":"Failure")]||Prototype.emptyFunction)(b,b.headerJSON)}catch(d){this.dispatchException(d)}var f=b.getHeader("Content-type");if(this.options.evalJS=="force"||(this.options.evalJS&&this.isSameOrigin()&&f&&f.match(/^\s*(text|application)\/(x-)?(java|ecma)script(;.*)?\s*$/i))){this.evalResponse()}}try{(this.options["on"+c]||Prototype.emptyFunction)(b,b.headerJSON);Ajax.Responders.dispatch("on"+c,this,b,b.headerJSON)}catch(d){this.dispatchException(d)}if(c=="Complete"){this.transport.onreadystatechange=Prototype.emptyFunction}},isSameOrigin:function(){var a=this.url.match(/^\s*https?:\/\/[^\/]*/);return !a||(a[0]=="#{protocol}//#{domain}#{port}".interpolate({protocol:location.protocol,domain:document.domain,port:location.port?":"+location.port:""}))},getHeader:function(a){try{return this.transport.getResponseHeader(a)||null}catch(b){return null}},evalResponse:function(){try{return eval((this.transport.responseText||"").unfilterJSON())}catch(e){this.dispatchException(e)}},dispatchException:function(a){(this.options.onException||Prototype.emptyFunction)(this,a);Ajax.Responders.dispatch("onException",this,a)}});Ajax.Request.Events=["Uninitialized","Loading","Loaded","Interactive","Complete"];Ajax.Response=Class.create({initialize:function(c){this.request=c;var d=this.transport=c.transport,a=this.readyState=d.readyState;if((a>2&&!Prototype.Browser.IE)||a==4){this.status=this.getStatus();this.statusText=this.getStatusText();this.responseText=String.interpret(d.responseText);this.headerJSON=this._getHeaderJSON()}if(a==4){var b=d.responseXML;this.responseXML=Object.isUndefined(b)?null:b;this.responseJSON=this._getResponseJSON()}},status:0,statusText:"",getStatus:Ajax.Request.prototype.getStatus,getStatusText:function(){try{return this.transport.statusText||""}catch(a){return""}},getHeader:Ajax.Request.prototype.getHeader,getAllHeaders:function(){try{return this.getAllResponseHeaders()}catch(a){return null}},getResponseHeader:function(a){return this.transport.getResponseHeader(a)},getAllResponseHeaders:function(){return this.transport.getAllResponseHeaders()},_getHeaderJSON:function(){var a=this.getHeader("X-JSON");if(!a){return null}a=decodeURIComponent(escape(a));try{return a.evalJSON(this.request.options.sanitizeJSON||!this.request.isSameOrigin())}catch(b){this.request.dispatchException(b)}},_getResponseJSON:function(){var a=this.request.options;if(!a.evalJSON||(a.evalJSON!="force"&&!(this.getHeader("Content-type")||"").include("application/json"))||this.responseText.blank()){return null}try{return this.responseText.evalJSON(a.sanitizeJSON||!this.request.isSameOrigin())}catch(b){this.request.dispatchException(b)}}});Ajax.Updater=Class.create(Ajax.Request,{initialize:function($super,a,c,b){this.container={success:(a.success||a),failure:(a.failure||(a.success?null:a))};b=Object.clone(b);var d=b.onComplete;b.onComplete=(function(e,f){this.updateContent(e.responseText);if(Object.isFunction(d)){d(e,f)}}).bind(this);$super(c,b)},updateContent:function(d){var c=this.container[this.success()?"success":"failure"],a=this.options;if(!a.evalScripts){d=d.stripScripts()}if(c=$(c)){if(a.insertion){if(Object.isString(a.insertion)){var b={};b[a.insertion]=d;c.insert(b)}else{a.insertion(c,d)}}else{c.update(d)}}}});Ajax.PeriodicalUpdater=Class.create(Ajax.Base,{initialize:function($super,a,c,b){$super(b);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=a;this.url=c;this.start()},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent()},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments)},updateComplete:function(a){if(this.options.decay){this.decay=(a.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=a.responseText}this.timer=this.onTimerEvent.bind(this).delay(this.decay*this.frequency)},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options)}});function $(b){if(arguments.length>1){for(var a=0,d=[],c=arguments.length;a<c;a++){d.push($(arguments[a]))}return d}if(Object.isString(b)){b=document.getElementById(b)}return Element.extend(b)}if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(f,a){var c=[];var e=document.evaluate(f,$(a)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var b=0,d=e.snapshotLength;b<d;b++){c.push(Element.extend(e.snapshotItem(b)))}return c}}if(!window.Node){var Node={}}if(!Node.ELEMENT_NODE){Object.extend(Node,{ELEMENT_NODE:1,ATTRIBUTE_NODE:2,TEXT_NODE:3,CDATA_SECTION_NODE:4,ENTITY_REFERENCE_NODE:5,ENTITY_NODE:6,PROCESSING_INSTRUCTION_NODE:7,COMMENT_NODE:8,DOCUMENT_NODE:9,DOCUMENT_TYPE_NODE:10,DOCUMENT_FRAGMENT_NODE:11,NOTATION_NODE:12})}(function(){var a=this.Element;this.Element=function(d,c){c=c||{};d=d.toLowerCase();var b=Element.cache;if(Prototype.Browser.IE&&c.name){d="<"+d+' name="'+c.name+'">';delete c.name;return Element.writeAttribute(document.createElement(d),c)}if(!b[d]){b[d]=Element.extend(document.createElement(d))}return Element.writeAttribute(b[d].cloneNode(false),c)};Object.extend(this.Element,a||{});if(a){this.Element.prototype=a.prototype}}).call(window);Element.cache={};Element.Methods={visible:function(a){return $(a).style.display!="none"},toggle:function(a){a=$(a);Element[Element.visible(a)?"hide":"show"](a);return a},hide:function(a){a=$(a);a.style.display="none";return a},show:function(a){a=$(a);a.style.display="";return a},remove:function(a){a=$(a);a.parentNode.removeChild(a);return a},update:function(a,b){a=$(a);if(b&&b.toElement){b=b.toElement()}if(Object.isElement(b)){return a.update().insert(b)}b=Object.toHTML(b);a.innerHTML=b.stripScripts();b.evalScripts.bind(b).defer();return a},replace:function(b,c){b=$(b);if(c&&c.toElement){c=c.toElement()}else{if(!Object.isElement(c)){c=Object.toHTML(c);var a=b.ownerDocument.createRange();a.selectNode(b);c.evalScripts.bind(c).defer();c=a.createContextualFragment(c.stripScripts())}}b.parentNode.replaceChild(c,b);return b},insert:function(c,e){c=$(c);if(Object.isString(e)||Object.isNumber(e)||Object.isElement(e)||(e&&(e.toElement||e.toHTML))){e={bottom:e}}var d,f,b,g;for(var a in e){d=e[a];a=a.toLowerCase();f=Element._insertionTranslations[a];if(d&&d.toElement){d=d.toElement()}if(Object.isElement(d)){f(c,d);continue}d=Object.toHTML(d);b=((a=="before"||a=="after")?c.parentNode:c).tagName.toUpperCase();g=Element._getContentFromAnonymousElement(b,d.stripScripts());if(a=="top"||a=="after"){g.reverse()}g.each(f.curry(c));d.evalScripts.bind(d).defer()}return c},wrap:function(b,c,a){b=$(b);if(Object.isElement(c)){$(c).writeAttribute(a||{})}else{if(Object.isString(c)){c=new Element(c,a)}else{c=new Element("div",c)}}if(b.parentNode){b.parentNode.replaceChild(c,b)}c.appendChild(b);return c},inspect:function(b){b=$(b);var a="<"+b.tagName.toLowerCase();$H({id:"id",className:"class"}).each(function(f){var e=f.first(),c=f.last();var d=(b[e]||"").toString();if(d){a+=" "+c+"="+d.inspect(true)}});return a+">"},recursivelyCollect:function(a,c){a=$(a);var b=[];while(a=a[c]){if(a.nodeType==1){b.push(Element.extend(a))}}return b},ancestors:function(a){return $(a).recursivelyCollect("parentNode")},descendants:function(a){return $(a).select("*")},firstDescendant:function(a){a=$(a).firstChild;while(a&&a.nodeType!=1){a=a.nextSibling}return $(a)},immediateDescendants:function(a){if(!(a=$(a).firstChild)){return[]}while(a&&a.nodeType!=1){a=a.nextSibling}if(a){return[a].concat($(a).nextSiblings())}return[]},previousSiblings:function(a){return $(a).recursivelyCollect("previousSibling")},nextSiblings:function(a){return $(a).recursivelyCollect("nextSibling")},siblings:function(a){a=$(a);return a.previousSiblings().reverse().concat(a.nextSiblings())},match:function(b,a){if(Object.isString(a)){a=new Selector(a)}return a.match($(b))},up:function(b,d,a){b=$(b);if(arguments.length==1){return $(b.parentNode)}var c=b.ancestors();return Object.isNumber(d)?c[d]:Selector.findElement(c,d,a)},down:function(b,c,a){b=$(b);if(arguments.length==1){return b.firstDescendant()}return Object.isNumber(c)?b.descendants()[c]:Element.select(b,c)[a||0]},previous:function(b,d,a){b=$(b);if(arguments.length==1){return $(Selector.handlers.previousElementSibling(b))}var c=b.previousSiblings();return Object.isNumber(d)?c[d]:Selector.findElement(c,d,a)},next:function(c,d,b){c=$(c);if(arguments.length==1){return $(Selector.handlers.nextElementSibling(c))}var a=c.nextSiblings();return Object.isNumber(d)?a[d]:Selector.findElement(a,d,b)},select:function(){var a=$A(arguments),b=$(a.shift());return Selector.findChildElements(b,a)},adjacent:function(){var a=$A(arguments),b=$(a.shift());return Selector.findChildElements(b.parentNode,a).without(b)},identify:function(b){b=$(b);var c=b.readAttribute("id"),a=arguments.callee;if(c){return c}do{c="anonymous_element_"+a.counter++}while($(c));b.writeAttribute("id",c);return c},readAttribute:function(c,a){c=$(c);if(Prototype.Browser.IE){var b=Element._attributeTranslations.read;if(b.values[a]){return b.values[a](c,a)}if(b.names[a]){a=b.names[a]}if(a.include(":")){return(!c.attributes||!c.attributes[a])?null:c.attributes[a].value}}return c.getAttribute(a)},writeAttribute:function(e,c,f){e=$(e);var b={},d=Element._attributeTranslations.write;if(typeof c=="object"){b=c}else{b[c]=Object.isUndefined(f)?true:f}for(var a in b){c=d.names[a]||a;f=b[a];if(d.values[a]){c=d.values[a](e,f)}if(f===false||f===null){e.removeAttribute(c)}else{if(f===true){e.setAttribute(c,c)}else{e.setAttribute(c,f)}}}return e},getHeight:function(a){return $(a).getDimensions().height},getWidth:function(a){return $(a).getDimensions().width},classNames:function(a){return new Element.ClassNames(a)},hasClassName:function(a,b){if(!(a=$(a))){return}var c=a.className;return(c.length>0&&(c==b||new RegExp("(^|\\s)"+b+"(\\s|$)").test(c)))},addClassName:function(a,b){if(!(a=$(a))){return}if(!a.hasClassName(b)){a.className+=(a.className?" ":"")+b}return a},removeClassName:function(a,b){if(!(a=$(a))){return}a.className=a.className.replace(new RegExp("(^|\\s+)"+b+"(\\s+|$)")," ").strip();return a},toggleClassName:function(a,b){if(!(a=$(a))){return}return a[a.hasClassName(b)?"removeClassName":"addClassName"](b)},cleanWhitespace:function(b){b=$(b);var c=b.firstChild;while(c){var a=c.nextSibling;if(c.nodeType==3&&!/\S/.test(c.nodeValue)){b.removeChild(c)}c=a}return b},empty:function(a){return $(a).innerHTML.blank()},descendantOf:function(b,a){b=$(b),a=$(a);if(b.compareDocumentPosition){return(b.compareDocumentPosition(a)&8)===8}if(a.contains){return a.contains(b)&&a!==b}while(b=b.parentNode){if(b==a){return true}}return false},scrollTo:function(a){a=$(a);var b=a.cumulativeOffset();window.scrollTo(b[0],b[1]);return a},getStyle:function(b,c){b=$(b);c=c=="float"?"cssFloat":c.camelize();var d=b.style[c];if(!d||d=="auto"){var a=document.defaultView.getComputedStyle(b,null);d=a?a[c]:null}if(c=="opacity"){return d?parseFloat(d):1}return d=="auto"?null:d},getOpacity:function(a){return $(a).getStyle("opacity")},setStyle:function(b,c){b=$(b);var e=b.style,a;if(Object.isString(c)){b.style.cssText+=";"+c;return c.include("opacity")?b.setOpacity(c.match(/opacity:\s*(\d?\.?\d*)/)[1]):b}for(var d in c){if(d=="opacity"){b.setOpacity(c[d])}else{e[(d=="float"||d=="cssFloat")?(Object.isUndefined(e.styleFloat)?"cssFloat":"styleFloat"):d]=c[d]}}return b},setOpacity:function(a,b){a=$(a);a.style.opacity=(b==1||b==="")?"":(b<0.00001)?0:b;return a},getDimensions:function(c){c=$(c);var g=c.getStyle("display");if(g!="none"&&g!=null){return{width:c.offsetWidth,height:c.offsetHeight}}var b=c.style;var f=b.visibility;var d=b.position;var a=b.display;b.visibility="hidden";b.position="absolute";b.display="block";var h=c.clientWidth;var e=c.clientHeight;b.display=a;b.position=d;b.visibility=f;return{width:h,height:e}},makePositioned:function(a){a=$(a);var b=Element.getStyle(a,"position");if(b=="static"||!b){a._madePositioned=true;a.style.position="relative";if(Prototype.Browser.Opera){a.style.top=0;a.style.left=0}}return a},undoPositioned:function(a){a=$(a);if(a._madePositioned){a._madePositioned=undefined;a.style.position=a.style.top=a.style.left=a.style.bottom=a.style.right=""}return a},makeClipping:function(a){a=$(a);if(a._overflow){return a}a._overflow=Element.getStyle(a,"overflow")||"auto";if(a._overflow!=="hidden"){a.style.overflow="hidden"}return a},undoClipping:function(a){a=$(a);if(!a._overflow){return a}a.style.overflow=a._overflow=="auto"?"":a._overflow;a._overflow=null;return a},cumulativeOffset:function(b){var a=0,c=0;do{a+=b.offsetTop||0;c+=b.offsetLeft||0;b=b.offsetParent}while(b);return Element._returnOffset(c,a)},positionedOffset:function(b){var a=0,d=0;do{a+=b.offsetTop||0;d+=b.offsetLeft||0;b=b.offsetParent;if(b){if(b.tagName.toUpperCase()=="BODY"){break}var c=Element.getStyle(b,"position");if(c!=="static"){break}}}while(b);return Element._returnOffset(d,a)},absolutize:function(b){b=$(b);if(b.getStyle("position")=="absolute"){return b}var d=b.positionedOffset();var f=d[1];var e=d[0];var c=b.clientWidth;var a=b.clientHeight;b._originalLeft=e-parseFloat(b.style.left||0);b._originalTop=f-parseFloat(b.style.top||0);b._originalWidth=b.style.width;b._originalHeight=b.style.height;b.style.position="absolute";b.style.top=f+"px";b.style.left=e+"px";b.style.width=c+"px";b.style.height=a+"px";return b},relativize:function(a){a=$(a);if(a.getStyle("position")=="relative"){return a}a.style.position="relative";var c=parseFloat(a.style.top||0)-(a._originalTop||0);var b=parseFloat(a.style.left||0)-(a._originalLeft||0);a.style.top=c+"px";a.style.left=b+"px";a.style.height=a._originalHeight;a.style.width=a._originalWidth;return a},cumulativeScrollOffset:function(b){var a=0,c=0;do{a+=b.scrollTop||0;c+=b.scrollLeft||0;b=b.parentNode}while(b);return Element._returnOffset(c,a)},getOffsetParent:function(a){if(a.offsetParent){return $(a.offsetParent)}if(a==document.body){return $(a)}while((a=a.parentNode)&&a!=document.body){if(Element.getStyle(a,"position")!="static"){return $(a)}}return $(document.body)},viewportOffset:function(d){var a=0,c=0;var b=d;do{a+=b.offsetTop||0;c+=b.offsetLeft||0;if(b.offsetParent==document.body&&Element.getStyle(b,"position")=="absolute"){break}}while(b=b.offsetParent);b=d;do{if(!Prototype.Browser.Opera||(b.tagName&&(b.tagName.toUpperCase()=="BODY"))){a-=b.scrollTop||0;c-=b.scrollLeft||0}}while(b=b.parentNode);return Element._returnOffset(c,a)},clonePosition:function(b,d){var a=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{});d=$(d);var e=d.viewportOffset();b=$(b);var f=[0,0];var c=null;if(Element.getStyle(b,"position")=="absolute"){c=b.getOffsetParent();f=c.viewportOffset()}if(c==document.body){f[0]-=document.body.offsetLeft;f[1]-=document.body.offsetTop}if(a.setLeft){b.style.left=(e[0]-f[0]+a.offsetLeft)+"px"}if(a.setTop){b.style.top=(e[1]-f[1]+a.offsetTop)+"px"}if(a.setWidth){b.style.width=d.offsetWidth+"px"}if(a.setHeight){b.style.height=d.offsetHeight+"px"}return b}};Element.Methods.identify.counter=1;Object.extend(Element.Methods,{getElementsBySelector:Element.Methods.select,childElements:Element.Methods.immediateDescendants});Element._attributeTranslations={write:{names:{className:"class",htmlFor:"for"},values:{}}};if(Prototype.Browser.Opera){Element.Methods.getStyle=Element.Methods.getStyle.wrap(function(d,b,c){switch(c){case"left":case"top":case"right":case"bottom":if(d(b,"position")==="static"){return null}case"height":case"width":if(!Element.visible(b)){return null}var e=parseInt(d(b,c),10);if(e!==b["offset"+c.capitalize()]){return e+"px"}var a;if(c==="height"){a=["border-top-width","padding-top","padding-bottom","border-bottom-width"]}else{a=["border-left-width","padding-left","padding-right","border-right-width"]}return a.inject(e,function(f,g){var h=d(b,g);return h===null?f:f-parseInt(h,10)})+"px";default:return d(b,c)}});Element.Methods.readAttribute=Element.Methods.readAttribute.wrap(function(c,a,b){if(b==="title"){return a.title}return c(a,b)})}else{if(Prototype.Browser.IE){Element.Methods.getOffsetParent=Element.Methods.getOffsetParent.wrap(function(c,b){b=$(b);try{b.offsetParent}catch(f){return $(document.body)}var a=b.getStyle("position");if(a!=="static"){return c(b)}b.setStyle({position:"relative"});var d=c(b);b.setStyle({position:a});return d});$w("positionedOffset viewportOffset").each(function(a){Element.Methods[a]=Element.Methods[a].wrap(function(f,c){c=$(c);try{c.offsetParent}catch(h){return Element._returnOffset(0,0)}var b=c.getStyle("position");if(b!=="static"){return f(c)}var d=c.getOffsetParent();if(d&&d.getStyle("position")==="fixed"){d.setStyle({zoom:1})}c.setStyle({position:"relative"});var g=f(c);c.setStyle({position:b});return g})});Element.Methods.cumulativeOffset=Element.Methods.cumulativeOffset.wrap(function(b,a){try{a.offsetParent}catch(c){return Element._returnOffset(0,0)}return b(a)});Element.Methods.getStyle=function(a,b){a=$(a);b=(b=="float"||b=="cssFloat")?"styleFloat":b.camelize();var c=a.style[b];if(!c&&a.currentStyle){c=a.currentStyle[b]}if(b=="opacity"){if(c=(a.getStyle("filter")||"").match(/alpha\(opacity=(.*)\)/)){if(c[1]){return parseFloat(c[1])/100}}return 1}if(c=="auto"){if((b=="width"||b=="height")&&(a.getStyle("display")!="none")){return a["offset"+b.capitalize()]+"px"}return null}return c};Element.Methods.setOpacity=function(b,e){function f(g){return g.replace(/alpha\([^\)]*\)/gi,"")}b=$(b);var a=b.currentStyle;if((a&&!a.hasLayout)||(!a&&b.style.zoom=="normal")){b.style.zoom=1}var d=b.getStyle("filter"),c=b.style;if(e==1||e===""){(d=f(d))?c.filter=d:c.removeAttribute("filter");return b}else{if(e<0.00001){e=0}}c.filter=f(d)+"alpha(opacity="+(e*100)+")";return b};Element._attributeTranslations={read:{names:{"class":"className","for":"htmlFor"},values:{_getAttr:function(a,b){return a.getAttribute(b,2)},_getAttrNode:function(a,c){var b=a.getAttributeNode(c);return b?b.value:""},_getEv:function(a,b){b=a.getAttribute(b);return b?b.toString().slice(23,-2):null},_flag:function(a,b){return $(a).hasAttribute(b)?b:null},style:function(a){return a.style.cssText.toLowerCase()},title:function(a){return a.title}}}};Element._attributeTranslations.write={names:Object.extend({cellpadding:"cellPadding",cellspacing:"cellSpacing"},Element._attributeTranslations.read.names),values:{checked:function(a,b){a.checked=!!b},style:function(a,b){a.style.cssText=b?b:""}}};Element._attributeTranslations.has={};$w("colSpan rowSpan vAlign dateTime accessKey tabIndex encType maxLength readOnly longDesc frameBorder").each(function(a){Element._attributeTranslations.write.names[a.toLowerCase()]=a;Element._attributeTranslations.has[a.toLowerCase()]=a});(function(a){Object.extend(a,{href:a._getAttr,src:a._getAttr,type:a._getAttr,action:a._getAttrNode,disabled:a._flag,checked:a._flag,readonly:a._flag,multiple:a._flag,onload:a._getEv,onunload:a._getEv,onclick:a._getEv,ondblclick:a._getEv,onmousedown:a._getEv,onmouseup:a._getEv,onmouseover:a._getEv,onmousemove:a._getEv,onmouseout:a._getEv,onfocus:a._getEv,onblur:a._getEv,onkeypress:a._getEv,onkeydown:a._getEv,onkeyup:a._getEv,onsubmit:a._getEv,onreset:a._getEv,onselect:a._getEv,onchange:a._getEv})})(Element._attributeTranslations.read.values)}else{if(Prototype.Browser.Gecko&&/rv:1\.8\.0/.test(navigator.userAgent)){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1)?0.999999:(b==="")?"":(b<0.00001)?0:b;return a}}else{if(Prototype.Browser.WebKit){Element.Methods.setOpacity=function(a,b){a=$(a);a.style.opacity=(b==1||b==="")?"":(b<0.00001)?0:b;if(b==1){if(a.tagName.toUpperCase()=="IMG"&&a.width){a.width++;a.width--}else{try{var d=document.createTextNode(" ");a.appendChild(d);a.removeChild(d)}catch(c){}}}return a};Element.Methods.cumulativeOffset=function(b){var a=0,c=0;do{a+=b.offsetTop||0;c+=b.offsetLeft||0;if(b.offsetParent==document.body){if(Element.getStyle(b,"position")=="absolute"){break}}b=b.offsetParent}while(b);return Element._returnOffset(c,a)}}}}}if(Prototype.Browser.IE||Prototype.Browser.Opera){Element.Methods.update=function(b,c){b=$(b);if(c&&c.toElement){c=c.toElement()}if(Object.isElement(c)){return b.update().insert(c)}c=Object.toHTML(c);var a=b.tagName.toUpperCase();if(a in Element._insertionTranslations.tags){$A(b.childNodes).each(function(d){b.removeChild(d)});Element._getContentFromAnonymousElement(a,c.stripScripts()).each(function(d){b.appendChild(d)})}else{b.innerHTML=c.stripScripts()}c.evalScripts.bind(c).defer();return b}}if("outerHTML" in document.createElement("div")){Element.Methods.replace=function(c,e){c=$(c);if(e&&e.toElement){e=e.toElement()}if(Object.isElement(e)){c.parentNode.replaceChild(e,c);return c}e=Object.toHTML(e);var d=c.parentNode,b=d.tagName.toUpperCase();if(Element._insertionTranslations.tags[b]){var f=c.next();var a=Element._getContentFromAnonymousElement(b,e.stripScripts());d.removeChild(c);if(f){a.each(function(g){d.insertBefore(g,f)})}else{a.each(function(g){d.appendChild(g)})}}else{c.outerHTML=e.stripScripts()}e.evalScripts.bind(e).defer();return c}}Element._returnOffset=function(b,c){var a=[b,c];a.left=b;a.top=c;return a};Element._getContentFromAnonymousElement=function(c,b){var d=new Element("div"),a=Element._insertionTranslations.tags[c];if(a){d.innerHTML=a[0]+b+a[1];a[2].times(function(){d=d.firstChild})}else{d.innerHTML=b}return $A(d.childNodes)};Element._insertionTranslations={before:function(a,b){a.parentNode.insertBefore(b,a)},top:function(a,b){a.insertBefore(b,a.firstChild)},bottom:function(a,b){a.appendChild(b)},after:function(a,b){a.parentNode.insertBefore(b,a.nextSibling)},tags:{TABLE:["<table>","</table>",1],TBODY:["<table><tbody>","</tbody></table>",2],TR:["<table><tbody><tr>","</tr></tbody></table>",3],TD:["<table><tbody><tr><td>","</td></tr></tbody></table>",4],SELECT:["<select>","</select>",1]}};(function(){Object.extend(this.tags,{THEAD:this.tags.TBODY,TFOOT:this.tags.TBODY,TH:this.tags.TD})}).call(Element._insertionTranslations);Element.Methods.Simulated={hasAttribute:function(a,c){c=Element._attributeTranslations.has[c]||c;var b=$(a).getAttributeNode(c);return !!(b&&b.specified)}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);if(!Prototype.BrowserFeatures.ElementExtensions&&document.createElement("div")["__proto__"]){window.HTMLElement={};window.HTMLElement.prototype=document.createElement("div")["__proto__"];Prototype.BrowserFeatures.ElementExtensions=true}Element.extend=(function(){if(Prototype.BrowserFeatures.SpecificElementExtensions){return Prototype.K}var a={},b=Element.Methods.ByTag;var c=Object.extend(function(f){if(!f||f._extendedByPrototype||f.nodeType!=1||f==window){return f}var d=Object.clone(a),e=f.tagName.toUpperCase(),h,g;if(b[e]){Object.extend(d,b[e])}for(h in d){g=d[h];if(Object.isFunction(g)&&!(h in f)){f[h]=g.methodize()}}f._extendedByPrototype=Prototype.emptyFunction;return f},{refresh:function(){if(!Prototype.BrowserFeatures.ElementExtensions){Object.extend(a,Element.Methods);Object.extend(a,Element.Methods.Simulated)}}});c.refresh();return c})();Element.hasAttribute=function(a,b){if(a.hasAttribute){return a.hasAttribute(b)}return Element.Methods.Simulated.hasAttribute(a,b)};Element.addMethods=function(c){var h=Prototype.BrowserFeatures,d=Element.Methods.ByTag;if(!c){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{FORM:Object.clone(Form.Methods),INPUT:Object.clone(Form.Element.Methods),SELECT:Object.clone(Form.Element.Methods),TEXTAREA:Object.clone(Form.Element.Methods)})}if(arguments.length==2){var b=c;c=arguments[1]}if(!b){Object.extend(Element.Methods,c||{})}else{if(Object.isArray(b)){b.each(g)}else{g(b)}}function g(j){j=j.toUpperCase();if(!Element.Methods.ByTag[j]){Element.Methods.ByTag[j]={}}Object.extend(Element.Methods.ByTag[j],c)}function a(l,k,j){j=j||false;for(var n in l){var m=l[n];if(!Object.isFunction(m)){continue}if(!j||!(n in k)){k[n]=m.methodize()}}}function e(l){var j;var k={OPTGROUP:"OptGroup",TEXTAREA:"TextArea",P:"Paragraph",FIELDSET:"FieldSet",UL:"UList",OL:"OList",DL:"DList",DIR:"Directory",H1:"Heading",H2:"Heading",H3:"Heading",H4:"Heading",H5:"Heading",H6:"Heading",Q:"Quote",INS:"Mod",DEL:"Mod",A:"Anchor",IMG:"Image",CAPTION:"TableCaption",COL:"TableCol",COLGROUP:"TableCol",THEAD:"TableSection",TFOOT:"TableSection",TBODY:"TableSection",TR:"TableRow",TH:"TableCell",TD:"TableCell",FRAMESET:"FrameSet",IFRAME:"IFrame"};if(k[l]){j="HTML"+k[l]+"Element"}if(window[j]){return window[j]}j="HTML"+l+"Element";if(window[j]){return window[j]}j="HTML"+l.capitalize()+"Element";if(window[j]){return window[j]}window[j]={};window[j].prototype=document.createElement(l)["__proto__"];return window[j]}if(h.ElementExtensions){a(Element.Methods,HTMLElement.prototype);a(Element.Methods.Simulated,HTMLElement.prototype,true)}if(h.SpecificElementExtensions){for(var i in Element.Methods.ByTag){var f=e(i);if(Object.isUndefined(f)){continue}a(d[i],f.prototype)}}Object.extend(Element,Element.Methods);delete Element.ByTag;if(Element.extend.refresh){Element.extend.refresh()}Element.cache={}};document.viewport={getDimensions:function(){var a={},b=Prototype.Browser;$w("width height").each(function(e){var c=e.capitalize();if(b.WebKit&&!document.evaluate){a[e]=self["inner"+c]}else{if(b.Opera&&parseFloat(window.opera.version())<9.5){a[e]=document.body["client"+c]}else{a[e]=document.documentElement["client"+c]}}});return a},getWidth:function(){return this.getDimensions().width},getHeight:function(){return this.getDimensions().height},getScrollOffsets:function(){return Element._returnOffset(window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft,window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop)}};var Selector=Class.create({initialize:function(a){this.expression=a.strip();if(this.shouldUseSelectorsAPI()){this.mode="selectorsAPI"}else{if(this.shouldUseXPath()){this.mode="xpath";this.compileXPathMatcher()}else{this.mode="normal";this.compileMatcher()}}},shouldUseXPath:function(){if(!Prototype.BrowserFeatures.XPath){return false}var a=this.expression;if(Prototype.Browser.WebKit&&(a.include("-of-type")||a.include(":empty"))){return false}if((/(\[[\w-]*?:|:checked)/).test(a)){return false}return true},shouldUseSelectorsAPI:function(){if(!Prototype.BrowserFeatures.SelectorsAPI){return false}if(!Selector._div){Selector._div=new Element("div")}try{Selector._div.querySelector(this.expression)}catch(a){return false}return true},compileMatcher:function(){var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m;if(Selector._cache[e]){this.matcher=Selector._cache[e];return}this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){p=ps[i];if(m=e.match(p)){this.matcher.push(Object.isFunction(c[i])?c[i](m):new Template(c[i]).evaluate(m));e=e.replace(m[0],"");break}}}this.matcher.push("return h.unique(n);\n}");eval(this.matcher.join("\n"));Selector._cache[this.expression]=this.matcher},compileXPathMatcher:function(){var f=this.expression,g=Selector.patterns,b=Selector.xpath,d,a;if(Selector._cache[f]){this.xpath=Selector._cache[f];return}this.matcher=[".//*"];while(f&&d!=f&&(/\S/).test(f)){d=f;for(var c in g){if(a=f.match(g[c])){this.matcher.push(Object.isFunction(b[c])?b[c](a):new Template(b[c]).evaluate(a));f=f.replace(a[0],"");break}}}this.xpath=this.matcher.join("");Selector._cache[this.expression]=this.xpath},findElements:function(a){a=a||document;var c=this.expression,b;switch(this.mode){case"selectorsAPI":if(a!==document){var d=a.id,f=$(a).identify();c="#"+f+" "+c}b=$A(a.querySelectorAll(c)).map(Element.extend);a.id=d;return b;case"xpath":return document._getElementsByXPath(this.xpath,a);default:return this.matcher(a)}},match:function(j){this.tokens=[];var o=this.expression,a=Selector.patterns,f=Selector.assertions;var b,d,g;while(o&&b!==o&&(/\S/).test(o)){b=o;for(var k in a){d=a[k];if(g=o.match(d)){if(f[k]){this.tokens.push([k,Object.clone(g)]);o=o.replace(g[0],"")}else{return this.findElements(document).include(j)}}}}var n=true,c,l;for(var k=0,h;h=this.tokens[k];k++){c=h[0],l=h[1];if(!Selector.assertions[c](j,l)){n=false;break}}return n},toString:function(){return this.expression},inspect:function(){return"#<Selector:"+this.expression.inspect()+">"}});Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:"/following-sibling::*",tagName:function(a){if(a[1]=="*"){return""}return"[local-name()='"+a[1].toLowerCase()+"' or local-name()='"+a[1].toUpperCase()+"']"},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:function(a){a[1]=a[1].toLowerCase();return new Template("[@#{1}]").evaluate(a)},attr:function(a){a[1]=a[1].toLowerCase();a[3]=a[5]||a[6];return new Template(Selector.xpath.operators[a[2]]).evaluate(a)},pseudo:function(a){var b=Selector.xpath.pseudos[a[1]];if(!b){return""}if(Object.isFunction(b)){return b(a)}return new Template(Selector.xpath.pseudos[a[1]]).evaluate(a)},operators:{"=":"[@#{1}='#{3}']","!=":"[@#{1}!='#{3}']","^=":"[starts-with(@#{1}, '#{3}')]","$=":"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']","*=":"[contains(@#{1}, '#{3}')]","~=":"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]","|=":"[contains(concat('-', @#{1}, '-'), '-#{3}-')]"},pseudos:{"first-child":"[not(preceding-sibling::*)]","last-child":"[not(following-sibling::*)]","only-child":"[not(preceding-sibling::* or following-sibling::*)]",empty:"[count(*) = 0 and (count(text()) = 0)]",checked:"[@checked]",disabled:"[(@disabled) and (@type!='hidden')]",enabled:"[not(@disabled) and (@type!='hidden')]",not:function(b){var j=b[6],h=Selector.patterns,a=Selector.xpath,f,c;var g=[];while(j&&f!=j&&(/\S/).test(j)){f=j;for(var d in h){if(b=j.match(h[d])){c=Object.isFunction(a[d])?a[d](b):new Template(a[d]).evaluate(b);g.push("("+c.substring(1,c.length-1)+")");j=j.replace(b[0],"");break}}}return"[not("+g.join(" and ")+")]"},"nth-child":function(a){return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ",a)},"nth-last-child":function(a){return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ",a)},"nth-of-type":function(a){return Selector.xpath.pseudos.nth("position() ",a)},"nth-last-of-type":function(a){return Selector.xpath.pseudos.nth("(last() + 1 - position()) ",a)},"first-of-type":function(a){a[6]="1";return Selector.xpath.pseudos["nth-of-type"](a)},"last-of-type":function(a){a[6]="1";return Selector.xpath.pseudos["nth-last-of-type"](a)},"only-of-type":function(a){var b=Selector.xpath.pseudos;return b["first-of-type"](a)+b["last-of-type"](a)},nth:function(g,e){var h,i=e[6],d;if(i=="even"){i="2n+0"}if(i=="odd"){i="2n+1"}if(h=i.match(/^(\d+)$/)){return"["+g+"= "+h[1]+"]"}if(h=i.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(h[1]=="-"){h[1]=-1}var f=h[1]?Number(h[1]):1;var c=h[2]?Number(h[2]):0;d="[((#{fragment} - #{b}) mod #{a} = 0) and ((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(d).evaluate({fragment:g,a:f,b:c})}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c);      c = false;',className:'n = h.className(n, r, "#{1}", c);    c = false;',id:'n = h.id(n, r, "#{1}", c);           c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}", c); c = false;',attr:function(a){a[3]=(a[5]||a[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}", c); c = false;').evaluate(a)},pseudo:function(a){if(a[6]){a[6]=a[6].replace(/"/g,'\\"')}return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(a)},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:{laterSibling:/^\s*~\s*/,child:/^\s*>\s*/,adjacent:/^\s*\+\s*/,descendant:/^\s/,tagName:/^\s*(\*|[\w\-]+)(\b|$)?/,id:/^#([\w\-\*]+)(\b|$)/,className:/^\.([\w\-\*]+)(\b|$)/,pseudo:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|(?=\s|[:+~>]))/,attrPresence:/^\[((?:[\w]+:)?[\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\4]*?)\4|([^'"][^\]]*?)))?\]/},assertions:{tagName:function(a,b){return b[1].toUpperCase()==a.tagName.toUpperCase()},className:function(a,b){return Element.hasClassName(a,b[1])},id:function(a,b){return a.id===b[1]},attrPresence:function(a,b){return Element.hasAttribute(a,b[1])},attr:function(b,c){var a=Element.readAttribute(b,c[1]);return a&&Selector.operators[c[2]](a,c[5]||c[6])}},handlers:{concat:function(d,c){for(var e=0,f;f=c[e];e++){d.push(f)}return d},mark:function(a){var d=Prototype.emptyFunction;for(var b=0,c;c=a[b];b++){c._countedByPrototype=d}return a},unmark:function(a){for(var b=0,c;c=a[b];b++){c._countedByPrototype=undefined}return a},index:function(a,d,g){a._countedByPrototype=Prototype.emptyFunction;if(d){for(var b=a.childNodes,e=b.length-1,c=1;e>=0;e--){var f=b[e];if(f.nodeType==1&&(!g||f._countedByPrototype)){f.nodeIndex=c++}}}else{for(var e=0,c=1,b=a.childNodes;f=b[e];e++){if(f.nodeType==1&&(!g||f._countedByPrototype)){f.nodeIndex=c++}}}},unique:function(b){if(b.length==0){return b}var d=[],e;for(var c=0,a=b.length;c<a;c++){if(!(e=b[c])._countedByPrototype){e._countedByPrototype=Prototype.emptyFunction;d.push(Element.extend(e))}}return Selector.handlers.unmark(d)},descendant:function(a){var d=Selector.handlers;for(var c=0,b=[],e;e=a[c];c++){d.concat(b,e.getElementsByTagName("*"))}return b},child:function(a){var e=Selector.handlers;for(var d=0,c=[],f;f=a[d];d++){for(var b=0,g;g=f.childNodes[b];b++){if(g.nodeType==1&&g.tagName!="!"){c.push(g)}}}return c},adjacent:function(a){for(var c=0,b=[],e;e=a[c];c++){var d=this.nextElementSibling(e);if(d){b.push(d)}}return b},laterSibling:function(a){var d=Selector.handlers;for(var c=0,b=[],e;e=a[c];c++){d.concat(b,Element.nextSiblings(e))}return b},nextElementSibling:function(a){while(a=a.nextSibling){if(a.nodeType==1){return a}}return null},previousElementSibling:function(a){while(a=a.previousSibling){if(a.nodeType==1){return a}}return null},tagName:function(a,j,c,b){var k=c.toUpperCase();var e=[],g=Selector.handlers;if(a){if(b){if(b=="descendant"){for(var f=0,d;d=a[f];f++){g.concat(e,d.getElementsByTagName(c))}return e}else{a=this[b](a)}if(c=="*"){return a}}for(var f=0,d;d=a[f];f++){if(d.tagName.toUpperCase()===k){e.push(d)}}return e}else{return j.getElementsByTagName(c)}},id:function(b,a,j,f){var g=$(j),d=Selector.handlers;if(!g){return[]}if(!b&&a==document){return[g]}if(b){if(f){if(f=="child"){for(var c=0,e;e=b[c];c++){if(g.parentNode==e){return[g]}}}else{if(f=="descendant"){for(var c=0,e;e=b[c];c++){if(Element.descendantOf(g,e)){return[g]}}}else{if(f=="adjacent"){for(var c=0,e;e=b[c];c++){if(Selector.handlers.previousElementSibling(g)==e){return[g]}}}else{b=d[f](b)}}}}for(var c=0,e;e=b[c];c++){if(e==g){return[g]}}return[]}return(g&&Element.descendantOf(g,a))?[g]:[]},className:function(b,a,c,d){if(b&&d){b=this[d](b)}return Selector.handlers.byClassName(b,a,c)},byClassName:function(c,b,f){if(!c){c=Selector.handlers.descendant([b])}var h=" "+f+" ";for(var e=0,d=[],g,a;g=c[e];e++){a=g.className;if(a.length==0){continue}if(a==f||(" "+a+" ").include(h)){d.push(g)}}return d},attrPresence:function(c,b,a,g){if(!c){c=b.getElementsByTagName("*")}if(c&&g){c=this[g](c)}var e=[];for(var d=0,f;f=c[d];d++){if(Element.hasAttribute(f,a)){e.push(f)}}return e},attr:function(a,j,h,k,c,b){if(!a){a=j.getElementsByTagName("*")}if(a&&b){a=this[b](a)}var l=Selector.operators[c],f=[];for(var e=0,d;d=a[e];e++){var g=Element.readAttribute(d,h);if(g===null){continue}if(l(g,k)){f.push(d)}}return f},pseudo:function(b,c,e,a,d){if(b&&d){b=this[d](b)}if(!b){b=a.getElementsByTagName("*")}return Selector.pseudos[c](b,e,a)}},pseudos:{"first-child":function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(Selector.handlers.previousElementSibling(e)){continue}c.push(e)}return c},"last-child":function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(Selector.handlers.nextElementSibling(e)){continue}c.push(e)}return c},"only-child":function(b,g,a){var e=Selector.handlers;for(var d=0,c=[],f;f=b[d];d++){if(!e.previousElementSibling(f)&&!e.nextElementSibling(f)){c.push(f)}}return c},"nth-child":function(b,c,a){return Selector.pseudos.nth(b,c,a)},"nth-last-child":function(b,c,a){return Selector.pseudos.nth(b,c,a,true)},"nth-of-type":function(b,c,a){return Selector.pseudos.nth(b,c,a,false,true)},"nth-last-of-type":function(b,c,a){return Selector.pseudos.nth(b,c,a,true,true)},"first-of-type":function(b,c,a){return Selector.pseudos.nth(b,"1",a,false,true)},"last-of-type":function(b,c,a){return Selector.pseudos.nth(b,"1",a,true,true)},"only-of-type":function(b,d,a){var c=Selector.pseudos;return c["last-of-type"](c["first-of-type"](b,d,a),d,a)},getIndices:function(d,c,e){if(d==0){return c>0?[c]:[]}return $R(1,e).inject([],function(a,b){if(0==(b-c)%d&&(b-c)/d>=0){a.push(b)}return a})},nth:function(c,s,u,r,e){if(c.length==0){return[]}if(s=="even"){s="2n+0"}if(s=="odd"){s="2n+1"}var q=Selector.handlers,p=[],d=[],g;q.mark(c);for(var o=0,f;f=c[o];o++){if(!f.parentNode._countedByPrototype){q.index(f.parentNode,r,e);d.push(f.parentNode)}}if(s.match(/^\d+$/)){s=Number(s);for(var o=0,f;f=c[o];o++){if(f.nodeIndex==s){p.push(f)}}}else{if(g=s.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(g[1]=="-"){g[1]=-1}var v=g[1]?Number(g[1]):1;var t=g[2]?Number(g[2]):0;var w=Selector.pseudos.getIndices(v,t,c.length);for(var o=0,f,k=w.length;f=c[o];o++){for(var n=0;n<k;n++){if(f.nodeIndex==w[n]){p.push(f)}}}}}q.unmark(c);q.unmark(d);return p},empty:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(e.tagName=="!"||e.firstChild){continue}c.push(e)}return c},not:function(a,d,k){var g=Selector.handlers,l,c;var j=new Selector(d).findElements(k);g.mark(j);for(var f=0,e=[],b;b=a[f];f++){if(!b._countedByPrototype){e.push(b)}}g.unmark(j);return e},enabled:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(!e.disabled&&(!e.type||e.type!=="hidden")){c.push(e)}}return c},disabled:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(e.disabled){c.push(e)}}return c},checked:function(b,f,a){for(var d=0,c=[],e;e=b[d];d++){if(e.checked){c.push(e)}}return c}},operators:{"=":function(b,a){return b==a},"!=":function(b,a){return b!=a},"^=":function(b,a){return b==a||b&&b.startsWith(a)},"$=":function(b,a){return b==a||b&&b.endsWith(a)},"*=":function(b,a){return b==a||b&&b.include(a)},"$=":function(b,a){return b.endsWith(a)},"*=":function(b,a){return b.include(a)},"~=":function(b,a){return(" "+b+" ").include(" "+a+" ")},"|=":function(b,a){return("-"+(b||"").toUpperCase()+"-").include("-"+(a||"").toUpperCase()+"-")}},split:function(b){var a=[];b.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(c){a.push(c[1].strip())});return a},matchElements:function(f,g){var e=$$(g),d=Selector.handlers;d.mark(e);for(var c=0,b=[],a;a=f[c];c++){if(a._countedByPrototype){b.push(a)}}d.unmark(e);return b},findElement:function(b,c,a){if(Object.isNumber(c)){a=c;c=false}return Selector.matchElements(b,c||"*")[a||0]},findChildElements:function(e,g){g=Selector.split(g.join(","));var d=[],f=Selector.handlers;for(var c=0,b=g.length,a;c<b;c++){a=new Selector(g[c].strip());f.concat(d,a.findElements(e))}return(b>1)?f.unique(d):d}});if(Prototype.Browser.IE){Object.extend(Selector.handlers,{concat:function(d,c){for(var e=0,f;f=c[e];e++){if(f.tagName!=="!"){d.push(f)}}return d},unmark:function(a){for(var b=0,c;c=a[b];b++){c.removeAttribute("_countedByPrototype")}return a}})}function $$(){return Selector.findChildElements(document,$A(arguments))}var Form={reset:function(a){$(a).reset();return a},serializeElements:function(g,b){if(typeof b!="object"){b={hash:!!b}}else{if(Object.isUndefined(b.hash)){b.hash=true}}var c,f,a=false,e=b.submit;var d=g.inject({},function(h,i){if(!i.disabled&&i.name){c=i.name;f=$(i).getValue();if(f!=null&&i.type!="file"&&(i.type!="submit"||(!a&&e!==false&&(!e||c==e)&&(a=true)))){if(c in h){if(!Object.isArray(h[c])){h[c]=[h[c]]}h[c].push(f)}else{h[c]=f}}}return h});return b.hash?d:Object.toQueryString(d)}};Form.Methods={serialize:function(b,a){return Form.serializeElements(Form.getElements(b),a)},getElements:function(a){return $A($(a).getElementsByTagName("*")).inject([],function(b,c){if(Form.Element.Serializers[c.tagName.toLowerCase()]){b.push(Element.extend(c))}return b})},getInputs:function(g,c,d){g=$(g);var a=g.getElementsByTagName("input");if(!c&&!d){return $A(a).map(Element.extend)}for(var e=0,h=[],f=a.length;e<f;e++){var b=a[e];if((c&&b.type!=c)||(d&&b.name!=d)){continue}h.push(Element.extend(b))}return h},disable:function(a){a=$(a);Form.getElements(a).invoke("disable");return a},enable:function(a){a=$(a);Form.getElements(a).invoke("enable");return a},findFirstElement:function(b){var c=$(b).getElements().findAll(function(d){return"hidden"!=d.type&&!d.disabled});var a=c.findAll(function(d){return d.hasAttribute("tabIndex")&&d.tabIndex>=0}).sortBy(function(d){return d.tabIndex}).first();return a?a:c.find(function(d){return["input","select","textarea"].include(d.tagName.toLowerCase())})},focusFirstElement:function(a){a=$(a);a.findFirstElement().activate();return a},request:function(b,a){b=$(b),a=Object.clone(a||{});var d=a.parameters,c=b.readAttribute("action")||"";if(c.blank()){c=window.location.href}a.parameters=b.serialize(true);if(d){if(Object.isString(d)){d=d.toQueryParams()}Object.extend(a.parameters,d)}if(b.hasAttribute("method")&&!a.method){a.method=b.method}return new Ajax.Request(c,a)}};Form.Element={focus:function(a){$(a).focus();return a},select:function(a){$(a).select();return a}};Form.Element.Methods={serialize:function(a){a=$(a);if(!a.disabled&&a.name){var b=a.getValue();if(b!=undefined){var c={};c[a.name]=b;return Object.toQueryString(c)}}return""},getValue:function(a){a=$(a);var b=a.tagName.toLowerCase();return Form.Element.Serializers[b](a)},setValue:function(a,b){a=$(a);var c=a.tagName.toLowerCase();Form.Element.Serializers[c](a,b);return a},clear:function(a){$(a).value="";return a},present:function(a){return $(a).value!=""},activate:function(a){a=$(a);try{a.focus();if(a.select&&(a.tagName.toLowerCase()!="input"||!["button","reset","submit"].include(a.type))){a.select()}}catch(b){}return a},disable:function(a){a=$(a);a.disabled=true;return a},enable:function(a){a=$(a);a.disabled=false;return a}};var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(a,b){switch(a.type.toLowerCase()){case"checkbox":case"radio":return Form.Element.Serializers.inputSelector(a,b);default:return Form.Element.Serializers.textarea(a,b)}},inputSelector:function(a,b){if(Object.isUndefined(b)){return a.checked?a.value:null}else{a.checked=!!b}},textarea:function(a,b){if(Object.isUndefined(b)){return a.value}else{a.value=b}},select:function(c,f){if(Object.isUndefined(f)){return this[c.type=="select-one"?"selectOne":"selectMany"](c)}else{var b,d,g=!Object.isArray(f);for(var a=0,e=c.length;a<e;a++){b=c.options[a];d=this.optionValue(b);if(g){if(d==f){b.selected=true;return}}else{b.selected=f.include(d)}}}},selectOne:function(b){var a=b.selectedIndex;return a>=0?this.optionValue(b.options[a]):null},selectMany:function(d){var a,e=d.length;if(!e){return null}for(var c=0,a=[];c<e;c++){var b=d.options[c];if(b.selected){a.push(this.optionValue(b))}}return a},optionValue:function(a){return Element.extend(a).hasAttribute("value")?a.value:a.text}};Abstract.TimedObserver=Class.create(PeriodicalExecuter,{initialize:function($super,a,b,c){$super(c,b);this.element=$(a);this.lastValue=this.getValue()},execute:function(){var a=this.getValue();if(Object.isString(this.lastValue)&&Object.isString(a)?this.lastValue!=a:String(this.lastValue)!=String(a)){this.callback(this.element,a);this.lastValue=a}}});Form.Element.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.Observer=Class.create(Abstract.TimedObserver,{getValue:function(){return Form.serialize(this.element)}});Abstract.EventObserver=Class.create({initialize:function(a,b){this.element=$(a);this.callback=b;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=="form"){this.registerFormCallbacks()}else{this.registerCallback(this.element)}},onElementEvent:function(){var a=this.getValue();if(this.lastValue!=a){this.callback(this.element,a);this.lastValue=a}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback,this)},registerCallback:function(a){if(a.type){switch(a.type.toLowerCase()){case"checkbox":case"radio":Event.observe(a,"click",this.onElementEvent.bind(this));break;default:Event.observe(a,"change",this.onElementEvent.bind(this));break}}}});Form.Element.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.Element.getValue(this.element)}});Form.EventObserver=Class.create(Abstract.EventObserver,{getValue:function(){return Form.serialize(this.element)}});if(!window.Event){var Event={}}Object.extend(Event,{KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,cache:{},relatedTarget:function(b){var a;switch(b.type){case"mouseover":a=b.fromElement;break;case"mouseout":a=b.toElement;break;default:return null}return Element.extend(a)}});Event.Methods=(function(){var a;if(Prototype.Browser.IE){var b={0:1,1:4,2:2};a=function(d,c){return d.button==b[c]}}else{if(Prototype.Browser.WebKit){a=function(d,c){switch(c){case 0:return d.which==1&&!d.metaKey;case 1:return d.which==1&&d.metaKey;default:return false}}}else{a=function(d,c){return d.which?(d.which===c+1):(d.button===c)}}}return{isLeftClick:function(c){return a(c,0)},isMiddleClick:function(c){return a(c,1)},isRightClick:function(c){return a(c,2)},element:function(e){e=Event.extend(e);var d=e.target,c=e.type,f=e.currentTarget;if(f&&f.tagName){if(c==="load"||c==="error"||(c==="click"&&f.tagName.toLowerCase()==="input"&&f.type==="radio")){d=f}}if(d.nodeType==Node.TEXT_NODE){d=d.parentNode}return Element.extend(d)},findElement:function(d,f){var c=Event.element(d);if(!f){return c}var e=[c].concat(c.ancestors());return Selector.findElement(e,f,0)},pointer:function(e){var d=document.documentElement,c=document.body||{scrollLeft:0,scrollTop:0};return{x:e.pageX||(e.clientX+(d.scrollLeft||c.scrollLeft)-(d.clientLeft||0)),y:e.pageY||(e.clientY+(d.scrollTop||c.scrollTop)-(d.clientTop||0))}},pointerX:function(c){return Event.pointer(c).x},pointerY:function(c){return Event.pointer(c).y},stop:function(c){Event.extend(c);c.preventDefault();c.stopPropagation();c.stopped=true}}})();Event.extend=(function(){var a=Object.keys(Event.Methods).inject({},function(b,c){b[c]=Event.Methods[c].methodize();return b});if(Prototype.Browser.IE){Object.extend(a,{stopPropagation:function(){this.cancelBubble=true},preventDefault:function(){this.returnValue=false},inspect:function(){return"[object Event]"}});return function(b){if(!b){return false}if(b._extendedByPrototype){return b}b._extendedByPrototype=Prototype.emptyFunction;var c=Event.pointer(b);Object.extend(b,{target:b.srcElement,relatedTarget:Event.relatedTarget(b),pageX:c.x,pageY:c.y});return Object.extend(b,a)}}else{Event.prototype=Event.prototype||document.createEvent("HTMLEvents")["__proto__"];Object.extend(Event.prototype,a);return Prototype.K}})();Object.extend(Event,(function(){var b=Event.cache;function c(j){if(j._prototypeEventID){return j._prototypeEventID[0]}arguments.callee.id=arguments.callee.id||1;return j._prototypeEventID=[++arguments.callee.id]}function g(j){if(j&&j.include(":")){return"dataavailable"}return j}function a(j){return b[j]=b[j]||{}}function f(l,j){var k=a(l);return k[j]=k[j]||[]}function h(k,j,l){var o=c(k);var n=f(o,j);if(n.pluck("handler").include(l)){return false}var m=function(p){if(!Event||!Event.extend||(p.eventName&&p.eventName!=j)){return false}Event.extend(p);l.call(k,p)};m.handler=l;n.push(m);return m}function i(m,j,k){var l=f(m,j);return l.find(function(n){return n.handler==k})}function d(m,j,k){var l=a(m);if(!l[j]){return false}l[j]=l[j].without(i(m,j,k))}function e(){for(var k in b){for(var j in b[k]){b[k][j]=null}}}if(window.attachEvent){window.attachEvent("onunload",e)}if(Prototype.Browser.WebKit){window.addEventListener("unload",Prototype.emptyFunction,false)}return{observe:function(l,j,m){l=$(l);var k=g(j);var n=h(l,j,m);if(!n){return l}if(l.addEventListener){l.addEventListener(k,n,false)}else{l.attachEvent("on"+k,n)}return l},stopObserving:function(l,j,m){l=$(l);var o=c(l),k=g(j);if(!m&&j){f(o,j).each(function(p){l.stopObserving(j,p.handler)});return l}else{if(!j){Object.keys(a(o)).each(function(p){l.stopObserving(p)});return l}}var n=i(o,j,m);if(!n){return l}if(l.removeEventListener){l.removeEventListener(k,n,false)}else{l.detachEvent("on"+k,n)}d(o,j,m);return l},fire:function(l,k,j){l=$(l);if(l==document&&document.createEvent&&!l.dispatchEvent){l=document.documentElement}var m;if(document.createEvent){m=document.createEvent("HTMLEvents");m.initEvent("dataavailable",true,true)}else{m=document.createEventObject();m.eventType="ondataavailable"}m.eventName=k;m.memo=j||{};if(document.createEvent){l.dispatchEvent(m)}else{l.fireEvent(m.eventType,m)}return Event.extend(m)}}})());Object.extend(Event,Event.Methods);Element.addMethods({fire:Event.fire,observe:Event.observe,stopObserving:Event.stopObserving});Object.extend(document,{fire:Element.Methods.fire.methodize(),observe:Element.Methods.observe.methodize(),stopObserving:Element.Methods.stopObserving.methodize(),loaded:false});(function(){var b;function a(){if(document.loaded){return}if(b){window.clearInterval(b)}document.fire("dom:loaded");document.loaded=true}if(document.addEventListener){if(Prototype.Browser.WebKit){b=window.setInterval(function(){if(/loaded|complete/.test(document.readyState)){a()}},0);Event.observe(window,"load",a)}else{document.addEventListener("DOMContentLoaded",a,false)}}else{document.write("<script id=__onDOMContentLoaded defer src=//:><\/script>");$("__onDOMContentLoaded").onreadystatechange=function(){if(this.readyState=="complete"){this.onreadystatechange=null;a()}}}})();Hash.toQueryString=Object.toQueryString;var Toggle={display:Element.toggle};Element.Methods.childOf=Element.Methods.descendantOf;var Insertion={Before:function(a,b){return Element.insert(a,{before:b})},Top:function(a,b){return Element.insert(a,{top:b})},Bottom:function(a,b){return Element.insert(a,{bottom:b})},After:function(a,b){return Element.insert(a,{after:b})}};var $continue=new Error('"throw $continue" is deprecated, use "return" instead');var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},within:function(b,a,c){if(this.includeScrollOffsets){return this.withinIncludingScrolloffsets(b,a,c)}this.xcomp=a;this.ycomp=c;this.offset=Element.cumulativeOffset(b);return(c>=this.offset[1]&&c<this.offset[1]+b.offsetHeight&&a>=this.offset[0]&&a<this.offset[0]+b.offsetWidth)},withinIncludingScrolloffsets:function(b,a,d){var c=Element.cumulativeScrollOffset(b);this.xcomp=a+c[0]-this.deltaX;this.ycomp=d+c[1]-this.deltaY;this.offset=Element.cumulativeOffset(b);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+b.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+b.offsetWidth)},overlap:function(b,a){if(!b){return 0}if(b=="vertical"){return((this.offset[1]+a.offsetHeight)-this.ycomp)/a.offsetHeight}if(b=="horizontal"){return((this.offset[0]+a.offsetWidth)-this.xcomp)/a.offsetWidth}},cumulativeOffset:Element.Methods.cumulativeOffset,positionedOffset:Element.Methods.positionedOffset,absolutize:function(a){Position.prepare();return Element.absolutize(a)},relativize:function(a){Position.prepare();return Element.relativize(a)},realOffset:Element.Methods.cumulativeScrollOffset,offsetParent:Element.Methods.getOffsetParent,page:Element.Methods.viewportOffset,clone:function(b,c,a){a=a||{};return Element.clonePosition(c,b,a)}};if(!document.getElementsByClassName){document.getElementsByClassName=function(b){function a(c){return c.blank()?null:"[contains(concat(' ', @class, ' '), ' "+c+" ')]"}b.getElementsByClassName=Prototype.BrowserFeatures.XPath?function(c,e){e=e.toString().strip();var d=/\s/.test(e)?$w(e).map(a).join(""):a(e);return d?document._getElementsByXPath(".//*"+d,c):[]}:function(e,f){f=f.toString().strip();var g=[],h=(/\s/.test(f)?$w(f):null);if(!h&&!f){return g}var c=$(e).getElementsByTagName("*");f=" "+f+" ";for(var d=0,k,j;k=c[d];d++){if(k.className&&(j=" "+k.className+" ")&&(j.include(f)||(h&&h.all(function(i){return !i.toString().blank()&&j.include(" "+i+" ")})))){g.push(Element.extend(k))}}return g};return function(d,c){return $(c||document.body).getElementsByClassName(d)}}(Element.Methods)}Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(a){this.element=$(a)},_each:function(a){this.element.className.split(/\s+/).select(function(b){return b.length>0})._each(a)},set:function(a){this.element.className=a},add:function(a){if(this.include(a)){return}this.set($A(this).concat(a).join(" "))},remove:function(a){if(!this.include(a)){return}this.set($A(this).without(a).join(" "))},toString:function(){return $A(this).join(" ")}};Object.extend(Element.ClassNames.prototype,Enumerable);Element.addMethods();

(function(){var aa="_gat",ba="_gaq",s=true,v=false,w=undefined,ca="4.5.7",y="length",z="cookie",A="location",C="&",D="=",E="__utma=",F="__utmb=",H="__utmc=",da="__utmk=",I="__utmv=",K="__utmz=",L="__utmx=",M="GASO=";var N=function(g){return w==g||"-"==g||""==g},ea=function(g){return g[y]>0&&" \n\r\t".indexOf(g)>-1},Q=function(g,i,b){var k="-",c;if(!N(g)&&!N(i)&&!N(b)){c=g.indexOf(i);if(c>-1){b=g.indexOf(b,c);if(b<0)b=g[y];k=P(g,c+i.indexOf(D)+1,b)}}return k},S=function(g){var i=v,b=0,k,c;if(!N(g)){i=s;for(k=0;k<g[y];k++){c=g.charAt(k);b+="."==c?1:0;i=i&&b<=1&&(0==k&&"-"==c||".0123456789".indexOf(c)>-1)}}return i},T=function(g,i){var b=encodeURIComponent;return b instanceof Function?i?encodeURI(g):b(g):escape(g)},
U=function(g,i){var b=decodeURIComponent,k;g=g.split("+").join(" ");if(b instanceof Function)try{k=i?decodeURI(g):b(g)}catch(c){k=unescape(g)}else k=unescape(g);return k},V=function(g,i){return g.indexOf(i)>-1},W=function(g,i){g[g[y]]=i},X=function(g){return g.toLowerCase()},Y=function(g,i){return g.split(i)},ga=function(g,i){return g.indexOf(i)},P=function(g,i,b){b=w==b?g[y]:b;return g.substring(i,b)},ha=function(g,i){return g.join(i)},ia=function(g){var i=1,b=0,k;if(!N(g)){i=0;for(k=g[y]-1;k>=0;k--){b=
g.charCodeAt(k);i=(i<<6&268435455)+b+(b<<14);b=i&266338304;i=b!=0?i^b>>21:i}}return i},ja=function(){var g=window,i=w;if(g&&g.gaGlobal&&g.gaGlobal.hid)i=g.gaGlobal.hid;else{i=Z();g.gaGlobal=g.gaGlobal?g.gaGlobal:{};g.gaGlobal.hid=i}return i},Z=function(){return Math.round(Math.random()*2147483647)},$={Fa:function(g,i){this.$a=g;this.lb=i},t:63072000000,gb:v,_gasoDomain:w,_gasoCPath:w};$.Fb=function(){var g=this,i=$.Fa;function b(c){return new i(c[0],c[1])}function k(c){var p=[];c=c.split(",");var n;for(n=0;n<c.length;++n)p.push(b(c[n].split(":")));return p}g.Ga="utm_campaign";g.Ha="utm_content";g.Ia="utm_id";g.Ja="utm_medium";g.Ka="utm_nooverride";g.La="utm_source";g.Ma="utm_term";g.Na="gclid";g.$=0;g.z=0;g.Wa="15768000";g.qb="1800";g.qa=[];g.ta=[];g.nc="cse";g.oc="q";g.mb=5;g.ra=k("images.google:q,google:q,yahoo:p,msn:q,bing:q,aol:query,aol:encquery,lycos:query,ask:q,altavista:q,netscape:query,cnn:query,looksmart:qt,about:terms,mamma:query,alltheweb:q,gigablast:q,voila:rdata,virgilio:qs,live:q,baidu:wd,alice:qs,yandex:text,najdi:q,aol:q,club-internet:query,mama:query,seznam:q,search:q,wp:szukaj,onet:qt,netsprint:q,google.interia:q,szukacz:q,yam:k,pchome:q,kvasir:q,sesam:q,ozu:q,terra:query,nostrum:query,mynet:q,ekolay:q,search.ilse:search_for,rambler:words");
g.u=w;g.jb=v;g.h="/";g.T=100;g.la="/__utm.gif";g.da=1;g.ea=1;g.v="|";g.ca=1;g.aa=1;g.Pa=1;g.c="auto";g.I=1;g.oa=1000;g.Ic=10;g.Pb=10;g.Jc=0.2;g.o=w;g.a=document;g.b=window};$.Gb=function(g){var i=this,b=g;i.r=(new Date).getTime();var k=[E,F,H,K,I,L,M];function c(j,m,q,a){var d="",l=0;d=Q(j,"2"+m,";");if(!N(d)){j=d.indexOf("^"+q+".");if(j<0)return["",0];d=P(d,j+q[y]+2);if(d.indexOf("^")>0)d=d.split("^")[0];q=d.split(":");d=q[1];l=parseInt(q[0],10);if(!a&&l<i.r)d=""}if(N(d))d="";return[d,l]}i.k=function(){var j=b.a[z];return b.o?i.Wb(j,b.o):j};i.Wb=function(j,m){var q=[],a,d;for(a=0;a<k[y];a++){d=c(j,k[a],m)[0];N(d)||(q[q[y]]=k[a]+d+";")}return q.join("")};i.l=function(j,
m,q){var a=q>0?h(q):"";if(b.o){m=i.lc(b.a[z],j,b.o,m,q);j="2"+j;a=e(q)}r(j+m,a)};i.lc=function(j,m,q,a,d){var l="";d=p(d);a=n([a,i.r+d*1],q);l=Q(j,"2"+m,";");if(!N(l)){j=n(c(j,m,q,s),q);l=ha(l.split(j),"");return l=a+l}return a};function p(j){return j||$.t}function n(j,m){return"^"+ha([[m,j[1]].join("."),j[0]],":")}function r(j,m){b.a[z]=j+"; path="+b.h+"; "+m+i.db()}i.db=function(){return N(b.c)?"":"domain="+b.c+";"};function e(j){return j>0?f():""}function f(){return h($.t)}function h(j){var m=
new Date;j=new Date(m.getTime()+j);return"expires="+j.toGMTString()+"; "}};$.Z=function(g){var i,b,k,c,p,n,r,e=this,f,h=g;e.j=new $.Gb(g);function j(a){a=a instanceof Array?a.join("."):"";return N(a)?"-":a}function m(a,d){var l=[];if(!N(a)){l=a.split(".");if(d)for(a=0;a<l[y];a++)S(l[a])||(l[a]="-")}return l}function q(a,d,l){var t=e.M,o,u;for(o=0;o<t[y];o++){u=t[o][0];u+=N(d)?d:d+t[o][4];t[o][2](Q(a,u,l))}}e.ib=function(){return w==f||f==e.P()};e.k=function(){return e.j.k()};e.ja=function(){return p?p:"-"};e.tb=function(a){p=a};e.xa=function(a){f=S(a)?a*1:"-"};e.ia=function(){return j(n)};
e.ya=function(a){n=m(a)};e.Vb=function(){e.j.l(I,"",-1)};e.mc=function(){return f?f:"-"};e.db=function(){return N(h.c)?"":"domain="+h.c+";"};e.ga=function(){return j(i)};e.rb=function(a){i=m(a,1)};e.C=function(){return j(b)};e.wa=function(a){b=m(a,1)};e.ha=function(){return j(k)};e.sb=function(a){k=m(a,1)};e.ka=function(){return j(c)};e.ub=function(a){c=m(a);for(a=0;a<c[y];a++)if(a<4&&!S(c[a]))c[a]="-"};e.gc=function(){return r};e.Dc=function(a){r=a};e.Sb=function(){i=[];b=[];k=[];c=[];p=w;n=[];f=
w};e.P=function(){var a="",d;for(d=0;d<e.M[y];d++)a+=e.M[d][1]();return ia(a)};e.sa=function(a){var d=e.k(),l=v;if(d){q(d,a,";");e.xa(e.P());l=s}return l};e.zc=function(a){q(a,"",C);e.xa(Q(a,da,C))};e.Gc=function(){var a=e.M,d=[],l;for(l=0;l<a[y];l++)W(d,a[l][0]+a[l][1]());W(d,da+e.P());return d.join(C)};e.Mc=function(a,d){var l=e.M,t=h.h;e.sa(a);h.h=d;for(a=0;a<l[y];a++)N(l[a][1]())||l[a][3]();h.h=t};e.Bb=function(){e.j.l(E,e.ga(),$.t)};e.Ca=function(){e.j.l(F,e.C(),h.qb*1000)};e.Cb=function(){e.j.l(H,
e.ha(),0)};e.Ea=function(){e.j.l(K,e.ka(),h.Wa*1000)};e.Db=function(){e.j.l(L,e.ja(),$.t)};e.Da=function(){e.j.l(I,e.ia(),$.t)};e.Nc=function(){e.j.l(M,e.gc(),0)};e.M=[[E,e.ga,e.rb,e.Bb,"."],[F,e.C,e.wa,e.Ca,""],[H,e.ha,e.sb,e.Cb,""],[L,e.ja,e.tb,e.Db,""],[K,e.ka,e.ub,e.Ea,"."],[I,e.ia,e.ya,e.Da,"."]]};$.Jb=function(g){var i=this,b=g,k=new $.Z(b),c=function(){},p=function(n){var r=(new Date).getTime(),e;e=(r-n[3])*(b.Jc/1000);if(e>=1){n[2]=Math.min(Math.floor(n[2]*1+e),b.Pb);n[3]=r}return n};i.H=function(n,r,e,f,h,j){var m,q=b.I,a=b.a[A];k.sa(e);m=Y(k.C(),".");if(m[1]<500||f){if(h)m=p(m);if(f||!h||m[2]>=1){if(!f&&h)m[2]=m[2]*1-1;m[1]=m[1]*1+1;n="?utmwv="+ca+"&utmn="+Z()+(N(a.hostname)?"":"&utmhn="+T(a.hostname))+(b.T==100?"":"&utmsp="+T(b.T))+n;if(0==q||2==q){f=2==q?c:j||c;i.Ya(b.la+n,f)}if(1==
q||2==q){n=("https:"==a.protocol?"https://ssl.google-analytics.com/__utm.gif":"http://www.google-analytics.com/__utm.gif")+n+"&utmac="+r+"&utmcc="+i.ac(e);if(ka)n+="&gaq=1";i.Ya(n,j)}}}k.wa(m.join("."));k.Ca()};i.Ya=function(n,r){var e=new Image(1,1);e.src=n;e.onload=function(){e.onload=null;(r||c)()}};i.ac=function(n){var r=[],e=[E,K,I,L],f,h=k.k(),j;for(f=0;f<e[y];f++){j=Q(h,e[f]+n,";");if(!N(j)){if(e[f]==I){j=Y(j.split(n+".")[1],"|")[0];if(N(j))continue;j=n+"."+j}W(r,e[f]+j+";")}}return T(r.join("+"))}};$.n=function(){var g=this;g.X=[];g.fb=function(i){var b,k=g.X,c;for(c=0;c<k.length;c++)b=i==k[c].q?k[c]:b;return b};g.Ob=function(i,b,k,c,p,n,r,e){var f=g.fb(i);if(w==f){f=new $.n.Mb(i,b,k,c,p,n,r,e);W(g.X,f)}else{f.Oa=b;f.zb=k;f.yb=c;f.vb=p;f.Ua=n;f.xb=r;f.Xa=e}return f}};$.n.Lb=function(g,i,b,k,c,p){var n=this;n.Ab=g;n.za=i;n.D=b;n.Sa=k;n.nb=c;n.ob=p;n.Aa=function(){return"&"+["utmt=item","tid="+T(n.Ab),"ipc="+T(n.za),"ipn="+T(n.D),"iva="+T(n.Sa),"ipr="+T(n.nb),"iqt="+T(n.ob)].join("&utm")}};
$.n.Mb=function(g,i,b,k,c,p,n,r){var e=this;e.q=g;e.Oa=i;e.zb=b;e.yb=k;e.vb=c;e.Ua=p;e.xb=n;e.Xa=r;e.R=[];e.Nb=function(f,h,j,m,q){var a=e.hc(f),d=e.q;if(w==a)W(e.R,new $.n.Lb(d,f,h,j,m,q));else{a.Ab=d;a.za=f;a.D=h;a.Sa=j;a.nb=m;a.ob=q}};e.hc=function(f){var h,j=e.R,m;for(m=0;m<j.length;m++)h=f==j[m].za?j[m]:h;return h};e.Aa=function(){return"&"+["utmt=tran","id="+T(e.q),"st="+T(e.Oa),"to="+T(e.zb),"tx="+T(e.yb),"sp="+T(e.vb),"ci="+T(e.Ua),"rg="+T(e.xb),"co="+T(e.Xa)].join("&utmt")}};$.Eb=function(g){var i=g,b=i.b,k=this,c="-";k.U=b.screen;k.Qa=!k.U&&b.java?java.awt.Toolkit.getDefaultToolkit():w;k.e=b.navigator;k.V=c;k.va=c;k.Ta=c;k.na=c;k.ma=1;k.cb=c;function p(){var n,r,e;r="ShockwaveFlash";var f="$version",h=k.e?k.e.plugins:w;if(h&&h[y]>0)for(n=0;n<h[y]&&!e;n++){r=h[n];if(V(r.name,"Shockwave Flash"))e=r.description.split("Shockwave Flash ")[1]}else{r=r+"."+r;try{n=new ActiveXObject(r+".7");e=n.GetVariable(f)}catch(j){}if(!e)try{n=new ActiveXObject(r+".6");e="WIN 6,0,21,0";
n.AllowScriptAccess="always";e=n.GetVariable(f)}catch(m){}if(!e)try{n=new ActiveXObject(r);e=n.GetVariable(f)}catch(q){}if(e){e=Y(e.split(" ")[1],",");e=e[0]+"."+e[1]+" r"+e[2]}}return e?e:c}k.bc=function(){var n;if(b.screen){k.V=k.U.width+"x"+k.U.height;k.va=k.U.colorDepth+"-bit"}else if(k.Qa)try{n=k.Qa.getScreenSize();k.V=n.width+"x"+n.height}catch(r){}k.na=X(k.e&&k.e.language?k.e.language:k.e&&k.e.browserLanguage?k.e.browserLanguage:c);k.ma=k.e&&k.e.javaEnabled()?1:0;k.cb=i.ea?p():c;k.Ta=T(i.a.characterSet?
i.a.characterSet:i.a.charset?i.a.charset:c)};k.Hc=function(){return C+"utm"+["cs="+T(k.Ta),"sr="+k.V,"sc="+k.va,"ul="+k.na,"je="+k.ma,"fl="+T(k.cb)].join("&utm")};k.$b=function(){var n=i.a,r=b.history[y];n=k.e.appName+k.e.version+k.na+k.e.platform+k.e.userAgent+k.ma+k.V+k.va+(n[z]?n[z]:"")+(n.referrer?n.referrer:"");for(var e=n[y];r>0;)n+=r--^e++;return ia(n)}};$.m=function(g,i,b,k){var c=k,p=this;p.d=g;p.pb=i;p.r=b;function n(f){return N(f)||"0"==f||!V(f,"://")}function r(f){var h="";f=X(f.split("://")[1]);if(V(f,"/")){f=f.split("/")[1];if(V(f,"?"))h=f.split("?")[0]}return h}function e(f){var h="";h=X(f.split("://")[1]);if(V(h,"/"))h=h.split("/")[0];return h}p.jc=function(f){var h=p.eb();return new $.m.w(Q(f,c.Ia+D,C),Q(f,c.La+D,C),Q(f,c.Na+D,C),p.Q(f,c.Ga,"(not set)"),p.Q(f,c.Ja,"(not set)"),p.Q(f,c.Ma,h&&!N(h.K)?U(h.K):w),p.Q(f,c.Ha,w))};p.hb=function(f){var h=
e(f),j=r(f);if(V(h,"google")){f=f.split("?").join(C);if(V(f,C+c.oc+D))if(j==c.nc)return s}return v};p.eb=function(){var f,h=p.pb,j,m,q=c.ra;if(!(n(h)||p.hb(h))){f=e(h);for(j=0;j<q[y];j++){m=q[j];if(V(f,X(m.$a))){h=h.split("?").join(C);if(V(h,C+m.lb+D)){f=h.split(C+m.lb+D)[1];if(V(f,C))f=f.split(C)[0];return new $.m.w(w,m.$a,w,"(organic)","organic",f,w)}}}}};p.Q=function(f,h,j){f=Q(f,h+D,C);return j=!N(f)?U(f):!N(j)?j:"-"};p.uc=function(f){var h=c.qa,j=v,m;if(f&&"organic"==f.S){f=X(U(f.K));for(m=0;m<
h[y];m++)j=j||X(h[m])==f}return j};p.ic=function(){var f="",h="";f=p.pb;if(!(n(f)||p.hb(f))){f=f.split("://")[1];if(V(f,"/")){h=P(f,f.indexOf("/"));h=h.split("?")[0];f=X(f.split("/")[0])}if(0==f.indexOf("www."))f=P(f,4);return new $.m.w(w,f,w,"(referral)","referral",w,h)}};p.Xb=function(f){var h="";if(c.$){h=f&&f.hash?f.href.substring(f.href.indexOf("#")):"";h=""!=h?h+C:h}h+=f.search;return h};p.ec=function(){return new $.m.w(w,"(direct)",w,"(direct)","(none)",w,w)};p.vc=function(f){var h=v,j,m=c.ta;
if(f&&"referral"==f.S){f=X(T(f.W));for(j=0;j<m[y];j++)h=h||V(f,X(m[j]))}return h};p.L=function(f){return w!=f&&f.kb()};p.cc=function(f,h){var j="",m="-",q,a=0,d,l,t=p.d;if(!f)return"";l=f.k();j=p.Xb(c.a[A]);if(c.z&&f.ib()){m=f.ka();if(!N(m)&&!V(m,";")){f.Ea();return""}}m=Q(l,K+t+".",";");q=p.jc(j);if(p.L(q)){j=Q(j,c.Ka+D,C);if("1"==j&&!N(m))return""}if(!p.L(q)){q=p.eb();if(!N(m)&&p.uc(q))return""}if(!p.L(q)&&h){q=p.ic();if(!N(m)&&p.vc(q))return""}if(!p.L(q))if(N(m)&&h)q=p.ec();if(!p.L(q))return"";
if(!N(m)){a=m.split(".");d=new $.m.w;d.Zb(a.slice(4).join("."));d=X(d.Ba())==X(q.Ba());a=a[3]*1}if(!d||h){h=Q(l,E+t+".",";");l=h.lastIndexOf(".");h=l>9?P(h,l+1)*1:0;a++;h=0==h?1:h;f.ub([t,p.r,h,a,q.Ba()].join("."));f.Ea();return C+"utmcn=1"}else return C+"utmcr=1"}};
$.m.w=function(g,i,b,k,c,p,n){var r=this;r.q=g;r.W=i;r.ba=b;r.D=k;r.S=c;r.K=p;r.Va=n;r.Ba=function(){var e=[],f=[["cid",r.q],["csr",r.W],["gclid",r.ba],["ccn",r.D],["cmd",r.S],["ctr",r.K],["cct",r.Va]],h,j;if(r.kb())for(h=0;h<f[y];h++)if(!N(f[h][1])){j=f[h][1].split("+").join("%20");j=j.split(" ").join("%20");W(e,"utm"+f[h][0]+D+j)}return e.join("|")};r.kb=function(){return!(N(r.q)&&N(r.W)&&N(r.ba))};r.Zb=function(e){var f=function(h){return U(Q(e,"utm"+h+D,"|"))};r.q=f("cid");r.W=f("csr");r.ba=f("gclid");
r.D=f("ccn");r.S=f("cmd");r.K=f("ctr");r.Va=f("cct")}};$.Hb=function(g,i,b,k){var c=this,p=i,n=D,r=g,e=k;c.O=b;c.pa="";c.p={};c.tc=function(){var h;h=Y(Q(c.O.k(),I+p+".",";"),p+".")[1];if(!N(h)){h=h.split("|");f(1,c.p,h[1]);c.pa=h[0];c.Y()}};c.Y=function(){c.Qb();var h=c.pa,j,m,q="";for(j in c.p)if((m=c.p[j])&&1===m[2])q+=j+n+m[0]+n+m[1]+n+1+",";N(q)||(h+="|"+q);if(N(h))c.O.Vb();else{c.O.ya(p+"."+h);c.O.Da()}};c.Ec=function(h){c.pa=h;c.Y()};c.Cc=function(h,j,m,q){if(1!=q&&2!=q&&3!=q)q=3;var a=v;if(j&&m&&h>0&&h<=r.mb){j=T(j);m=T(m);if(j[y]+m[y]<=64){c.p[h]=
[j,m,q];c.Y();a=s}}return a};c.dc=function(h){if(h=c.p[h])return{value:h[1],scope:h[2]}};c.Ub=function(h){var j=c.p;if(j[h]){delete j[h];c.Y()}};c.Qb=function(){e._clearKey(8);e._clearKey(9);e._clearKey(11);var h=c.p,j,m;for(m in h)if(j=h[m]){e._setKey(8,m,j[0]);e._setKey(9,m,j[1]);j=j[2];3!=j&&e._setKey(11,m,j.toString())}};function f(h,j,m){var q;if(!N(m)){m=m.split(",");for(var a=0;a<m[y];a++){q=m[a];if(!N(q)){q=q.split(n);if(q[y]==4)j[q[0]]=[q[1],q[2],h]}}}}};$.N=function(){var g=this,i={},b="k",k="v",c=[b,k],p="(",n=")",r="*",e="!",f="'",h={};h[f]="'0";h[n]="'1";h[r]="'2";h[e]="'3";var j=1;function m(o,u,x,B){if(w==i[o])i[o]={};if(w==i[o][u])i[o][u]=[];i[o][u][x]=B}function q(o,u,x){return w!=i[o]&&w!=i[o][u]?i[o][u][x]:w}function a(o,u){if(w!=i[o]&&w!=i[o][u]){i[o][u]=w;u=s;var x;for(x=0;x<c[y];x++)if(w!=i[o][c[x]]){u=v;break}if(u)i[o]=w}}function d(o){var u="",x=v,B,O;for(B=0;B<c[y];B++){O=o[c[B]];if(w!=O){if(x)u+=c[B];u+=l(O);x=v}else x=s}return u}
function l(o){var u=[],x,B;for(B=0;B<o[y];B++)if(w!=o[B]){x="";if(B!=j&&w==o[B-1])x+=B.toString()+e;x+=t(o[B]);W(u,x)}return p+u.join(r)+n}function t(o){var u="",x,B,O;for(x=0;x<o[y];x++){B=o.charAt(x);O=h[B];u+=w!=O?O:B}return u}g.qc=function(o){return w!=i[o]};g.G=function(){var o="",u;for(u in i)if(w!=i[u])o+=u.toString()+d(i[u]);return o};g.Ac=function(o){if(o==w)return g.G();var u=o.G(),x;for(x in i)if(w!=i[x]&&!o.qc(x))u+=x.toString()+d(i[x]);return u};g._setKey=function(o,u,x){if(typeof x!=
"string")return v;m(o,b,u,x);return s};g._setValue=function(o,u,x){if(typeof x!="number"&&(w==Number||!(x instanceof Number))||Math.round(x)!=x||x==NaN||x==Infinity)return v;m(o,k,u,x.toString());return s};g._getKey=function(o,u){return q(o,b,u)};g._getValue=function(o,u){return q(o,k,u)};g._clearKey=function(o){a(o,b)};g._clearValue=function(o){a(o,k)}};$.Ib=function(g,i){var b=this;b.Pc=i;b.xc=g;b._trackEvent=function(k,c,p){return i._trackEvent(b.xc,k,c,p)}};$.Kb=function(g,i){var b=this,k=w,c=new $.Fb,p=v,n=w;b.b=window;b.r=Math.round((new Date).getTime()/1000);b.s=g||"UA-XXXXX-X";b.Za=c.a.referrer;b.fa=w;b.f=w;b.B=w;b.F=v;b.A=w;b.Ra="";b.g=w;b.ab=w;b.d=w;b.i=w;c.o=i?T(i):w;function r(){if("auto"==c.c){var a=c.a.domain;if("www."==P(a,0,4))a=P(a,4);c.c=a}c.c=X(c.c)}function e(){var a=c.c,d=a.indexOf("www.google.")*a.indexOf(".google.")*a.indexOf("google.");return d||"/"!=c.h||a.indexOf("google.org")>-1}function f(a,d,l){if(N(a)||N(d)||N(l))return"-";
a=Q(a,E+b.d+".",d);if(!N(a)){a=a.split(".");a[5]=a[5]?a[5]*1+1:1;a[3]=a[4];a[4]=l;a=a.join(".")}return a}function h(){return"file:"!=c.a[A].protocol&&e()}function j(a){if(!a||""==a)return"";for(;ea(a.charAt(0));)a=P(a,1);for(;ea(a.charAt(a[y]-1));)a=P(a,0,a[y]-1);return a}function m(a,d,l,t){if(!N(a())){d(t?U(a()):a());V(a(),";")||l()}}function q(a){var d,l=""!=a&&c.a[A].host!=a;if(l)for(d=0;d<c.u[y];d++)l=l&&ga(X(a),X(c.u[d]))==-1;return l}b.wc=function(){var a=v;if(b.B)a=b.B.match(/^[0-9a-z-_.]{10,1200}$/i);
return a};b.kc=function(){return Z()^b.A.$b()&2147483647};b.fc=function(){if(!c.c||""==c.c||"none"==c.c){c.c="";return 1}r();return c.Pa?ia(c.c):1};b.Yb=function(a,d){if(N(a))a="-";else{d+=c.h&&"/"!=c.h?c.h:"";d=a.indexOf(d);a=d>=0&&d<=8?"0":"["==a.charAt(0)&&"]"==a.charAt(a[y]-1)?"-":a}return a};b.ua=function(a){var d="",l=c.a;d+=c.ca?b.A.Hc():"";d+=c.aa?b.Ra:"";d+=c.da&&!N(l.title)?"&utmdt="+T(l.title):"";d+="&utmhid="+ja()+"&utmr="+T(b.fa)+"&utmp="+T(b.Bc(a));return d};b.Bc=function(a){var d=c.a[A];
return a=w!=a&&""!=a?T(a,s):T(d.pathname+d.search,s)};b.Kc=function(a){if(b.J()){var d="";if(b.g!=w&&b.g.G()[y]>0)d+="&utme="+T(b.g.G());d+=b.ua(a);k.H(d,b.s,b.d)}};b.Tb=function(){var a=new $.Z(c);return a.sa(b.d)?a.Gc():w};b._getLinkerUrl=function(a,d){var l=a.split("#"),t=a,o=b.Tb();if(o)if(d&&1>=l[y])t+="#"+o;else if(!d||1>=l[y])if(1>=l[y])t+=(V(a,"?")?C:"?")+o;else t=l[0]+(V(a,"?")?C:"?")+o+"#"+l[1];return t};b.wb=function(){var a;if(b.wc()){b.i.Dc(b.B);b.i.Nc();$._gasoDomain=c.c;$._gasoCPath=
c.h;a=c.a.createElement("script");a.type="text/javascript";a.id="_gasojs";a.src="https://www.google.com/analytics/reporting/overlay_js?gaso="+b.B+C+Z();c.a.getElementsByTagName("head")[0].appendChild(a)}};b.pc=function(){var a=b.r,d=b.i,l=d.k(),t=b.d+"",o=c.b,u=o?o.gaGlobal:w,x,B=V(l,E+t+"."),O=V(l,F+t),la=V(l,H+t),G,J=[],R="",fa=v;l=N(l)?"":l;if(c.z){x=c.a[A]&&c.a[A].hash?c.a[A].href.substring(c.a[A].href.indexOf("#")):"";if(c.$&&!N(x))R=x+C;R+=c.a[A].search;if(!N(R)&&V(R,E)){d.zc(R);d.ib()||d.Sb();
G=d.ga()}m(d.ja,d.tb,d.Db,true);m(d.ia,d.ya,d.Da)}if(N(G))if(B)if(!O||!la){G=f(l,";",a);b.F=s}else{G=Q(l,E+t+".",";");J=Y(Q(l,F+t,";"),".")}else{G=ha([t,b.kc(),a,a,a,1],".");fa=b.F=s}else if(N(d.C())||N(d.ha())){G=f(R,C,a);b.F=s}else{J=Y(d.C(),".");t=J[0]}G=G.split(".");if(o&&u&&u.dh==t&&!c.o){G[4]=u.sid?u.sid:G[4];if(fa){G[3]=u.sid?u.sid:G[4];if(u.vid){a=u.vid.split(".");G[1]=a[0];G[2]=a[1]}}}d.rb(G.join("."));J[0]=t;J[1]=J[1]?J[1]:0;J[2]=w!=J[2]?J[2]:c.Ic;J[3]=J[3]?J[3]:G[4];d.wa(J.join("."));d.sb(t);
N(d.mc())||d.xa(d.P());d.Bb();d.Ca();d.Cb()};b.rc=function(){k=new $.Jb(c)};b._initData=function(){var a;if(!p){if(!b.A){b.A=new $.Eb(c);b.A.bc()}b.d=b.fc();b.i=new $.Z(c);b.g=new $.N;n=new $.Hb(c,b.d,b.i,b.g);b.rc()}if(h()){b.pc();n.tc()}if(!p){if(h()){b.fa=b.Yb(b.Za,c.a.domain);if(c.aa){a=new $.m(b.d,b.fa,b.r,c);b.Ra=a.cc(b.i,b.F)}}b.ab=new $.N;p=s}$.gb||b.sc()};b._visitCode=function(){b._initData();var a=Q(b.i.k(),E+b.d+".",";");a=a.split(".");return a[y]<4?"":a[1]};b._cookiePathCopy=function(a){b._initData();
b.i&&b.i.Mc(b.d,a)};b.sc=function(){var a=c.a[A].hash;if(a&&1==a.indexOf("gaso="))a=Q(a,"gaso=",C);else a=(a=c.b.name)&&0<=a.indexOf("gaso=")?Q(a,"gaso=",C):Q(b.i.k(),M,";");if(a[y]>=10){b.B=a;c.b.addEventListener?c.b.addEventListener("load",b.wb,v):c.b.attachEvent("onload",b.wb)}$.gb=s};b.J=function(){return b._visitCode()%10000<c.T*100};b.Fc=function(){var a,d,l=c.a.links;if(!c.jb){a=c.a.domain;if("www."==P(a,0,4))a=P(a,4);c.u.push("."+a)}for(a=0;a<l[y]&&(c.oa==-1||a<c.oa);a++){d=l[a];if(q(d.host))if(!d.gatcOnclick){d.gatcOnclick=
d.onclick?d.onclick:b.yc;d.onclick=function(t){var o=!this.target||this.target=="_self"||this.target=="_top"||this.target=="_parent";o=o&&!b.Rb(t);b.Lc(t,this,o);return o?v:this.gatcOnclick?this.gatcOnclick(t):s}}}};b.yc=function(){};b._trackPageview=function(a){if(h()){b._initData();c.u&&b.Fc();b.Kc(a);b.F=v}};b._trackTrans=function(){var a=b.d,d=[],l,t,o;b._initData();if(b.f&&b.J()){for(l=0;l<b.f.X[y];l++){t=b.f.X[l];W(d,t.Aa());for(o=0;o<t.R[y];o++)W(d,t.R[o].Aa())}for(l=0;l<d[y];l++)k.H(d[l],
b.s,a,s)}};b._setTrans=function(){var a=c.a,d,l,t;a=a.getElementById?a.getElementById("utmtrans"):a.utmform&&a.utmform.utmtrans?a.utmform.utmtrans:w;b._initData();if(a&&a.value){b.f=new $.n;t=a.value.split("UTM:");c.v=!c.v||""==c.v?"|":c.v;for(a=0;a<t[y];a++){t[a]=j(t[a]);d=t[a].split(c.v);for(l=0;l<d[y];l++)d[l]=j(d[l]);if("T"==d[0])b._addTrans(d[1],d[2],d[3],d[4],d[5],d[6],d[7],d[8]);else"I"==d[0]&&b._addItem(d[1],d[2],d[3],d[4],d[5],d[6])}}};b._addTrans=function(a,d,l,t,o,u,x,B){b.f=b.f?b.f:new $.n;
return b.f.Ob(a,d,l,t,o,u,x,B)};b._addItem=function(a,d,l,t,o,u){var x;b.f=b.f?b.f:new $.n;(x=b.f.fb(a))||(x=b._addTrans(a,"","","","","","",""));x.Nb(d,l,t,o,u)};b._setVar=function(a){if(a&&""!=a&&e()){b._initData();n.Ec(T(a));b.J()&&k.H("&utmt=var",b.s,b.d)}};b._setCustomVar=function(a,d,l,t){b._initData();return n.Cc(a,d,l,t)};b._deleteCustomVar=function(a){b._initData();n.Ub(a)};b._getCustomVar=function(a){b.initData();n.dc(a)};b._setMaxCustomVariables=function(a){c.mb=a};b._link=function(a,d){if(c.z&&
a){b._initData();c.a[A].href=b._getLinkerUrl(a,d)}};b._linkByPost=function(a,d){if(c.z&&a&&a.action){b._initData();a.action=b._getLinkerUrl(a.action,d)}};b._setXKey=function(a,d,l){b.g._setKey(a,d,l)};b._setXValue=function(a,d,l){b.g._setValue(a,d,l)};b._getXKey=function(a,d){return b.g._getKey(a,d)};b._getXValue=function(a,d){return b.g.getValue(a,d)};b._clearXKey=function(a){b.g._clearKey(a)};b._clearXValue=function(a){b.g._clearValue(a)};b._createXObj=function(){b._initData();return new $.N};b._sendXEvent=
function(a){var d="";b._initData();if(b.J()){d+="&utmt=event&utme="+T(b.g.Ac(a))+b.ua();k.H(d,b.s,b.d,v,s)}};b._createEventTracker=function(a){b._initData();return new $.Ib(a,b)};b._trackEvent=function(a,d,l,t){var o=b.ab;if(w!=a&&w!=d&&""!=a&&""!=d){o._clearKey(5);o._clearValue(5);(a=o._setKey(5,1,a)&&o._setKey(5,2,d)&&(w==l||o._setKey(5,3,l))&&(w==t||o._setValue(5,1,t)))&&b._sendXEvent(o)}else a=v;return a};b.Lc=function(a,d,l){b._initData();if(b.J()){var t=new $.N;t._setKey(6,1,d.href);var o=l?
function(){b.bb(a,d)}:w;k.H("&utmt=event&utme="+T(t.G())+b.ua(),b.s,b.d,v,s,o);if(l){var u=this;c.b.setTimeout(function(){u.bb(a,d)},500)}}};b.bb=function(a,d){if(!a)a=c.b.event;var l=s;if(d.gatcOnclick)l=d.gatcOnclick(a);if(l||typeof l=="undefined")if(!d.target||d.target=="_self")c.b[A]=d.href;else if(d.target=="_top")c.b.top.document[A]=d.href;else if(d.target=="_parent")c.b.parent.document[A]=d.href};b.Rb=function(a){if(!a)a=c.b.event;var d=a.shiftKey||a.ctrlKey||a.altKey;if(!d)if(a.modifiers&&
c.b.Event)d=a.modifiers&c.b.Event.CONTROL_MASK||a.modifiers&c.b.Event.SHIFT_MASK||a.modifiers&c.b.Event.ALT_MASK;return d};b.Oc=function(){return c};b._setDomainName=function(a){c.c=a};b._addOrganic=function(a,d){c.ra.splice(0,0,new $.Fa(a,d))};b._clearOrganic=function(){c.ra=[]};b._addIgnoredOrganic=function(a){W(c.qa,a)};b._clearIgnoredOrganic=function(){c.qa=[]};b._addIgnoredRef=function(a){W(c.ta,a)};b._clearIgnoredRef=function(){c.ta=[]};b._setAllowHash=function(a){c.Pa=a?1:0};b._setCampaignTrack=
function(a){c.aa=a?1:0};b._setClientInfo=function(a){c.ca=a?1:0};b._getClientInfo=function(){return c.ca};b._setCookiePath=function(a){c.h=a};b._setTransactionDelim=function(a){c.v=a};b._setCookieTimeout=function(a){c.Wa=a};b._setDetectFlash=function(a){c.ea=a?1:0};b._getDetectFlash=function(){return c.ea};b._setDetectTitle=function(a){c.da=a?1:0};b._getDetectTitle=function(){return c.da};b._setLocalGifPath=function(a){c.la=a};b._getLocalGifPath=function(){return c.la};b._setLocalServerMode=function(){c.I=
0};b._setRemoteServerMode=function(){c.I=1};b._setLocalRemoteServerMode=function(){c.I=2};b._getServiceMode=function(){return c.I};b._setSampleRate=function(a){c.T=a};b._setSessionTimeout=function(a){c.qb=a};b._setAllowLinker=function(a){c.z=a?1:0};b._setAllowAnchor=function(a){c.$=a?1:0};b._setCampNameKey=function(a){c.Ga=a};b._setCampContentKey=function(a){c.Ha=a};b._setCampIdKey=function(a){c.Ia=a};b._setCampMediumKey=function(a){c.Ja=a};b._setCampNOKey=function(a){c.Ka=a};b._setCampSourceKey=
function(a){c.La=a};b._setCampTermKey=function(a){c.Ma=a};b._setCampCIdKey=function(a){c.Na=a};b._getAccount=function(){return b.s};b._setAccount=function(a){b.s=a};b._setNamespace=function(a){c.o=a?T(a):w};b._getVersion=function(){return ca};b._setAutoTrackOutbound=function(a){c.u=[];if(a)c.u=a};b._setTrackOutboundSubdomains=function(a){c.jb=a};b._setHrefExamineLimit=function(a){c.oa=a};b._setReferrerOverride=function(a){b.Za=a};b._setCookiePersistence=function(a){$.t=a}};
$._getTracker=function(g,i){return new $.Kb(g,i)};window[aa]=$;var ka=window[ba];})()

//window.dhtmlHistory={isIE:false,isOpera:false,isSafari:false,isKonquerer:false,isGecko:false,isSupported:false,create:function(_1){var _2=this;var UA=navigator.userAgent.toLowerCase();var _4=navigator.platform.toLowerCase();var _5=navigator.vendor||"";if(_5==="KDE"){this.isKonqueror=true;this.isSupported=false;}else{if(typeof window.opera!=="undefined"){this.isOpera=true;this.isSupported=true;}else{if(typeof document.all!=="undefined"){this.isIE=true;this.isSupported=true;}else{if(_5.indexOf("Apple Computer, Inc.")>-1){this.isSafari=true;this.isSupported=(_4.indexOf("mac")>-1);}else{if(UA.indexOf("gecko")!=-1){this.isGecko=true;this.isSupported=true;}}}}}window.historyStorage.setup(_1);if(this.isSafari){this.createSafari();}else{if(this.isOpera){this.createOpera();}}var _6=this.getCurrentLocation();this.currentLocation=_6;if(this.isIE){this.createIE(_6);}var _7=function(){_2.firstLoad=null;};this.addEventListener(window,"unload",_7);if(this.isIE){this.ignoreLocationChange=true;}else{if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.ignoreLocationChange=true;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true);}else{this.ignoreLocationChange=false;this.fireOnNewListener=true;}}var _8=function(){_2.checkLocation();};setInterval(_8,100);},initialize:function(){if(this.isIE){if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.fireOnNewListener=false;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true);}else{this.fireOnNewListener=true;this.firstLoad=false;}}},addListener:function(_9){this.listener=_9;if(this.fireOnNewListener){this.fireHistoryEvent(this.currentLocation);this.fireOnNewListener=false;}},addEventListener:function(o,e,l){if(o.addEventListener){o.addEventListener(e,l,false);}else{if(o.attachEvent){o.attachEvent("on"+e,function(){l(window.event);});}}},add:function(_d,_e){if(this.isSafari){_d=this.removeHash(_d);historyStorage.put(_d,_e);this.currentLocation=_d;window.location.hash=_d;this.putSafariState(_d);}else{var _f=this;var _10=function(){if(_f.currentWaitTime>0){_f.currentWaitTime=_f.currentWaitTime-_f.waitTime;}_d=_f.removeHash(_d);if(document.getElementById(_d)&&_f.debugMode){var e="Exception: History locations can not have the same value as _any_ IDs that might be in the document,"+" due to a bug in IE; please ask the developer to choose a history location that does not match any HTML"+" IDs in this document. The following ID is already taken and cannot be a location: "+_d;throw new Error(e);}historyStorage.put(_d,_e);_f.ignoreLocationChange=true;_f.ieAtomicLocationChange=true;_f.currentLocation=_d;window.location.hash=_d;if(_f.isIE){_f.iframe.src="blank.html?"+_d;}_f.ieAtomicLocationChange=false;};window.setTimeout(_10,this.currentWaitTime);this.currentWaitTime=this.currentWaitTime+this.waitTime;}},isFirstLoad:function(){return this.firstLoad;},getVersion:function(){return "0.6";},getCurrentLocation:function(){var r=(this.isSafari?this.getSafariState():this.getCurrentHash());return r;},getCurrentHash:function(){var r=window.location.href;var i=r.indexOf("#");return (i>=0?r.substr(i+1):"");},PAGELOADEDSTRING:"DhtmlHistory_pageLoaded",listener:null,waitTime:200,currentWaitTime:0,currentLocation:null,iframe:null,safariHistoryStartPoint:null,safariStack:null,safariLength:null,ignoreLocationChange:null,fireOnNewListener:null,firstLoad:null,ieAtomicLocationChange:null,createIE:function(_15){this.waitTime=400;var _16=(historyStorage.debugMode?"width: 800px;height:80px;border:1px solid black;":historyStorage.hideStyles);var _17="rshHistoryFrame";var _18="<iframe frameborder=\"0\" id=\""+_17+"\" style=\""+_16+"\" src=\"blank.html?"+_15+"\"></iframe>";document.write(_18);this.iframe=document.getElementById(_17);},createOpera:function(){this.waitTime=400;var _19="<img src=\"javascript:location.href='javascript:dhtmlHistory.checkLocation();';\" style=\""+historyStorage.hideStyles+"\" />";document.write(_19);},createSafari:function(){var _1a="rshSafariForm";var _1b="rshSafariStack";var _1c="rshSafariLength";var _1d=historyStorage.debugMode?historyStorage.showStyles:historyStorage.hideStyles;var _1e=(historyStorage.debugMode?"width:800px;height:20px;border:1px solid black;margin:0;padding:0;":historyStorage.hideStyles);var _1f="<form id=\""+_1a+"\" style=\""+_1d+"\">"+"<input type=\"text\" style=\""+_1e+"\" id=\""+_1b+"\" value=\"[]\"/>"+"<input type=\"text\" style=\""+_1e+"\" id=\""+_1c+"\" value=\"\"/>"+"</form>";document.write(_1f);this.safariStack=document.getElementById(_1b);this.safariLength=document.getElementById(_1c);if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.safariHistoryStartPoint=history.length;this.safariLength.value=this.safariHistoryStartPoint;}else{this.safariHistoryStartPoint=this.safariLength.value;}},getSafariStack:function(){var r=this.safariStack.value;return historyStorage.fromJSON(r);},getSafariState:function(){var _21=this.getSafariStack();var _22=_21[history.length-this.safariHistoryStartPoint-1];return _22;},putSafariState:function(_23){var _24=this.getSafariStack();_24[history.length-this.safariHistoryStartPoint]=_23;this.safariStack.value=historyStorage.toJSON(_24);},fireHistoryEvent:function(_25){var _26=historyStorage.get(_25);this.listener.call(null,_25,_26);},checkLocation:function(){if(!this.isIE&&this.ignoreLocationChange){this.ignoreLocationChange=false;return;}if(!this.isIE&&this.ieAtomicLocationChange){return;}var _27=this.getCurrentLocation();if(_27==this.currentLocation){return;}this.ieAtomicLocationChange=true;if(this.isIE&&this.getIframeHash()!=_27){this.iframe.src="blank.html?"+_27;}else{if(this.isIE){return;}}this.currentLocation=_27;this.ieAtomicLocationChange=false;this.fireHistoryEvent(_27);},getIframeHash:function(){var doc=this.iframe.contentWindow.document;var _29=String(doc.location.search);if(_29.length==1&&_29.charAt(0)=="?"){_29="";}else{if(_29.length>=2&&_29.charAt(0)=="?"){_29=_29.substring(1);}}return _29;},removeHash:function(_2a){var r;if(_2a===null||_2a===undefined){r=null;}else{if(_2a===""){r="";}else{if(_2a.length==1&&_2a.charAt(0)=="#"){r="";}else{if(_2a.length>1&&_2a.charAt(0)=="#"){r=_2a.substring(1);}else{r=_2a;}}}}return r;},iframeLoaded:function(_2c){if(this.ignoreLocationChange){this.ignoreLocationChange=false;return;}var _2d=String(_2c.search);if(_2d.length==1&&_2d.charAt(0)=="?"){_2d="";}else{if(_2d.length>=2&&_2d.charAt(0)=="?"){_2d=_2d.substring(1);}}window.location.hash=_2d;this.fireHistoryEvent(_2d);}};window.historyStorage={setup:function(_2e){if(typeof _2e!=="undefined"){if(_2e.debugMode){this.debugMode=_2e.debugMode;}if(_2e.toJSON){this.toJSON=_2e.toJSON;}if(_2e.fromJSON){this.fromJSON=_2e.fromJSON;}}var _2f="rshStorageForm";var _30="rshStorageField";var _31=this.debugMode?historyStorage.showStyles:historyStorage.hideStyles;var _32=(historyStorage.debugMode?"width: 800px;height:80px;border:1px solid black;":historyStorage.hideStyles);var _33="<form id=\""+_2f+"\" style=\""+_31+"\">"+"<textarea id=\""+_30+"\" style=\""+_32+"\"></textarea>"+"</form>";document.write(_33);this.storageField=document.getElementById(_30);if(typeof window.opera!=="undefined"){this.storageField.focus();}},put:function(key,_35){this.assertValidKey(key);if(this.hasKey(key)){this.remove(key);}this.storageHash[key]=_35;this.saveHashTable();},get:function(key){this.assertValidKey(key);this.loadHashTable();var _37=this.storageHash[key];if(_37===undefined){_37=null;}return _37;},remove:function(key){this.assertValidKey(key);this.loadHashTable();delete this.storageHash[key];this.saveHashTable();},reset:function(){this.storageField.value="";this.storageHash={};},hasKey:function(key){this.assertValidKey(key);this.loadHashTable();return (typeof this.storageHash[key]!=="undefined");},isValidKey:function(key){return (typeof key==="string");},showStyles:"border:0;margin:0;padding:0;",hideStyles:"left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;",debugMode:false,storageHash:{},hashLoaded:false,storageField:null,assertValidKey:function(key){var _3c=this.isValidKey(key);if(!_3c&&this.debugMode){throw new Error("Please provide a valid key for window.historyStorage. Invalid key = "+key+".");}},loadHashTable:function(){if(!this.hashLoaded){var _3d=this.storageField.value;if(_3d!==""&&_3d!==null){this.storageHash=this.fromJSON(_3d);this.hashLoaded=true;}}},saveHashTable:function(){this.loadHashTable();var _3e=this.toJSON(this.storageHash);this.storageField.value=_3e;},toJSON:function(o){return o.toJSONString();},fromJSON:function(s){return s.parseJSON();}};
window.dhtmlHistory={isIE:false,isOpera:false,isSafari:false,isKonquerer:false,isGecko:false,isSupported:false,create:function(i){var c=this;window.historyStorage.setup(i);if(i&&i.baseTitle){if(i.baseTitle.indexOf("@@@")<0&&historyStorage.debugMode){throw new Error("Programmer error: options.baseTitle must contain the replacement parameter '@@@' to be useful.")}this.baseTitle=i.baseTitle}var d=navigator.userAgent.toLowerCase();var a=navigator.platform.toLowerCase();var e=navigator.vendor||"";if(e==="KDE"){this.isKonqueror=true;this.isSupported=false}else{if(typeof window.opera!=="undefined"){this.isOpera=true;this.isSupported=true}else{if(typeof document.all!=="undefined"){this.isIE=true;this.isSupported=true}else{if(e.indexOf("Apple Computer, Inc.")>-1){this.isSafari=true;this.isSupported=(a.indexOf("mac")>-1)}else{if(d.indexOf("gecko")!=-1){this.isGecko=true;this.isSupported=true}}}}}if(this.isSafari){this.createSafari()}else{if(this.isOpera){this.createOpera()}}var b=this.getCurrentLocation();this.currentLocation=b;if(this.isIE){if(i&&i.blankURL){var f=i.blankURL;this.blankURL=(f.indexOf("?")!=f.length-1?f+"?":f)}this.createIE(b)}var h=function(){c.firstLoad=null};this.addEventListener(window,"unload",h);if(this.isIE){this.ignoreLocationChange=true}else{if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.ignoreLocationChange=true;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true)}else{this.ignoreLocationChange=false;this.firstLoad=false;this.fireOnNewListener=true}}var g=function(){c.checkLocation()};setInterval(g,100)},initialize:function(a){this.originalTitle=document.title;if(this.isIE){if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.fireOnNewListener=false;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true)}else{this.fireOnNewListener=true;this.firstLoad=false}}if(a){this.addListener(a)}},addListener:function(a){this.listener=a;if(this.fireOnNewListener){this.fireHistoryEvent(this.currentLocation);this.fireOnNewListener=false}},changeTitle:function(d){var b=(d&&d.newTitle?this.baseTitle.replace("@@@",d.newTitle):this.originalTitle);if(document.title==b){return}document.title=b;if(this.isIE){this.iframe.contentWindow.document.title=b}if(!this.isIE&&!this.isOpera){var c=decodeURIComponent(document.location.hash);if(c!=""){var a=encodeURIComponent(this.removeHash(c));document.location.hash=a}else{}}},add:function(d,e){var c=this;var a=encodeURIComponent(this.removeHash(d));if(this.isSafari){historyStorage.put(d,e);this.currentLocation=a;window.location.hash=a;this.putSafariState(a);this.changeTitle(e)}else{var b=function(){if(c.currentWaitTime>0){c.currentWaitTime=c.currentWaitTime-c.waitTime}if(document.getElementById(a)&&c.debugMode){var f="Exception: History locations can not have the same value as _any_ IDs that might be in the document, due to a bug in IE; please ask the developer to choose a history location that does not match any HTML IDs in this document. The following ID is already taken and cannot be a location: "+d;throw new Error(f)}historyStorage.put(d,e);c.ignoreLocationChange=true;c.ieAtomicLocationChange=true;c.currentLocation=a;window.location.hash=a;if(c.isIE){c.iframe.src=c.blankURL+a}c.ieAtomicLocationChange=false;c.changeTitle(e)};window.setTimeout(b,this.currentWaitTime);this.currentWaitTime=this.currentWaitTime+this.waitTime}},isFirstLoad:function(){return this.firstLoad},getVersion:function(){return this.VERSIONNUMBER},PAGELOADEDSTRING:"DhtmlHistory_pageLoaded",VERSIONNUMBER:"0.8",baseTitle:"@@@",originalTitle:null,blankURL:"blank.html?",listener:null,waitTime:200,currentWaitTime:0,currentLocation:null,iframe:null,safariHistoryStartPoint:null,safariStack:null,safariLength:null,ignoreLocationChange:null,fireOnNewListener:null,firstLoad:null,ieAtomicLocationChange:null,addEventListener:function(c,b,a){if(c.addEventListener){c.addEventListener(b,a,false)}else{if(c.attachEvent){c.attachEvent("on"+b,function(){a(window.event)})}}},createIE:function(a){this.waitTime=400;var b=(historyStorage.debugMode?"width: 800px;height:80px;border:1px solid black;":historyStorage.hideStyles);var d="rshHistoryFrame";var c='<iframe frameborder="0" id="'+d+'" style="'+b+'" src="'+this.blankURL+a+'"></iframe>';document.write(c);this.iframe=document.getElementById(d)},createOpera:function(){this.waitTime=400;var a='<img src="javascript:location.href=\'javascript:dhtmlHistory.checkLocation();\';" style="'+historyStorage.hideStyles+'" />';document.write(a)},createSafari:function(){var d="rshSafariForm";var c="rshSafariStack";var b="rshSafariLength";var a=historyStorage.debugMode?historyStorage.showStyles:historyStorage.hideStyles;var g=(historyStorage.debugMode?"width: 800px;height:80px;border:1px solid black;":historyStorage.hideStyles);var f=(historyStorage.debugMode?"width:800px;height:20px;border:1px solid black;margin:0;padding:0;":historyStorage.hideStyles);var e='<form id="'+d+'" style="'+a+'"><textarea style="'+g+'" id="'+c+'">[]</textarea><input type="text" style="'+f+'" id="'+b+'" value=""/></form>';document.write(e);this.safariStack=document.getElementById(c);this.safariLength=document.getElementById(b);if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.safariHistoryStartPoint=history.length;this.safariLength.value=this.safariHistoryStartPoint}else{this.safariHistoryStartPoint=this.safariLength.value}},getCurrentLocation:function(){var a=(this.isSafari?this.getSafariState():this.getCurrentHash());return a},getCurrentHash:function(){var b=window.location.href;var a=b.indexOf("#");return(a>=0?b.substr(a+1):"")},getSafariStack:function(){var a=this.safariStack.value;return historyStorage.fromJSON(a)},getSafariState:function(){var a=this.getSafariStack();var b=a[history.length-this.safariHistoryStartPoint-1];return b},putSafariState:function(b){var a=this.getSafariStack();a[history.length-this.safariHistoryStartPoint]=b;this.safariStack.value=historyStorage.toJSON(a)},fireHistoryEvent:function(b){var a=decodeURIComponent(b);var c=historyStorage.get(a);this.changeTitle(c);this.listener.call(null,a,c)},checkLocation:function(){if(!this.isIE&&this.ignoreLocationChange){this.ignoreLocationChange=false;return}if(!this.isIE&&this.ieAtomicLocationChange){return}var a=this.getCurrentLocation();if(a==this.currentLocation){return}this.ieAtomicLocationChange=true;if(this.isIE&&this.getIframeHash()!=a){this.iframe.src=this.blankURL+a}else{if(this.isIE){return}}this.currentLocation=a;this.ieAtomicLocationChange=false;this.fireHistoryEvent(a)},getIframeHash:function(){var b=this.iframe.contentWindow.document;var a=String(b.location.search);if(a.length==1&&a.charAt(0)=="?"){a=""}else{if(a.length>=2&&a.charAt(0)=="?"){a=a.substring(1)}}return a},removeHash:function(b){var a;if(b===null||b===undefined){a=null}else{if(b===""){a=""}else{if(b.length==1&&b.charAt(0)=="#"){a=""}else{if(b.length>1&&b.charAt(0)=="#"){a=b.substring(1)}else{a=b}}}}return a},iframeLoaded:function(a){if(this.ignoreLocationChange){this.ignoreLocationChange=false;return}var b=String(a.search);if(b.length==1&&b.charAt(0)=="?"){b=""}else{if(b.length>=2&&b.charAt(0)=="?"){b=b.substring(1)}}window.location.hash=b;this.fireHistoryEvent(b)}};window.historyStorage={setup:function(b){if(typeof b!=="undefined"){if(b.debugMode){this.debugMode=b.debugMode}if(b.toJSON){this.toJSON=b.toJSON}if(b.fromJSON){this.fromJSON=b.fromJSON}}var d="rshStorageForm";var f="rshStorageField";var a=this.debugMode?historyStorage.showStyles:historyStorage.hideStyles;var e=(historyStorage.debugMode?"width: 800px;height:80px;border:1px solid black;":historyStorage.hideStyles);var c='<form id="'+d+'" style="'+a+'"><textarea id="'+f+'" style="'+e+'"></textarea></form>';document.write(c);this.storageField=document.getElementById(f);if(typeof window.opera!=="undefined"){this.storageField.focus()}},put:function(a,c){var b=encodeURIComponent(a);this.assertValidKey(b);if(this.hasKey(a)){this.remove(a)}this.storageHash[b]=c;this.saveHashTable()},get:function(a){var c=encodeURIComponent(a);this.assertValidKey(c);this.loadHashTable();var b=this.storageHash[c];if(b===undefined){b=null}return b},remove:function(a){var b=encodeURIComponent(a);this.assertValidKey(b);this.loadHashTable();delete this.storageHash[b];this.saveHashTable()},reset:function(){this.storageField.value="";this.storageHash={}},hasKey:function(a){var b=encodeURIComponent(a);this.assertValidKey(b);this.loadHashTable();return(typeof this.storageHash[b]!=="undefined")},isValidKey:function(a){return(typeof a==="string")},showStyles:"border:0;margin:0;padding:0;",hideStyles:"left:-1000px;top:-1000px;width:1px;height:1px;border:0;position:absolute;",debugMode:false,storageHash:{},hashLoaded:false,storageField:null,assertValidKey:function(a){var b=this.isValidKey(a);if(!b&&this.debugMode){throw new Error("Please provide a valid key for window.historyStorage. Invalid key = "+a+".")}},loadHashTable:function(){if(!this.hashLoaded){var a=this.storageField.value;if(a!==""&&a!==null){this.storageHash=this.fromJSON(a);this.hashLoaded=true}}},saveHashTable:function(){this.loadHashTable();var a=this.toJSON(this.storageHash);this.storageField.value=a},toJSON:function(a){return a.toJSONString()},fromJSON:function(a){return a.parseJSON()}};

// styled checkbox/radio/select
var checkboxHeight = "25";
var radioHeight = "25";
var selectWidth = "190";
var Custom = {
    init: function() {
      var inputs = document.getElementsByTagName("input"), span = Array(), textnode, option, active;
      for(a = 0; a < inputs.length; a++) {
        if((inputs[a].type == "checkbox" || inputs[a].type == "radio") && inputs[a].className == "styled") {
          span[a] = document.createElement("span");
          span[a].className = inputs[a].type;

          if(inputs[a].checked == true) {
            if(inputs[a].type == "checkbox") {
              position = "0 -" + (checkboxHeight*2) + "px";
              span[a].style.backgroundPosition = position;
            } else {
              position = "0 -" + (radioHeight*2) + "px";
              span[a].style.backgroundPosition = position;
            }
          }
          inputs[a].parentNode.insertBefore(span[a], inputs[a]);
          inputs[a].onchange = Custom.clear;
          span[a].onmousedown = Custom.pushed;
          span[a].onmouseup = Custom.check;
          document.onmouseup = Custom.clear;
        }
      }
      inputs = document.getElementsByTagName("select");
      for(a = 0; a < inputs.length; a++) {
        if(inputs[a].className == "styled") {
          option = inputs[a].getElementsByTagName("option");
          active = option[0].childNodes[0].nodeValue;
          textnode = document.createTextNode(active);
          for(b = 0; b < option.length; b++) {
            if(option[b].selected == true) {
              textnode = document.createTextNode(option[b].childNodes[0].nodeValue);
            }
          }
          span[a] = document.createElement("span");
          span[a].className = "select";
          span[a].id = "select" + inputs[a].name;
          span[a].appendChild(textnode);
          inputs[a].parentNode.insertBefore(span[a], inputs[a]);
          inputs[a].onchange = Custom.choose;
        }
      }
    },
    pushed: function() {
      element = this.nextSibling;
      if(element.checked == true && element.type == "checkbox") {
        this.style.backgroundPosition = "0 -" + checkboxHeight*3 + "px";
      } else if(element.checked == true && element.type == "radio") {
        this.style.backgroundPosition = "0 -" + radioHeight*3 + "px";
      } else if(element.checked != true && element.type == "checkbox") {
        this.style.backgroundPosition = "0 -" + checkboxHeight + "px";
      } else {
        this.style.backgroundPosition = "0 -" + radioHeight + "px";
      }
    },
    check: function() {
      element = this.nextSibling;
      if(element.checked == true && element.type == "checkbox") {
        this.style.backgroundPosition = "0 0";
        element.checked = false;
      } else {
        if(element.type == "checkbox") {
          this.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
        } else {
          this.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
          group = this.nextSibling.name;
          inputs = document.getElementsByTagName("input");
          for(a = 0; a < inputs.length; a++) {
            if(inputs[a].name == group && inputs[a] != this.nextSibling) {
              inputs[a].previousSibling.style.backgroundPosition = "0 0";
            }
          }
        }
        element.checked = true;
      }
    },
    clear: function() {
      inputs = document.getElementsByTagName("input");
      for(var b = 0; b < inputs.length; b++) {
        if(inputs[b].type == "checkbox" && inputs[b].checked == true && inputs[b].className == "styled") {
          inputs[b].previousSibling.style.backgroundPosition = "0 -" + checkboxHeight*2 + "px";
        } else if(inputs[b].type == "checkbox" && inputs[b].className == "styled") {
          inputs[b].previousSibling.style.backgroundPosition = "0 0";
        } else if(inputs[b].type == "radio" && inputs[b].checked == true && inputs[b].className == "styled") {
          inputs[b].previousSibling.style.backgroundPosition = "0 -" + radioHeight*2 + "px";
        } else if(inputs[b].type == "radio" && inputs[b].className == "styled") {
          inputs[b].previousSibling.style.backgroundPosition = "0 0";
        }
      }
    },
    choose: function() {
      option = this.getElementsByTagName("option");
      for(d = 0; d < option.length; d++) {
        if(option[d].selected == true) {
          document.getElementById("select" + this.name).childNodes[0].nodeValue = option[d].childNodes[0].nodeValue;
        }
      }
    }
  }

searches = [];
searches[0] = 0;
searchTimeout = false;
pageMovieId = false; // <- is set in movie.php

// clear miniprofiles
document.onclick = function(e)
{
  var mpIds = [];
  for ( var i = 0; i < document.body.childNodes.length; i++)
  {
    var element = document.body.childNodes[i];
    if (element.className == 'mpdiv' || element.className == 'mp2')
    {
      mpIds.push(element.id);
    }
  }
  for ( var i = 0; i < mpIds.length; i++)
  {
    document.body.removeChild($(mpIds[i]));
  }
}




function handleThemeClick(e)
{
  return true;// alert('tmp');
  var e = e ? e : window.event;
  if (e.target)
  {
    if (e.target.className.indexOf('theme') > -1)
    {
      window.location = '/movie/2009/the_twilight_saga_new_moon_review';
      Event.stop(e);
    }
  }
}

function doLogin()
{
  var username = trim($('login_username').value);
  var password = trim($('login_password').value);
  var remember = $('login_remember').checked;
  if (username == '' || password == '')
  {
    alert('Please enter both username and password');
    if (username == '')
    {
      $('login_username').focus();
    }
    else
    {
      $('login_password').focus();
    }
    return;
  }
  var url = '/login?u=' + username;// + '&p=' + password;
  var postData = {
    p : password,
    r : (remember ? '1' : '0')
  };
  new Ajax.Request(url, {
    parameters :postData,
    onSuccess : function(t) {
      var result = eval('(' + t.responseText + ')');
      if (result.error == null)
      {
        location.reload(true);
      }
      else
      {
        alert(result.error);
      }
    }
  });
}

function fireOnKey(event, keyCode, functionName)
{
  if (event.keyCode == keyCode)
  {
    setTimeout(functionName, 0);
  }
}

function showLogin()
{
  toggle('login_div', true);
  scroll(0, 0);
}
function trim(string)
{
  return string.replace(/^\s+|\s+$/g, '');
}
function highlight(element)
{
  if (element.className == 'light')
  {
    element.className = 'dark';
    if (element.id != null && element.id.indexOf('_row') > 0)
    {
      var id = element.id;
      var movieId = id.substring(0, id.indexOf('_'));
      var img = $(movieId + '_expand');
      if (img.src.indexOf('minus') > 0)
      {
        img.src = '/pictures/minus_highlight.png';
      }
      else
      {
        img.src = '/pictures/plus_highlight.png';
      }
    }
  }
  else
  {
    element.className = 'light';
    if (element.id != null && element.id.indexOf('_row') > 0)
    {
      var id = element.id;
      var movieId = id.substring(0, id.indexOf('_'));
      var img = $(movieId + '_expand');
      if (img.src.indexOf('minus') > 0)
      {
        img.src = '/pictures/minus.png';
      }
      else
      {
        img.src = '/pictures/plus.png';
      }
    }
  }
}

function mouseoverRating(star, suffix)
{
  var s = getStarInfo(star);

  for (i = 1; i <= 10; i++)
  {
    $(s.movieId + '_' + i).src = (i <= s.starNr) ? '/black/pics/star_gold' + suffix + '_10.png'
        : '/black/pics/star_gold' + suffix + '_00.png';
  }
}

function mouseoutRating(star)
{
  /*
   * var imgId = star.id; var movieId = imgId.substring(0, imgId.indexOf('_'));
   * for (i = 1; i <= 10; i++) { document.getElementById(movieId + '_' + i).src =
   * (i <= 5) ? 'img/star.gif' : 'img/star_grey.gif'; }
   */
}

function resetRating(movieId, suffix)
{
  if (suffix == null)
    suffix = '';
  showStars(movieId, ratings[movieId], suffix);
}

function getStarInfo(star)
{
  var o = new Object();
  o.imgId = star.id;
  o.movieId = o.imgId.substring(0, o.imgId.indexOf('_'));
  o.starNr = o.imgId.substring(o.imgId.indexOf('_') + 1);
  return o;
}

function addStars(id, rating, enable, suffix)
{
  __addStars(id, rating, enable, true, suffix);
  showStars(id, rating, suffix);
}

function __addStars(id, rating, enable, realtime, suffix)
{
  if (suffix == null)
    suffix = '';
  var whole = Math.floor(rating);
  var fraction = rating * 10 - whole * 10;
  ratings['' + id] = rating;
  var totalhtml = '';
  for (i = 1; i <= 10; i++)
  {
    var html = '<img src="/black/pics/star_gold' + suffix
        + '_00.png" alt="star" id="' + id + '_' + i + '" ';
    if (enable == 1)
    {
      html += ' style="cursor: pointer;" onmouseover="mouseoverRating(this, \''
          + suffix + '\');" onmouseout="resetRating(' + id + ', \'' + suffix
          + '\');" onclick="rate(' + id + ', ' + i + ', \'' + suffix + '\');"'
    }
    html += ' />';
    if (realtime)
    {
      document.write(html);
    }
    else
    {
      totalhtml += html;
    }
  }
  return totalhtml;
}

function rate(id, rating, suffix)
{
  var url = '/ajax/rank.php?id=' + id + '&rank=' + rating + '&suffix=' + suffix;
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :rankHandlerFunc
  });
}

function resetUserRating(movieId, suffix)
{
  if (suffix == null)
    suffix = '';
  new Ajax.Request('/ajax/reset_rating.php?movie_id=' + movieId + '&suffix='
      + suffix, {
    asynchronous :true,
    onSuccess :resetUserRatingHandler
  });
}
resetUserRatingHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.ok)
  {
    var html = __addStars(result.movie_id, 0, 1, false, result.suffix);
    $('user_rating').innerHTML = html;
    toggle('reset_user_rating', false);
  }
}

function showStars(id, rating, suffix)
{
  if (suffix == null)
    suffix = '';
  var whole = Math.floor(rating);
  var fraction = Math.round((rating - whole) * 10) / 10;
  fraction = ('' + fraction).replace(/\./, '');
  if (fraction == 1)
  {
    whole++;
    fraction = 0;
  }
  for (i = 1; i <= 10; i++)
  {
    var img = $(id + '_' + i);
    var file = 'star_gold' + suffix + '_00';
    if (i <= whole)
    {
      file = 'star_gold' + suffix + '_10';
    }
    else if (i == whole + 1)
    {
      file = 'star_gold_' + fraction;
      if (fraction == 0)
      {
        // document.write('fraction=' + fraction);
        file = 'star_gold' + suffix + '_00';
      }
    }
    img.src = '/black/pics/' + file + '.png';
  }
}

function enableSpeedRating(container, id)
{
  container = $(container);
  var oldHtml = container.innerHTML;
  var starz = [];
  for (i = 1; i <= 10; i++)
  {
    var val = eval(i);
    var div = document.createElement('div');
    div.className = 'sl00 slg';
    div.style.cursor = 'pointer';

    Event.observe(div, 'mouseover', function(e) {
      this.setAttribute('class', 'sl10 slg');
      this.previousSiblings().each(function(item) {
        item.setAttribute('class', 'sl10 slg');
      });
      this.nextSiblings().each(function(item) {
        item.setAttribute('class', 'sl00 slg');
      });
    });

    Event.observe(div, 'click', function(e) {
      var rating = this.previousSiblings().length + 1;
      $(id + '_rate_it_td').update('You: ' + (rating));
      new Ajax.Request('/ajax/rank.php?id=' + id + '&rank=' + rating, { method : 'get' });
      container.update(oldHtml);
      Event.stop(e);
    });

    starz.push(div);
  }
  container.update('');
  container.onclick = function(e) {};
  starz.each(function(item) { container.appendChild(item);  });

  Event.observe(container, 'mouseout', function(e) {
    var target = (e.relatedTarget) ? e.relatedTarget : e.toElement;
    if (!target) return;
    while (target.tagName != 'BODY')
    {
      if (target.id == container.id)
      {
        return;
      }
      target = target.parentNode;
      if (!target) return;
    }
    container.onmouseover = function(e) { enableSpeedRating(container, id); };
    container.update(oldHtml);
  });

  container.onmouseover = function(e) {};
}

var emptyFunc = function()
{
};

var rankHandlerFunc = function(t)
{
  var movie = eval('(' + t.responseText + ')');
  ratings[movie.id] = movie.rating;

  if ($('user_rating') != null)
  { // rating from the movie page!
    showStars(movie.id, movie.user_rating, movie.suffix);
    $('reset_user_rating').style.display = 'inline';
    // TODO: update member rating on page
  }
  else
  {
    showStars(movie.id, (movie.votes < 5) ? 0 : movie.rating);
    $(movie.id + '_votes').innerHTML = movie.votes;
    addCheckmark(movie.id);
  }
  disableRating(movie.id);
}

function disableRating(movieId)
{
  for (i = 1; i <= 10; i++)
  {
    var img = $(movieId + '_' + i);
    img.onmouseover = emptyFunc;
    img.onmouseout = emptyFunc;
    img.onclick = emptyFunc;
    img.style.cursor = 'default';
  }
}

function addCheckmark(movieId)
{
  var votedImg = $(movieId + '_voted');
  if (votedImg.src.indexOf('empty') < 0)
  {
    return;
  }
  votedImg.src = '/pictures/star_rated.png';
}

function toggleExpanded(movieId, updateAjaxParam)
{
  if (updateAjaxParam == null)
    updateAjaxParam = true;
  var movieIds = [];
  if (typeof movieId == 'string')
  {
    movieIds = movieId.split(',');
  }
  else
  {
    movieIds.push(movieId);
  }
  for ( var i = 0; i < movieIds.length; i++)
  {
    movieId = movieIds[i];
    var tr = $(movieId + '_expanded');
    var expand = true;
    if (tr != null && tr.style.display == 'none')
    { // expand
      $(movieId + '_expand').src = '/pictures/minus_highlight.png';
      tr.style.display = '';
      new Effect.BlindDown(movieId + '_blinddown_div', {
        duration :0.20
      });
      if (expanded[movieId] == null)
      {
        var url = '/ajax/details.php?id=' + movieId;
        new Ajax.Request(url, {
          asynchronous :true,
          onSuccess :detailsHandler
        });
        expanded[movieId] = true;
      }
      else
      {
        // reload image
        // $(movieId + '_poster').src = $(movieId + '_poster').src;
      }
    }
    else if (tr != null)
    { // hide
      expand = false;
      new Effect.BlindUp(movieId + '_blinddown_div', {
        duration :0
      });
      $(movieId + '_expand').src = '/pictures/plus_highlight.png';
      tr.style.display = 'none';
    }

    if (updateAjaxParam)
    {
      updateAjaxExpandedParam(movieId, expand);
    }
  }

}

function updateAjaxExpandedParam(movieId, add)
{

  var url = window.location.toString();
  var paramName = 'e';
  var ajaxParams = getAjaxParams();
  if (ajaxParams[paramName] != null)
  {
    if (add)
    {
      url = concatAjaxParam(paramName, movieId, ',');
    }
    else
    {
      // setting the last arg to true causes browser to scroll to top when
      // the param is empty -> removed (http://www.filmgator.com/#)
      url = removeConcatedAjaxParam(paramName, movieId, ',', false);
    }
  }
  else if (add)
  {
    url = setAjaxParam(paramName, movieId);
  }
  window.location.replace(url);
}

function setAjaxParam(name, value, update)
{
  update = (update == null) ? true : update;
  var ap = getAjaxParams();
  ap[name] = value;
  return putAjaxParams(ap);
}

function setAjaxParams(params) {
    for(var field in params){
       window.location= setAjaxParam(field,params[field]);
    }

}


function concatAjaxParam(name, value, concatDelim)
{
  concatDelim = (concatDelim == null) ? '' : concatDelim;
  var ap = getAjaxParams();
  var old = ap[name];
  var tmp = old.split(concatDelim);
  var exists = false;
  for ( var i = 0; i < tmp.length; i++)
  {
    if (tmp[i] == value)
    {
      exists = true;
      break;
    }
  }
  if (!exists)
  {
    var concated = (old == null || old == '') ? value : old + concatDelim
        + value;
    ap[name] = concated;
  }
  return putAjaxParams(ap);
}

function removeConcatedAjaxParam(name, value, concatDelim, removeParamIfEmpty)
{
  if (removeParamIfEmpty == null)
    removeParamIfEmpty = false;
  var ap = getAjaxParams();
  var old = ap[name];
  if (old != null)
  {
    var removed = [];
    var tmp = old.split(concatDelim);
    for ( var i = 0; i < tmp.length; i++)
    {
      if (tmp[i] != value)
        removed.push(tmp[i]);
    }
    if (removed.length == 0 && removeParamIfEmpty)
    {
      delete ap[name];
    }
    else
    {
      ap[name] = removed.join(concatDelim);
    }
  }
  return putAjaxParams(ap);
}

function removeAjaxParam(names)
{
  var ap = getAjaxParams();
  for ( var i = 0; i < names.length; i++)
  {
    delete ap[names[i]];
  }
  return putAjaxParams(ap);
}

function getAjaxParams(url)
{
  if (url == null)
    url = window.location.toString();
  var ajaxParamStr = '';
  if (url.indexOf('#') > 0)
  {
    ajaxParamStr = url.substring(url.indexOf('#') + 1);
  }
  var ajaxParams = {};
  if (ajaxParamStr.indexOf('=') > 0)
  {
    var tmp = ajaxParamStr.split('&');
    for ( var i = 0; i < tmp.length; i = i + 1)
    {
      var tmp2 = tmp[i].split('=');
      if (tmp2 != null && tmp2.length == 2)
      {
        ajaxParams[tmp2[0]] = tmp2[1];
      }
    }
  }
  return ajaxParams;
}

function getUrl(inclAjaxParams)
{
  var url = window.location.toString();
  if (inclAjaxParams == null || url.indexOf('#') < 0)
  {
    return url;
  }
  else
  {
    return url.substr(0, url.indexOf('#'));
  }
}

function putAjaxParams(params, url)
{
  url = (url == null) ? getUrl() : url;
  if (params == null || params.lenght < 1)
    return url;
  var str = [];
  for ( var key in params)
  {
    str.push(key + '=' + params[key]);
  }
  url = (url.indexOf('#') > 0) ? url.substring(0, url.indexOf('#')) : url;
  url += '#' + str.join('&');
  return url;
}

detailsHandler = function(t)
{
  var movie = eval('(' + t.responseText + ')');
  var poster = '/pictures/movies/' + movie.imdb_title_no + '_M.jpg';
  var link = '/movie/' + movie.url_friendly_name;
  var divId = movie.id + '_poster_placeholder';
  var imgId = movie.id + '_poster';
  createPhotoWithShadow(divId, imgId, poster, link);
  var rtslnk = $(movie.id + '_rtsearchlink');
  if (rtslnk)
  {
    var tmpname = movie.name.replace(/&/g, 'and');
    tmpname = tmpname.replace(/ /g, '+');
    rtslnk.href = 'http://www.rottentomatoes.com/search/web_search.php?q=' + tmpname + '&sitesearch=www.rottentomatoes.com';
    rtslnk.target = '_new';
  }
  if (movie.country)
  {
    $(movie.id + '_country').innerHTML = movie.country;
  }
  else
  {
    // $(movie.id + '_country').innerHTML = 'unknown';
  }
  if (movie.runtime)
  {
    $(movie.id + '_runtime').innerHTML = movie.runtime;
  }
  else
  {
    // $(movie.id + '_runtime').innerHTML = 'unknown';
  }
  if (movie.genres)
  {
    $(movie.id + '_genre').innerHTML = movie.genres;
  }

  if (movie.directors)
  {
    var str = '';
    for (i = 0; i < movie.directors.length; i = i + 1)
    {
      var d = movie.directors[i];
      if (i > 0)
      {
        str += ', ';
      }
      str += d.name;
    }
    $(movie.id + '_director').innerHTML = str;
  }
  else
  {
    // $(movie.id + '_director').innerHTML = 'unknown';
  }
  if (movie.actors)
  {
    var actors = new Array();
    for ( var i = 0; i < movie.actors.length; i = i + 1)
    {
      if (actors.length > 0)
        actors.push(', ');
      actors.push(movie.actors[i].name);
    }
    $(movie.id + '_actors').innerHTML = actors.join('');// movie.actors;
  }

  if (movie.votes < 5)
  {
    $(movie.id + '_memberrank').innerHTML = '<span class="grey">&lt;too few votes&gt;</span>';
  }
  else
  {
    $(movie.id + '_memberrank').innerHTML = Math.round(movie.rating * 10) / 10;
  }
  $(movie.id + '_imdbrank').innerHTML = formatIMDbRating(movie.imdb_rating);
  if (movie.rt_tomatometer != null)
  {
    $(movie.id + '_rtcriticrank').innerHTML = movie.rt_tomatometer;
  }
  $(movie.id + '_links').innerHTML = getLinksHtmlForExpandedRow(movie);
}

function formatIMDbRating(rating)
{
  if (rating != null)
  {
    if (rating.match(/[\d]+\.[\d]+/))
    {
      return rating;
    }
    else
    {
      return rating + '.0';
    }
  }
}

function getLinksHtmlForExpandedRow(movie)
{
  var imdb = '<a title="IMDb" target="_new" href="http://www.imdb.com/title/tt' + movie.imdb_title_no + '/"><img src="/pictures/imdb.gif" alt="IMDb" /></a>';

  var rt = '';
  if (movie.rt_name != null)
  {
    var rt = ' <a target="_new" title="Rotten Tomatoes" href="http://www.rottentomatoes.com/m/' + movie.rt_name + '/">' + '<img src="/pictures/tomato.gif" /></a>';
  }
  else
  {
    var rt = ' <a target="_new" title="Rotten Tomatoes" href="http://www.rottentomatoes.com">' + '<img src="/pictures/tomato_grey.gif" /></a>'
  }
  return imdb + rt;
}

function blackSearch(string, evt, timeout)
{

}

function search(string, evt, timeout)
{
  removeMpNow(true); // clear miniprofile
  if (timeout == null)
    timeout = 400;
  if (string != '')
  {
    activateClearSearch();
  }
  else
  {
    deactivateClearSearch();
  }
  if (string.length < 1)
  {
    hideSearchList();
    return;
  }
  string = trim(string);
  while (string.indexOf('  ') >= 0)
  {
    string = string.replace(/  /, ' ');
  }
  if (string.length < 2)
  {
    return;
  }
  if (typeof evt != 'string')
  { // <- will be true on page reload
    var keyCode = evt.keyCode;
    var altKey = (evt.modifiers) ? false : (evt.altKey || evt.altLeft
        || evt.charCode == 18 || evt.charCode == 57388);
    var ctrlKey = (evt.modifiers) ? (evt.modifiers & Event.CONTROL_MASK)
        : (evt.ctrlKey || evt.ctrlLeft || evt.charCode == 17 || evt.charCode == 57391);
    var shiftKey = (evt.modifiers) ? (evt.modifiers & Event.SHIFT_MASK)
        : (evt.shiftKey || evt.shiftLeft || evt.charCode == 16 || evt.charCode == 57390);
    if ((altKey || ctrlKey))
      return;
  }
  switch (keyCode)
  {
  case 9:
    /* case 13: */
  case 16:
  case 17:
  case 18:
  case 19:
  case 20:
  case 33:
  case 34:
  case 36:
  case 35:
  case 37:
  case 38:
  case 39:
  case 40:
  case 45:
  case 44:
  case 91:
  case 92:
  case 93:
  case 112:
  case 113:
  case 114:
  case 115:
  case 116:
  case 117:
  case 118:
  case 119:
  case 120:
  case 121:
  case 122:
  case 123:
  case 144:
  case 145:
    return;
    break;
  }
  showSearchIndicator();
  var url = '/ajax/search4.php?s=' + encodeURIComponent(string);
  if (pageMovieId)
  {
    url += '&m=' + pageMovieId;
  }
  // escaping to avoid bug when search str contains '
  var timeoutFunction = "__fireSearch('" + escape(url) + "', '" + escape(encodeURIComponent(string)) + "');";
  clearInterval(searchTimeout);
  searchTimeout = setTimeout(timeoutFunction, timeout);
}

function __fireSearch(url, string)
{
  url = unescape(url);
  string = unescape(string);
  window.location.replace(setAjaxParam('s', string));
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :searchHandler
  });
  lastSearchString = decodeURIComponent(string);

}

searchHandler = function(t)
{
  expanded = [];
  hideCenterList();
  var result = eval('(' + t.responseText + ')');
  if (decodeURIComponent(result.string) != lastSearchString)
  {
    return;
  }
  $('movie_search_results').innerHTML = decodeURIComponent(result.movie_html);
  $('celebrity_search_results').innerHTML = decodeURIComponent(result.people_html);
  if ($('user_search_results'))
  {
    $('user_search_results').innerHTML = decodeURIComponent(result.user_html);
    modifyLinksMp($('user_search_results'));
  }
  // toggle('search_row', true);
  $('search_row').style.display = '';
  hideSearchIndicator();
  if ($('slider_transparent')){
    prepare_slider();

  }
}

function showSearchIndicator()
{
  $('search_left').style.backgroundImage = "url('/black/pics/search_bg_left_active.gif')";
}

function hideSearchIndicator()
{
  $('search_left').style.backgroundImage = '';
}
function hideCenterList()
{
}

function showCenterList()
{
}

function showSearchList()
{
}

function hideSearchList()
{
  if ($('search_row') != null)
    toggle('search_row', false);
}

function fieldOnBlur(field, content, isPassword)
{
  if (field.value != '')
    return;
  if (isPassword)
  {
    field.type = 'text';
  }
  field.className += '_empty';
  field.value = content;
}

function fieldOnFocus(field, isPassword)
{
  var index = false;
  if ((index = field.className.indexOf('_empty')) > 0)
  {
    var newClassName = field.className.substring(0, index);
    field.className = newClassName;
    field.value = '';
  }
  if (isPassword)
  {
    field.type = 'password';
  }
}

function clearSearch()
{
  toggle('search_row', false);
  toggle('search_row_add_movie_div', false);
  hideAddMovieFromSearch();
  hideAddCelebrityFromSearch();
  hideSearchIndicator();
  window.location.replace(removeAjaxParam( [ 's', 'es' ]));
  removeMpNow(true);
  if ($('slider_transparent')){
    prepare_slider();
  }
  $('search_field').value = '';
  setTimeout("$('search_field').focus();", 1);
}
function activateClearSearch()
{
  var clearBtn = $('clear_search_button');
  if (clearBtn != null)
  {
    $('clear_search_button').src = '/pictures/btn_clear_search.png';
  }
}

function deactivateClearSearch()
{
  if ($('search_field').value == '')
  {
    var clearBtn = $('clear_search_button');
    if (clearBtn != null)
    {
      $('clear_search_button').src = '/pictures/btn_clear_search_grey.png';
    }
  }
}

function btnmo(btn, t)
{
  var p = '/black/pics/btn_';
  btn.src = p + t + ((btn.src.indexOf('_m') > 0) ? '' : '_m') + '.png';
}

function createPhotoWithShadow(divId, imgId, imgSrc, link)
{
  // table created with innerHTML to simplify keep cellspacing out of css
  if (divId)
  {
    var div = $(divId);
  }
  else
  {
    var div = document.createElement('div');
  }
  div.innerHTML = '<table cellspacing="0" cellpadding="0"><thead/><tfoot/></table>';
  var table = div.childNodes[0];
  var tbody = table.appendChild(document.createElement('tbody'));

  var tr, td, img, d = null;
  tr = tbody.appendChild(document.createElement('tr'));
  td = tr.appendChild(document.createElement('td'))
  if (link)
  {
    a = td.appendChild(document.createElement('a'));
    a.href = link;
    img = a.appendChild(document.createElement('img'));
  }
  else
  {
    img = td.appendChild(document.createElement('img'));
  }
  img.id = imgId;
  img.src = imgSrc;

  //td = tr.appendChild(document.createElement('td'));
  //td.className = 'shadow_top_right_td';
  //d = td.appendChild(document.createElement('div'));
  //d.className = 'shadow_corner_div';

  //img = d.appendChild(document.createElement('img'));
  //img.src = '/pictures/shadow_tr.gif';
  //img.width = img.height = '7';

  tr = tbody.appendChild(document.createElement('tr'));
  td = tr.appendChild(document.createElement('td'));
  td.className = 'shadow_bottom_left_td';
  d = td.appendChild(document.createElement('div'));
  d.className = 'shadow_corner_div';
  img = d.appendChild(document.createElement('img'));
  img.src = '/pictures/shadow_bl.gif';
  img.width = img.height = '7';

  td = tr.appendChild(document.createElement('td'));
  d = td.appendChild(document.createElement('div'));
  d.className = 'shadow_corner_div';

  img = d.appendChild(document.createElement('img'));
  img.src = '/pictures/shadow_br.gif';
  img.width = img.height = '7';

  return div;
}

function submitComment()
{
  var movieId = $('movie_id').value;
  var comment = $('comment_text').value;
  var url = '/ajax/comment.php';
  var postData = {
    movie_id :movieId,
    comment :comment
  };
  new Ajax.Request(url, {
    parameters :postData,
    onSuccess :submitCommentHandler
  });
}

var submitCommentHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.error == null)
  {
    $('comment_text').value = '';
    var tr = document.createElement('tr');
    var td = tr.appendChild(document.createElement('td'));
    td.setAttribute('colspan', 3);
    var p1 = td.appendChild(document.createElement('p'));
    p1.style.fontWeight = 'bold';
    p1.innerHTML = result.commenter_username;
    var p2 = td.appendChild(document.createElement('p'));
    p2.innerHTML = decodeURIComponent(result.comment);
    var firstRow = $('comment_table_first_row');
    $('comment_table_body').insertBefore(tr, firstRow.nextSibling);
  }
  else
  {
    alert(result.error);
  }
}

function togglePosterUpload()
{
  var div = $('poster_upload');
  var display = 'none';
  var linkText = 'Upload new poster';
  if (div.style.display != 'block')
  {
    display = 'block';
    linkText = 'Hide poster upload form';
  }
  div.style.display = display;
  $('poster_img_url').focus();
}

function populateBacklink(prefix)
{
  $(prefix + '_backlink').value = getUrl();
}

function askForRTLink(movieId)
{
  var link = prompt('Please enter this movie\'s Rotten Tomatoes link');
  if (link == null || !link || link == '')
    return;
  if (link.match(/http:\/\/www\.rottentomatoes\.com\/m\/[\da-z0-9_]+/))
  {
    var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
        + '&property=rt_link&value=' + encodeURIComponent(link);
    new Ajax.Request(url, {
      asynchronous :true,
      onSuccess :setMoviePropertyHandlerFunc
    });
  }
  else
  {
    alert('The link does not seem to be valid');
  }
}

function askForRTRating(movieId)
{
  var rating = prompt('Please enter this movie\'s Rotten Tomatoes rating ("Tomatometer")');
  if (rating == null || !rating || rating == '')
    return;
  if (rating.match(/[\d]+/))
  {
    var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
        + '&property=rt_tomatometer&value=' + rating;
    new Ajax.Request(url, {
      asynchronous :true,
      onSuccess :setMoviePropertyHandlerFunc
    });
  }
  else
  {
    alert('The rating does not seem to be valid');
  }
}

function updateRTRating(imdbId)
{
  var url = '/ajax/parser.php?imdbid=' + imdbId;
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function askForRuntime(movieId)
{
  var runtime = prompt('Please enter this movie\'s runtime in minutes');
  if (runtime == null || !runtime || runtime == '')
    return;
  if (runtime.match(/[\d]+/) || runtime < 60 || runtime > 300)
  {
    var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
        + '&property=runtime&value=' + runtime;
    new Ajax.Request(url, {
      asynchronous :true,
      onSuccess :setMoviePropertyHandlerFunc
    });
  }
  else
  {
    alert('The runtime does not seem to be valid');
  }
}
function askForReleaseDate(movieId)
{
  var reldate = prompt('Please enter this movie\'s release date and country (yyyy-mm-dd country)');
  if (reldate == null || !reldate || reldate == '')
    return;
  if (reldate.match(/\d{4}-\d{2}-\d{2} [A-Za-z\- \.]+/))
  {
    var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
      + '&property=reldate&value=' + encodeURIComponent(reldate);
    new Ajax.Request(url, {
      asynchronous :true,
      onSuccess :setMoviePropertyHandlerFunc
    });
  }
  else
  {
    alert('The release date + country does not seem to be valid');
  }
}
function askForActorName(movieId)
{
  var name = prompt('Please enter the actor\'s name');
  if (name == null || !name || name == '')
    return;
  var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
      + '&property=actor&value=' + encodeURIComponent(name);
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function addActorFromSearch(actorId,lead)
{
  var url = '/ajax/black_set_movie_property.php?movie_id=' + pageMovieId
      + '&property=actor_id&value=' + actorId;
  if (lead){
    url+='&lead=1';
  }
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
  $('search_field').focus();
  $('search_field').select();
}
function addAssocFromSearch(movieId,assocMovieId)
{
  var valid = ['sequel', 'prequel', 'story', 'theme'];
  var association = '';
  while (association !== null && valid.indexOf(association) == -1)
  {
    association = prompt('Enter one of: ' + valid.join(', '));
    if (association) association = association.toLowerCase();
  }
  if (association === null) return;
  new Ajax.Request('/ajax/set_movie_association.php',
  {
    method: 'post',
    parameters: { 'movie_id': movieId, 'associated_movie_id': assocMovieId, 'association': association },
    onSuccess: function(t)
    {
      $('assoc_' + assocMovieId + '_from_search').remove();
      var result = eval('(' + t.responseText + ')');
      if (result.error)
      {
        alert(decodeURIComponent(result.error));
      }
    }
  });
}
function removeAssoc(movieId,assocMovieId)
{
  $('assoc_movie_' + assocMovieId).remove();
  new Ajax.Request('/ajax/remove_movie_association.php',
  {
    method: 'post',
    parameters: { 'movie_id': movieId, 'associated_movie_id': assocMovieId },
    onSuccess: function(t)
    {
      //console.log(t.responseText);
    }
  });
}

function removeActorFromMovie(actorId){
  var url = '/ajax/black_set_movie_property.php?movie_id=' + pageMovieId
      + '&property=remove_actor_id&value=' + actorId;

  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function askForGenre(movieId)
{
  var oldgenres = $('genres').innerHTML;
  if (oldgenres != '')
  {
    oldgenres = oldgenres.replace(/<\/?[^>]*>/g, '');
  }
  var name = prompt(
      'Please enter the movie\'s genre(s), separated with commas', oldgenres);
  if (name == null || !name || name == '')
    return;
  if (!name.match(/^[a-zA-Z\-]+( *(,|\|) *[a-zA-Z\-]+)*$/))
  {
    alert('Invalid genre name(s)');
    return;
  }
  var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
      + '&property=genre&value=' + name;
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function askForCountry(movieId)
{
  var oldcountry = $('country').innerHTML;
  if (oldcountry != '')
  {
    oldcountry = oldcountry.replace(/<\/?[^>]*>/g, '');
  }
  var country = prompt('Please enter the movie\'s country of origin',
      oldcountry);
  if (country == null || !country || country == '')
    return;
  if (!country.match(/^[ a-zA-Z]+( ?, ?[ a-zA-Z]+)*$/))
  {
    alert('Invalid country name(s)');
    return;
  }
  var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
      + '&property=country&value=' + encodeURIComponent(country);
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function askForIMDbRating(movieId)
{
  var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId + '&property=imdb_rating&value=dummy';
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function askForAllPostersUrl(movieId)
{
  var apurl = prompt('Please enter the url to this movie\'s poster at AllPosters.com');
  if (apurl == null || !apurl || apurl == '')
    return;
  if (!apurl.match(/^http:\/\/www\.allposters\.com\// ))
  {
    alert('Unexpected url format (must start with http://www.allposters.com/)');
    return;
  }
  apurl = apurl.replace('http://www.allposters.com', '');
  var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId
      + '&property=allposters_url&value=' + encodeURIComponent(apurl);
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function askForAmazonDvdLink(movieId)
{
  __askForAmazonLink(movieId, 'amazon_dvd_id', 'DVD');
}

function askForAmazonBluRayLink(movieId)
{
  __askForAmazonLink(movieId, 'amazon_bluray_id', 'Blu-Ray');
}

function askForAmazonDownloadLink(movieId)
{
  __askForAmazonLink(movieId, 'amazon_dl_id', 'downloadable');
}

function __askForAmazonLink(movieId, property, type)
{
  var link = prompt('Please enter the url to this movie\'s ' + type + ' version on Amazon.com');
  // if (link == null || !link || link == '') return;
  if (link != ''
      && !link
          .match(/^http:\/\/www\.amazon\.com\/(([a-zA-Z\-]+\/dp)|(gp\/product))\/[A-Z0-9]+(\/.*)?$/))
  {
    // http://www.amazon.com/gp/product/B000NDMREQ/ref=atv_dvd_mov_buy
    alert('Unexpected url format');
    return;
  }
  if (link == '')
  {
    id = '';
  }
  else
  {
    id = link
        .replace(
            /^http:\/\/www\.amazon\.com\/(([a-zA-Z\-]+\/dp)|(gp\/product))\/([A-Z0-9]+)(\/.*)?$/,
            '$4');
  }
  var url = '/ajax/black_set_movie_property.php?movie_id=' + movieId + '&property='
      + property + '&value=' + id;
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :setMoviePropertyHandlerFunc
  });
}

function moviesPerPage(nr)
{
  var newUrl = getNewUrl('pp', nr, null);
  window.location = newUrl;
}

function next()
{
  var newUrl = getNewUrl('p', p + 1, null);
  window.location = newUrl;
}

function prev()
{
  if (p <= 1)
  {
    var newUrl = window.location.toString().replace(/(&|\?)p=[\d]+/, '');
  }
  else
  {
    var newUrl = getNewUrl('p', p - 1, null);
  }
  window.location = newUrl;
}

function getNewUrl(changedParamName, changedParamValue, url, keepAjaxParams)
{
  var ajaxParams = null;
  if (url == null)
  {
    url = getUrl(false);
    if (keepAjaxParams != null && keepAjaxParams)
    {
      ajaxParams = getAjaxParams();
    }
  }
  var paramString = '';
  var existed = false;
  if (url.indexOf('?') > 0)
  {
    var paramstr = url.substring(url.indexOf('?') + 1);
    if (paramstr != '')
    {
      url = url.substring(0, url.indexOf('?'));
      var pairs = paramstr.split('&');
      for ( var i = 0; i < pairs.length; i = i + 1)
      {
        var name = pairs[i].substring(0, pairs[i].indexOf('='));
        var value = pairs[i].substring(pairs[i].indexOf('=') + 1);
        if (paramString != '')
          paramString += '&';
        paramString += name + '=';
        if (name == changedParamName)
        {
          paramString += changedParamValue;
          existed = true;
        }
        else
        {
          paramString += value;
        }
      }
    }
  }

  if (!existed)
  {
    if (paramString != '')
      paramString += '&';
    paramString += changedParamName + '=' + changedParamValue;
  }

  var newurl = putAjaxParams(ajaxParams, url + '?' + paramString);
  return newurl;
}

function topbarHighlight(td, on)
{
  var img = (on) ? '/pictures/top_bar_bg_a.png' : '/pictures/top_bar_bg.png';
  td.style.backgroundImage = "url('" + img + "')";
}

var setMoviePropertyHandlerFunc = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.error == null)
  {
    if (result.property == 'rt_link')
    {
      var a = $(result.movie_id + '_rtlink');
      a.href = 'http://www.rottentomatoes.com/m/' + result.rt_name + '/';
      a.target = '_new';
      $(result.movie_id + '_rtlinkimg').src = '/pictures/tomato.gif';
      var rts = $(result.movie_id + '_rtsearchlink')
      if (rts != null)
      {
        rts.parentNode.removeChild(rts);
      }
      score($(result.movie_id + '_rtlinkimg'), 1);
    }
    else if (result.property == 'rt_tomatometer')
    {
      $('rt_tomatometer').innerHTML = result.rt_tomatometer + '%';
      if (result.score)
      {
        score($('rt_tomatometer'), 1);
      }
    }
    else if (result.property == 'runtime')
    {
      $('runtime').innerHTML = result.runtime + ' minutes';
      if (result.score)
      {
        score($('runtime'), 1);
      }
    }
    else if (result.property == 'reldate')
    {
      $('reldate').innerHTML = decodeURIComponent(result.reldate);
    }
    else if (result.property == 'actor')
    {
      $('actors').innerHTML = decodeURIComponent(result.actors);
      score($('new_actor'), 1);
    }
    else if (result.property == 'actor_id')
    {
      $('actors').innerHTML = decodeURIComponent(result.actors);
      $('add_' + result.added_actor_id + '_from_search').style.display = 'none';
      score($('actors'), 1);

    }
    else if (result.property == 'remove_actor_id')
    {
      $('actors').innerHTML = decodeURIComponent(result.actors);

      //score($('new_actor'), 1);

    }
    else if (result.property == 'genre')
    {
      $('genres').innerHTML = decodeURIComponent(result.genres);
      if (result.score)
      {
        score($('genres'), 1);
      }
    }
    else if (result.property == 'tags')
    {
      $('tags').innerHTML = decodeURIComponent(result.tags);
      if (result.score)
      {
        score($('tags'), 1);
      }
    }
    else if (result.property == 'country')
    {
      $('country').innerHTML = decodeURIComponent(result.country);
      if (result.score)
      {
        score($('country'), 1);
      }

    }
    else if (result.property == 'allposters_url')
    {
      $('allposters_link').href = decodeURIComponent(result.url);
      $('allposters_add_link').innerHTML = 'edit';
      toggle('allposters_link', true);

      if (result.score)
      {
        score($('allposters'), 1);
      }
    }
    else if (result.property == 'amazon_dvd_id')
    {
      if (result.url == null)
      {
        $('amazon_dvd_link').href = '#';
        $('amazon_add_dvd_link').innerHTML = 'add dvd link';
        toggle('amazon_dvd_link', false);
      }
      else
      {
        $('amazon_dvd_link').href = decodeURIComponent(result.url);
        $('amazon_add_dvd_link').innerHTML = 'edit';
        toggle('amazon', true);
        toggle('amazon_dvd_link', true);
        if (result.score)
        {
          score($('amazon_dvd_link'), 1);
        }
      }
    }
    else if (result.property == 'amazon_bluray_id')
    {
      if (result.url == null)
      {
        $('amazon_bluray_link').href = '#';
        $('amazon_add_bluray_link').innerHTML = 'add blu-ray link';
        toggle('amazon_bluray_link', false);
      }
      else
      {
        $('amazon_bluray_link').href = decodeURIComponent(result.url);
        $('amazon_add_bluray_link').innerHTML = 'edit';
        toggle('amazon', true);
        toggle('amazon_bluray_link', true);
        if (result.score)
        {
          score($('amazon_bluray_link'), 1);
        }
      }
    }
    else if (result.property == 'amazon_dl_id')
    {
      if (result.url == null)
      {
        $('amazon_dl_link').href = '#';
        $('amazon_add_dl_link').innerHTML = 'add download link';
        toggle('amazon_dl_link', false);
      }
      else
      {
        $('amazon_dl_link').href = decodeURIComponent(result.url);
        $('amazon_add_dl_link').innerHTML = 'edit';
        toggle('amazon', true);
        toggle('amazon_dl_link', true);
        if (result.score)
        {
          score($('amazon_dl_link'), 1);
        }
      }
    }
    else if (result.property == 'imdb_rating')
    {
      $('imdb_rating').innerHTML = decodeURIComponent(result.imdb_rating);
    }
    else
    {
      // unknown property_name
    }
  }
  else
  {
    alert(decodeURIComponent(result.error));
  }
}

function getTopPos(element)
{
  var val = element.offsetTop;
  while ((element = element.offsetParent) != null)
  {
    val += element.offsetTop;
  }
  return val;
}

function getLeftPos(element)
{
  var val = element.offsetLeft;
  while ((element = element.offsetParent) != null)
  {
    val += element.offsetLeft;
  }
  return val;
}
function score(element, points)
{
  mpX = getLeftPos(element) * 1 + (element.offsetWidth / 2) * 1 - 30;
  mpY = getTopPos(element) * 1 + (element.offsetHeight / 2) * 1 - 33;
  var img = document.createElement('img');
  img.className = 'contrib_score';
  img.src = '/pictures/score_' + points + '.png';
  img.style.top = Math.round(mpY) + 'px';
  img.style.left = Math.round(mpX) + 'px';
  scoreObject = new Object();
  scoreObject.originalY = mpY;
  scoreObject.points = points;
  scores.push(scoreObject);
  scoreNr = scores.length - 1;
  img.id = 'score_' + scoreNr;
  document.body.appendChild(img);
  setTimeout('moveScore(\'' + scoreNr + '\');', 25);
}

function moveScore(scoreNr)
{
  var img = $('score_' + scoreNr);
  var scoreObject = scores[scoreNr];
  var top = img.style.top;
  top = top.replace(/\D/g, '');
  if (top > scoreObject.originalY - 100)
  {
    img.style.top = (top - 5) + 'px';
    setTimeout('moveScore(\'' + scoreNr + '\');', 25);
  }
  else
  {
    // alert('Setting top ' + (top + 5));
    img.style.top = (top * 1 + 2) + 'px';
    updateScore(scoreObject.points);
    setTimeout(
        'new Effect.Opacity(\'score_' + scoreNr + '\', {duration:1, from:1.0, to:0.0});',
        250);
    setTimeout('document.body.removeChild($(\'score_' + scoreNr + '\'));', 1250);
  }
}

function updateScore(points)
{
  var old = $('score').innerHTML;
  if (old == '-')
    old = 0;
  else
    old = old * 1;
  $('score').innerHTML = (old + points);
  new Ajax.Request('/ajax/score.php?score=' + points, {
    asynchronous :true
  });
}

function reportComment(cid)
{
  new Ajax.Request('/ajax/comment_action.php?action=report&cid=' + cid, {
    asynchronous :true,
    onSuccess :commentActionHandler
  });
}

function reportMovieInfo()
{
  var movieId = $('movie_id').value; // stolen from timeline form
  var report = trim($('report_movie_info_field').value);
  if (report == '')
  {
    $('report_movie_info_field').focus();
    $('report_movie_info_message').innerHTML = 'Please let us know what information is incorrect.<br /><br />';
    showWindow('window');
  }
  else
  {
    var url = '/ajax/report.php?type=movie&movie_id=' + movieId;
    var postData = {
      report :encodeURIComponent(report)
    };
    new Ajax.Request(url, {
      parameters :postData,
      onSuccess :reportMovieInfoHandler
    });
  }
}
reportMovieInfoHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.error != null)
  {
    showWindow('report_movie_info_message');
    $('report_movie_info_message').innerHTML = decodeURIComponent(result.error) + '<br /><br />';
  }
  else
  {
    //$('report_movie_info_field').value = '';
    showWindow('report_movie_info_message');
    $('report_movie_info_message').innerHTML = decodeURIComponent(result.ok);
  }
}

function clearCommentFeedback(cid)
{
  setTimeout(
      'new Effect.BlindUp(\'comment_' + cid + '_feedback_container\', {duration:0.5});',
      2500);
  setTimeout('$(\'comment_' + cid + '_feedback\').innerHTML = \'\';', 3000);
}

function rateComment(cid, helpful)
{
  var rating = (helpful) ? 1 : -1;
  new Ajax.Request('/ajax/comment_action.php?action=rate&cid=' + cid
      + '&rating=' + rating, {
    asynchronous :true,
    onSuccess :rateCommentHandler
  });
}

rateCommentHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.error == null)
  {
    var cid = result.cid;
    var rating = result.rating;
    var span = $('comment_' + cid + '_rating');
    span.innerHTML = rating;
    if (rating < 0)
    {
      span.style.color = 'red';
    }
    else
    {
      span.style.color = 'black';
    }
  }
  commentActionHandler(t);
}

commentActionHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  var div = $('comment_' + result.cid + '_feedback');
  var cid = result.cid;
  if (result.error == null)
  {
    div.className = 'feedback';
    div.innerHTML = decodeURIComponent(result.ok);
    clearCommentFeedback(cid);
  }
  else
  {
    div.className = 'error';
    div.innerHTML = decodeURIComponent(result.error);
  }
  new Effect.BlindDown('comment_' + cid + '_feedback_container', {
    duration :0.25
  });
  clearCommentFeedback(cid);
}

function wordCount(elementWithValue)
{
  var count = 0;
  var value = elementWithValue.value;
  value = value.replace(/\n/g, ' ');
  /*
   * while (value.indexOf("\n" > 0)) { value = value.replace("\n", ' '); }
   */
  var words = value.split(" ");
  for ( var i = 0; i < words.length; i++)
  {
    if (words[i].length == 0)
      continue;
    count++;
  }
  return count;
}

function editReview()
{
  $('user_review_exists_text').style.display = 'none';
  $('review_form').style.display = 'block';
  $('review_overwrite').value = true;
  scrollTo(0, 10000);
}

function toggle(id, force)
{
  if (isArray(id))
  {
    for ( var i = 0; i < id.length; i++)
    {
      toggle(id[i], force);
    }
    return;
  }
  var e = $(id);
  var visibleDisplayStyle = 'block';
  if (e)
  {
    if (e.tagName.toLowerCase() == 'table')
      visibleDisplayStyle = 'table';
    else if (e.tagName.toLowerCase() == 'tr')
    {
      var ie = ieVersion();
      visibleDisplayStyle = (ie > 0 && ie < 7) ? 'block' : 'table-row';
    }
    else if (e.tagName.toLowerCase() == 'span')
      visibleDisplayStyle = 'inline';
    else if (e.tagName.toLowerCase() == 'a')
      visibleDisplayStyle = 'inline';
    if (force != null)
    {
      /*
       * if (visibleDisplayStyle == 'table-row') { visibleDisplayStyle = ''; }
       */
      e.style.display = (force) ? visibleDisplayStyle : 'none';
    }
    else
    {
      if (e.style.display != visibleDisplayStyle)
      {
        /*
         * if (visibleDisplayStyle != 'block') { e.style.display =
         * '';//visibleDisplayStyle; } else {
         */
        e.style.display = visibleDisplayStyle;
        // }
      }
      else
      {
        e.style.display = 'none';
      }
    }
  }
  // return e.style.display != 'none';
}

function isArray(smth)
{
  if (!smth)
  {
    return false;
  }
  if (typeof smth === 'object')
  {
    return true;
  }
  return false;
}

function requestMovieFromSearch()
{
  var message = trim($('request_movie_from_search').value);
  if (message == '')
  {
    $('request_movie_error').innerHTML = 'Message is empty.<br /><br />';
    toggle('request_movie_error', true);
  }
  else
  {
    var url = '/ajax/request.php?type=movie';
    var postData = {
      message :encodeURIComponent(message),
      search :encodeURIComponent(lastSearchString)
    };
    new Ajax.Request(url, {
      parameters :postData,
      onSuccess :requestMovieFromSearchHandler
    });
  }
}

requestMovieFromSearchHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.error != null)
  {
    $('request_movie_error').innerHTML = decodeURIComponent(result.error) + '<br /><br />';
    toggle('request_movie_error', true);
  }
  else
  {
    $('search_no_matches').innerHTML = decodeURIComponent(result.ok);
  }
}

function showAddMovieFromSearch()
{
  $('movie_not_found_link').hide();
  $('movie_not_found_inactive').show();
  $('search_row_add_movie_div').show();
  $('add_movie_imdb').focus();
  $('add_movie_imdb').select();
  $('add_movie_title').value = '';
  $('add_movie_year').value = '';
  if ($('slider_transparent')){
    prepare_slider();
  }
}

function changeUIState(showThese, hideThese, emptyValues, emptyInnerHTMLs)
{
  for ( var i = 0; i < showThese.length; i++)
  {
    toggle(showThese[i], true);
  }
  for ( var i = 0; i < hideThese.length; i++)
  {
    toggle(hideThese[i], false);
  }
  for ( var i = 0; i < emptyValues.length; i++)
  {
    var e = $(emptyValues[i]);
    if (e != null)
      e.value = '';
  }
  for ( var i = 0; i < emptyInnerHTMLs.length; i++)
  {
    var e = $(emptyInnerHTMLs[i]);
    if (e != null)
      e.innerHTML = '';
  }
}
function hideAddMovieFromSearch()
{
  var showThese = [ 'movie_not_found_link' ];
  var hideThese = [ 'movie_not_found_inactive', 'search_row_add_movie_div' ];
  var emptyValues = [ 'add_movie_title', 'add_movie_year', 'add_movie_imdb' ];
  var emptyInnerHTMLs = [ 'add_movie_title_error', 'add_movie_year_error',
      'add_movie_imdb_error', 'add_movie_feedback', 'add_movie_error' ];
  changeUIState(showThese, hideThese, emptyValues, emptyInnerHTMLs);
}

function showAddCelebrityFromSearch()
{
  alert('Still working on this');
  return;
  toggle('celebrity_not_found_link', false);
  toggle('celebrity_not_found_inactive', true);
  toggle('search_row_add_celebrity_div', true);
}

function hideAddCelebrityFromSearch()
{
  var showThese = [ 'celebrity_not_found_link' ];
  var hideThese = [ 'celebrity_not_found_inactive',
      'search_row_add_celebrity_div' ];
  var emptyValues = [ 'add_celebrity_name', 'add_celebrity_imdb' ];
  changeUIState(showThese, hideThese, emptyValues, new Array());
}

function addMovie_getTitleAndYear() {
  $('add_movie_feedback').update('');
  var err = $('add_movie_imdb_error');
  var title = $('add_movie_title');
  var year = $('add_movie_year');

  err.update('');
  title.value = '';
  year.value = '';

  var imdb = trim($F($('add_movie_imdb')));
  var error = false;
  if (imdb == '')
  {
    error = 'IMDb link is required.';
  }
  else if (!isValidIMDbTitleUrl(imdb))
  {
    error = 'Invalid IMDb link (see guidelines).';
  }
  if (error) {
    err.update(error);
    return false;
  }

  var id = /^.+tt(\d{7})\/?$/.exec(imdb)[1];
  new Ajax.Request(
      '/ajax/get_title_and_year.php?id=' + id,
      { onSuccess : function(t)
        {
          var json = eval('(' + t.responseText + ')');
          if (typeof json.error != 'undefined') {
            err.update(decodeURIComponent(json.error));
          } else {
            $('add_movie_title').value = json.title;
            $('add_movie_year').value = json.year;
          }
        }
      });
  return false;
}

function addMovieFromSearch()
{
  var imdb = trim($('add_movie_imdb').value);
  var title = trim($('add_movie_title').value);
  var year = trim($('add_movie_year').value);

  var focus = false;
  var errors = {};

   if (imdb == '')
    {
      if (!focus)
        focus = $('add_movie_imdb');
      errors['imdb'] = 'IMDb link is required.';
    }
    else if (!isValidIMDbTitleUrl(imdb))
    {
      if (!focus)
        focus = $('add_movie_imdb');
      errors['imdb'] = 'Invalid IMDb link (see guidelines).';
    }
    else
    {
      errors['imdb'] = '';
    }

  if (title == '')
  {
    focus = (focus) ? focus : $('add_movie_title');
    errors['title'] = 'Title is required (see guidelines).';
  }
  else
  {
    errors['title'] = '';
  }

  if (year == '')
  {
    if (!focus)
      focus = $('add_movie_year');
    errors['year'] = 'Year is required.';
  }
  else if (!year.match(/^((19)[\d]{2})|((200)[\d])|(2010)|(2011)$/))
  {
    if (!focus)
      focus = $('add_movie_year');
    errors['year'] = 'Invalid year, 1900 - 2011 only (for now).';
  }
  else
  {
    errors['year'] = '';
  }

  for (var field in errors)
  {
    $('add_movie_' + field + '_error').update(errors[field]);
  }

  if (focus)
  {
    focus.focus();
  }
  else
  {
    var parameters = {
      imdb_url:imdb,
      title:encodeURIComponent(title),
      year:year
    }
    var url = '/ajax/add.php?type=movie';
    new Ajax.Request(url, {
      asynchronous :true,
      parameters:parameters,
      onSuccess :addMovieFromSearchHandler
    });
  }
}

addMovieFromSearchHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.error != null)
  {
    $('add_movie_error').update(decodeURIComponent(result.error));
  }
  else
  {
    $('add_movie_error').update('');
    $('add_movie_feedback').update(decodeURIComponent(result.ok));
    postAddMovieCountdownInterval = setInterval('postAddMovieCountdown(\'' + decodeURIComponent(result.url) + '\');', 1000);
    $('add_movie_imdb').value = '';
    $('add_movie_imdb').focus();
    $('add_movie_title').value = '';
    $('add_movie_year').value = '';
  }
}

function postAddMovieCountdown(url)
{
  var count = $('post_add_movie_countdown').innerHTML;
  count = count * 1;
  if (count > 1)
  {
    $('post_add_movie_countdown').innerHTML = count - 1;
  }
  else
  {
    window.location = url;
  }
}

function cancelPostAddMovieCountdown()
{
  clearInterval(postAddMovieCountdownInterval);
  $('post_add_redirect').style.textDecoration = 'line-through';
  $('add_movie_imdb').focus();
}

function isValidIMDbTitleUrl(link)
{
  if (link == null)
    return false;
  else
    return link.match(/^(http:\/\/)?((www|us)\.)?imdb.com\/title\/tt[\d]{7}(\/)?$/);
}

function confirmAvatarRemoval()
{
  toggle('remove_avatar_link');
  toggle('remove_avatar_confirm');
}
function removeAvatar()
{
  var form = document.createElement('form');
  form.action = '/settings';
  form.method = 'post';
  var input = form.appendChild(document.createElement('input'));
  input.type = 'hidden';
  input.name = 'remove_avatar';
  document.body.appendChild(form);
  form.submit();
}
/**
 * Returns page to it's true state including ajax/dhtml search/row expands.
 */
function redoAjaxOnload()
{
  var ap = getAjaxParams();
  if (ap['e'] != null)
  {
    toggleExpanded(ap['e'], false);
  }
  if (ap['es'] != null)
  {
    if (ap['s'] != null)
    {
      // store the value together with the search string, and have search
      // handler evaluate it when the results arrive, IF the results'
      // search
      // string equals ap['s']
      expandAfterSearch = {};
      expandAfterSearch[ap['s']] = ap['es'];
    }
    else
    {
      // shouldn't be here
    }
  }
  if (ap['s'] != null)
  {
    $('search_field').value = decodeURIComponent(ap['s']);
    search(decodeURIComponent(ap['s']), '', 0);
  }
}

function addFriend(friend)
{
  var url = '/ajax/friend.php?friend=' + encodeURIComponent(friend);
  new Ajax.Request(url, {
    asynchronous :true,
    onSuccess :addFriendHandler
  });
}
addFriendHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.ok != null)
  {
    toggle('add_friend_button', false);
    alert(result.ok);
  }
  else
  {
    alert(result.error);
  }
}
function getBrowserDate()
{
  var D = new Date();
  var m = D.getMonth() + 1;
  if (m < 10)
    m = '0' + m;
  var d = D.getDate();
  if (d < 10)
    d = '0' + d;
  var h = D.getHours();
  if (h < 10)
    h = '0' + h;
  var i = D.getMinutes();
  if (i < 10)
    i = '0' + i;
  return D.getFullYear() + "-" + m + "-" + d + " " + h + ":" + i;
}
function ieVersion()
{
  var rv = -1;
  if (navigator.appName == 'Microsoft Internet Explorer')
  {
    var ua = navigator.userAgent;
    var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat(RegExp.$1);
  }
  return rv;
}

checkUsernameTimeout = false;
function initiateCheckUsername(username, event)
{
  clearInterval(checkUsernameTimeout);
  timeoutFunction = 'checkUsername(\'' + encodeURIComponent(trim(username)) + '\');';
  checkUsernameTimeout = setTimeout(timeoutFunction, 500);
}
function checkUsername(username, event)
{
  if (trim(username) == '')
  {
    $('usernameFeedback').innerHTML = 'Start typing to see if it\'s available';
    return;
  }
  new Ajax.Request('/ajax/check_username.php?username=' + username, {
    asynchronous :true,
    onSuccess :checkUsernameHandler
  });
}
checkUsernameHandler = function(t)
{
  var result = eval('(' + t.responseText + ')');
  if (result.ok != null)
  {
    $('usernameFeedback').innerHTML = decodeURIComponent(result.ok);
  }
  else if (result.error != null)
  {
    $('usernameFeedback').innerHTML = decodeURIComponent(result.error);
  }
}

function showReviewRating(mId, rating)
{
  var div = document.createElement('div');
  div.className = 'big_star';
  div.innerHTML = rating;
  div.style.position = 'absolute';
  div.style.top = (getTopPos($('review_poster_' + mId)) + 55) + 'px';
  div.style.left = (getLeftPos($('review_poster_' + mId)) + 30) + 'px';
  document.body.appendChild(div);
}
// ------------------------------------------------------------------------------
// TOP LIST FUNCTIONS
// ------------------------------------------------------------------------------
function toplist_highlightBar(imgDir, current, rating, on)
{
  if (current == rating)
    return;
  var bar = $('bar_' + rating);
  if (!bar)
    return;
  bar.src = imgDir + '/pixel_' + (on ? '4D603A' : '333333') + '.png';
}
// ------------------------------------------------------------------------------
// WATCH LIST FUNCTIONS
// ------------------------------------------------------------------------------
function watchlist_addEntry(movieId)
{
  window.location = '/watchlist_add_entry.php?movie_id=' + movieId;
}
function watchlist_removeEntry(movieId)
{
  new Ajax.Request('/ajax/remove_from_watchlist.php?movie_id=' + movieId);
  var rowId = 'watchlist_row_' + movieId;
  $(rowId).parentNode.removeChild($(rowId));
}
// ------------------------------------------------------------------------------
// MOVIE REVIEW FUNCTIONS
// ------------------------------------------------------------------------------
function validateReview()
{
  try
  {
    if (trim($('comment_text').value) == '')
    {
      alert('Please write your review with 30+ words');
      return false;
    }
  }
  catch (err)
  {
    return false;
  }
  return true;
}

//------------------------------------------------------------------------------
// FEED
//------------------------------------------------------------------------------
function feed_more(container, minEntryId)
{
  new Ajax.Request('/ajax/feed_more.php', {
    method : 'get',
    parameters : {
      id : minEntryId
    },
    onSuccess : function(t) {
      var response = eval("(" + t.responseText + ")");
      feed_minEntryId = response.minEntryId;
      var addtlHtml = decodeURIComponent(response.html);
      container.update(container.innerHTML + addtlHtml);
    }
  });
}

//------------------------------------------------------------------------------
// RECOMMENDE MOVIES
//------------------------------------------------------------------------------

// ------------------------------------------------------------------------------
// MINI PROFILE FUNCTIONS
// ------------------------------------------------------------------------------
mpOnTimeout = mpOffTimeout = false;
mpData = [];
mpParents = [];
mpUid = 0;
mpInput = false;

function mpOn(a, parent, e) {
  var e = e ? e : window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();

  var href = a.href;

  if (!href.match(/^.*\/users\/[^\/]+(\/.*)?$/)) {return;}
  var pos = href.indexOf('/users/');
  var uid = href.substr(pos + 7);
  pos = uid.indexOf('/');
  if (pos > -1) {
    uid = uid.substr(0, pos);
  }
  pos = uid.lastIndexOf('#');
  if (pos > -1) {
    uid = uid.substr(0, pos);
  }

  // corrent miniprofile already showing - cancel off timeout if any
  var tmp = $('mp_' + uid);
  if (tmp != null) {
    removeMpNow(true, uid, parent);
    return;
  }

  /*if (uid == mpUid) {
    removeMpNow(true,uid); // testing onclick..
    if (mpOffTimeout) {clearTimeout(mpOffTimeout);}
    return;
  }*/

  // wrong miniprofile showing - remove it
  if (uid != mpUid && mpUid > 0) {
    //removeMpNow();
  }

  //mpUid = uid;
  mpX = getLeftPos(a);
  mpY = getTopPos(a) + a.offsetHeight;
  if (mpData[uid]) {
    // cached
    mpShow(uid, parent);
    return;
    mpOnTimeout = setTimeout('mpShow(\'' + uid + '\')', 500);
  } else {
    mpDoAjax(uid, parent);
    return;
    //mpOnTimeout = setTimeout('mpDoAjax(\'' + uid + '\')', 500);
  }

}

function mpOff() {
  // mouseout before miniprofile was shown
  if (mpUid == 0) {
    removeMpNow();
    return;
  }

  // miniprofile visible - remove after timeout
  mpOffTimeout = setTimeout('removeMpNow()', 200);
}

function mpDoAjax(username, parent) {
  var url = '/ajax/miniprofile.php?username=' + username;
  if (parent != null) {
    url += '&parent=' + parent;
  }
  new Ajax.Request(url, {asynchronous:true, onSuccess:mpHandler});
}

mpHandler = function(t) {
  var response = eval("(" + t.responseText + ")");
  if (response.user.uid) mpData[response.user.username] = response;
  mpShow(response.user.username, response.parent);
  //alert(response.user.username);
}

function mpShow(uid, parent) {
  if (parent == null) parent = false;
  if (parent) {
    mpParents[uid] = parent;
  }
  mpUid = uid;
  var data = mpData[uid];
  var user = data.user;

  var div = document.createElement('div');

  // stop event propagation - otherwise all mps are closed by document.onclick handler
  div.onclick = function(e) {
    var e = (e) ? e : window.event;
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
  }

  div.id = 'mp_' + mpUid;
  div.className = 'mp2';
  div.style.left = mpX + 'px';
  div.style.top = mpY + 'px';
  div.onmouseover = function(e) { cancelMpRemoval(); };

  var avatarImg = document.createElement('img');
  avatarImg.id = 'mp_pic_' + mpUid;
  avatarImg.src = '/pictures/users/' + uid + '_M.jpg';
  avatarImg.className = 'mp2_pic';
  div.appendChild(avatarImg);

  //var avatarDiv = createPhotoWithShadow(false, 'mp_pic_' + mpUid, '/pictures/users/' + uid + '_M.jpg', '/users/' + uid + '/timeline');
  //avatarDiv.className = 'mp2_pic';
  //div.appendChild(avatarDiv);
  var span = div.appendChild(document.createElement('span'));
  span.innerHTML = '<strong>' + uid + '</strong>';// (score: ' + data.user.score + ')';
  div.appendChild(document.createElement('br'));
  div.appendChild(document.createElement('br'));
  div.appendChild(link('/users/' + uid + '/timeline', 'Timeline'));
  var rssLink = link('/users/' + uid + '/feed', '');
  rssLink.style.paddingLeft = '5px';
  rssLink.innerHTML = '<img src="/black/pics/rss_16px.png" />';
  div.appendChild(rssLink);
  div.appendChild(document.createElement('br'));
  div.appendChild(link('/users/' + uid + '/recommended', 'Recommended'));
  div.appendChild(document.createElement('br'));
  div.appendChild(link('/users/' + uid + '/ratings', 'Top List'));
  div.appendChild(document.createElement('br'));
  div.appendChild(link('/users/' + uid + '/watchlist', 'Watch List'));
  div.appendChild(document.createElement('br'));
  div.appendChild(link('/users/' + uid + '/reviews', 'Reviews'));
  div.appendChild(document.createElement('br'));
  div.appendChild(document.createElement('br'));

  var span = div.appendChild(document.createElement('span'));
  html = '<span class="mp_label">Last seen:</span> ';
  if (data.timeline_entry != null) {
    html += '<a href="' + decodeURIComponent(data.timeline_entry.link) + '">'
         +  decodeURIComponent(data.timeline_entry.title)
         + '</a>';
         //+ ' (' + data.timeline_entry.watched + ')';

  } else {
    html += '-';
  }
  span.innerHTML = html;

  div.appendChild(document.createElement('br'));

  span = div.appendChild(document.createElement('span'));
  html = '<span class="mp_label">Last reviewed:</span> ';
  if (data.reviews > 0) {
    html += '<a href="' + unescape(data.latest_review.link) + '#' + uid + '">'
         +  unescape(data.latest_review.title)
         + '</a>';
         //+ ' (' + data.latest_review.added + ')';

  } else {
    html += '-';
  }
  span.innerHTML = html;

  div.appendChild(document.createElement('br'));

  span = div.appendChild(document.createElement('span'));
  html = '<span class="mp_label">Follows:</span> ';
  if (data.friends) {
    var friendsHtml = '';
    for (var i = 0; i < data.friends.length; i++) {
      if (friendsHtml != '') friendsHtml += ', ';
      friendsHtml += '<a onclick="mpOn(this, \'' + uid + '\', event); return false;" href="/users/' + data.friends[i] + '">' + data.friends[i] + '</a>';
      //friendsHtml += '<a href="javascript:mpOn(this);">' + data.friends[i] + '</a>';
    }
    html += friendsHtml;
  } else {
    html += '-';
  }
  span.innerHTML = html;

  if (!data.self && data.loggedIn) {
    var bottomdiv = div.appendChild(document.createElement('div'));
    bottomdiv.style.clear = 'both';
    bottomdiv.style.borderTop = '1px solid #ccc';
    bottomdiv.style.marginTop = '10px';
    bottomdiv.style.paddingTop = '5px';
    bottomdiv.style.paddingBottom = '5px';
    span = bottomdiv.appendChild(document.createElement('span'));
    html = '<a href="javascript:showMpMessaging(' + data.user.uid + ');">Send a message</a>';
    html += ' | <span id="follow_status">';
    if (data.friends_with_viewer) {
      html += 'Already following! <a id="stop_following_link" href="javascript:mpStopFollowing(' + data.user.uid + ', \'' + data.user.username + '\');">Stop</a>';
    } else {
      html += '<a href="javascript:mpFollow(' + data.user.uid + ', \'' + data.user.username + '\');">Follow this user</a>';
    }
    html += '</span>';

    span.innerHTML = html;
    msgdiv = bottomdiv.appendChild(document.createElement('div'));
    msgdiv.style.display = 'none';
    msgdiv.id = 'mp_msg_div'
    var msgarea = msgdiv.appendChild(document.createElement('textarea'));
    msgarea.id = 'mp_msg_area';
    msgarea.cols = 34;
    msgdiv.appendChild(document.createElement('br'));
    var errorspan = msgdiv.appendChild(document.createElement('span'));
    errorspan.id = 'mp_msg_error';
    errorspan.className = 'error';
    errorspan.style.display = 'none';
    var okspan = msgdiv.appendChild(document.createElement('span'));
    okspan.id = 'mp_msg_feedback';
    okspan.className = 'feedback';
    okspan.style.display = 'none';
    var sendspan = msgdiv.appendChild(document.createElement('span'));
    sendspan.innerHTML = '<a href="javascript:sendMpMessage(' + data.user.uid + ');">Send</a>'
                       + ' | '
                       + '<a href="javascript:cancelMpMessaging();">Cancel</a>';
  }

  if (showAdSense) {
    var ad = $('mpad');
    var iframe = ad.getElementsByTagName('iframe')[0];
    //iframe.src += "&" + Math.floor(Math.random()*1000) + '=true';
    var tmp = iframe.src.split('&');
    var tmp2 = '';
    for (var i = 0; i < tmp.length; i++) {
      tmp2 += tmp[i] + "\n";
    }
    var mpaddiv = div.appendChild(document.createElement('div'));
    mpaddiv.id = 'mpaddiv';
    mpaddiv.appendChild(iframe);
    /*var newiframe = div.appendChild(document.createElement('iframe'));
    newiframe.src = iframe.src + '&random=' + Math.floor(Math.random() * 10000);
    newiframe.setAttribute('marginwidth', 0);
    newiframe.setAttribute('marginheight', 0);
    newiframe.setAttribute('vspace', 0);
    newiframe.setAttribute('allowtransparency', true);
    newiframe.setAttribute('scrolling', 'no');
    newiframe.setAttribute('frameborder', 'no');
    newiframe.height = 60;
    newiframe.width = 234;*/
  }

  document.body.appendChild(div);
}

function removeChildren(parent) {
  for (var child in mpParents) {
    if (mpParents[child] == parent) {
      removeChildren(child);
      delete mpParents[child];
      var tmp = $('mp_' + child);
      if (tmp) tmp.parentNode.removeChild(tmp);
    }
  }
}

function removeMpNow(force, owner, parent) {
  /*if (force == null) { force = false; }
  if (mpInput) {
      if (!force) {
      return; // sending msg etc
    } else {
      mpInput = false;
    }
  }*/

  if (parent != null) {
    // let's make sure we're not killing everyone

    // we've clicked on a nick whose mp was open, and are now closing the
    // mp_nickname - we might have clicked on the nick somewhere down a "tree",
    // while the mp itself is further up the tree and contains the mp where we
    // clicked (mp_owner) .. if this is the case, let's not close it but
    // flash the border instead
    var lala = mpParents[parent]
    while (lala != null) { // traverse UP the tree
      if (lala == owner) {
        $('mp_' + owner).style.borderColor = '#000';
        setTimeout('$(\'mp_' + owner + '\').style.borderColor = \'#ccc\'', 250);
        return;
      }
      lala = mpParents[lala];
    }
  }
  var div = $('mp_' + owner);
  if (div) {
    // remove children
    removeChildren(owner);
    // remove as parent's child
    delete mpParents[owner];

    /*var ad = $('mpaddiv').getElementsByTagName('iframe')[0];
    $('mpad').appendChild(ad);*/
  }
  if (div) div.parentNode.removeChild(div);
  if (mpOnTimeout) clearTimeout(mpOnTimeout);
  if (mpOffTimeout) clearTimeout(mpOffTimeout);
  //mpUid = 0;
}

function cancelMpRemoval() {
  if (mpOffTimeout) clearTimeout(mpOffTimeout);
}
function modifyLinksMp(element) {
  if (element == null) element = document;
  links = element.getElementsByTagName("a");
  for (i = 0; i < links.length; i = i + 1) {
    var href = links[i].href;
    //if (!href.match(/\/users\/[^\/]+(\/.*)?$/)) continue;
    if (!href.match(/\/users\/[^\/]+$/)) continue;
    if (links[i].rel == 'nomp') continue;
    /*links[i].onmouseover = function() { mpOn(this); };
    links[i].onmouseout = function() { mpOff(); }*/
    links[i].onclick = function(e) { mpOn(this, false, e);/*removeMpNow();*/return false; };
  }
}

function showMpMessaging() {
  toggle('mp_msg_div', true);
  mpInput = true;
  $('mp_msg_area').focus();
}

function cancelMpMessaging() {
  toggle('mp_msg_div', false);
  $('mp_msg_area').value = '';
  mpInput = false;
}

function sendMpMessage(recipient) {
  toggle('mp_msg_feedback', false);
  $('mp_msg_feedback').innerHTML = '';
  var msg = $('mp_msg_area').value;
  if (trim(msg) == '') {
    $('mp_msg_error').innerHTML = 'Empty message<br />';
    toggle('mp_msg_error', true);
    $('mp_msg_area').focus();
    return;
  }
  toggle('mp_msg_error', false);
  $('mp_msg_error').innerHTML = '';

  var postData = {message : escape(msg), recipient_uid : recipient};
  new Ajax.Request('/ajax/message.php', { parameters: postData, onSuccess:sendMpMessageHandler });
}
sendMpMessageHandler = function(t) {
  var response = eval("(" + t.responseText + ")");
  if (response.ok != null) {
    $('mp_msg_area').value = '';
    $('mp_msg_feedback').innerHTML = 'Message sent!<br />';
    toggle('mp_msg_feedback', true);
  } else {
    $('mp_msg_error').innerHTML = unescape(response.error) + '<br />';
    toggle('mp_msg_error', true);
    $('mp_msg_area').focus();
  }
}
function mpFollow(friendId, friendName) {
  var url = '/ajax/friend.php?friend=' + friendId;
  new Ajax.Request(url, {asynchronous:true});
  $('follow_status').innerHTML = 'Now following ' + friendName;
  mpData[friendName].friends_with_viewer = true; // update cache
}
function mpStopFollowing(friendId, friendName, really) {
  if (really == null) {
    $('stop_following_link').innerHTML = 'Really stop?';
    $('stop_following_link').href = 'javascript:mpStopFollowing(' + friendId + ', \'' + friendName + '\', true);';
  } else {
    var url = '/ajax/friend.php?remove&friend=' + friendId;
    new Ajax.Request(url, {asynchronous:true});
    $('follow_status').innerHTML = '<a href="javascript:mpFollow(' + friendId + ', \'' + friendName + '\');">Follow this user</a>';
    mpData[friendName].friends_with_viewer = false; // update cache
  }
}
function link(href, text) {
  var tmp = document.createElement('a');
  tmp.href = href;
  tmp.innerHTML = text;
  return tmp;
}
// ------------------------------------------------------------------------------
// END MINI PROFILE FUNCTIONS
// ------------------------------------------------------------------------------
