(function(b){b.fn.ajaxSubmit=function(r){if(!this.length){a("ajaxSubmit: skipping submit process - no element selected");return this}if(typeof r=="function"){r={success:r}}var e=this.attr("action")||window.location.href;e=(e.match(/^([^#]+)/)||[])[1];e=e||"";r=b.extend({url:e,type:this.attr("method")||"GET"},r||{});var t={};this.trigger("form-pre-serialize",[this,r,t]);if(t.veto){a("ajaxSubmit: submit vetoed via form-pre-serialize trigger");return this}if(r.beforeSerialize&&r.beforeSerialize(this,r)===false){a("ajaxSubmit: submit aborted via beforeSerialize callback");return this}var l=this.formToArray(r.semantic);if(r.data){r.extraData=r.data;for(var f in r.data){if(r.data[f] instanceof Array){for(var g in r.data[f]){l.push({name:f,value:r.data[f][g]})}}else{l.push({name:f,value:r.data[f]})}}}if(r.beforeSubmit&&r.beforeSubmit(l,this,r)===false){a("ajaxSubmit: submit aborted via beforeSubmit callback");return this}this.trigger("form-submit-validate",[l,this,r,t]);if(t.veto){a("ajaxSubmit: submit vetoed via form-submit-validate trigger");return this}var d=b.param(l);if(r.type.toUpperCase()=="GET"){r.url+=(r.url.indexOf("?")>=0?"&":"?")+d;r.data=null}else{r.data=d}var s=this,i=[];if(r.resetForm){i.push(function(){s.resetForm()})}if(r.clearForm){i.push(function(){s.clearForm()})}if(!r.dataType&&r.target){var o=r.success||function(){};i.push(function(j){b(r.target).html(j).each(o,arguments)})}else{if(r.success){i.push(r.success)}}r.success=function(q,k){for(var n=0,j=i.length;n<j;n++){i[n].apply(r,[q,k,s])}};var c=b("input:file",this).fieldValue();var p=false;for(var h=0;h<c.length;h++){if(c[h]){p=true}}if(r.iframe||p){if(r.closeKeepAlive){b.get(r.closeKeepAlive,m)}else{m()}}else{b.ajax(r)}this.trigger("form-submit-notify",[this,r]);return this;function m(){var v=s[0];if(b(":input[name=submit]",v).length){alert('Error: Form elements must not be named "submit".');return}var q=b.extend({},b.ajaxSettings,r);var F=b.extend(true,{},b.extend(true,{},b.ajaxSettings),q);var u="jqFormIO"+(new Date().getTime());var B=b('<iframe id="'+u+'" name="'+u+'" src="about:blank" />');var D=B[0];B.css({position:"absolute",top:"-1000px",left:"-1000px"});var E={aborted:0,responseText:null,responseXML:null,status:0,statusText:"n/a",getAllResponseHeaders:function(){},getResponseHeader:function(){},setRequestHeader:function(){},abort:function(){this.aborted=1;B.attr("src","about:blank")}};var C=q.global;if(C&&!b.active++){b.event.trigger("ajaxStart")}if(C){b.event.trigger("ajaxSend",[E,q])}if(F.beforeSend&&F.beforeSend(E,F)===false){F.global&&b.active--;return}if(E.aborted){return}var k=0;var x=0;var j=v.clk;if(j){var w=j.name;if(w&&!j.disabled){r.extraData=r.extraData||{};r.extraData[w]=j.value;if(j.type=="image"){r.extraData[name+".x"]=v.clk_x;r.extraData[name+".y"]=v.clk_y}}}setTimeout(function(){var I=s.attr("target"),G=s.attr("action");v.setAttribute("target",u);if(v.getAttribute("method")!="POST"){v.setAttribute("method","POST")}if(v.getAttribute("action")!=q.url){v.setAttribute("action",q.url)}if(!r.skipEncodingOverride){s.attr({encoding:"multipart/form-data",enctype:"multipart/form-data"})}if(q.timeout){setTimeout(function(){x=true;y()},q.timeout)}var H=[];try{if(r.extraData){for(var J in r.extraData){H.push(b('<input type="hidden" name="'+J+'" value="'+r.extraData[J]+'" />').appendTo(v)[0])}}B.appendTo("body");D.attachEvent?D.attachEvent("onload",y):D.addEventListener("load",y,false);v.submit()}finally{v.setAttribute("action",G);I?v.setAttribute("target",I):s.removeAttr("target");b(H).remove()}},10);var z=0;function y(){if(k++){return}D.detachEvent?D.detachEvent("onload",y):D.removeEventListener("load",y,false);var G=true;try{if(x){throw"timeout"}var H,J;J=D.contentWindow?D.contentWindow.document:D.contentDocument?D.contentDocument:D.document;if((J.body==null||J.body.innerHTML=="")&&!z){z=1;k--;setTimeout(y,100);return}E.responseText=J.body?J.body.innerHTML:null;E.responseXML=J.XMLDocument?J.XMLDocument:J;E.getResponseHeader=function(L){var K={"content-type":q.dataType};return K[L]};if(q.dataType=="json"||q.dataType=="script"){var n=J.getElementsByTagName("textarea")[0];E.responseText=n?n.value:E.responseText}else{if(q.dataType=="xml"&&!E.responseXML&&E.responseText!=null){E.responseXML=A(E.responseText)}}H=b.httpData(E,q.dataType)}catch(I){G=false;b.handleError(q,E,"error",I)}if(G){q.success(H,"success");if(C){b.event.trigger("ajaxSuccess",[E,q])}}if(C){b.event.trigger("ajaxComplete",[E,q])}if(C&&!--b.active){b.event.trigger("ajaxStop")}if(q.complete){q.complete(E,G?"success":"error")}setTimeout(function(){B.remove();E.responseXML=null},100)}function A(n,G){if(window.ActiveXObject){G=new ActiveXObject("Microsoft.XMLDOM");G.async="false";G.loadXML(n)}else{G=(new DOMParser()).parseFromString(n,"text/xml")}return(G&&G.documentElement&&G.documentElement.tagName!="parsererror")?G:null}}};b.fn.ajaxForm=function(c){return this.ajaxFormUnbind().bind("submit.form-plugin",function(){b(this).ajaxSubmit(c);return false}).each(function(){b(":submit,input:image",this).bind("click.form-plugin",function(f){var d=this.form;d.clk=this;if(this.type=="image"){if(f.offsetX!=undefined){d.clk_x=f.offsetX;d.clk_y=f.offsetY}else{if(typeof b.fn.offset=="function"){var g=b(this).offset();d.clk_x=f.pageX-g.left;d.clk_y=f.pageY-g.top}else{d.clk_x=f.pageX-this.offsetLeft;d.clk_y=f.pageY-this.offsetTop}}}setTimeout(function(){d.clk=d.clk_x=d.clk_y=null},10)})})};b.fn.ajaxFormUnbind=function(){this.unbind("submit.form-plugin");return this.each(function(){b(":submit,input:image",this).unbind("click.form-plugin")})};b.fn.formToArray=function(q){var p=[];if(this.length==0){return p}var d=this[0];var h=q?d.getElementsByTagName("*"):d.elements;if(!h){return p}for(var k=0,m=h.length;k<m;k++){var e=h[k];var f=e.name;if(!f){continue}if(q&&d.clk&&e.type=="image"){if(!e.disabled&&d.clk==e){p.push({name:f+".x",value:d.clk_x},{name:f+".y",value:d.clk_y})}continue}var r=b.fieldValue(e,true);if(r&&r.constructor==Array){for(var g=0,c=r.length;g<c;g++){p.push({name:f,value:r[g]})}}else{if(r!==null&&typeof r!="undefined"){p.push({name:f,value:r})}}}if(!q&&d.clk){var l=d.getElementsByTagName("input");for(var k=0,m=l.length;k<m;k++){var o=l[k];var f=o.name;if(f&&!o.disabled&&o.type=="image"&&d.clk==o){p.push({name:f+".x",value:d.clk_x},{name:f+".y",value:d.clk_y})}}}return p};b.fn.formSerialize=function(c){return b.param(this.formToArray(c))};b.fn.fieldSerialize=function(d){var c=[];this.each(function(){var h=this.name;if(!h){return}var f=b.fieldValue(this,d);if(f&&f.constructor==Array){for(var g=0,e=f.length;g<e;g++){c.push({name:h,value:f[g]})}}else{if(f!==null&&typeof f!="undefined"){c.push({name:this.name,value:f})}}});return b.param(c)};b.fn.fieldValue=function(h){for(var g=[],e=0,c=this.length;e<c;e++){var f=this[e];var d=b.fieldValue(f,h);if(d===null||typeof d=="undefined"||(d.constructor==Array&&!d.length)){continue}d.constructor==Array?b.merge(g,d):g.push(d)}return g};b.fieldValue=function(c,j){var e=c.name,p=c.type,q=c.tagName.toLowerCase();if(typeof j=="undefined"){j=true}if(j&&(!e||c.disabled||p=="reset"||p=="button"||(p=="checkbox"||p=="radio")&&!c.checked||(p=="submit"||p=="image")&&c.form&&c.form.clk!=c||q=="select"&&c.selectedIndex==-1)){return null}if(q=="select"){var k=c.selectedIndex;if(k<0){return null}var m=[],d=c.options;var g=(p=="select-one");var l=(g?k+1:d.length);for(var f=(g?k:0);f<l;f++){var h=d[f];if(h.selected){var o=h.value;if(!o){o=(h.attributes&&h.attributes.value&&!(h.attributes.value.specified))?h.text:h.value}if(g){return o}m.push(o)}}return m}return c.value};b.fn.clearForm=function(){return this.each(function(){b("input,select,textarea",this).clearFields()})};b.fn.clearFields=b.fn.clearInputs=function(){return this.each(function(){var d=this.type,c=this.tagName.toLowerCase();if(d=="text"||d=="password"||c=="textarea"){this.value=""}else{if(d=="checkbox"||d=="radio"){this.checked=false}else{if(c=="select"){this.selectedIndex=-1}}}})};b.fn.resetForm=function(){return this.each(function(){if(typeof this.reset=="function"||(typeof this.reset=="object"&&!this.reset.nodeType)){this.reset()}})};b.fn.enable=function(c){if(c==undefined){c=true}return this.each(function(){this.disabled=!c})};b.fn.selected=function(c){if(c==undefined){c=true}return this.each(function(){var d=this.type;if(d=="checkbox"||d=="radio"){this.checked=c}else{if(this.tagName.toLowerCase()=="option"){var e=b(this).parent("select");if(c&&e[0]&&e[0].type=="select-one"){e.find("option").selected(false)}this.selected=c}}})};function a(){if(b.fn.ajaxSubmit.debug&&window.console&&window.console.log){window.console.log("[jquery.form] "+Array.prototype.join.call(arguments,""))}}})(jQuery);

/*
 * Metadata - jQuery plugin for parsing metadata from elements
 *
 * Copyright (c) 2006 John Resig, Yehuda Katz, J�örn Zaefferer, Paul McLanahan
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: $Id: jquery.metadata.js 3620 2007-10-10 20:55:38Z pmclanahan $
 *
 */
(function($){$.extend({metadata:{defaults:{type:'class',name:'metadata',cre:/({.*})/,single:'metadata'},setType:function(type,name){this.defaults.type=type;this.defaults.name=name;},get:function(elem,opts){var settings=$.extend({},this.defaults,opts);if(!settings.single.length)settings.single='metadata';var data=$.data(elem,settings.single);if(data)return data;data="{}";if(settings.type=="class"){var m=settings.cre.exec(elem.className);if(m)data=m[1];}else if(settings.type=="elem"){if(!elem.getElementsByTagName)return;var e=elem.getElementsByTagName(settings.name);if(e.length)data=$.trim(e[0].innerHTML);}else if(elem.getAttribute!=undefined){var attr=elem.getAttribute(settings.name);if(attr)data=attr;}if(data.indexOf('{')<0)data="{"+data+"}";data=eval("("+data+")");$.data(elem,settings.single,data);return data;}}});$.fn.metadata=function(opts){return $.metadata.get(this[0],opts);};})(jQuery);

if(window.jQuery){(function(a){if(a.browser.msie){try{document.execCommand("BackgroundImageCache",false,true)}catch(b){}}a.fn.rating=function(d){if(this.length==0){return this}if(typeof arguments[0]=="string"){if(this.length>1){var c=arguments;return this.each(function(){a.fn.rating.apply(a(this),c)})}a.fn.rating[arguments[0]].apply(this,a.makeArray(arguments).slice(1)||[]);return this}var d=a.extend({},a.fn.rating.options,d||{});a.fn.rating.calls++;this.not(".star-rating-applied").addClass("star-rating-applied").each(function(){var g,l=a(this);var e=(this.name||"unnamed-rating").replace(/\[|\]/g,"_").replace(/^\_+|\_+$/g,"");var f=a(this.form||document.body);var k=f.data("rating");if(!k||k.call!=a.fn.rating.calls){k={count:0,call:a.fn.rating.calls}}var n=k[e];if(n){g=n.data("rating")}if(n&&g){g.count++}else{g=a.extend({},d||{},(a.metadata?l.metadata():(a.meta?l.data():null))||{},{count:0,stars:[],inputs:[]});g.serial=k.count++;n=a('<span class="star-rating-control"/>');l.before(n);n.addClass("rating-to-be-drawn");if(l.attr("disabled")){g.readOnly=true}n.append(g.cancel=a('<div class="rating-cancel"><a title="'+g.cancel+'">'+g.cancelValue+"</a></div>").mouseover(function(){a(this).rating("drain");a(this).addClass("star-rating-hover")}).mouseout(function(){a(this).rating("draw");a(this).removeClass("star-rating-hover")}).click(function(){a(this).rating("select")}).data("rating",g))}var j=a('<div class="star-rating rater-'+g.serial+'"><a title="'+(this.title||this.value)+'">'+this.value+"</a></div>");n.append(j);if(this.id){j.attr("id",this.id)}if(this.className){j.addClass(this.className)}if(g.half){g.split=2}if(typeof g.split=="number"&&g.split>0){var i=(a.fn.width?j.width():0)||g.starWidth;var h=(g.count%g.split),m=Math.floor(i/g.split);j.width(m).find("a").css({"margin-left":"-"+(h*m)+"px"})}if(g.readOnly){j.addClass("star-rating-readonly")}else{j.addClass("star-rating-live").mouseover(function(){a(this).rating("fill");a(this).rating("focus")}).mouseout(function(){a(this).rating("draw");a(this).rating("blur")}).click(function(){a(this).rating("select")})}if(this.checked){g.current=j}l.hide();l.change(function(){a(this).rating("select")});j.data("rating.input",l.data("rating.star",j));g.stars[g.stars.length]=j[0];g.inputs[g.inputs.length]=l[0];g.rater=k[e]=n;g.context=f;l.data("rating",g);n.data("rating",g);j.data("rating",g);f.data("rating",k)});a(".rating-to-be-drawn").rating("draw").removeClass("rating-to-be-drawn");return this};a.extend(a.fn.rating,{calls:0,focus:function(){var d=this.data("rating");if(!d){return this}if(!d.focus){return this}var c=a(this).data("rating.input")||a(this.tagName=="INPUT"?this:null);if(d.focus){d.focus.apply(c[0],[c.val(),a("a",c.data("rating.star"))[0]])}},blur:function(){var d=this.data("rating");if(!d){return this}if(!d.blur){return this}var c=a(this).data("rating.input")||a(this.tagName=="INPUT"?this:null);if(d.blur){d.blur.apply(c[0],[c.val(),a("a",c.data("rating.star"))[0]])}},fill:function(){var c=this.data("rating");if(!c){return this}if(c.readOnly){return}this.rating("drain");this.prevAll().andSelf().filter(".rater-"+c.serial).addClass("star-rating-hover")},drain:function(){var c=this.data("rating");if(!c){return this}if(c.readOnly){return}c.rater.children().filter(".rater-"+c.serial).removeClass("star-rating-on").removeClass("star-rating-hover")},draw:function(){var c=this.data("rating");if(!c){return this}this.rating("drain");if(c.current){c.current.data("rating.input").attr("checked","checked");c.current.prevAll().andSelf().filter(".rater-"+c.serial).addClass("star-rating-on")}else{a(c.inputs).removeAttr("checked")}c.cancel[c.readOnly||c.required?"hide":"show"]();this.siblings()[c.readOnly?"addClass":"removeClass"]("star-rating-readonly")},select:function(d){var e=this.data("rating");if(!e){return this}if(e.readOnly){return}e.current=null;if(typeof d!="undefined"){if(typeof d=="number"){return a(e.stars[d]).rating("select")}if(typeof d=="string"){a.each(e.stars,function(){if(a(this).data("rating.input").val()==d){a(this).rating("select")}})}}else{e.current=this[0].tagName=="INPUT"?this.data("rating.star"):(this.is(".rater-"+e.serial)?this:null)}this.data("rating",e);this.rating("draw");var c=a(e.current?e.current.data("rating.input"):null);if(e.callback){e.callback.apply(c[0],[c.val(),a("a",e.current)[0]])}},readOnly:function(c,d){var e=this.data("rating");if(!e){return this}e.readOnly=c||c==undefined?true:false;if(d){a(e.inputs).attr("disabled","disabled")}else{a(e.inputs).removeAttr("disabled")}this.data("rating",e);this.rating("draw")},disable:function(){this.rating("readOnly",true,true)},enable:function(){this.rating("readOnly",false,false)}});a.fn.rating.options={cancel:"Cancel Rating",cancelValue:"",split:0,starWidth:16};a(function(){a("input[type=radio].star").rating()})})(jQuery)};

(function(C){var s="colorbox",q="hover",y=true,Q=false,V,o=!C.support.opacity,S=o&&!window.XMLHttpRequest,z="cbox_open",K="cbox_load",v="cbox_complete",J="cbox_cleanup",p="cbox_closed",N="resize.cbox_resize",H,T,U,d,A,l,b,G,c,O,E,h,g,t,k,n,L,m,I,u,W,j,f,a,r,i,B,P,x,M,D={transition:"elastic",speed:350,width:Q,height:Q,innerWidth:Q,innerHeight:Q,initialWidth:"400",initialHeight:"400",maxWidth:Q,maxHeight:Q,relVerticalPos:0.5,scalePhotos:y,scrolling:y,inline:Q,html:Q,iframe:Q,photo:Q,href:Q,title:Q,rel:Q,opacity:0.9,preloading:y,current:"image {current} of {total}",previous:"previous",next:"next",close:"close",open:Q,overlayClose:y,escClose:y,slideshow:Q,slideshowAuto:y,slideshowSpeed:2500,slideshowStart:"start slideshow",slideshowStop:"stop slideshow",onOpen:Q,onLoad:Q,onComplete:Q,onCleanup:Q,onClosed:Q};function F(X,Y){Y=Y==="x"?O.width():O.height();return(typeof X==="string")?Math.round((X.match(/%/)?(Y/100)*parseInt(X,10):parseInt(X,10))):X}function w(X){X=C.isFunction(X)?X.call(r):X;return P.photo||X.match(/\.(gif|png|jpg|jpeg|bmp)(?:\?([^#]*))?(?:#(\.*))?$/i)}function R(){for(var X in P){if(C.isFunction(P[X])&&X.substring(0,2)!=="on"){P[X]=P[X].call(r)}}}function e(Y){r=Y;P=C(r).data(s);R();var X=P.rel||r.rel;if(X&&X!=="nofollow"){c=C(".cboxElement").filter(function(){var Z=C(this).data(s).rel||this.rel;return(Z===X)});B=c.index(r);if(B<0){c=c.add(r);B=c.length-1}}else{c=C(r);B=0}if(!x){x=y;M=y;i=r;i.blur();C().bind("keydown.cbox_close",function(Z){if(Z.keyCode===27&&P.escClose){Z.preventDefault();V.close()}}).bind("keydown.cbox_arrows",function(Z){if(c.length>1){if(Z.keyCode===37){Z.preventDefault();I.click()}else{if(Z.keyCode===39){Z.preventDefault();m.click()}}}});if(P.overlayClose){H.css({cursor:"pointer"}).one("click",V.close)}C.event.trigger(z);if(P.onOpen){P.onOpen.call(r)}u.html(P.close);H.css({opacity:P.opacity}).show();P.w=F(P.initialWidth,"x");P.h=F(P.initialHeight,"y");V.position(0);if(S){O.bind("resize.cboxie6 scroll.cboxie6",function(){H.css({width:O.width(),height:O.height(),top:O.scrollTop(),left:O.scrollLeft()})}).trigger("scroll.cboxie6")}}V.slideshow();V.load()}V=C.fn.colorbox=function(X,Z){var Y=this;if(!Y.length){if(Y.selector===""){Y=C(Y);X.open=y}else{return this}}Y.each(function(){var aa=C.extend({},C(this).data(s)?C(this).data(s):D,X);C(this).data(s,aa).addClass("cboxElement");if(Z){C(this).data(s).onComplete=Z}});if(X&&X.open){e(Y)}return this};V.init=function(){function X(Y){return C('<div id="cbox'+Y+'"/>')}O=C(window);T=C('<div id="colorbox"/>');H=X("Overlay").hide();U=X("Wrapper");d=X("Content").append(E=X("LoadedContent").css({width:0,height:0}),g=X("LoadingOverlay"),t=X("LoadingGraphic"),k=X("Title"),n=X("Current"),L=X("Slideshow"),m=X("Next"),I=X("Previous"),u=X("Close"));U.append(C("<div/>").append(X("TopLeft"),A=X("TopCenter"),X("TopRight")),C("<div/>").append(l=X("MiddleLeft"),d,b=X("MiddleRight")),C("<div/>").append(X("BottomLeft"),G=X("BottomCenter"),X("BottomRight"))).children().children().css({"float":"left"});h=C("<div style='position:absolute; top:0; left:0; width:0; height:0; overflow:hidden;'/>");C("body").prepend(H,T.append(U),h);if(o){T.addClass("cboxIE");if(S){H.css("position","absolute")}}d.children().addClass(q).mouseover(function(){C(this).addClass(q)}).mouseout(function(){C(this).removeClass(q)}).hide();W=A.height()+G.height()+d.outerHeight(y)-d.height();j=l.width()+b.width()+d.outerWidth(y)-d.width();f=E.outerHeight(y);a=E.outerWidth(y);T.css({"padding-bottom":W,"padding-right":j}).hide();m.click(V.next);I.click(V.prev);u.click(V.close);d.children().removeClass(q);C(".cboxElement").live("click",function(Y){if(Y.button!==0){return y}else{e(this);return Q}})};V.position=function(ac,Z){var ab,Y=O.height(),aa=Math.max(Y-P.h-f-W,0)*(P.relVerticalPos)+O.scrollTop(),X=Math.max(document.documentElement.clientWidth-P.w-a-j,0)/2+O.scrollLeft();ab=(T.width()===P.w+a&&T.height()===P.h+f)?0:ac;U[0].style.width=U[0].style.height="9999px";function ad(ae){A[0].style.width=G[0].style.width=d[0].style.width=ae.style.width;t[0].style.height=g[0].style.height=d[0].style.height=l[0].style.height=b[0].style.height=ae.style.height}T.dequeue().animate({width:P.w+a,height:P.h+f,top:aa,left:X},{duration:ab,complete:function(){ad(this);M=Q;U[0].style.width=(P.w+a+j)+"px";U[0].style.height=(P.h+f+W)+"px";if(Z){Z()}},step:function(){ad(this)}})};V.resize=function(ab){if(!x){return}var ac,aa,Y,ae,ai,X,ag,Z=P.transition==="none"?0:P.speed;O.unbind(N);if(!ab){ag=setTimeout(function(){var aj=E.wrapInner("<div style='overflow:auto'></div>").children();P.h=aj.height();E.css({height:P.h});aj.replaceWith(aj.children());V.position(Z)},1);return}E.remove();E=C('<div id="cboxLoadedContent"/>').html(ab);function af(){P.w=P.w||E.width();P.w=P.mw&&P.mw<P.w?P.mw:P.w;return P.w}function ad(){P.h=P.h||E.height();P.h=P.mh&&P.mh<P.h?P.mh:P.h;return P.h}E.hide().appendTo(h).css({width:af(),overflow:P.scrolling?"auto":"hidden"}).css({height:ad()}).prependTo(d);C("#cboxPhoto").css({cssFloat:"none"});if(S){C("select:not(#colorbox select)").filter(function(){return this.style.visibility!=="hidden"}).css({visibility:"hidden"}).one(J,function(){this.style.visibility="inherit"})}function ah(aj){V.position(aj,function(){if(!x){return}if(o){if(X){E.fadeIn(100)}T[0].style.removeAttribute("filter")}d.children().show();if(P.iframe){E.append("<iframe id='cboxIframe'"+(P.scrolling?" ":"scrolling='no'")+" name='iframe_"+new Date().getTime()+"' frameborder=0 src='"+(P.href||r.href)+"' "+(o?"allowtransparency='true'":"")+" />")}g.hide();t.hide();L.hide();if(c.length>1){n.html(P.current.replace(/\{current\}/,B+1).replace(/\{total\}/,c.length));m.html(P.next);I.html(P.previous);if(P.slideshow){L.show()}}else{n.hide();m.hide();I.hide()}k.html(P.title||r.title);C.event.trigger(v);if(P.onComplete){P.onComplete.call(r)}if(P.transition==="fade"){T.fadeTo(Z,1,function(){if(o){T[0].style.removeAttribute("filter")}})}O.bind(N,function(){V.position(0)})})}if((P.transition==="fade"&&T.fadeTo(Z,0,function(){ah(0)}))||ah(Z)){}if(P.preloading&&c.length>1){aa=B>0?c[B-1]:c[c.length-1];ae=B<c.length-1?c[B+1]:c[0];ai=C(ae).data(s).href||ae.href;Y=C(aa).data(s).href||aa.href}};V.load=function(){var Y,X,aa,Z=V.resize;M=y;r=c[B];P=C(r).data(s);R();C.event.trigger(K);if(P.onLoad){P.onLoad.call(r)}P.h=P.height?F(P.height,"y")-f-W:P.innerHeight?F(P.innerHeight,"y"):Q;P.w=P.width?F(P.width,"x")-a-j:P.innerWidth?F(P.innerWidth,"x"):Q;P.mw=P.w;P.mh=P.h;if(P.maxWidth){P.mw=F(P.maxWidth,"x")-a-j;P.mw=P.w&&P.w<P.mw?P.w:P.mw}if(P.maxHeight){P.mh=F(P.maxHeight,"y")-f-W;P.mh=P.h&&P.h<P.mh?P.h:P.mh}Y=P.href||C(r).attr("href");g.show();t.show();u.show();if(P.inline){C('<div id="cboxInlineTemp" />').hide().insertBefore(C(Y)[0]).bind(K+" "+J,function(){C(this).replaceWith(E.children())});Z(C(Y))}else{if(P.iframe){Z(" ")}else{if(P.html){Z(P.html)}else{if(w(Y)){X=new Image();X.onload=function(){var ab;X.onload=null;X.id="cboxPhoto";C(X).css({margin:"auto",border:"none",display:"block",cssFloat:"left"});if(P.scalePhotos){aa=function(){X.height-=X.height*ab;X.width-=X.width*ab};if(P.mw&&X.width>P.mw){ab=(X.width-P.mw)/X.width;aa()}if(P.mh&&X.height>P.mh){ab=(X.height-P.mh)/X.height;aa()}}if(P.h){X.style.marginTop=Math.max(P.h-X.height,0)/2+"px"}Z(X);if(c.length>1){C(X).css({cursor:"pointer"}).click(V.next)}if(o){X.style.msInterpolationMode="bicubic"}};X.src=Y}else{C("<div />").appendTo(h).load(Y,function(ab,ac){if(ac==="success"){Z(this)}else{Z(C("<p>Request unsuccessful.</p>"))}})}}}}};V.next=function(){if(!M){B=B<c.length-1?B+1:0;V.load()}};V.prev=function(){if(!M){B=B>0?B-1:c.length-1;V.load()}};V.slideshow=function(){var Y,X,Z="cboxSlideshow_";L.bind(p,function(){L.unbind();clearTimeout(X);T.removeClass(Z+"off "+Z+"on")});function aa(){L.text(P.slideshowStop).bind(v,function(){X=setTimeout(V.next,P.slideshowSpeed)}).bind(K,function(){clearTimeout(X)}).one("click",function(){Y();C(this).removeClass(q)});T.removeClass(Z+"off").addClass(Z+"on")}Y=function(){clearTimeout(X);L.text(P.slideshowStart).unbind(v+" "+K).one("click",function(){aa();X=setTimeout(V.next,P.slideshowSpeed);C(this).removeClass(q)});T.removeClass(Z+"on").addClass(Z+"off")};if(P.slideshow&&c.length>1){if(P.slideshowAuto){aa()}else{Y()}}};V.close=function(){C.event.trigger(J);if(P.onCleanup){P.onCleanup.call(r)}x=Q;C().unbind("keydown.cbox_close keydown.cbox_arrows");O.unbind(N+" resize.cboxie6 scroll.cboxie6");H.css({cursor:"auto"}).fadeOut("fast");T.stop(y,Q).fadeOut("fast",function(){E.remove();T.css({opacity:1});d.children().hide();try{i.focus()}catch(X){}C.event.trigger(p);if(P.onClosed){P.onClosed.call(r)}})};V.element=function(){return C(r)};V.settings=D;C(V.init)}(jQuery));

/*
 * jquery.qtip. The jQuery tooltip plugin
 *
 * Copyright (c) 2009 Craig Thompson
 * http://craigsworks.com
 *
 * Licensed under MIT
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Launch  : February 2009
 * Version : 1.0.0-rc3
 * Released: Tuesday 12th May, 2009 - 00:00
 * Debug: jquery.qtip.debug.js
 */
(function(f){f.fn.qtip=function(B,u){var y,t,A,s,x,w,v,z;if(typeof B=="string"){if(typeof f(this).data("qtip")!=="object"){f.fn.qtip.log.error.call(self,1,f.fn.qtip.constants.NO_TOOLTIP_PRESENT,false)}if(B=="api"){return f(this).data("qtip").interfaces[f(this).data("qtip").current]}else{if(B=="interfaces"){return f(this).data("qtip").interfaces}}}else{if(!B){B={}}if(typeof B.content!=="object"||(B.content.jquery&&B.content.length>0)){B.content={text:B.content}}if(typeof B.content.title!=="object"){B.content.title={text:B.content.title}}if(typeof B.position!=="object"){B.position={corner:B.position}}if(typeof B.position.corner!=="object"){B.position.corner={target:B.position.corner,tooltip:B.position.corner}}if(typeof B.show!=="object"){B.show={when:B.show}}if(typeof B.show.when!=="object"){B.show.when={event:B.show.when}}if(typeof B.show.effect!=="object"){B.show.effect={type:B.show.effect}}if(typeof B.hide!=="object"){B.hide={when:B.hide}}if(typeof B.hide.when!=="object"){B.hide.when={event:B.hide.when}}if(typeof B.hide.effect!=="object"){B.hide.effect={type:B.hide.effect}}if(typeof B.style!=="object"){B.style={name:B.style}}B.style=c(B.style);s=f.extend(true,{},f.fn.qtip.defaults,B);s.style=a.call({options:s},s.style);s.user=f.extend(true,{},B)}return f(this).each(function(){if(typeof B=="string"){w=B.toLowerCase();A=f(this).qtip("interfaces");if(typeof A=="object"){if(u===true&&w=="destroy"){while(A.length>0){A[A.length-1].destroy()}}else{if(u!==true){A=[f(this).qtip("api")]}for(y=0;y<A.length;y++){if(w=="destroy"){A[y].destroy()}else{if(A[y].status.rendered===true){if(w=="show"){A[y].show()}else{if(w=="hide"){A[y].hide()}else{if(w=="focus"){A[y].focus()}else{if(w=="disable"){A[y].disable(true)}else{if(w=="enable"){A[y].disable(false)}}}}}}}}}}}else{v=f.extend(true,{},s);v.hide.effect.length=s.hide.effect.length;v.show.effect.length=s.show.effect.length;if(v.position.container===false){v.position.container=f(document.body)}if(v.position.target===false){v.position.target=f(this)}if(v.show.when.target===false){v.show.when.target=f(this)}if(v.hide.when.target===false){v.hide.when.target=f(this)}t=f.fn.qtip.interfaces.length;for(y=0;y<t;y++){if(typeof f.fn.qtip.interfaces[y]=="undefined"){t=y;break}}x=new d(f(this),v,t);f.fn.qtip.interfaces[t]=x;if(typeof f(this).data("qtip")=="object"){if(typeof f(this).attr("qtip")==="undefined"){f(this).data("qtip").current=f(this).data("qtip").interfaces.length}f(this).data("qtip").interfaces.push(x)}else{f(this).data("qtip",{current:0,interfaces:[x]})}if(v.content.prerender===false&&v.show.when.event!==false&&v.show.ready!==true){v.show.when.target.bind(v.show.when.event+".qtip-"+t+"-create",{qtip:t},function(C){z=f.fn.qtip.interfaces[C.data.qtip];z.options.show.when.target.unbind(z.options.show.when.event+".qtip-"+C.data.qtip+"-create");z.cache.mouse={x:C.pageX,y:C.pageY};p.call(z);z.options.show.when.target.trigger(z.options.show.when.event)})}else{x.cache.mouse={x:v.show.when.target.offset().left,y:v.show.when.target.offset().top};p.call(x)}}})};function d(u,t,v){var s=this;s.id=v;s.options=t;s.status={animated:false,rendered:false,disabled:false,focused:false};s.elements={target:u.addClass(s.options.style.classes.target),tooltip:null,wrapper:null,content:null,contentWrapper:null,title:null,button:null,tip:null,bgiframe:null};s.cache={mouse:{},position:{},toggle:0};s.timers={};f.extend(s,s.options.api,{show:function(y){var x,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"show")}if(s.elements.tooltip.css("display")!=="none"){return s}s.elements.tooltip.stop(true,false);x=s.beforeShow.call(s,y);if(x===false){return s}function w(){if(s.options.position.type!=="static"){s.focus()}s.onShow.call(s,y);if(f.browser.msie){s.elements.tooltip.get(0).style.removeAttribute("filter")}}s.cache.toggle=1;if(s.options.position.type!=="static"){s.updatePosition(y,(s.options.show.effect.length>0))}if(typeof s.options.show.solo=="object"){z=f(s.options.show.solo)}else{if(s.options.show.solo===true){z=f("div.qtip").not(s.elements.tooltip)}}if(z){z.each(function(){if(f(this).qtip("api").status.rendered===true){f(this).qtip("api").hide()}})}if(typeof s.options.show.effect.type=="function"){s.options.show.effect.type.call(s.elements.tooltip,s.options.show.effect.length);s.elements.tooltip.queue(function(){w();f(this).dequeue()})}else{switch(s.options.show.effect.type.toLowerCase()){case"fade":s.elements.tooltip.fadeIn(s.options.show.effect.length,w);break;case"slide":s.elements.tooltip.slideDown(s.options.show.effect.length,function(){w();if(s.options.position.type!=="static"){s.updatePosition(y,true)}});break;case"grow":s.elements.tooltip.show(s.options.show.effect.length,w);break;default:s.elements.tooltip.show(null,w);break}s.elements.tooltip.addClass(s.options.style.classes.active)}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_SHOWN,"show")},hide:function(y){var x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"hide")}else{if(s.elements.tooltip.css("display")==="none"){return s}}clearTimeout(s.timers.show);s.elements.tooltip.stop(true,false);x=s.beforeHide.call(s,y);if(x===false){return s}function w(){s.onHide.call(s,y)}s.cache.toggle=0;if(typeof s.options.hide.effect.type=="function"){s.options.hide.effect.type.call(s.elements.tooltip,s.options.hide.effect.length);s.elements.tooltip.queue(function(){w();f(this).dequeue()})}else{switch(s.options.hide.effect.type.toLowerCase()){case"fade":s.elements.tooltip.fadeOut(s.options.hide.effect.length,w);break;case"slide":s.elements.tooltip.slideUp(s.options.hide.effect.length,w);break;case"grow":s.elements.tooltip.hide(s.options.hide.effect.length,w);break;default:s.elements.tooltip.hide(null,w);break}s.elements.tooltip.removeClass(s.options.style.classes.active)}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_HIDDEN,"hide")},updatePosition:function(w,x){var C,G,L,J,H,E,y,I,B,D,K,A,F,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updatePosition")}else{if(s.options.position.type=="static"){return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.CANNOT_POSITION_STATIC,"updatePosition")}}G={position:{left:0,top:0},dimensions:{height:0,width:0},corner:s.options.position.corner.target};L={position:s.getPosition(),dimensions:s.getDimensions(),corner:s.options.position.corner.tooltip};if(s.options.position.target!=="mouse"){if(s.options.position.target.get(0).nodeName.toLowerCase()=="area"){J=s.options.position.target.attr("coords").split(",");for(C=0;C<J.length;C++){J[C]=parseInt(J[C])}H=s.options.position.target.parent("map").attr("name");E=f('img[usemap="#'+H+'"]:first').offset();G.position={left:Math.floor(E.left+J[0]),top:Math.floor(E.top+J[1])};switch(s.options.position.target.attr("shape").toLowerCase()){case"rect":G.dimensions={width:Math.ceil(Math.abs(J[2]-J[0])),height:Math.ceil(Math.abs(J[3]-J[1]))};break;case"circle":G.dimensions={width:J[2]+1,height:J[2]+1};break;case"poly":G.dimensions={width:J[0],height:J[1]};for(C=0;C<J.length;C++){if(C%2==0){if(J[C]>G.dimensions.width){G.dimensions.width=J[C]}if(J[C]<J[0]){G.position.left=Math.floor(E.left+J[C])}}else{if(J[C]>G.dimensions.height){G.dimensions.height=J[C]}if(J[C]<J[1]){G.position.top=Math.floor(E.top+J[C])}}}G.dimensions.width=G.dimensions.width-(G.position.left-E.left);G.dimensions.height=G.dimensions.height-(G.position.top-E.top);break;default:return f.fn.qtip.log.error.call(s,4,f.fn.qtip.constants.INVALID_AREA_SHAPE,"updatePosition");break}G.dimensions.width-=2;G.dimensions.height-=2}else{if(s.options.position.target.add(document.body).length===1){G.position={left:f(document).scrollLeft(),top:f(document).scrollTop()};G.dimensions={height:f(window).height(),width:f(window).width()}}else{if(typeof s.options.position.target.attr("qtip")!=="undefined"){G.position=s.options.position.target.qtip("api").cache.position}else{G.position=s.options.position.target.offset()}G.dimensions={height:s.options.position.target.outerHeight(),width:s.options.position.target.outerWidth()}}}y=f.extend({},G.position);if(G.corner.search(/right/i)!==-1){y.left+=G.dimensions.width}if(G.corner.search(/bottom/i)!==-1){y.top+=G.dimensions.height}if(G.corner.search(/((top|bottom)Middle)|center/)!==-1){y.left+=(G.dimensions.width/2)}if(G.corner.search(/((left|right)Middle)|center/)!==-1){y.top+=(G.dimensions.height/2)}}else{G.position=y={left:s.cache.mouse.x,top:s.cache.mouse.y};G.dimensions={height:1,width:1}}if(L.corner.search(/right/i)!==-1){y.left-=L.dimensions.width}if(L.corner.search(/bottom/i)!==-1){y.top-=L.dimensions.height}if(L.corner.search(/((top|bottom)Middle)|center/)!==-1){y.left-=(L.dimensions.width/2)}if(L.corner.search(/((left|right)Middle)|center/)!==-1){y.top-=(L.dimensions.height/2)}I=(f.browser.msie)?1:0;B=(f.browser.msie&&parseInt(f.browser.version.charAt(0))===6)?1:0;if(s.options.style.border.radius>0){if(L.corner.search(/Left/)!==-1){y.left-=s.options.style.border.radius}else{if(L.corner.search(/Right/)!==-1){y.left+=s.options.style.border.radius}}if(L.corner.search(/Top/)!==-1){y.top-=s.options.style.border.radius}else{if(L.corner.search(/Bottom/)!==-1){y.top+=s.options.style.border.radius}}}if(I){if(L.corner.search(/top/)!==-1){y.top-=I}else{if(L.corner.search(/bottom/)!==-1){y.top+=I}}if(L.corner.search(/left/)!==-1){y.left-=I}else{if(L.corner.search(/right/)!==-1){y.left+=I}}if(L.corner.search(/leftMiddle|rightMiddle/)!==-1){y.top-=1}}if(s.options.position.adjust.screen===true){y=o.call(s,y,G,L)}if(s.options.position.target==="mouse"&&s.options.position.adjust.mouse===true){if(s.options.position.adjust.screen===true&&s.elements.tip){K=s.elements.tip.attr("rel")}else{K=s.options.position.corner.tooltip}y.left+=(K.search(/right/i)!==-1)?-6:6;y.top+=(K.search(/bottom/i)!==-1)?-6:6}if(!s.elements.bgiframe&&f.browser.msie&&parseInt(f.browser.version.charAt(0))==6){f("select, object").each(function(){A=f(this).offset();A.bottom=A.top+f(this).height();A.right=A.left+f(this).width();if(y.top+L.dimensions.height>=A.top&&y.left+L.dimensions.width>=A.left){k.call(s)}})}y.left+=s.options.position.adjust.x;y.top+=s.options.position.adjust.y;F=s.getPosition();if(y.left!=F.left||y.top!=F.top){z=s.beforePositionUpdate.call(s,w);if(z===false){return s}s.cache.position=y;if(x===true){s.status.animated=true;s.elements.tooltip.animate(y,200,"swing",function(){s.status.animated=false})}else{s.elements.tooltip.css(y)}s.onPositionUpdate.call(s,w);if(typeof w!=="undefined"&&w.type&&w.type!=="mousemove"){f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_POSITION_UPDATED,"updatePosition")}}return s},updateWidth:function(w){var x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateWidth")}else{if(w&&typeof w!=="number"){return f.fn.qtip.log.error.call(s,2,"newWidth must be of type number","updateWidth")}}x=s.elements.contentWrapper.siblings().add(s.elements.tip).add(s.elements.button);if(!w){if(typeof s.options.style.width.value=="number"){w=s.options.style.width.value}else{s.elements.tooltip.css({width:"auto"});x.hide();if(f.browser.msie){s.elements.wrapper.add(s.elements.contentWrapper.children()).css({zoom:"normal"})}w=s.getDimensions().width+1;if(!s.options.style.width.value){if(w>s.options.style.width.max){w=s.options.style.width.max}if(w<s.options.style.width.min){w=s.options.style.width.min}}}}if(w%2!==0){w-=1}s.elements.tooltip.width(w);x.show();if(s.options.style.border.radius){s.elements.tooltip.find(".qtip-betweenCorners").each(function(y){f(this).width(w-(s.options.style.border.radius*2))})}if(f.browser.msie){s.elements.wrapper.add(s.elements.contentWrapper.children()).css({zoom:"1"});s.elements.wrapper.width(w);if(s.elements.bgiframe){s.elements.bgiframe.width(w).height(s.getDimensions.height)}}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_WIDTH_UPDATED,"updateWidth")},updateStyle:function(w){var z,A,x,y,B;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateStyle")}else{if(typeof w!=="string"||!f.fn.qtip.styles[w]){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.STYLE_NOT_DEFINED,"updateStyle")}}s.options.style=a.call(s,f.fn.qtip.styles[w],s.options.user.style);s.elements.content.css(q(s.options.style));if(s.options.content.title.text!==false){s.elements.title.css(q(s.options.style.title,true))}s.elements.contentWrapper.css({borderColor:s.options.style.border.color});if(s.options.style.tip.corner!==false){if(f("<canvas>").get(0).getContext){z=s.elements.tooltip.find(".qtip-tip canvas:first");x=z.get(0).getContext("2d");x.clearRect(0,0,300,300);y=z.parent("div[rel]:first").attr("rel");B=b(y,s.options.style.tip.size.width,s.options.style.tip.size.height);h.call(s,z,B,s.options.style.tip.color||s.options.style.border.color)}else{if(f.browser.msie){z=s.elements.tooltip.find('.qtip-tip [nodeName="shape"]');z.attr("fillcolor",s.options.style.tip.color||s.options.style.border.color)}}}if(s.options.style.border.radius>0){s.elements.tooltip.find(".qtip-betweenCorners").css({backgroundColor:s.options.style.border.color});if(f("<canvas>").get(0).getContext){A=g(s.options.style.border.radius);s.elements.tooltip.find(".qtip-wrapper canvas").each(function(){x=f(this).get(0).getContext("2d");x.clearRect(0,0,300,300);y=f(this).parent("div[rel]:first").attr("rel");r.call(s,f(this),A[y],s.options.style.border.radius,s.options.style.border.color)})}else{if(f.browser.msie){s.elements.tooltip.find('.qtip-wrapper [nodeName="arc"]').each(function(){f(this).attr("fillcolor",s.options.style.border.color)})}}}return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_STYLE_UPDATED,"updateStyle")},updateContent:function(A,y){var z,x,w;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateContent")}else{if(!A){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.NO_CONTENT_PROVIDED,"updateContent")}}z=s.beforeContentUpdate.call(s,A);if(typeof z=="string"){A=z}else{if(z===false){return}}if(f.browser.msie){s.elements.contentWrapper.children().css({zoom:"normal"})}if(A.jquery&&A.length>0){A.clone(true).appendTo(s.elements.content).show()}else{s.elements.content.html(A)}x=s.elements.content.find("img[complete=false]");if(x.length>0){w=0;x.each(function(C){f('<img src="'+f(this).attr("src")+'" />').load(function(){if(++w==x.length){B()}})})}else{B()}function B(){s.updateWidth();if(y!==false){if(s.options.position.type!=="static"){s.updatePosition(s.elements.tooltip.is(":visible"),true)}if(s.options.style.tip.corner!==false){n.call(s)}}}s.onContentUpdate.call(s);return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_CONTENT_UPDATED,"loadContent")},loadContent:function(w,z,A){var y;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"loadContent")}y=s.beforeContentLoad.call(s);if(y===false){return s}if(A=="post"){f.post(w,z,x)}else{f.get(w,z,x)}function x(B){s.onContentLoad.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_CONTENT_LOADED,"loadContent");s.updateContent(B)}return s},updateTitle:function(w){if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"updateTitle")}else{if(!w){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.NO_CONTENT_PROVIDED,"updateTitle")}}returned=s.beforeTitleUpdate.call(s);if(returned===false){return s}if(s.elements.button){s.elements.button=s.elements.button.clone(true)}s.elements.title.html(w);if(s.elements.button){s.elements.title.prepend(s.elements.button)}s.onTitleUpdate.call(s);return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_TITLE_UPDATED,"updateTitle")},focus:function(A){var y,x,w,z;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"focus")}else{if(s.options.position.type=="static"){return f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.CANNOT_FOCUS_STATIC,"focus")}}y=parseInt(s.elements.tooltip.css("z-index"));x=6000+f("div.qtip[qtip]").length-1;if(!s.status.focused&&y!==x){z=s.beforeFocus.call(s,A);if(z===false){return s}f("div.qtip[qtip]").not(s.elements.tooltip).each(function(){if(f(this).qtip("api").status.rendered===true){w=parseInt(f(this).css("z-index"));if(typeof w=="number"&&w>-1){f(this).css({zIndex:parseInt(f(this).css("z-index"))-1})}f(this).qtip("api").status.focused=false}});s.elements.tooltip.css({zIndex:x});s.status.focused=true;s.onFocus.call(s,A);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_FOCUSED,"focus")}return s},disable:function(w){if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"disable")}if(w){if(!s.status.disabled){s.status.disabled=true;f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_DISABLED,"disable")}else{f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.TOOLTIP_ALREADY_DISABLED,"disable")}}else{if(s.status.disabled){s.status.disabled=false;f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_ENABLED,"disable")}else{f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.TOOLTIP_ALREADY_ENABLED,"disable")}}return s},destroy:function(){var w,x,y;x=s.beforeDestroy.call(s);if(x===false){return s}if(s.status.rendered){s.options.show.when.target.unbind("mousemove.qtip",s.updatePosition);s.options.show.when.target.unbind("mouseout.qtip",s.hide);s.options.show.when.target.unbind(s.options.show.when.event+".qtip");s.options.hide.when.target.unbind(s.options.hide.when.event+".qtip");s.elements.tooltip.unbind(s.options.hide.when.event+".qtip");s.elements.tooltip.unbind("mouseover.qtip",s.focus);s.elements.tooltip.remove()}else{s.options.show.when.target.unbind(s.options.show.when.event+".qtip-create")}if(typeof s.elements.target.data("qtip")=="object"){y=s.elements.target.data("qtip").interfaces;if(typeof y=="object"&&y.length>0){for(w=0;w<y.length-1;w++){if(y[w].id==s.id){y.splice(w,1)}}}}delete f.fn.qtip.interfaces[s.id];if(typeof y=="object"&&y.length>0){s.elements.target.data("qtip").current=y.length-1}else{s.elements.target.removeData("qtip")}s.onDestroy.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_DESTROYED,"destroy");return s.elements.target},getPosition:function(){var w,x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"getPosition")}w=(s.elements.tooltip.css("display")!=="none")?false:true;if(w){s.elements.tooltip.css({visiblity:"hidden"}).show()}x=s.elements.tooltip.offset();if(w){s.elements.tooltip.css({visiblity:"visible"}).hide()}return x},getDimensions:function(){var w,x;if(!s.status.rendered){return f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.TOOLTIP_NOT_RENDERED,"getDimensions")}w=(!s.elements.tooltip.is(":visible"))?true:false;if(w){s.elements.tooltip.css({visiblity:"hidden"}).show()}x={height:s.elements.tooltip.outerHeight(),width:s.elements.tooltip.outerWidth()};if(w){s.elements.tooltip.css({visiblity:"visible"}).hide()}return x}})}function p(){var s,w,u,t,v,y,x;s=this;s.beforeRender.call(s);s.status.rendered=true;s.elements.tooltip='<div qtip="'+s.id+'" class="qtip '+(s.options.style.classes.tooltip||s.options.style)+'"style="display:none; -moz-border-radius:0; -webkit-border-radius:0; border-radius:0;position:'+s.options.position.type+';">  <div class="qtip-wrapper" style="position:relative; text-align:left;">    <div class="qtip-contentWrapper" style="overflow:hidden;">       <div class="qtip-content '+s.options.style.classes.content+'"></div></div></div></div>';s.elements.tooltip=f(s.elements.tooltip);s.elements.tooltip.appendTo(s.options.position.container);s.elements.tooltip.data("qtip",{current:0,interfaces:[s]});s.elements.wrapper=s.elements.tooltip.children("div:first");s.elements.contentWrapper=s.elements.wrapper.children("div:first").css({background:s.options.style.background});s.elements.content=s.elements.contentWrapper.children("div:first").css(q(s.options.style));if(f.browser.msie){s.elements.wrapper.add(s.elements.content).css({zoom:1})}if(s.options.hide.when.event=="unfocus"){s.elements.tooltip.attr("unfocus",true)}if(typeof s.options.style.width.value=="number"){s.updateWidth()}if(f("<canvas>").get(0).getContext||f.browser.msie){if(s.options.style.border.radius>0){m.call(s)}else{s.elements.contentWrapper.css({border:s.options.style.border.width+"px solid "+s.options.style.border.color})}if(s.options.style.tip.corner!==false){e.call(s)}}else{s.elements.contentWrapper.css({border:s.options.style.border.width+"px solid "+s.options.style.border.color});s.options.style.border.radius=0;s.options.style.tip.corner=false;f.fn.qtip.log.error.call(s,2,f.fn.qtip.constants.CANVAS_VML_NOT_SUPPORTED,"render")}if((typeof s.options.content.text=="string"&&s.options.content.text.length>0)||(s.options.content.text.jquery&&s.options.content.text.length>0)){u=s.options.content.text}else{if(typeof s.elements.target.attr("title")=="string"&&s.elements.target.attr("title").length>0){u=s.elements.target.attr("title").replace("\\n","<br />");s.elements.target.attr("title","")}else{if(typeof s.elements.target.attr("alt")=="string"&&s.elements.target.attr("alt").length>0){u=s.elements.target.attr("alt").replace("\\n","<br />");s.elements.target.attr("alt","")}else{u=" ";f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.NO_VALID_CONTENT,"render")}}}if(s.options.content.title.text!==false){j.call(s)}s.updateContent(u);l.call(s);if(s.options.show.ready===true){s.show()}if(s.options.content.url!==false){t=s.options.content.url;v=s.options.content.data;y=s.options.content.method||"get";s.loadContent(t,v,y)}s.onRender.call(s);f.fn.qtip.log.error.call(s,1,f.fn.qtip.constants.EVENT_RENDERED,"render")}function m(){var F,z,t,B,x,E,u,G,D,y,w,C,A,s,v;F=this;F.elements.wrapper.find(".qtip-borderBottom, .qtip-borderTop").remove();t=F.options.style.border.width;B=F.options.style.border.radius;x=F.options.style.border.color||F.options.style.tip.color;E=g(B);u={};for(z in E){u[z]='<div rel="'+z+'" style="'+((z.search(/Left/)!==-1)?"left":"right")+":0; position:absolute; height:"+B+"px; width:"+B+'px; overflow:hidden; line-height:0.1px; font-size:1px">';if(f("<canvas>").get(0).getContext){u[z]+='<canvas height="'+B+'" width="'+B+'" style="vertical-align: top"></canvas>'}else{if(f.browser.msie){G=B*2+3;u[z]+='<v:arc stroked="false" fillcolor="'+x+'" startangle="'+E[z][0]+'" endangle="'+E[z][1]+'" style="width:'+G+"px; height:"+G+"px; margin-top:"+((z.search(/bottom/)!==-1)?-2:-1)+"px; margin-left:"+((z.search(/Right/)!==-1)?E[z][2]-3.5:-1)+'px; vertical-align:top; display:inline-block; behavior:url(#default#VML)"></v:arc>'}}u[z]+="</div>"}D=F.getDimensions().width-(Math.max(t,B)*2);y='<div class="qtip-betweenCorners" style="height:'+B+"px; width:"+D+"px; overflow:hidden; background-color:"+x+'; line-height:0.1px; font-size:1px;">';w='<div class="qtip-borderTop" dir="ltr" style="height:'+B+"px; margin-left:"+B+'px; line-height:0.1px; font-size:1px; padding:0;">'+u.topLeft+u.topRight+y;F.elements.wrapper.prepend(w);C='<div class="qtip-borderBottom" dir="ltr" style="height:'+B+"px; margin-left:"+B+'px; line-height:0.1px; font-size:1px; padding:0;">'+u.bottomLeft+u.bottomRight+y;F.elements.wrapper.append(C);if(f("<canvas>").get(0).getContext){F.elements.wrapper.find("canvas").each(function(){A=E[f(this).parent("[rel]:first").attr("rel")];r.call(F,f(this),A,B,x)})}else{if(f.browser.msie){F.elements.tooltip.append('<v:image style="behavior:url(#default#VML);"></v:image>')}}s=Math.max(B,(B+(t-B)));v=Math.max(t-B,0);F.elements.contentWrapper.css({border:"0px solid "+x,borderWidth:v+"px "+s+"px"})}function r(u,w,s,t){var v=u.get(0).getContext("2d");v.fillStyle=t;v.beginPath();v.arc(w[0],w[1],s,0,Math.PI*2,false);v.fill()}function e(v){var t,s,x,u,w;t=this;if(t.elements.tip!==null){t.elements.tip.remove()}s=t.options.style.tip.color||t.options.style.border.color;if(t.options.style.tip.corner===false){return}else{if(!v){v=t.options.style.tip.corner}}x=b(v,t.options.style.tip.size.width,t.options.style.tip.size.height);t.elements.tip='<div class="'+t.options.style.classes.tip+'" dir="ltr" rel="'+v+'" style="position:absolute; height:'+t.options.style.tip.size.height+"px; width:"+t.options.style.tip.size.width+'px; margin:0 auto; line-height:0.1px; font-size:1px;">';if(f("<canvas>").get(0).getContext){t.elements.tip+='<canvas height="'+t.options.style.tip.size.height+'" width="'+t.options.style.tip.size.width+'"></canvas>'}else{if(f.browser.msie){u=t.options.style.tip.size.width+","+t.options.style.tip.size.height;w="m"+x[0][0]+","+x[0][1];w+=" l"+x[1][0]+","+x[1][1];w+=" "+x[2][0]+","+x[2][1];w+=" xe";t.elements.tip+='<v:shape fillcolor="'+s+'" stroked="false" filled="true" path="'+w+'" coordsize="'+u+'" style="width:'+t.options.style.tip.size.width+"px; height:"+t.options.style.tip.size.height+"px; line-height:0.1px; display:inline-block; behavior:url(#default#VML); vertical-align:"+((v.search(/top/)!==-1)?"bottom":"top")+'"></v:shape>';t.elements.tip+='<v:image style="behavior:url(#default#VML);"></v:image>';t.elements.contentWrapper.css("position","relative")}}t.elements.tooltip.prepend(t.elements.tip+"</div>");t.elements.tip=t.elements.tooltip.find("."+t.options.style.classes.tip).eq(0);if(f("<canvas>").get(0).getContext){h.call(t,t.elements.tip.find("canvas:first"),x,s)}if(v.search(/top/)!==-1&&f.browser.msie&&parseInt(f.browser.version.charAt(0))===6){t.elements.tip.css({marginTop:-4})}n.call(t,v)}function h(t,v,s){var u=t.get(0).getContext("2d");u.fillStyle=s;u.beginPath();u.moveTo(v[0][0],v[0][1]);u.lineTo(v[1][0],v[1][1]);u.lineTo(v[2][0],v[2][1]);u.fill()}function n(u){var t,w,s,x,v;t=this;if(t.options.style.tip.corner===false||!t.elements.tip){return}if(!u){u=t.elements.tip.attr("rel")}w=positionAdjust=(f.browser.msie)?1:0;t.elements.tip.css(u.match(/left|right|top|bottom/)[0],0);if(u.search(/top|bottom/)!==-1){if(f.browser.msie){if(parseInt(f.browser.version.charAt(0))===6){positionAdjust=(u.search(/top/)!==-1)?-3:1}else{positionAdjust=(u.search(/top/)!==-1)?1:2}}if(u.search(/Middle/)!==-1){t.elements.tip.css({left:"50%",marginLeft:-(t.options.style.tip.size.width/2)})}else{if(u.search(/Left/)!==-1){t.elements.tip.css({left:t.options.style.border.radius-w})}else{if(u.search(/Right/)!==-1){t.elements.tip.css({right:t.options.style.border.radius+w})}}}if(u.search(/top/)!==-1){t.elements.tip.css({top:-positionAdjust})}else{t.elements.tip.css({bottom:positionAdjust})}}else{if(u.search(/left|right/)!==-1){if(f.browser.msie){positionAdjust=(parseInt(f.browser.version.charAt(0))===6)?1:((u.search(/left/)!==-1)?1:2)}if(u.search(/Middle/)!==-1){t.elements.tip.css({top:"50%",marginTop:-(t.options.style.tip.size.height/2)})}else{if(u.search(/Top/)!==-1){t.elements.tip.css({top:t.options.style.border.radius-w})}else{if(u.search(/Bottom/)!==-1){t.elements.tip.css({bottom:t.options.style.border.radius+w})}}}if(u.search(/left/)!==-1){t.elements.tip.css({left:-positionAdjust})}else{t.elements.tip.css({right:positionAdjust})}}}s="padding-"+u.match(/left|right|top|bottom/)[0];x=t.options.style.tip.size[(s.search(/left|right/)!==-1)?"width":"height"];t.elements.tooltip.css("padding",0);t.elements.tooltip.css(s,x);if(f.browser.msie&&parseInt(f.browser.version.charAt(0))==6){v=parseInt(t.elements.tip.css("margin-top"))||0;v+=parseInt(t.elements.content.css("margin-top"))||0;t.elements.tip.css({marginTop:v})}}function j(){var s=this;if(s.elements.title!==null){s.elements.title.remove()}s.elements.title=f('<div class="'+s.options.style.classes.title+'">').css(q(s.options.style.title,true)).css({zoom:(f.browser.msie)?1:0}).prependTo(s.elements.contentWrapper);if(s.options.content.title.text){s.updateTitle.call(s,s.options.content.title.text)}if(s.options.content.title.button!==false&&typeof s.options.content.title.button=="string"){s.elements.button=f('<a class="'+s.options.style.classes.button+'" style="float:right; position: relative"></a>').css(q(s.options.style.button,true)).html(s.options.content.title.button).prependTo(s.elements.title).click(function(t){if(!s.status.disabled){s.hide(t)}})}}function l(){var t,v,u,s;t=this;v=t.options.show.when.target;u=t.options.hide.when.target;if(t.options.hide.fixed){u=u.add(t.elements.tooltip)}if(t.options.hide.when.event=="inactive"){s=["click","dblclick","mousedown","mouseup","mousemove","mouseout","mouseenter","mouseleave","mouseover"];function y(z){if(t.status.disabled===true){return}clearTimeout(t.timers.inactive);t.timers.inactive=setTimeout(function(){f(s).each(function(){u.unbind(this+".qtip-inactive");t.elements.content.unbind(this+".qtip-inactive")});t.hide(z)},t.options.hide.delay)}}else{if(t.options.hide.fixed===true){t.elements.tooltip.bind("mouseover.qtip",function(){if(t.status.disabled===true){return}clearTimeout(t.timers.hide)})}}function x(z){if(t.status.disabled===true){return}if(t.options.hide.when.event=="inactive"){f(s).each(function(){u.bind(this+".qtip-inactive",y);t.elements.content.bind(this+".qtip-inactive",y)});y()}clearTimeout(t.timers.show);clearTimeout(t.timers.hide);t.timers.show=setTimeout(function(){t.show(z)},t.options.show.delay)}function w(z){if(t.status.disabled===true){return}if(t.options.hide.fixed===true&&t.options.hide.when.event.search(/mouse(out|leave)/i)!==-1&&f(z.relatedTarget).parents("div.qtip[qtip]").length>0){z.stopPropagation();z.preventDefault();clearTimeout(t.timers.hide);return false}clearTimeout(t.timers.show);clearTimeout(t.timers.hide);t.elements.tooltip.stop(true,true);t.timers.hide=setTimeout(function(){t.hide(z)},t.options.hide.delay)}if((t.options.show.when.target.add(t.options.hide.when.target).length===1&&t.options.show.when.event==t.options.hide.when.event&&t.options.hide.when.event!=="inactive")||t.options.hide.when.event=="unfocus"){t.cache.toggle=0;v.bind(t.options.show.when.event+".qtip",function(z){if(t.cache.toggle==0){x(z)}else{w(z)}})}else{v.bind(t.options.show.when.event+".qtip",x);if(t.options.hide.when.event!=="inactive"){u.bind(t.options.hide.when.event+".qtip",w)}}if(t.options.position.type.search(/(fixed|absolute)/)!==-1){t.elements.tooltip.bind("mouseover.qtip",t.focus)}if(t.options.position.target==="mouse"&&t.options.position.type!=="static"){v.bind("mousemove.qtip",function(z){t.cache.mouse={x:z.pageX,y:z.pageY};if(t.status.disabled===false&&t.options.position.adjust.mouse===true&&t.options.position.type!=="static"&&t.elements.tooltip.css("display")!=="none"){t.updatePosition(z)}})}}function o(u,v,A){var z,s,x,y,t,w;z=this;if(A.corner=="center"){return v.position}s=f.extend({},u);y={x:false,y:false};t={left:(s.left<f.fn.qtip.cache.screen.scroll.left),right:(s.left+A.dimensions.width+2>=f.fn.qtip.cache.screen.width+f.fn.qtip.cache.screen.scroll.left),top:(s.top<f.fn.qtip.cache.screen.scroll.top),bottom:(s.top+A.dimensions.height+2>=f.fn.qtip.cache.screen.height+f.fn.qtip.cache.screen.scroll.top)};x={left:(t.left&&(A.corner.search(/right/i)!=-1||(A.corner.search(/right/i)==-1&&!t.right))),right:(t.right&&(A.corner.search(/left/i)!=-1||(A.corner.search(/left/i)==-1&&!t.left))),top:(t.top&&A.corner.search(/top/i)==-1),bottom:(t.bottom&&A.corner.search(/bottom/i)==-1)};if(x.left){if(z.options.position.target!=="mouse"){s.left=v.position.left+v.dimensions.width}else{s.left=z.cache.mouse.x}y.x="Left"}else{if(x.right){if(z.options.position.target!=="mouse"){s.left=v.position.left-A.dimensions.width}else{s.left=z.cache.mouse.x-A.dimensions.width}y.x="Right"}}if(x.top){if(z.options.position.target!=="mouse"){s.top=v.position.top+v.dimensions.height}else{s.top=z.cache.mouse.y}y.y="top"}else{if(x.bottom){if(z.options.position.target!=="mouse"){s.top=v.position.top-A.dimensions.height}else{s.top=z.cache.mouse.y-A.dimensions.height}y.y="bottom"}}if(s.left<0){s.left=u.left;y.x=false}if(s.top<0){s.top=u.top;y.y=false}if(z.options.style.tip.corner!==false){s.corner=new String(A.corner);if(y.x!==false){s.corner=s.corner.replace(/Left|Right|Middle/,y.x)}if(y.y!==false){s.corner=s.corner.replace(/top|bottom/,y.y)}if(s.corner!==z.elements.tip.attr("rel")){e.call(z,s.corner)}}return s}function q(u,t){var v,s;v=f.extend(true,{},u);for(s in v){if(t===true&&s.search(/(tip|classes)/i)!==-1){delete v[s]}else{if(!t&&s.search(/(width|border|tip|title|classes|user)/i)!==-1){delete v[s]}}}return v}function c(s){if(typeof s.tip!=="object"){s.tip={corner:s.tip}}if(typeof s.tip.size!=="object"){s.tip.size={width:s.tip.size,height:s.tip.size}}if(typeof s.border!=="object"){s.border={width:s.border}}if(typeof s.width!=="object"){s.width={value:s.width}}if(typeof s.width.max=="string"){s.width.max=parseInt(s.width.max.replace(/([0-9]+)/i,"$1"))}if(typeof s.width.min=="string"){s.width.min=parseInt(s.width.min.replace(/([0-9]+)/i,"$1"))}if(typeof s.tip.size.x=="number"){s.tip.size.width=s.tip.size.x;delete s.tip.size.x}if(typeof s.tip.size.y=="number"){s.tip.size.height=s.tip.size.y;delete s.tip.size.y}return s}function a(){var s,t,u,x,v,w;s=this;u=[true,{}];for(t=0;t<arguments.length;t++){u.push(arguments[t])}x=[f.extend.apply(f,u)];while(typeof x[0].name=="string"){x.unshift(c(f.fn.qtip.styles[x[0].name]))}x.unshift(true,{classes:{tooltip:"qtip-"+(arguments[0].name||"defaults")}},f.fn.qtip.styles.defaults);v=f.extend.apply(f,x);w=(f.browser.msie)?1:0;v.tip.size.width+=w;v.tip.size.height+=w;if(v.tip.size.width%2>0){v.tip.size.width+=1}if(v.tip.size.height%2>0){v.tip.size.height+=1}if(v.tip.corner===true){v.tip.corner=(s.options.position.corner.tooltip==="center")?false:s.options.position.corner.tooltip}return v}function b(v,u,t){var s={bottomRight:[[0,0],[u,t],[u,0]],bottomLeft:[[0,0],[u,0],[0,t]],topRight:[[0,t],[u,0],[u,t]],topLeft:[[0,0],[0,t],[u,t]],topMiddle:[[0,t],[u/2,0],[u,t]],bottomMiddle:[[0,0],[u,0],[u/2,t]],rightMiddle:[[0,0],[u,t/2],[0,t]],leftMiddle:[[u,0],[u,t],[0,t/2]]};s.leftTop=s.bottomRight;s.rightTop=s.bottomLeft;s.leftBottom=s.topRight;s.rightBottom=s.topLeft;return s[v]}function g(s){var t;if(f("<canvas>").get(0).getContext){t={topLeft:[s,s],topRight:[0,s],bottomLeft:[s,0],bottomRight:[0,0]}}else{if(f.browser.msie){t={topLeft:[-90,90,0],topRight:[-90,90,-s],bottomLeft:[90,270,0],bottomRight:[90,270,-s]}}}return t}function k(){var s,t,u;s=this;u=s.getDimensions();t='<iframe class="qtip-bgiframe" frameborder="0" tabindex="-1" src="javascript:false" style="display:block; position:absolute; z-index:-1; filter:alpha(opacity=\'0\'); border: 1px solid red; height:'+u.height+"px; width:"+u.width+'px" />';s.elements.bgiframe=s.elements.wrapper.prepend(t).children(".qtip-bgiframe:first")}f(document).ready(function(){f.fn.qtip.cache={screen:{scroll:{left:f(window).scrollLeft(),top:f(window).scrollTop()},width:f(window).width(),height:f(window).height()}};var s;f(window).bind("resize scroll",function(t){clearTimeout(s);s=setTimeout(function(){if(t.type==="scroll"){f.fn.qtip.cache.screen.scroll={left:f(window).scrollLeft(),top:f(window).scrollTop()}}else{f.fn.qtip.cache.screen.width=f(window).width();f.fn.qtip.cache.screen.height=f(window).height()}for(i=0;i<f.fn.qtip.interfaces.length;i++){var u=f.fn.qtip.interfaces[i];if(u.status.rendered===true&&(u.options.position.type!=="static"||u.options.position.adjust.scroll&&t.type==="scroll"||u.options.position.adjust.resize&&t.type==="resize")){u.updatePosition(t,true)}}},100)});f(document).bind("mousedown.qtip",function(t){if(f(t.target).parents("div.qtip").length===0){f(".qtip[unfocus]").each(function(){var u=f(this).qtip("api");if(f(this).is(":visible")&&!u.status.disabled&&f(t.target).add(u.elements.target).length>1){u.hide(t)}})}})});f.fn.qtip.interfaces=[];f.fn.qtip.log={error:function(){return this}};f.fn.qtip.constants={};f.fn.qtip.defaults={content:{prerender:false,text:false,url:false,data:null,title:{text:false,button:false}},position:{target:false,corner:{target:"bottomRight",tooltip:"topLeft"},adjust:{x:0,y:0,mouse:true,screen:false,scroll:true,resize:true},type:"absolute",container:false},show:{when:{target:false,event:"mouseover"},effect:{type:"fade",length:100},delay:140,solo:false,ready:false},hide:{when:{target:false,event:"mouseout"},effect:{type:"fade",length:100},delay:0,fixed:false},api:{beforeRender:function(){},onRender:function(){},beforePositionUpdate:function(){},onPositionUpdate:function(){},beforeShow:function(){},onShow:function(){},beforeHide:function(){},onHide:function(){},beforeContentUpdate:function(){},onContentUpdate:function(){},beforeContentLoad:function(){},onContentLoad:function(){},beforeTitleUpdate:function(){},onTitleUpdate:function(){},beforeDestroy:function(){},onDestroy:function(){},beforeFocus:function(){},onFocus:function(){}}};f.fn.qtip.styles={defaults:{background:"white",color:"#111",overflow:"hidden",textAlign:"left",width:{min:0,max:250},padding:"5px 9px",border:{width:1,radius:0,color:"#d3d3d3"},tip:{corner:false,color:false,size:{width:13,height:13},opacity:1},title:{background:"#e1e1e1",fontWeight:"bold",padding:"7px 12px"},button:{cursor:"pointer"},classes:{target:"",tip:"qtip-tip",title:"qtip-title",button:"qtip-button",content:"qtip-content",active:"qtip-active"}},cream:{border:{width:3,radius:0,color:"#F9E98E"},title:{background:"#F0DE7D",color:"#A27D35"},background:"#FBF7AA",color:"#A27D35",classes:{tooltip:"qtip-cream"}},light:{border:{width:3,radius:0,color:"#E2E2E2"},title:{background:"#f1f1f1",color:"#454545"},background:"white",color:"#454545",classes:{tooltip:"qtip-light"}},dark:{border:{width:3,radius:0,color:"#303030"},title:{background:"#404040",color:"#f3f3f3"},background:"#505050",color:"#f3f3f3",classes:{tooltip:"qtip-dark"}},red:{border:{width:3,radius:0,color:"#CE6F6F"},title:{background:"#f28279",color:"#9C2F2F"},background:"#F79992",color:"#9C2F2F",classes:{tooltip:"qtip-red"}},green:{border:{width:3,radius:0,color:"#A9DB66"},title:{background:"#b9db8c",color:"#58792E"},background:"#CDE6AC",color:"#58792E",classes:{tooltip:"qtip-green"}},blue:{border:{width:3,radius:0,color:"#ADD9ED"},title:{background:"#D0E9F5",color:"#5E99BD"},background:"#E5F6FE",color:"#4D9FBF",classes:{tooltip:"qtip-blue"}}}})(jQuery);

/*
 * jQuery BBQ: Back Button & Query Library - v1.1.1 - 1/22/2010
 * http://benalman.com/projects/jquery-bbq-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,n){var g,o=n.location,k=Array.prototype.slice,q=decodeURIComponent,a=$.param,c,j,u,b=$.bbq=$.bbq||{},p,t,h,e=$.event.special,d="hashchange",z="querystring",C="fragment",x="elemUrlAttr",i="href",s="src",w=/^.*\?|#.*$/g,v=/^.*\#/,B={};function D(E){return typeof E==="string"}function A(F){var E=k.call(arguments,1);return function(){return F.apply(this,E.concat(k.call(arguments)))}}function l(E){return E.replace(/^[^#]*#?(.*)$/,"$1")}function m(E){return E.replace(/(?:^[^?#]*\?([^#]*).*$)?.*/,"$1")}function f(G,L,E,H,F){var N,K,J,M,I;if(H!==g){J=E.match(G?/^([^#]*)\#?(.*)$/:/^([^#?]*)\??([^#]*)(#?.*)/);I=J[3]||"";if(F===2&&D(H)){K=H.replace(G?v:w,"")}else{M=j(J[2]);H=D(H)?j[G?C:z](H):H;K=F===2?H:F===1?$.extend({},H,M):$.extend({},M,H);K=a(K)}N=J[1]+(G?"#":K||!J[1]?"?":"")+K+I}else{N=L(E!==g?E:o[i])}return N}a[z]=A(f,0,m);a[C]=c=A(f,1,l);$.deparam=j=function(H,E){var G={},F={"true":!0,"false":!1,"null":null};$.each(H.replace(/\+/g," ").split("&"),function(K,P){var J=P.split("="),O=q(J[0]),I,N=G,L=0,Q=O.split("]["),M=Q.length-1;if(/\[/.test(Q[0])&&/\]$/.test(Q[M])){Q[M]=Q[M].replace(/\]$/,"");Q=Q.shift().split("[").concat(Q);M=Q.length-1}else{M=0}if(J.length===2){I=q(J[1]);if(E){I=I&&!isNaN(I)?+I:I==="undefined"?g:F[I]!==g?F[I]:I}if(M){for(;L<=M;L++){O=Q[L]===""?N.length:Q[L];N=N[O]=L<M?N[O]||(Q[L+1]&&isNaN(Q[L+1])?{}:[]):I}}else{if($.isArray(G[O])){G[O].push(I)}else{if(G[O]!==g){G[O]=[G[O],I]}else{G[O]=I}}}}else{if(O){G[O]=E?g:""}}});return G};function y(G,E,F){if(E===g||typeof E==="boolean"){F=E;E=a[G?C:z]()}else{E=D(E)?E.replace(G?v:w,""):E}return j(E,F)}j[z]=A(y,0);j[C]=u=A(y,1);$[x]||($[x]=function(E){return $.extend(B,E)})({a:i,base:i,iframe:s,img:s,input:s,form:"action",link:i,script:s});h=$[x];function r(H,F,G,E){if(!D(G)&&typeof G!=="object"){E=G;G=F;F=g}return this.each(function(){var K=$(this),I=F||h()[(this.nodeName||"").toLowerCase()]||"",J=I&&K.attr(I)||"";K.attr(I,a[H](J,G,E))})}$.fn[z]=A(r,z);$.fn[C]=A(r,C);b.pushState=p=function(H,E){if(D(H)&&/^#/.test(H)&&E===g){E=2}var G=H!==g,F=c(o[i],G?H:{},G?E:2);o[i]=F+(/#/.test(F)?"":"#")};b.getState=t=function(E,F){return E===g||typeof E==="boolean"?u(E):u(F)[E]};b.removeState=function(E){var F={};if(E!==g){F=t();$.each($.isArray(E)?E:arguments,function(H,G){delete F[G]})}p(F,2)};e[d]=$.extend(e[d],{add:function(E,G,F){return function(I){var H=I[C]=c();I.getState=function(J,K){return J===g||typeof J==="boolean"?j(H,J):j(H,K)[J]};E.apply(this,arguments)}}})})(jQuery,this);
/*
 * jQuery hashchange event - v1.1 - 1/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 * 
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,i,b){var h=i.location,j,k=$.event.special,c="hashchange",e=$.browser,f=document.documentMode,g=e.msie&&(f===b||f<8),d="on"+c in i&&!g;function a(l){l=l||h.href;return l.replace(/^[^#]*#?(.*)$/,"$1")}$[c+"Delay"]=100;k[c]=$.extend(k[c],{setup:function(){if(d){return false}j.start()},teardown:function(){if(d){return false}j.stop()}});j=(function(){var l={},q,m,n,p;function o(){n=p=function(r){return r};if(g){m=$('<iframe src="javascript:0"/>').hide().insertAfter("body")[0].contentWindow;p=function(){return a(m.document.location.href)};n=function(t,r){if(t!==r){var s=m.document;s.open().close();s.location.hash="#"+t}};n(a())}}l.start=function(){if(q){return}var s=a();n||o();(function r(){var u=a(),t=p(s);if(u!==s){n(s=u,t);$(i).trigger(c)}else{if(t!==s){h.href=h.href.replace(/#.*/,"")+"#"+t}}q=setTimeout(r,$[c+"Delay"])})()};l.stop=function(){if(!m){q&&clearTimeout(q);q=0}};return l})()})(jQuery,this);

/**
 * Single Drop Down Menu
 * March 24, 2008
 * Corey Hart @ http://www.codenothing.com
 *
 * @timer: milliseconds to keep dropped menus open
 * @parentMO: CSS class to add/remove to parent list on mouseover/mouseout's
 * @childMO: CSS class to add/remove to child list on mouseover/mouseout's
 */ 
;(function(A){A.fn.singleDropMenu=function(C){var F;var E;var D=A.extend({timer:500,parentMO:null,childMO:null},C||{});this.each(function(){A("li",this).mouseover(function(){B();A("a",this).addClass(D.parentMO).siblings("ul").show()}).mouseout(function(){E=this;F=setTimeout(function(){B()},D.timer)});A("li ul li",this).mouseover(function(){A("a",this).addClass(D.childMO)}).mouseout(function(){A("a",this).removeClass(D.childMO)})});A(document).click(function(){B()});var B=function(){if(E&&F){A("a",E).removeClass(D.parentMO).siblings("ul").hide();clearTimeout(F);E=""}}}})(jQuery);


/* Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.1.0-pre
 * Requires jQuery 1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */
(function(a){a.extend(a.fn,{livequery:function(e,d,c){var b=this,f;if(a.isFunction(e)){c=d,d=e,e=undefined}a.each(a.livequery.queries,function(g,h){if(b.selector==h.selector&&b.context==h.context&&e==h.type&&(!d||d.$lqguid==h.fn.$lqguid)&&(!c||c.$lqguid==h.fn2.$lqguid)){return(f=h)&&false}});f=f||new a.livequery(this.selector,this.context,e,d,c);f.stopped=false;f.run();return this},expire:function(e,d,c){var b=this;if(a.isFunction(e)){c=d,d=e,e=undefined}a.each(a.livequery.queries,function(f,g){if(b.selector==g.selector&&b.context==g.context&&(!e||e==g.type)&&(!d||d.$lqguid==g.fn.$lqguid)&&(!c||c.$lqguid==g.fn2.$lqguid)&&!this.stopped){a.livequery.stop(g.id)}});return this}});a.livequery=function(b,d,f,e,c){this.selector=b;this.context=d;this.type=f;this.fn=e;this.fn2=c;this.elements=[];this.stopped=false;this.id=a.livequery.queries.push(this)-1;e.$lqguid=e.$lqguid||a.livequery.guid++;if(c){c.$lqguid=c.$lqguid||a.livequery.guid++}return this};a.livequery.prototype={stop:function(){var b=this;if(this.type){this.elements.unbind(this.type,this.fn)}else{if(this.fn2){this.elements.each(function(c,d){b.fn2.apply(d)})}}this.elements=[];this.stopped=true},run:function(){if(this.stopped){return}var d=this;var e=this.elements,c=a(this.selector,this.context),b=c.not(e);this.elements=c;if(this.type){b.bind(this.type,this.fn);if(e.length>0){a.each(e,function(f,g){if(a.inArray(g,c)<0){a.event.remove(g,d.type,d.fn)}})}}else{b.each(function(){d.fn.apply(this)});if(this.fn2&&e.length>0){a.each(e,function(f,g){if(a.inArray(g,c)<0){d.fn2.apply(g)}})}}}};a.extend(a.livequery,{guid:0,queries:[],queue:[],running:false,timeout:null,checkQueue:function(){if(a.livequery.running&&a.livequery.queue.length){var b=a.livequery.queue.length;while(b--){a.livequery.queries[a.livequery.queue.shift()].run()}}},pause:function(){a.livequery.running=false},play:function(){a.livequery.running=true;a.livequery.run()},registerPlugin:function(){a.each(arguments,function(c,d){if(!a.fn[d]){return}var b=a.fn[d];a.fn[d]=function(){var e=b.apply(this,arguments);a.livequery.run();return e}})},run:function(b){if(b!=undefined){if(a.inArray(b,a.livequery.queue)<0){a.livequery.queue.push(b)}}else{a.each(a.livequery.queries,function(c){if(a.inArray(c,a.livequery.queue)<0){a.livequery.queue.push(c)}})}if(a.livequery.timeout){clearTimeout(a.livequery.timeout)}a.livequery.timeout=setTimeout(a.livequery.checkQueue,20)},stop:function(b){if(b!=undefined){a.livequery.queries[b].stop()}else{a.each(a.livequery.queries,function(c){a.livequery.queries[c].stop()})}}});a.livequery.registerPlugin("append","prepend","after","before","wrap","attr","removeAttr","addClass","removeClass","toggleClass","empty","remove");a(function(){a.livequery.play()})})(jQuery);

(function(a){a.fn.checkTree=function(b){b=a.extend({onExpand:null,onCollapse:null,onCheck:null,onUnCheck:null,onHalfCheck:null,onLabelHoverOver:null,onLabelHoverOut:null,labelAction:"expand",debug:false},b);var c=this;c.find("li").find(":checkbox").change(function(){var e=a(this).siblings("ul").find(":checkbox");var d=e.filter(":checked");if(e.length==d.length){a(this).attr("checked","checked").siblings(".checkbox").removeClass("half_checked").addClass("checked")}else{if(d.length==0){a(this).attr("checked","").siblings(".checkbox").removeClass("checked").removeClass("half_checked")}else{if(b.onHalfCheck&&!a(this).siblings(".checkbox").hasClass("half_checked")){b.onHalfCheck(a(this).parent())}a(this).attr("checked","").siblings(".checkbox").removeClass("checked").addClass("half_checked")}}}).css("display","none").end().each(function(){a(this).find("ul").each(function(){if(!a(this).siblings(".expanded").length){a(this).hide()}});var d=a(this).children("label").clone();var f=a('<div class="checkbox"></div>');var e=a('<div class="arrow"></div>');if(a(this).is(":has(ul)")){if(a(this).children("ul").is(":hidden")){e.addClass("collapsed")}else{e.addClass("expanded")}e.click(function(){a(this).siblings("ul").toggle();if(a(this).hasClass("collapsed")){a(this).addClass("expanded").removeClass("collapsed");if(b.onExpand){b.onExpand(a(this).parent())}}else{a(this).addClass("collapsed").removeClass("expanded");if(b.onCollapse){b.onCollapse(a(this).parent())}}})}f.click(function(){a(this).toggleClass("checked").removeClass("half_checked").siblings(":checkbox").click();if(a(this).hasClass("checked")){if(b.onCheck){b.onCheck(a(this).parent())}a(this).siblings("ul").find(".checkbox").not(".checked").removeClass("half_checked").addClass("checked").each(function(){}).siblings(":checkbox").attr("checked","checked")}else{if(b.onUnCheck){b.onUnCheck(a(this).parent())}a(this).siblings("ul").find(".checkbox").filter(".checked").removeClass("half_checked").removeClass("checked").each(function(){}).siblings(":checkbox").attr("checked","")}a(this).parents("ul").siblings(":checkbox").change()});if(a(this).children(".checkbox").hasClass("checked")){f.addClass("checked")}else{if(a(this).children(":checkbox").attr("checked")){f.addClass("checked");a(this).parents("ul").siblings(":checkbox").change()}else{if(a(this).children(".checkbox").hasClass("half_checked")){f.addClass("half_checked")}}}a(this).children(".arrow").remove();a(this).children(".checkbox").remove();a(this).children("label").remove();a(this).prepend(d).prepend(f).prepend(e)}).find("label").click(function(){var d=b.labelAction;switch(b.labelAction){case"expand":a(this).siblings(".arrow").click();break;case"check":a(this).siblings(".checkbox").click();break}}).hover(function(){a(this).addClass("hover");if(b.onLabelHoverOver){b.onLabelHoverOver(a(this).parent())}},function(){a(this).removeClass("hover");if(b.onLabelHoverOut){b.onLabelHoverOut(a(this).parent())}}).end();return c}})(jQuery);

﻿;(function(g){if(/1\.(0|1|2)\.(0|1|2)/.test(g.fn.jquery)||/^1.1/.test(g.fn.jquery)){alert("blockUI requires jQuery v1.2.3 or later!  You are using v"+g.fn.jquery);return}g.fn._fadeIn=g.fn.fadeIn;var i=document.documentMode||0;var d=g.browser.msie&&((g.browser.version<8&&!i)||i<8);var e=g.browser.msie&&/MSIE 6.0/.test(navigator.userAgent)&&!i;g.blockUI=function(o){c(window,o)};g.unblockUI=function(o){h(window,o)};g.growlUI=function(s,q,r,o){var p=g('<div class="growlUI"></div>');if(s){p.append("<h1>"+s+"</h1>")}if(q){p.append("<h2>"+q+"</h2>")}if(r==undefined){r=3000}g.blockUI({message:p,fadeIn:700,fadeOut:1000,centerY:false,timeout:r,showOverlay:false,onUnblock:o,css:g.blockUI.defaults.growlCSS})};g.fn.block=function(o){return this.unblock({fadeOut:0}).each(function(){if(g.css(this,"position")=="static"){this.style.position="relative"}if(g.browser.msie){this.style.zoom=1}c(this,o)})};g.fn.unblock=function(o){return this.each(function(){h(this,o)})};g.blockUI.version=2.23;g.blockUI.defaults={message:"<h1>Please wait...</h1>",css:{padding:0,margin:0,width:"30%",top:"40%",left:"35%",textAlign:"center",color:"#000",border:"3px solid #aaa",backgroundColor:"#fff",cursor:"wait"},overlayCSS:{backgroundColor:"#000",opacity:0.6,cursor:"wait"},growlCSS:{width:"350px",top:"10px",left:"",right:"10px",border:"none",padding:"5px",opacity:0.6,cursor:null,color:"#fff",backgroundColor:"#000","-webkit-border-radius":"10px","-moz-border-radius":"10px"},iframeSrc:/^https/i.test(window.location.href||"")?"javascript:false":"about:blank",forceIframe:false,baseZ:1000,centerX:true,centerY:true,allowBodyStretch:true,bindEvents:true,constrainTabKey:true,fadeIn:200,fadeOut:400,timeout:0,showOverlay:true,focusInput:true,applyPlatformOpacityRules:true,onUnblock:null,quirksmodeOffsetHack:4};var b=null;var f=[];function c(q,o){var B=(q==window);var r=o&&o.message!==undefined?o.message:undefined;o=g.extend({},g.blockUI.defaults,o||{});o.overlayCSS=g.extend({},g.blockUI.defaults.overlayCSS,o.overlayCSS||{});var A=g.extend({},g.blockUI.defaults.css,o.css||{});r=r===undefined?o.message:r;if(B&&b){h(window,{fadeOut:0})}if(r&&typeof r!="string"&&(r.parentNode||r.jquery)){var u=r.jquery?r[0]:r;var y={};g(q).data("blockUI.history",y);y.el=u;y.parent=u.parentNode;y.display=u.style.display;y.position=u.style.position;if(y.parent){y.parent.removeChild(u)}}var C=o.baseZ;var x=(g.browser.msie||o.forceIframe)?g('<iframe class="blockUI" style="z-index:'+(C++)+';display:none;border:none;margin:0;padding:0;position:absolute;width:100%;height:100%;top:0;left:0" src="'+o.iframeSrc+'"></iframe>'):g('<div class="blockUI" style="display:none"></div>');var w=g('<div class="blockUI blockOverlay" style="z-index:'+(C++)+';display:none;border:none;width:100%;height:100%;top:0;left:0"></div>');var s=B?g('<div class="blockUI blockMsg blockPage" style="z-index:'+C+';display:none;position:fixed"></div>'):g('<div class="blockUI blockMsg blockElement" style="z-index:'+C+';display:none;position:absolute"></div>');if(r){s.css(A)}if(!o.applyPlatformOpacityRules||!(g.browser.mozilla&&/Linux/.test(navigator.platform))){w.css(o.overlayCSS)}w.css("position",B?"fixed":"absolute");if(g.browser.msie||o.forceIframe){x.css("opacity",0)}g([x[0],w[0],s[0]]).appendTo(B?"body":q);var F=d&&(!g.boxModel||g("object,embed",B?null:q).length>0);if(e||F){if(B&&o.allowBodyStretch&&g.boxModel){g("html,body").css("height","100%")}if((e||!g.boxModel)&&!B){var G=l(q,"borderTopWidth"),v=l(q,"borderLeftWidth");var E=G?"(0 - "+G+")":0;var p=v?"(0 - "+v+")":0}g.each([x,w,s],function(t,J){var z=J[0].style;z.position="absolute";if(t<2){B?z.setExpression("height","Math.max(document.body.scrollHeight, document.body.offsetHeight) - (jQuery.boxModel?0:"+o.quirksmodeOffsetHack+') + "px"'):z.setExpression("height",'this.parentNode.offsetHeight + "px"');B?z.setExpression("width",'jQuery.boxModel && document.documentElement.clientWidth || document.body.clientWidth + "px"'):z.setExpression("width",'this.parentNode.offsetWidth + "px"');if(p){z.setExpression("left",p)}if(E){z.setExpression("top",E)}}else{if(o.centerY){if(B){z.setExpression("top",'(document.documentElement.clientHeight || document.body.clientHeight) / 2 - (this.offsetHeight / 2) + (blah = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "px"')}z.marginTop=0}else{if(!o.centerY&&B){var H=(o.css&&o.css.top)?parseInt(o.css.top):0;var I="((document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + "+H+') + "px"';z.setExpression("top",I)}}}})}if(r){s.append(r);if(r.jquery||r.nodeType){g(r).show()}}if((g.browser.msie||o.forceIframe)&&o.showOverlay){x.show()}if(o.fadeIn){if(o.showOverlay){w._fadeIn(o.fadeIn)}if(r){s.fadeIn(o.fadeIn)}}else{if(o.showOverlay){w.show()}if(r){s.show()}}k(1,q,o);if(B){b=s[0];f=g(":input:enabled:visible",b);if(o.focusInput){setTimeout(n,20)}}else{a(s[0],o.centerX,o.centerY)}if(o.timeout){var D=setTimeout(function(){B?g.unblockUI(o):g(q).unblock(o)},o.timeout);g(q).data("blockUI.timeout",D)}}function h(r,s){var q=r==window;var p=g(r);var t=p.data("blockUI.history");var u=p.data("blockUI.timeout");if(u){clearTimeout(u);p.removeData("blockUI.timeout")}s=g.extend({},g.blockUI.defaults,s||{});k(0,r,s);var o=q?g("body").children().filter(".blockUI"):g(".blockUI",r);if(q){b=f=null}if(s.fadeOut){o.fadeOut(s.fadeOut);setTimeout(function(){j(o,t,s,r)},s.fadeOut)}else{j(o,t,s,r)}}function j(o,r,q,p){o.each(function(s,t){if(this.parentNode){this.parentNode.removeChild(this)}});if(r&&r.el){r.el.style.display=r.display;r.el.style.position=r.position;if(r.parent){r.parent.appendChild(r.el)}g(r.el).removeData("blockUI.history")}if(typeof q.onUnblock=="function"){q.onUnblock(p,q)}}function k(o,s,t){var r=s==window,q=g(s);if(!o&&(r&&!b||!r&&!q.data("blockUI.isBlocked"))){return}if(!r){q.data("blockUI.isBlocked",o)}if(!t.bindEvents||(o&&!t.showOverlay)){return}var p="mousedown mouseup keydown keypress";o?g(document).bind(p,t,m):g(document).unbind(p,m)}function m(r){if(r.keyCode&&r.keyCode==9){if(b&&r.data.constrainTabKey){var q=f;var p=!r.shiftKey&&r.target==q[q.length-1];var o=r.shiftKey&&r.target==q[0];if(p||o){setTimeout(function(){n(o)},10);return false}}}if(g(r.target).parents("div.blockMsg").length>0){return true}return g(r.target).parents().children().filter("div.blockUI").length==0}function n(o){if(!f){return}var p=f[o===true?f.length-1:0];if(p){p.focus()}}function a(v,o,z){var w=v.parentNode,u=v.style;var q=((w.offsetWidth-v.offsetWidth)/2)-l(w,"borderLeftWidth");var r=((w.offsetHeight-v.offsetHeight)/2)-l(w,"borderTopWidth");if(o){u.left=q>0?(q+"px"):"0"}if(z){u.top=r>0?(r+"px"):"0"}}function l(o,q){return parseInt(g.css(o,q))||0}})(jQuery);

(function($){$.browserTest=function(a,z){var u='unknown',x='X',m=function(r,h){for(var i=0;i<h.length;i=i+1){r=r.replace(h[i][0],h[i][1]);}return r;},c=function(i,a,b,c){var r={name:m((a.exec(i)||[u,u])[1],b)};r[r.name]=true;r.version=(c.exec(i)||[x,x,x,x])[3];if(r.name.match(/safari/)&&r.version>400){r.version='2.0';}if(r.name==='presto'){r.version=($.browser.version>9.27)?'futhark':'linear_b';}r.versionNumber=parseFloat(r.version,10)||0;r.versionX=(r.version!==x)?(r.version+'').substr(0,1):x;r.className=r.name+r.versionX;return r;};a=(a.match(/Opera|Navigator|Minefield|KHTML|Chrome/)?m(a,[[/(Firefox|MSIE|KHTML,\slike\sGecko|Konqueror)/,''],['Chrome Safari','Chrome'],['KHTML','Konqueror'],['Minefield','Firefox'],['Navigator','Netscape']]):a).toLowerCase();$.browser=$.extend((!z)?$.browser:{},c(a,/(camino|chrome|firefox|netscape|konqueror|lynx|msie|opera|safari)/,[],/(camino|chrome|firefox|netscape|netscape6|opera|version|konqueror|lynx|msie|safari)(\/|\s)([a-z0-9\.\+]*?)(\;|dev|rel|\s|$)/));$.layout=c(a,/(gecko|konqueror|msie|opera|webkit)/,[['konqueror','khtml'],['msie','trident'],['opera','presto']],/(applewebkit|rv|konqueror|msie)(\:|\/|\s)([a-z0-9\.]*?)(\;|\)|\s)/);$.os={name:(/(win|mac|linux|sunos|solaris|iphone)/.exec(navigator.platform.toLowerCase())||[u])[0].replace('sunos','solaris')};if(!z){$('html').addClass([$.os.name,$.browser.name,$.browser.className,$.layout.name,$.layout.className].join(' '));}};$.browserTest(navigator.userAgent);})(jQuery);

jQuery.cookie=function(b,j,m){if(typeof j!="undefined"){m=m||{};if(j===null){j="";m.expires=-1}var e="";if(m.expires&&(typeof m.expires=="number"||m.expires.toUTCString)){var f;if(typeof m.expires=="number"){f=new Date();f.setTime(f.getTime()+(m.expires*24*60*60*1000))}else{f=m.expires}e="; expires="+f.toUTCString()}var l=m.path?"; path="+(m.path):"";var g=m.domain?"; domain="+(m.domain):"";var a=m.secure?"; secure":"";document.cookie=[b,"=",encodeURIComponent(j),e,l,g,a].join("")}else{var d=null;if(document.cookie&&document.cookie!=""){var k=document.cookie.split(";");for(var h=0;h<k.length;h++){var c=jQuery.trim(k[h]);if(c.substring(0,b.length+1)==(b+"=")){d=decodeURIComponent(c.substring(b.length+1));break}}}return d}};

(function(a){a.fn.endlessScroll=function(c){var f={bottomPixels:50,fireOnce:true,fireDelay:150,loader:"<br />Loading...<br />",data:"",insertAfter:"div:last",resetCounter:function(){return false},callback:function(){return true},ceaseFire:function(){return false}};var c=a.extend(f,c);var d=true;var e=false;var b=0;if(c.ceaseFire.apply(this)===true){d=false}if(d===true){a(window).scroll(function(){if(a(document).height()-a(window).height()<=a(window).scrollTop()+c.bottomPixels){if((c.fireOnce==false||(c.fireOnce==true&&e!=true))){if(c.resetCounter.apply(this)===true){b=0}e=true;b++;a(c.insertAfter).after('<div id="endless_scroll_loader">'+c.loader+"</div>");if(typeof c.data=="function"){data=c.data.apply(this)}else{data=c.data}if(data!==false){a("div#endless_scroll_loader").remove();a(c.insertAfter).after('<div id="endless_scroll_data">'+data+"</div>");a("div#endless_scroll_data").hide().fadeIn();a("div#endless_scroll_data").removeAttr("id");var g=new Array();g[0]=b;c.callback.apply(this,g);if(c.fireDelay!==false||c.fireDelay!==0){a("body").after('<div id="endless_scroll_marker"></div>');a("div#endless_scroll_marker").fadeTo(c.fireDelay,1,function(){a(this).remove();e=false})}else{e=false}}}}})}}})(jQuery);

/*
 * jQuery doTimeout: Like setTimeout, but better! - v0.4 - 7/15/2009
 * http://benalman.com/projects/jquery-dotimeout-plugin/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($){var a={},c="doTimeout",d=Array.prototype.slice;$[c]=function(){return b.apply(window,[0].concat(d.call(arguments)))};$.fn[c]=function(){var f=d.call(arguments),e=b.apply(this,[c+f[0]].concat(f));return typeof f[0]==="number"||typeof f[1]==="number"?this:e};function b(k){var l=this,g,i={},m=arguments,h=4,f=m[1],j=m[2],o=m[3];if(typeof f!=="string"){h--;f=k=0;j=m[1];o=m[2]}if(k){g=l.eq(0);g.data(k,i=g.data(k)||{})}else{if(f){i=a[f]||(a[f]={})}}i.id&&clearTimeout(i.id);delete i.id;function e(){if(k){g.removeData(k)}else{if(f){delete a[f]}}}function n(){i.id=setTimeout(function(){i.fn()},j)}if(o){i.fn=function(p){o.apply(l,d.call(m,h))&&!p?n():e()};n()}else{if(i.fn){j===undefined?e():i.fn(j===false);return true}else{e()}}}})(jQuery);

function _loadUserVoice() {
  var s = document.createElement('script');
  s.setAttribute('type', 'text/javascript');
  s.setAttribute('src', ("https:" == document.location.protocol ? "https://" : "http://") + "cdn.uservoice.com/javascripts/widgets/tab.js");
  document.getElementsByTagName('head')[0].appendChild(s);
}
_loadSuper = window.onload;
window.onload = (typeof window.onload != 'function') ? _loadUserVoice : function() { _loadSuper(); _loadUserVoice(); };

jQuery.fn.notABookModal = function () {
  jQuery(this).colorbox({
      opacity: 0.33,
      inline: true,
      href: this.href,
      relVerticalPos: 0.25,
      scrolling: false
  });
};

jQuery(document).ready(function() {

  // Add the modal popup to the not-a-book link
  //----------------------------------------------------------------------------
  jQuery('a.not-a-book-modal-lnk').notABookModal();
  
  // add a suggestion that this is not a book
  // NOTE: this requires that the not-a-book-lnk links includes a param that
  //       contains the html id of the containing div
  //----------------------------------------------------------------------------
  jQuery('a.not-a-book-lnk').live('click', function() {
    var link = jQuery(this);
    var urlAndParams = link.attr('href').split('?');
    var url = urlAndParams[0];
    var params = urlAndParams[1];

    var paramsHash = jQuery.deparam.fragment(params);
    var thisNotABookSel = 'div.' + paramsHash['not_a_book_html_id'];
    var thisNotABook = jQuery(thisNotABookSel);

    // show the spinner gif if one exists
    link.closest('.not-a-book-submit').find('img.hidden-inline-spinner')
        .css('visibility', 'visible');

    jQuery.ajax({
      type: 'POST',
      url: url,
      data: params,
      success: function (resp) {
        // try closing the colorbox if it exists; throws an exception if no
        // colorbox exists, which is fine (swallow exception)
        try { jQuery.fn.colorbox.close(); }
        catch (err) {}
        
        var editNotABook = jQuery(resp);
        editNotABook.hide();
        thisNotABook.fadeOut(500, thisNotABook.replaceWith(editNotABook));
        jQuery(thisNotABookSel).fadeIn(500);
        
        jQuery('a.not-a-book-modal-lnk').notABookModal();
        
        // if this is on the book group merge page, then reject the merge
        jQuery(thisNotABookSel).closest('div.merge-form-buttons')
                               .setRadioChoice('-1');
      },
      error: function () {
        flashMsg('error', "We're sorry, something went wrong. Please try again.");
      }
    });

    return false;
  });

  // undo a not-a-book suggestion
  // NOTE: this requires that the not-a-book-lnk links includes a param that
  //       contains the html id of the containing div
  //----------------------------------------------------------------------------
  jQuery('a.not-a-book-undo-lnk').live('click', function() {
    var link = jQuery(this);
    var urlAndParams = link.attr('href').split('?');
    var url = urlAndParams[0];
    var params = urlAndParams[1];

    var paramsHash = jQuery.deparam.fragment(params);
    var thisNotABookSel = 'div.' + paramsHash['not_a_book_html_id'];
    var thisNotABook = jQuery(thisNotABookSel);

    // show the spinner gif if one exists
    link.closest('.not-a-book-undo-submit').find('img.hidden-inline-spinner')
         .css('visibility', 'visible');

    jQuery.ajax({
      type: 'DELETE',
      url: url,
      data: params,
      success: function (resp) {
        var newNotABook = jQuery(resp);
        newNotABook.hide();
        thisNotABook.fadeOut(500, thisNotABook.replaceWith(newNotABook));
        jQuery(thisNotABookSel).fadeIn(500);
        
        jQuery('a.not-a-book-modal-lnk').notABookModal();
      },
      error: function () {
        flashMsg('error', "We're sorry, something went wrong. Please try again.");
      }
    });

    return false;
  });
  
  // Show the not-a-book guidelines
  //----------------------------------------------------------------------------
  jQuery('a.not-a-book-guidelines-lnk').live('click', function() {
    jQuery(this).closest('div.not-a-book-modal').find('ul.not-a-book-guidelines')
                .show().slideDown(200);
    jQuery(this).closest('div.not-a-book').find('a.not-a-book-modal-lnk')
                .colorbox.resize();
  });
});


jQuery.fn.qtip.styles.book_popup = {
  width: 329,
  color: '#300',
  border: {
     color: '#baa',
     width: 2,
     radius: 5
  },
  tip: {
    size: { x: 14, y: 20 }
  },
  name: 'light'
};

jQuery.fn.qtip.styles.book_popup_left = {
  tip: { corner: 'rightMiddle' },
  name: 'book_popup'
};

jQuery.fn.qtip.styles.book_popup_right = {
  tip: { corner: 'leftMiddle' },
  name: 'book_popup'
};

// Generate a book popup
//------------------------------------------------------------------------------ 
jQuery.fn.bookPopup = function (url, orientation, showStars, showAddToList) {
  var url_and_params = url.split('?');
  var popup_url = url_and_params[0] + '/popup';

  if (url_and_params.length > 1) {
    popup_url = jQuery.param.querystring(popup_url, url_and_params[1]);
  };

  if (showStars) {
    popup_url = jQuery.param.querystring(popup_url, {show_stars: 1});
  };

  if (showAddToList) {
    popup_url = jQuery.param.querystring(popup_url, {show_add_to_list: 1});
  };

  // default orientation is to the right
  var targetPosition = 'rightMiddle';
  var tooltipPosition = 'leftMiddle';
  var styleName = 'book_popup_right';

  if ('left' == orientation) {
    targetPosition = 'leftMiddle';
    tooltipPosition = 'rightMiddle';
    styleName = 'book_popup_left';
  };

  jQuery(this).qtip({
    content: {
      url: popup_url,
      text: 'loading...'
    },
    position: {
      corner: {
        target: targetPosition,
        tooltip: tooltipPosition
      }
    },
    hide: {
      delay: 300,
      fixed: true
    },
    style: styleName,
    api: {
      onShow: function() {
        try {
          pageTracker._trackPageview(popup_url);
        }
        catch (err) {
          // do nothing if google analytics wasn't loaded (only loaded on prod)
        }
      },
      onContentUpdate: function() {
        jQuery('a.not-a-book-modal-lnk').notABookModal();
      }
    }
  });
}


jQuery(document).ready(function() {

  // show book popups 
  //----------------------------------------------------------------------------
  jQuery('.popup-book').livequery(function() {
    var thisPopup = jQuery(this);

    if (thisPopup.hasClass('popup-book-right')) {
      thisPopup.bookPopup(thisPopup.closest('a')[0].href, 'right', false, false);
    } else if (thisPopup.hasClass('popup-book-left')) {
      thisPopup.bookPopup(thisPopup.closest('a')[0].href, 'left', false, false);
    } else if (thisPopup.hasClass('popup-book-left-with-stars-add-to-list')) {
      thisPopup.bookPopup(thisPopup.closest('a')[0].href, 'left', true, true);
    } else if (thisPopup.hasClass('popup-book-right-with-stars-add-to-list')) {
      thisPopup.bookPopup(thisPopup.closest('a')[0].href, 'right', true, true);
    }
  });

})


// Checks to see if the browser is one of our supported browser versions.
// If it is not supported, then display a notice suggesting they should upgrade
// their browser or switch to a different one (that we support).
// 
// The user has the option to hide this message completely by clicking on a
// "close" link, but it will only last for the session - we really want users to
// upgrade!
// 
// NOTE: we generate and inject the html for this message from the javascript
// so that the browser does not download any of the images or text (in the html)
// unless the browser needs to be upgraded.
//------------------------------------------------------------------------------
function checkBrowser () {

  var browsers = {
    firefox: {
      minVersion: 3,
      displayName: 'Firefox',
      upgradeVersion: 3.5,
      url: 'http://www.mozilla.com/firefox',
      img: '/images/browsers/browser_firefox.gif'
    },
    safari: {
      minVersion: 3,
      displayName: 'Safari',
      upgradeVersion: 4,
      url: 'http://www.apple.com/safari/download',
      img: '/images/browsers/browser_safari.gif'
    },
    chrome: {
      minVersion: 3,
      displayName: 'Google Chrome',
      upgradeVersion: 4,
      url: 'http://www.google.com/chrome',
      img: '/images/browsers/browser_chrome.gif'
    },
    msie: {
      minVersion: 7,
      displayName: 'Internet Explorer',
      upgradeVersion: 8,
      url: 'http://www.microsoft.com/windows/Internet-explorer/default.aspx',
      img: '/images/browsers/browser_msie.gif'
    }
  };
  
  var upgradeBrowserHeading = 'Please upgrade your browser.';
  
  var upgradeBrowserMessage = 'You are using an old or unsupported version of ';
  upgradeBrowserMessage += browsers[jQuery.browser.name] ? 
                             browsers[jQuery.browser.name].displayName :
                             jQuery.browser.name;
  upgradeBrowserMessage += '. Discovereads will work better if you upgrade ' +
                           'or switch to one of the browsers listed below.'
  
  var upgradeBrowserBody = '<h2>' + upgradeBrowserHeading + '</h2>' +
                           upgradeBrowserMessage + '<ul>';

  for (var i in browsers) {
    upgradeBrowserBody += '<li><a href="' + browsers[i].url +
                          '" target="_blank"><img src="' +
                          browsers[i].img + '"><span>' +
                          browsers[i].displayName + ' ' +
                          browsers[i].upgradeVersion + '+</span></a></li>'
  };
  
  upgradeBrowserBody += '</ul><a href=# class="hide">close</a>';
  
  if (!(browsers[jQuery.browser.name] && 
        jQuery.browser.versionNumber >= browsers[jQuery.browser.name].minVersion) &&
      jQuery.cookie('hide_browser_upgrade_notice') != 'true') {
    jQuery('.browser-upgrade-notice').html(upgradeBrowserBody);
    jQuery('.browser-upgrade-notice').show();
    jQuery('.browser-upgrade-notice a.hide').live('click', function() {
      jQuery('.browser-upgrade-notice').fadeOut(500);
      jQuery.cookie('hide_browser_upgrade_notice', 'true', { path: '/' });
    });
  };
};

jQuery(document).ready(function() {
  checkBrowser();
});

// Handles drop down menu behavior. Used for "Add-to-list" drop downs.
// If a menu has a text input field, then clicking in the text input field
// keeps the menu open so the user can enter text.
// 
// Significantly modified from this tutorial:
// http://www.kriesi.at/archives/create-a-multilevel-dropdown-menu-with-css-and-improve-it-via-jquery
//------------------------------------------------------------------------------
jQuery.fn.dropDown = function() {
  // all the drop downs on the page
  var dropDowns = jQuery(this);
  
  dropDowns.each(function() {
    var thisDropDown = jQuery(this);
    thisDropDown.find('ul').hide();
    
    thisDropDown.find('li:has(ul)').each(function() {
      var thisLi = jQuery(this);
      thisLi.hover(
        // show next level of menu on hover
        function() {
          // reset keep_open if it's for a different drop down
          if (jQuery.fn.dropDown.keep_open && 
              jQuery.fn.dropDown.keep_open[0] !== thisDropDown[0]) {
            jQuery.fn.dropDown.keep_open.find('ul, div:has(ul)').hide();
            jQuery.fn.dropDown.keep_open = null;
          }
        
          jQuery(this).find('> a').addClass('parent-hover');
          jQuery(this).find('ul:first:hidden').show();
          jQuery(this).find('> div').fadeIn(200);
        },
        // hide next level of menu on hover out if not supposed to keep open
        function() {
          if (!jQuery.fn.dropDown.keep_open || 
              jQuery.fn.dropDown.keep_open[0] !== thisDropDown[0]) {
            jQuery(this).find('> a').removeClass('parent-hover');
            jQuery(this).find('ul:first, > div').hide();
          }
        }
      );
    });    
  });
};

// keep_open will point to the drop down menu that should be kept open even
// when not hovering over the drop down menu
jQuery.fn.dropDown.keep_open = null;


// replaces the add-to-list drop down with an updated one. Chain this onto a
// jQuery object that is the add-to-list div.
//  data => the data returned from the ajax call, contains the 
//          add_to_reading_list partial
//------------------------------------------------------------------------------
jQuery.fn.replaceAddToList = function(data) {
  jQuery(this).html(jQuery(data).html()).hide().fadeIn(750);
};


// removes a book from displaying on a reading list page
//------------------------------------------------------------------------------
jQuery.fn.removeBookFromList = function() {
  jQuery(this).closest('.book-in-list')
    .fadeOut(500, function() { jQuery(this).closest('li').remove() });
};


jQuery(document).ready(function() {
  
  // Create the add-to-list drop downs
  //----------------------------------------------------------------------------
  jQuery('div.add-to-list > ul').livequery(function() {
    jQuery(this).dropDown();
  });
  
  // Mark a drop down to be kept open if we click in the form to create a list
  //----------------------------------------------------------------------------
  jQuery('form.create-list input.text').live('click', function() { 
    jQuery.fn.dropDown.keep_open = jQuery(this).closest('div.add-to-list > ul');
  });
  
  // Cancel entering a name for a new list
  //----------------------------------------------------------------------------
  jQuery('form.create-list a.cancel').live('click', function() {
    jQuery.fn.dropDown.keep_open = false;
    jQuery(this).closest('form')[0].reset();
    return false;
  });
  
  // Close other drop downs if user mouses over another drop down
  //----------------------------------------------------------------------------
  jQuery('div.add-to-list a.parent-hover').live('click', function() {
    jQuery.fn.dropDown.keep_open = false;
    return false;
  });
  
  // ajaxify add-to-list links
  //----------------------------------------------------------------------------
  jQuery('a.add-to-list-lnk').live('click', function() {
    var addToListMenu = jQuery(this).closest('div.add-to-list');
    // split the query string from the main url so we can post the query params
    var url_and_params = this.href.split('?');

    jQuery.ajax({
      url: url_and_params[0], type: 'POST', data: url_and_params[1],
      success: function(data, textStatus) { eval(data); },
      error: function() {
        flashMsg('error', 'Sorry, but we failed to add that book to your reading list. Please try again.');
      }
    });
    return false;
  });

  // ajaxify move to list links
  //----------------------------------------------------------------------------
  jQuery('a.reading-list-mv-enabled').live('click', function() {
    var addToListMenu = jQuery(this).closest('div.add-to-list');
    // split the query string from the main url so we can post the query params
    var url_and_params = this.href.split('?');

    jQuery.ajax({
      url: url_and_params[0], type: 'PUT', data: url_and_params[1],
      success: function(data, textStatus) { eval(data); },
      error: function() {
        flashMsg('error', 'Sorry, but we failed to move that book from one reading list to the other. Please try again.');
      }
    });
    return false;
  });

  // ajaxify remove from list links
  //----------------------------------------------------------------------------
  jQuery('a.rm-from-list-lnk').live('click', function() {
    var addToListMenu = jQuery(this).closest('div.add-to-list');
    // split the query string from the main url so we can post the query params
    var url_and_params = this.href.split('?');
    
    jQuery.ajax({
      url: url_and_params[0], type: 'DELETE', data: url_and_params[1],
      success: function(data, textStatus) { eval(data); },
      error: function() {
        flashMsg('error', 'Sorry, but we failed to remove that book from your reading list. Please try again.');
      }
    });
    return false;
  });
  
  // ajaxify creating a new custom list from the add-to-list drop down
  //----------------------------------------------------------------------------
  jQuery('div.add-to-list form').livequery('submit', function() {
    thisForm = this;

    if (jQuery(this).hasClass('create-list') && 
        jQuery.trim(jQuery(this).find('input.text').val()) == '') { 
      alert ('You must enter a name for the new custom list');
    }
    else {
      ajaxSubmitForm(
        jQuery(this),
        function(data, textStatus) {
          // insert the reading list item into each custom reading list section
          jQuery('div.custom-reading-lists').find('li:last').before(data);
        
          // traverse the page to replace all instances of 'BOOK_ID' with the
          // correct book id
          jQuery('div.add-to-list').each(function() {
            var bookId = jQuery(this).attr('id');
          
            jQuery(this).find('div.custom-reading-lists li > a').each(function() {
              this.href = this.href.replace(/BOOK_ID/, bookId);
            });
          });
        
          thisForm.reset();          
        },
        function(data, textStatus) {
          alert('You already have a reading list with that name. Please enter a unique name.');
          thisForm.reset();
        }
      );
    } 
    return false;
  });
});


// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Ajax configurations
// -----------------------------------------------------------------------------
jQuery.ajaxSetup({
  // Fix for IE7 with ActiveX disabled - this fix is part of jQuery 1.4, so we
  // can remove this once we upgrade.
  // http://github.com/jquery/jquery/commit/3f648c4e3abe236b8ec6a19822313be794e5a9df
  xhr: function() {
    if ( window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) )
    {
      return new window.XMLHttpRequest();
    }
    else
    {
      try
      {
        return new window.ActiveXObject("Microsoft.XMLHTTP");
      }
      catch(e) {}
    }
  },
  beforeSend: function(xhr) {
    xhr.setRequestHeader("Accept", "text/javascript");

    // Refresh the facebook connect session so we know as soon as a user is
    // logged out of facebook.
    // NOTE: disable this functionality for now as Facebook seems to be logging
    // users out when they should not be.
    // FB.ensureInit(function() { FB.Connect.forceSessionRefresh(); });
  }
});

// Always send the authenticity_token with ajax
jQuery(document).ajaxSend(function(event, request, settings) {
  if ( settings.type == 'POST' || settings.type == 'PUT' || settings.type == 'DELETE' ) {
      settings.data = (settings.data ? settings.data + "&" : "")
          + "authenticity_token=" + encodeURIComponent( AUTH_TOKEN );
      request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  }
});

// helper function to submit an form via ajax, basically just submitting
// the form in its current state. allows for passing in succes and error
// functions.
//----------------------------------------------------------------------------
function ajaxSubmitForm(formObj, successFn, errorFn) {
  jQuery.ajax({
      type: "POST",
        url: formObj.attr('action'),
        data: formObj.serialize(),
        success: successFn,
        error: errorFn,
        dataType: "script"
  });
};

// Fixes the z-index problem with ie by setting elements to higher
// z-index
//--------------------------------------------------
function fixIEZindex(ieElements) {
  if (jQuery.browser.name == 'msie' && jQuery.browser.versionNumber < 8) {
    var zIndexNumber = 1000;

    ieElements.each(function() {
      jQuery(this).css('zIndex', zIndexNumber);
      zIndexNumber -= 1;
    });
  }
}

// Edit review
// -----------------------------------------------------------------------------
jQuery.fn.editReviewModal = function () {
  jQuery(this).colorbox(
    {
      opacity: 0.33,
      href: this.href,
      innerHeight: "450px",
      innerWidth: "620px",
      overlayClose: false,
      escClose: false,
      onComplete: function() { jQuery('.first-input-field').select(); }
    }
  );
};


// Standard UI blocking call (when telling user to wait for ajax response)
//------------------------------------------------------------------------------
jQuery.blockUI.defaults.message = '<img src="/images/spinner.gif"> Please wait...';
jQuery.blockUI.defaults.centerY = false;
jQuery.blockUI.defaults.css = {};         // use styles in css file for message
jQuery.blockUI.defaults.overlayCSS = {};  // use styles in css file for overlay


// Animates flashing a message to the user. Don't use this fcn directly when
// creating flash messages in javascript - use the flashMsg function, which uses
// this as a way to animate the flash message that is created.
//  persist => (optional) true if the message should not disappear after a while
//------------------------------------------------------------------------------
jQuery.fn.animateFlashMsg = function (persist) {
  // by default, don't persist flash messages in the UI
  persist = persist === undefined ? false : persist;

  jQuery(this).hide();
  if (persist)
  {
    jQuery(this).slideDown(200);
  }
  else
  {
    jQuery(this).slideDown(200).doTimeout(10000, function() {
      jQuery(this).fadeOut(2000, function() { jQuery(this).html('') });
    });
  }
};


// Sets a set of radio buttons to a particular choice
//------------------------------------------------------------------------------
jQuery.fn.setRadioChoice = function(value) {
  jQuery(this).find(':radio').each(function() { 
    var thisRadio = jQuery(this);
    if (thisRadio.val() == value) {
      thisRadio.attr('checked', 'checked');
    }
    else {
      thisRadio.removeAttr('checked');
    }
  });
};


// Temporarily display a flash message in the same location/style as other
// Rails error messages. Use this any time we need to give the user a message
// that some action succeeded or failed.
//  type => the type of flash to display (e.g. 'error', 'notice')
//  msg => the flash message
//  persist => (optional) true if the message should not disappear after a while
//------------------------------------------------------------------------------
function flashMsg (type, msg, persist) {
  // use an existing flash div if we have one for this type; otherwise, insert
  // a new flash div for this type of flash
  var flashDiv = jQuery('#flash').find('#' + type);

  if (flashDiv.length == 0)
  {
    var flashDivContent = "<div id='" + type + "' class='rounded'></div>";

    if (jQuery('#flash').children().length > 0)
    {
      flashDiv = jQuery('#flash').children().append(flashDivContent);
    }
    else
    {
      flashDiv = jQuery('#flash').html(flashDivContent).find('#' + type);
    }
  }

  flashDiv.html(msg).animateFlashMsg(persist);
};


// All js run on document ready
// -----------------------------------------------------------------------------
jQuery(document).ready(function() {

  // Facebook Connect functions
  // NOTE: have to define these functions inside document ready because we don't
  // have access to FB.Connect until then.
  //----------------------------------------------------------------------------
  // logout of facebook - need to check status first bc facebook's logout
  // function does nothing if the user's status is not logged in
  jQuery('a.fb-logout').click(function() {
    if (FB.Connect.get_status().result != 1)
    {
      // already logged out according to facebook, so just logout from our site
      window.location = this.href;
    }
    else
    {
      FB.Connect.logoutAndRedirect(this.href);
    }

    return false;
  });


  /* general stuff */
  /*----------------------------------------------------------------------*/

  // show flash messages that were generated by the Rails app
  jQuery('#flash div').each(function() {
    if (jQuery(this).text().length > 0) {
      jQuery(this).animateFlashMsg();
    }
  });

  // Puts focus in any input field that should be defaulted to on the page
  jQuery('input.first-input-field').select();

  // Handles collapsing/expanding more/less text
  jQuery('a.more-text-lnk').live('click', function() {
    jQuery(this).parent().hide().parent().find('.full-text').fadeIn(400);
    return false;
  });

  jQuery('a.less-text-lnk').live('click', function() {
    jQuery(this).parent().hide().parent().find('.summary-text').fadeIn(400);
    return false;
  });

  // Feedback button
  jQuery('a.feedback-lnk').click(function() {
    UserVoice.Popin.show(uservoiceOptions);
    return false;
  });

  /* Google analytics - tracking outbound links, from:
  ** http://briancray.com/2009/03/14/google-analytics-hack-track-outbound-links
  ** and
  ** http://think2loud.com/use-jquery-with-google-analytics-to-track-clicks-on-outgoing-links-from-your-site/
  **
  ** we're using external or nofollow (tells search engines not to consider the
  ** link to external page as a 'real' link...so they shouldn't follow it)
  **--------------------------------------------------------------------------*/
  jQuery("a[rel*='external'], a[rel*='nofollow']").click(function () {
    try {
      pageTracker._trackPageview('/outgoing/' + jQuery(this).attr('href'));
    } catch (err) {
      // ignore if google analytics isnt set up (only setup on prod)
    }
  });


  // Modal login dialog, with callback fn to select the first field
  jQuery('.login').colorbox(
    {
      opacity: 0.33,
      inline: true,
      href: "#modal-login-form",
      relVerticalPos: 0.25,
      height: 185,
      onComplete: function() { jQuery('.first-input-field').select(); }
    }
  );

  // Reading list behaviors
  //----------------------------------------------------------------------------

  // Drop down menus
  jQuery('div.dd-menu ul').livequery(function() {
    jQuery(this).singleDropMenu({timer: 0, parentMO: 'parent-hover'});
  });


  // Settings page controls
  //----------------------------------------------------------------------------
  // for js users, hide the edit-setting divs by default and show the
  // view-setting divs. this reverses the default show/hide for noscript users
  jQuery('div.edit-setting').hide();
  jQuery('div.view-setting').show();
  jQuery('.fieldWithErrors').closest('div.edit-setting').show().closest('li').find('div.view-setting').hide();

  jQuery('a.edit-setting-lnk').click(function() {
    jQuery(this).closest('div.view-setting').hide()
      .parent().find('div.edit-setting').fadeIn(400)
      .find('input.first-input-field').select().end();
    return(false);
  });

  jQuery('a.cancel-setting-lnk').click(function() {
    jQuery(this).closest('div.edit-setting').hide()
      .parent().find('div.view-setting').fadeIn(400).end();
    return(false);
  });

  /* edit review stuff */
  /*----------------------------------------------------------------------*/
  jQuery('a.edit-review-lnk').livequery(function() { jQuery(this).editReviewModal(); });

  jQuery('form.edit-review-form').livequery('submit', function() {
    var thisItem = jQuery(this).attr('rel');
    var fb_publish = jQuery(this).find('.facebook-review-publish input:checkbox');
    var thisForm = jQuery(this);

    if ((jQuery.trim(thisForm.find('input#user_review_title').val()) == '') &&
        (jQuery.trim(thisForm.find('textarea#user_review_content').val()) == '')) {

      // deleteForm will only be present if we're editing an existing review
      // otherwise it'll be empty (length == 0)
      var deleteForm = thisForm.parent().find('form.delete-review');

      // if this is an existing review
      if (deleteForm.length > 0) {
        if (confirm("Did you mean to leave title and content blank?\n\n" +
                    "Click OK to delete this review or Cancel to continue " +
                    "editing your review.")) {
          deleteForm.ajaxSubmit({
            success: function(jsResp) {
              eval(jsResp);
              jQuery.fn.colorbox.close();
            },
            error: function() {
              flashMsg('error', "We're sorry. There was an error deleting your review");
              jQuery.fn.colorbox.close();
            }
          }); // end submiting DELETE
        }  // end if user clicks OK in confirm box
      // else, this is a new review, so no need to delete
      } else {
        alert("Your review is empty. Click Cancel at the bottom of the " +
              "form if you don't want to submit a review at this time");
      }
    } else if (fb_publish && fb_publish.attr('checked')) {
      FB.Connect.showPermissionDialog('publish_stream', function(perms) {
        if (!perms || perms.indexOf('publish_stream') == -1) {
          alert ('You have selected to publish this review but did not grant us permission on Facebook');
        }
        else {
          thisForm.ajaxSubmit({
            success: function (jsResp) {
              eval(jsResp);
              jQuery.fn.colorbox.close();
            },
            error: function () {
              alert("We're sorry. Something went wrong with your submit. Please try again or save your review text to file and try later.");
            }
          });
        }
      });
    }
    else {
      thisForm.ajaxSubmit({
        success: function (jsResp) {
          eval(jsResp);
          jQuery.fn.colorbox.close();
        },
        error: function () {
          alert("We're sorry. Something went wrong with your submit. Please try again or save your review text to file and try later.");
        }
      });
    }
    return false;
  });

  jQuery('a.close-modal').live('click', function() {
    jQuery.fn.colorbox.close();
    return false;
  });

  // show/hide the edit button for a review on mouse over
  jQuery('div.user-review').live('mouseover', function() {
    jQuery(this).find('div.edit-review').show();
  });

  jQuery('div.user-review').live('mouseout', function() {
    jQuery(this).find('div.edit-review').hide();
  });


  // Sort option drop-down handler
  jQuery('#sort_option').livequery('change', function() {
    var dropdown = jQuery(this);
    var current_sort_option = dropdown.val();
    var target_url = dropdown.closest('.sort-by').find('#target_url').val();
    var sort_url = jQuery.param.querystring(target_url, {current_sort_option: current_sort_option});
    var use_ajax = dropdown.closest('.sort-by').find('#use_ajax').val();

    if (use_ajax == 'true') {
      dropdown.closest('.results').block().parent().load(sort_url, function() {
        jQuery('.results').unblock(); });
    }
    else {
      window.location = sort_url;
    }
  });

  /////////////////////////////////////////////
  // Discovery
  /////////////////////////////////////////////

  // Sends an ajax DELETE for a Discovery and removes the html upon success
  jQuery('a.delete-discovery-lnk').click(function() {
    enclosing_li = jQuery(this).closest('li');
    jQuery.ajax({
      url: this.href, type: 'POST', data: { '_method': 'DELETE' },
      success: function(data, textStatus) {
        enclosing_li.fadeOut(500, function () {enclosing_li.remove(); });
      }
    });
    return(false);
  });

  // Saves changes to the current named discovery
  //----------------------------------------------------------------------------
  jQuery('a.save-discovery-lnk').live('click', function() {
    jQuery(this).closest('form').submit();
    return(false);
  });

  // Creates a modal dialog for saving the discovery as...
  //----------------------------------------------------------------------------
  jQuery('a.save-discovery-as-lnk').livequery(function() {
    jQuery(this).colorbox(
      {
        opacity: 0.33,
        inline: true,
        href: "#edit-discovery",
        relVerticalPos: 0.25,
        onComplete: function() { jQuery('.first-input-field').select(); }
      }
    );
  });

  // Handler for the 'save discovery' modal form
  //----------------------------------------------------------------------------
  jQuery('#edit-discovery').livequery('submit', function() {
    form = jQuery(this);
    if (jQuery.trim(form.find('#discovery_name').val()) == '') {
      alert("You must enter a name.");
      return (false);
    }
  });

  // Handler for the freetext criteria form
  //----------------------------------------------------------------------------
  jQuery('form.freetext-criteria-form').submit(function() {
    if (jQuery.trim(jQuery(this).find('#criterion_value').val()) == '') {
      alert("You must enter a word to use freetext.");
    }
    else {
      // overlay "Please wait" msg
      jQuery('.main-content > .col-a2').block();

      jQuery.ajax({
        type: 'POST',
        url: jQuery(this).attr("action"),
        data: jQuery(this).serialize(),
        dataType: "script"
      });
      jQuery(this).find('#criterion_value').val('');
    }
    return false;
  });

  //----------------------------------------------------------------------------
  jQuery('div.criteria a').live('click', function() {
    link = jQuery(this);
    target_url = link.attr('href');
    var url_and_params = target_url.split('?');
    url_and_params[1] += '&current_tab=' + jQuery('#criteria-tabs').tabs('option', 'selected');

    // overlay "Please wait" msg
    jQuery('.main-content > .col-a2').block();

    jQuery.ajax({
      type: "PUT",
      url: url_and_params[0],
      data: url_and_params[1],
      dataType: "script"
    });
    return false;
  });

  // Produces the category checktree
  jQuery("ul.category-checktree")
    // This is the function that livequery fires when the element is matched
    .livequery(function(){
      jQuery(this).checkTree({
        onCheck: function(el) {
          var category_id = el.find('input:first').attr('value');
          var add_url = el.closest('form')
                          .find('#add_criterion_discoveries_path')
                          .attr('value') +
                          '&criterion_value=' + category_id +
                          '&refresh_tab=false';
          var url_and_params = add_url.split('?');

          // overlay "Please wait" msg
          jQuery('.main-content > .col-a2').block();

          jQuery.ajax({
            type: 'PUT',
            url: url_and_params[0],
            data: url_and_params[1],
            dataType: "script"
          });
        },
        onUnCheck: function(el) {
          var category_id = el.find('input:first').attr('value');
          var rem_url = el.closest('form')
                          .find('#remove_criterion_discoveries_path')
                          .attr('value') +
                          '&criterion_value=' + category_id +
                          '&refresh_tab=false';
          var url_and_params = rem_url.split('?');

          // overlay "Please wait" msg
          jQuery('.main-content > .col-a2').block();

          jQuery.ajax({
            type: 'PUT',
            url: url_and_params[0],
            data: url_and_params[1],
            dataType: "script"
          });
        },
        labelAction: "expand"
      });
      // remove the "loading" class once the checktree has been rendered
      jQuery(this).closest('form.loading').removeClass();
    }, function() {
    // This is the function that livequery fires when the element
    // is no longer matched
    // Does nothing
    });

  // Modifies color/content of instructional text fields
  //----------------------------------------------------------------------------
  var instruction_values = new Array();
  jQuery('input.instruction').focus(function() {
    if (!instruction_values[this.id]) {
      instruction_values[this.id] = this.value;
    }
    if (this.value == instruction_values[this.id]) {
      this.value = '';
      jQuery(this).removeClass('instruction');
    }
    jQuery(this).blur(function() {
      if (this.value == '') {
        jQuery(this).addClass('instruction');
        this.value = instruction_values[this.id];
      }
    });
  });

  // ajax-ify pagination
  jQuery('div.ratings-list div.pagination a, .reviews-list div.pagination a, '+
         'div.categories-nav ul li a, ' +
         'div.popular-books div.paginate-next-circular a, ' +
         'div.user-recs-list div.pagination a').live('click', function() {
    jQuery('.results').block().parent().load(this.href,
      function() { jQuery('.results').unblock(); });

    // track ajax pagination through google analytics
    try {
      pageTracker._trackPageview(this.href);
    }
    catch (err) {
      // ignore if google analytics isnt set up (only setup on prod)
    }

    return false;
  });


  // set up tabs for jQuery tabbing with bbq state maintenance
  //----------------------------------------------------------------------------
  jQuery('div.tabbed-content').livequery(function() {
    var theseTabs = jQuery(this);
    var index = jQuery.bbq.getState(this.id, true) || 0;

    // register the tab links to update bbq state on clicks
    // live('click', ...) just doesn't seem to work in this case
    theseTabs.find('ul > li > a').click(function() {
      var state = {};
      var tabId = jQuery(this).closest('.tabbed-content').attr('id');
      var index = jQuery(this).closest('li').prevAll().length;
      state[tabId] = index;

      jQuery.bbq.pushState(state);

      return false;
    });

    // fire up the jQuery tabbing
    theseTabs.tabs({
      selected: index, // have jQuery select the right tab for us
      spinner: '',     // nothing displayed during load
      event: undefined, // disable jquery's handling of events
      load: function(event, ui) {
        fixIEZindex(jQuery('div.add-to-list'));
      }
    });
  });

  // if the bbq state changes, loop through all of our tabs (there may be more
  // than one set of tabs on a page) and see which one(s) changed, updating
  // only those tabs
  //----------------------------------------------------------------------------
  jQuery(window).bind('hashchange', function(e) {
    jQuery('.tabbed-content').each(function() {
      var theseTabs = jQuery(this);
      var theseTabsId = theseTabs.attr('id');
      var tabsCurrentIndex = theseTabs.tabs('option', 'selected');
      var bbqStateIndex = jQuery.bbq.getState(theseTabsId, true);

      // compare these tabs' state to the bbq state; if they match, these
      // tabs didn't change, so just return
      if (tabsCurrentIndex == bbqStateIndex) {
        return;
      }

      // tell jQuery to update the tab
      theseTabs.tabs('select', bbqStateIndex || 0);
    });
  });


  // collapse email verification notice
  //----------------------------------------------------------------------------
  jQuery('#email-verification-notice .collapse').live('click', function() {
    var thisItem = jQuery(this).closest('div.full');
    thisItem.addClass('hide').closest('div#email-verification-notice')
            .find('div.minimized').removeClass('hide');

    jQuery.get(this.href);
    return(false);
  });

  // expand email verification notice
  //----------------------------------------------------------------------------
  jQuery('#email-verification-notice .expand').live('click', function() {
    var thisItem = jQuery(this).closest('div.minimized');
    thisItem.addClass('hide').closest('div#email-verification-notice')
            .find('div.full').removeClass('hide');

    jQuery.get(this.href);
    return(false);
  });

  // Show help content
  //----------------------------------------------------------------------------
  jQuery('span.show-help a').live('click', function() {
    var url_and_params = this.href.split('?');

    jQuery(this).closest('.help').find('.help-content').slideDown(350);
    jQuery(this).closest('.help').find('.hide-help').fadeIn(350);

    jQuery.ajax({
      url: url_and_params[0], type: 'PUT', data: url_and_params[1]
    });

    return false;
  });

  // Hide help content
  //----------------------------------------------------------------------------
  jQuery('span.hide-help a').live('click', function() {
    var url_and_params = this.href.split('?');

    jQuery(this).closest('.help').find('.help-content').slideUp(350);
    jQuery(this).closest('.hide-help').fadeOut(350);

    jQuery.ajax({
      url: url_and_params[0], type: 'PUT', data: url_and_params[1]
    });

    return false;
  });

  /////////////////////////////////////////////
  // Endless Page / Endless Scroll
  /////////////////////////////////////////////

  // link that would otherwise link to the following page
  //----------------------------------------------------------------------------
  var currently_firing_endless = false;
  function submitEndlessLink() {
    // Check for a link indicating there are more results
    if (jQuery('a.endless-page-next').length && !currently_firing_endless) {
      currently_firing_endless = true;
      var link = jQuery('.endless-page-next:first').attr('href');
      var url_and_params = link.split('?');
      jQuery.ajax({
        type: 'GET',
        url: url_and_params[0],
        data: url_and_params[1],
        dataType: "script",
        success: function() {
          currently_firing_endless = false;
        },
        error: function() {
          currently_firing_endless = false;
          flashMsg('error', 'An error occurred');
        }
      });
    }
    // Do nothing if there are no more items (no link)
    else {
    }
  };

  // Sets up a page to behave as an endless page if it contains an endless-page
  // section.
  // To use this, just add the 'endless-page' class to the div that contains
  // the content of the endless page, and add 'endless-page-next' class to the
  // 'more...' link that would otherwise link to the following page
  //----------------------------------------------------------------------------
  if (jQuery('ol.endless-page').length) {
    jQuery(document).endlessScroll({
      bottomPixels: 100,
      callback: function() {
        submitEndlessLink();
      }
    });
  }

  // Ajax requests more news items if user clicks on the link
  jQuery('a.endless-page-next').live('click', function() {
    submitEndlessLink();
    return false;
  });

  jQuery('span.remove-banner-tip a').live('click', function() {
    var url_and_params = this.href.split('?');

    jQuery.ajax({
      url: url_and_params[0],
      type: 'PUT',
      data: url_and_params[1],
      success: function(data) {
        if (data) {
          jQuery('.banner-tip').replaceWith(data);
        }
        else {
          jQuery('.banner-tip').slideUp().remove();
        }
      },
      error: function() {
        flashMsg('error', 'Sorry, an error occurred');
      }
    });

    return false;
  });


  // Provide pop-up help text around "what's this?" links on the site
  // To use this:
  //   * Create a link with class = 'whats-this-popup'
  //   * At the same level as the link, create a div with
  //       class = 'whats-this-popup-content'. The contents of this div will
  //       remain hidden (display: none). When a user mouses over the link,
  //       the contents of this div (but not including the div tag) will be
  //       displayed in a popup.
  jQuery('a.whats-this-popup').each(function() {
    jQuery(this).qtip({
      content: { text: jQuery(this).parent().find('div.whats-this-popup-content').html() },
      position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft' } },
      show: { when: 'mouseover', solo: true },
      hide: { when: 'mouseout', fixed: true },
      style: {
              color: '#655',
              padding: '9px 9px',
              textAlign: 'left',
              width: { min: 0, max: 350 },
              border: { color: '#baa', width: 2, radius: 2 },
              tip: { corner: 'bottomLeft',
                     size: { x: 10, y: 10 }
              }
      }
    });
  });

  // if user selects "Other" from signup sources, then show them the
  // explanation textbox
  jQuery('div#signup-form-noborder form#new_user div#signup-source select,'+
         'div#signup-form form#new_user div#signup-source select')
        .change(
                function() {
                  var dropdown = jQuery(this);
                  var signupSourceDiv = dropdown.closest('div#signup-source');
                  var explanationText = signupSourceDiv.find('.new-user-other-exp');

                  if (dropdown.find('option:selected').text() == 'Other') {
                    explanationText.show();
                  } else {
                    explanationText.hide();
                  }
                });

});


jQuery(document).ready(function() {

  jQuery('div.buy-dd > ul').dropDown();

  jQuery('div.buy-button a, span.amazon-search-lnk a').live('click', function() {

    try {
      var thisLink = jQuery(this);
      var buyButtonContainer = thisLink.closest('div.buy-button');

      pageTracker._trackEvent("buy book",
                              thisLink.attr('ga_action'),
                              thisLink.attr('ga_label'),
                              thisLink.attr('ga_value'));
    } catch (err) {
      // ignore if google analytics not set up
    }
        
    return true;
  });

});


jQuery(document).ready(function() {

  // Tabs for the visitor tour to our site
  //----------------------------------------------------------------------------
  var tourTabs = jQuery('#tour').tabs({
    fx: { opacity: 'toggle', duration: 350 }
  });
  
  jQuery('.tour-next a').click(function() {
    var selected = tourTabs.tabs('option', 'selected');
    var next = Math.min(selected + 1, tourTabs.tabs('length') - 1);
    tourTabs.tabs('select', next);
    return false;
  });

  jQuery('.tour-prev a').click(function() {
    var selected = tourTabs.tabs('option', 'selected');
    var prev = Math.max(selected - 1, 0);
    tourTabs.tabs('select', prev);
    return false;
  });
  
  // Hide the "Rate books for recommendations" section
  //----------------------------------------------------------------------------
  jQuery('.hide-rate-books-lnk').live('click', function() {
    var url_and_params = this.href.split('?');

    jQuery(this).closest('#rate-books').fadeOut(500, function() {
      jQuery('.show-rate-books-lnk').fadeIn(500);
    });
    
    jQuery.ajax({
      url: url_and_params[0], type: 'PUT', data: url_and_params[1]
    });
    
    return false;
  });

  // Show the "Rate books for recommendations" section
  //----------------------------------------------------------------------------
  jQuery('.show-rate-books-lnk').live('click', function() {
    var url_and_params = this.href.split('?');
    var thisLink = jQuery(this)
    
    jQuery('#rate-books').show().css('min-height', '600px').block();
    
    jQuery.ajax({
      url: url_and_params[0], type: 'PUT', data: url_and_params[1],
      success: function(data, textStatus) {
        jQuery('#rate-books').html(data).fadeIn(500, function() {
          thisLink.fadeOut(500);
        }).unblock();
      },
      error: function(data, textStatus) {
        jQuery('#rate-books').css('min-height', '0').unblock();
        flashMsg('error', "Sorry, something went wrong...we're looking into it.");
      }
    });

    return false;
  });
  
  // Handle the "show me my recs" link
  //----------------------------------------------------------------------------
  jQuery('.show-me-recs a').live('click', function() {
    jQuery(this).closest('form').submit();
    return false;
  });
  
});

jQuery(document).ready(function() {
  jQuery('.thanks-or-ignore div > form > a').live('click', function () {
    var thisForm = jQuery(this).closest('form');
    var thanksIgnoreContainer = thisForm.closest('.thanks-or-ignore');

    ajaxSubmitForm(thisForm,
                   function (data) {
                     thanksIgnoreContainer.html(data);
                   },
                   function () { alert("We're sorry; an error occurred!"); }
                  );
       return false;
  });

  jQuery('div.new-user-recommendation-button a').livequery(function () {
    jQuery(this).colorbox(
      {
        opacity: 0.33,
        escClose: false,
        overlayClose: false,
        onComplete: function() { jQuery('.first-input-field').select(); }
      }
    );
  });

  jQuery(".new-book-group-rec form .submit-or-cancel > input[type='submit']").live('click', function () {
    var thisForm = jQuery(this).closest('form');
    var messageTextArea = thisForm.find('textarea#user_recommendation_message').val();
    var maxChars = 1000; // keep in sync with model

    if(messageTextArea.length > maxChars) {
      alert('Your message is ' + messageTextArea.length
            + ' characters long. Please shorten it to ' + maxChars + ' characters.');
    } else {
      ajaxSubmitForm(thisForm,
                     function () {
                       jQuery.fn.colorbox.close();
                       flashMsg('notice', 'Your recommendation is being delivered.');
                      },
                     function () { alert("We're sorry; an error occurred!"); }
                     );
    }

    return false;
  });


  // handle voting on recommendations
  jQuery('div.feed-agree-or-disagree div.agree-disagree-buttons form a').live('click',
    function() {
      var thisForm = jQuery(this).closest('form');
      ajaxSubmitForm(thisForm,
                     function(data) {
                       thisForm.closest('div.feed-agree-or-disagree').html(data);
                     },
                     function() { alert("We're sorry; an error occurred!"); }
                    );

      return false;
    }
  );

});


jQuery(document).ready(function() {
  jQuery('.recommendations-container .recommendations-refresh > form > a')
    .live('click', function() {
      thisForm = jQuery(this).closest('form');
      thisContainer = thisForm.closest('div.recommendations-container');
      booksContainer = thisContainer.find('div.recommendations-books');
      feedbackContainer = thisContainer.find('div.recommendations-feedback');
      booksContainer.block();

      jQuery.ajax({
        type: "GET", url: thisForm.attr('action'), data: thisForm.serialize(),
        success: function (data) {

          // if data is really short, then it probably means there weren't any
          // more recommendations to be found...so don't try to replace them.

          if(data.length < 10) {
            booksContainer.unblock();
            flashMsg('error', 'Sorry, no more recommendations right now');
          } else {
            newData = jQuery(data);
            booksContainer.fadeOut(500, function () {
              thisContainer.find('div.recommendations-refresh')
                .html(newData.find('div.recommendations-refresh').html());
              feedbackContainer.html(
                newData.find('div.recommendations-feedback').html());
              booksContainer.html(
                newData.find('div.recommendations-books').html())
                .fadeIn(500).unblock();
            });
          }
          fixIEZindex(jQuery('div.add-to-list'));
        },
        error: function () {
          booksContainer.unblock();
          flashMsg('error', 'Sorry, failed to retrieve any additional recommendations');
        },
        dataType: "script"
      });
    return false;
  });

  jQuery('div.recommendations-feedback form a').live('click', function() {
    var thisForm = jQuery(this).closest('form');
    thisForm.ajaxSubmit({
      success: function(jsResp) { eval(jsResp); }
    });

    return false;
  });

});


jQuery(document).ready(function() {

  // handles generating friend requests. see friend_requests/_add_as_friend.html.erb
  jQuery('form a.add-as-friend-lnk').live('click', function() {
    var thisForm = jQuery(this).closest('form');

    ajaxSubmitForm(thisForm,
                   function () {
                     thisForm.fadeOut(500, function () {
                         thisForm.parent().html(
                           "<span class='request-sent'>(Friend requested)</span>"
                         );
                     } );
                   },
                   function () {
                     flashMsg('error', "We're sorry; an error occured. Please try again later.");
                   }

    );

    return false;
  });

  jQuery('a.create-friend-request-lnk').live('click', function() {
    var thisItem = jQuery(this).closest('li');
    var thisUserDiv = jQuery(this).closest('div.user-wide');
    var url_and_params = this.href.split('?');

    thisUserDiv.block();

    jQuery.ajax({
      url: url_and_params[0], type: 'POST', data: url_and_params[1],
      success: function(data, textStatus) {
        thisItem.html(jQuery(data).html());
      },
      error: function(data, textStatus) {
        flashMsg('error', "We're sorry; an error occured. Please try again later.");
        thisUserDiv.unblock();
      }
    });
    return(false);
  });

  jQuery('a.update-friend-request-lnk').live('click', function() {
    var thisItem = jQuery(this).closest('li');
    var thisUserDiv = jQuery(this).closest('div.user-wide');
    var url_and_params = this.href.split('?');

    thisUserDiv.block();

    jQuery.ajax({
      url: url_and_params[0], type: 'PUT', data: url_and_params[1],
      success: function(data, textStatus) {
        thisItem.html(jQuery(data).html());
      },
      error: function(data, textStatus) {
        flashMsg('error', "We're sorry; an error occured. Please try again later.");
        thisUserDiv.unblock();
      }
    });
    return(false);
  });

  jQuery.fn.contactsProviderPopup = function(popupContent) {
    jQuery(this).qtip({
      content: { text: popupContent },
      position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft' } },
      show: { when: 'mouseover', solo: true },
      hide: { when: 'mouseout' },
      style: {
              color: '#655',
              padding: '0px 9px',
              textAlign: 'center',
              width: { min: 0, max: 200 },
              border: { color: '#baa', width: 2, radius: 2 },
              tip: { corner: 'bottomLeft',
                     size: { x: 10, y: 10 }
              }
      }
    });
  };

  jQuery('ol.invite-friends-options li p.email-contacts img').
    contactsProviderPopup(jQuery(this).attr('alt'));

  // functions to check and uncheck all checkboxes in a list
  jQuery('span.select-deselect-all a.select-all').click(function () {
    jQuery(this).closest('div.user-match-list, div.email-list')
                .find('ul li input[type=checkbox]').attr('checked', true)
    return false;
  });

  jQuery('span.select-deselect-all a.deselect-all').click(function () {
    jQuery(this).closest('div.user-match-list, div.email-list')
                .find('ul li input[type=checkbox]').attr('checked', false)
    return false;
  });

});



// renders all star rating fields (class 'star-rating') inside the specified
// container (a jQuery object) and makes them ajax submit on click
// -----------------------------------------------------------------------------
function renderStars (container) {
  container.find(".stars-not-loaded .star-rating").rating({
    required: true,
    callback: function(value, link) {
      // ignore callback if it's due to clearing ratings (if it were a real
      // rating, then value wouldn't be empty
      if (value == "") { return; }

      var ratingDiv = jQuery(this).closest('div.rating');
      var starsForm = jQuery(this.form);
      starsForm.removeClass().addClass('user-rating');

      starsForm.ajaxSubmit({
        success: function(jsResp, textStatus) {
          // if we added the book to a reading list as a side effect,
          // update appropriate parts of the page
          if (jsResp.length > 0) {
            var addToListMenu;

            if ((jQuery('div.popular-books, div.recommendations-books').length > 0) ||
                (container.find('.book-in-list').length > 0)) {
              addToListMenu =
                starsForm.closest('.rating').parent().find('div.add-to-list');
            } else {
              addToListMenu =
                starsForm.closest('div.book-info').find('div.add-to-list');
            }

            eval(jsResp);
          }

          // if converting from not-interested or not-rated, set up
          // clear rating icon
          ratingDiv.find('div.clear-not-interested div.not-interested, ' +
                         'div.clear-not-interested .undo-not-interested')
                   .removeClass().addClass('clear-rating');
        },
        error: function() {
          // CARD #1238: figure out how to go back to old stars
          flashMsg('error', "Sorry, we encountered an error saving your rating. Please try again");
        }
      });
    }
  });
  container.find('.stars-not-loaded.rating').css('visibility', 'visible').
                                             removeClass('stars-not-loaded');
  return container;
};

// helper for displaying the popup for clear-rating or not-interested
//
// arguments:
//   - popupContent: the text to display in the popup
// ---------------------------------------------------------------------------
jQuery.fn.clearRatingNotInterestedPopup = function (popupContent) {
  jQuery(this).qtip({
    content: { text: popupContent },
    position: { corner: { target: 'topMiddle', tooltip: 'bottomLeft' } },
    show: { when: 'mouseover', solo: jQuery('div.clear-not-interested-tooltip') },
    hide: { when: 'mouseout' },
    style: {
             color: '#655',
             padding: '0px 9px',
             textAlign: 'center',
             width: { min: 0, max: 500 },
             border: { color: '#baa', width: 2, radius: 2 },
             tip: { corner: 'bottomLeft',
                    size: { x: 10, y: 10 } },
             classes: { content: 'clear-not-interested-content',
                        tooltip: 'clear-not-interested-tooltip' }
           }
  });
};

// used to replace the ratings divs when a user rates or unrates a book
// so that the form is up-to-date for subsequent ajax calls
//
// Chain this onto a jQuery object that is the div.rating surrounding the
// whole ratings complex
//
// argument is the html snippet generated from rendering the rating complex
//------------------------------------------------------------------------------
jQuery.fn.replaceRating = function(data) {
  var ratingDiv = jQuery(this);
  ratingDiv.addClass('stars-not-loaded');
  ratingDiv.html(jQuery(data).html()).hide();
  renderStars(ratingDiv.parent());
  ratingDiv.show();
}


// general function to clear ratings, used below.
//------------------------------------------------------------------------------
function clearRating(clearRatingLink) {
  var ratingDiv = clearRatingLink.closest('div.rating');
  var clearContainer = clearRatingLink.closest('div');
  var thisForm = clearContainer.closest('form');
  var clearRatingApiHandle = clearRatingLink.qtip('api');

  // using ajaxSubmit as it looks like a nice shortcut for submitting forms,
  // also avoids a weird bug that our javascript response is being run
  // automatically in context of the HTML doc in addition to within this
  // callback function (which necessitated a little hack to only run the code
  // to update the page within the callback)
  thisForm.ajaxSubmit({
    success: function(jsResp, textStatus) {
      // destroy the popup associated with the clear button
      clearRatingApiHandle.destroy();
      // clear the stars display
      ratingDiv.find('div.rating-cancel').rating('select');
      // run the js response
      eval(jsResp);
    },
    error: function() {
      alert("We're sorry; something went wrong. Please try again.");
    }
  });

};

jQuery(document).ready(function() {
  // Renders all the star rating fields within all container selectors listed
  jQuery('.wait-for-star-load').livequery(function() {
    renderStars(jQuery(this));
  });

  // configure popups and behaviors for clear-ratings, not-interested, 
  // undo-not-interested
  jQuery('.rating form.clear-not-interested').livequery(function() {
    var thisRating = jQuery(this);
 
    // configure hover behavior for the not-interested and clear-ratings buttons
    // NOTE: can't just use jquery's .live with mouseover and mouseout events
    // bc the mouseout event is not fired inside of a popup for some odd reason.
    thisRating.find('div.clear-rating').each(function() {
      var thisClear = jQuery(this);
      thisClear.clearRatingNotInterestedPopup('Clear rating');
      thisClear.hover(
        function() {
          thisClear.closest('div.rating').find('.star-rating').rating('drain');
        },
        function() {
          thisClear.closest('div.rating').find('.star-rating').rating('draw');
        }
      );

      thisClear.click(function() {
        clearRating(thisClear);
        return false;
      });
    });

    thisRating.find('div.not-interested, div.not-interested-hover').each(function() {
      var thisClear = jQuery(this);
      thisClear.clearRatingNotInterestedPopup('Not interested?');
      thisClear.click(function() {
        var ratingDiv = thisClear.closest('div.rating');
        var clearContainer = thisClear.closest('div');
        var thisForm = clearContainer.closest('form');
        var notInterestedApiHandle = thisClear.qtip('api');

        thisForm.ajaxSubmit({
          success: function(jsResp, textStatus) {
            // destroy the popup associated with the not-interested button
            notInterestedApiHandle.destroy();
            // clear the stars display
            ratingDiv.find('div.rating-cancel').rating('select');
            // reset the clear rating icon
            clearContainer.removeClass().addClass('undo-not-interested');
            // run the returned js
            eval(jsResp);
          },
          error: function() {
            alert("We're sorry; something went wrong. Please try again.");
          }
        });

        return false;
      });
    });

    thisRating.find('div.undo-not-interested').each(function() {
      var thisClear = jQuery(this); 
      thisClear.clearRatingNotInterestedPopup('Undo');
      thisClear.click(function() {
        clearRating(thisClear);
        return false;
      });
    });

    thisRating.find('div.not-interested').each(function() {
      var thisClear = jQuery(this);
      thisClear.hover(
        function() {
          thisClear.closest('div.rating').find('.star-rating').rating('drain');
          thisClear.addClass('not-interested-hover');
        },
        function() {
          thisClear.closest('div.rating').find('.star-rating').rating('draw');
          thisClear.removeClass('not-interested-hover');
        }
      );
    });
  });
});


jQuery('.publish-reading-list input:checkbox').live('click', function() {
  var checkBox = jQuery(this);
  var thisForm = checkBox.closest('form');
  var savedMessage = thisForm.find('.saved-message');
  var form_params = thisForm.serialize();

  if (checkBox.attr('checked')) {
    FB.Connect.showPermissionDialog('publish_stream', function(perms) {
      if (!perms || perms.indexOf('publish_stream') == -1) {
        alert ('You tried to enable publishing for this list but you did not grant us permission on Facebook');
        checkBox.attr('checked', false);
        return false;
      }
      else {
        jQuery.ajax({
          type: 'POST',
          url: thisForm.attr('action'),
          data: form_params,
          success: function () { savedMessage.fadeIn(1500).fadeOut(3000); },
          error: function () { flashMsg('error', 'An error occurred'); }
        });
      } 
    });
  }
  else {
    thisForm.ajaxSubmit({
      success: function () { savedMessage.fadeIn(1500).fadeOut(3000); },
      error: function () { flashMsg('error', 'An error occurred'); }
    });
  }
  return true;
}); 


jQuery(document).ready(function() {

  // Submit a confirmation for a merge conflict
  jQuery('a.confirm-conflict').click(function() {
    jQuery(this).closest('form').submit();
    return false;
  });

  // Sets all radio-button values on a book merge page to a particular value
  jQuery('div.set-all-links a').click(function() {
    var link = jQuery(this);
    var confirmation_value = link.attr('confirmation_value');
    link.closest('form').find('input').each(function() {
      var thisRadio = jQuery(this);
      if (thisRadio.val() == confirmation_value) {
        thisRadio.attr('checked', 'checked');
      }
      else {
        thisRadio.removeAttr('checked');
      }
    });
    return false;
  });

  // Ajax submits a same-book-different-language record
  // Handles both create and destroy
  jQuery('a.different-languages').live('click', function(){
    var thisLink = jQuery(this);
    var url_and_params = this.href.split('?');
    var thisItem = thisLink.closest('li');
    
    thisItem.block();
    
    jQuery.ajax({
      type: "POST",
      url: url_and_params[0],
      data: url_and_params[1],
      dataType: 'html',
      // On success, update the link and set the book group merge 
      // confirmation to 'not a match'
      success: function(data) {
        thisLink.closest('li').setRadioChoice('1');
        thisLink.replaceWith(data);
        thisItem.unblock();
      },
      error: function() {
        thisItem.unblock();
        flashMsg('error', "We're sorry; an error occured. Please try again later.");
      }
    });
    return false;
  });

});


jQuery(document).ready(function() {
  jQuery('form.related-books-scores a#submit-scores').click(function() {
    jQuery('form.related-books-scores').submit();
    return false;
  });
});

//------------------------------------------------------------------------------
jQuery.fn.expandEditions = function() {
  var expandLink = jQuery(this).find('a.show-editions-lnk');

  jQuery(this).parent().find('div.editions-expanded').slideDown(100);
  expandLink.removeClass('show-editions-lnk').addClass('hide-editions-lnk');
  jQuery(expandLink[1]).text('Hide editions');
  jQuery(this).find('img.expanding-spinner').css('visibility', 'hidden');
};

//------------------------------------------------------------------------------
jQuery.fn.collapseEditions = function() {
  var collapseLink = jQuery(this).find('a.hide-editions-lnk');
  
  jQuery(this).parent().find('div.editions-expanded').slideUp(100);
  collapseLink.removeClass('hide-editions-lnk').addClass('show-editions-lnk');
  jQuery(collapseLink[1]).text('Show editions');
};

//------------------------------------------------------------------------------
jQuery(document).ready(function() {

  // Search form submit handler. if criteria empty, warn user and block query
  jQuery('#search > form').submit(function() {
    var submitSearch = true;
    if (jQuery.trim(jQuery(this).find('#search_string').val()) == '') {
      flashMsg('error', "Please enter search criteria.");
      submitSearch = false;
    }
    return(submitSearch);
  });

  // Ajax link for the user to tell us they do not find what they are looking
  // for with their search
  jQuery('span.no-books-found > a').click(function() {
    link = jQuery(this);
    target_url = link.attr('href');
    var url_and_params = target_url.split('?');

    jQuery.ajax({
      type: 'GET',
      url: url_and_params[0],
      data: url_and_params[1],
      success: function(data, textStatus) {
                 link.closest('.no-books-found').text(data);
               }
    });
    return false;
  });

  // hiding/showing editions for book_group
  //----------------------------------------------------------------------------
  jQuery('div.editions-header a.show-editions-lnk, ' +
         'div.editions-header a.show-editions-lnk > img').
    live('click', function() {
      var headerDiv = jQuery(this).closest('div.editions-header');
      var expandedDiv  = headerDiv.parent().find('div.editions-expanded');
      var expandLink   = headerDiv.find('a.show-editions-lnk');
      var expandingSpinner = headerDiv.find('img.expanding-spinner');

      headerDiv.find('.expand-arrow-right-arrow')
               .removeClass('expand-arrow-right-arrow')
               .addClass('expand-arrow-down-arrow');

      if (expandedDiv.attr('class').match(/not-loaded/)) {
        expandingSpinner.css('visibility', 'visible');
        jQuery.ajax({
          type: 'GET',
          url: expandLink[0].href,
          dataType: 'script',
          success: function() {
            headerDiv.expandEditions();
          },
          error: function() {
            // if it fails, then just make the html request and load the
            // editions page
            return true;
          }
        });
      }
      else
      {
        headerDiv.expandEditions();
      }
      return false;
    });
    
  jQuery('div.editions-header a.hide-editions-lnk, ' +
         'div.editions-header a.hide-editions-lnk > img').
    live('click', function() {
      var headerDiv = jQuery(this).closest('div.editions-header');
      
      headerDiv.find('.expand-arrow-down-arrow')
               .removeClass('expand-arrow-down-arrow')
               .addClass('expand-arrow-right-arrow');
      headerDiv.collapseEditions();
      return false;
    });

  //hiding/showing books in a particular top-level format
  //----------------------------------------------------------------------------
  jQuery('div.books-in-format-collapsed a.show-books-in-format-lnk, ' +
         'div.books-in-format-collapsed a.show-books-in-format-lnk > img').
    live('click', function () {
      var divToHide = jQuery(this).closest('div.books-in-format-collapsed');
      divToHide.hide();
      divToHide.parent().find('div.books-in-format-expanded').fadeIn(500);
      return false;
    });
  jQuery('div.books-in-format-expanded a.hide-books-in-format-lnk, ' +
         'div.books-in-format-expanded a.hide-books-in-format-lnk > img').
    live('click', function () {
      var divToHide = jQuery(this).closest('div.books-in-format-expanded');
      divToHide.hide();
      divToHide.parent().find('div.books-in-format-collapsed').fadeIn(500);
      return false;
    });
});


jQuery(document).ready(function() {
  jQuery('div.not-a-book-approval form a').live('click', function() {
    var thisForm = jQuery(this).closest('form');
    var thisApprovalDiv = thisForm.closest('div.not-a-book-approval');
    var thisRow = thisApprovalDiv.closest('li');
    
    thisRow.block();

    thisForm.ajaxSubmit({
      success: function(resp) {
        thisApprovalDiv.replaceWith(jQuery(resp));
        thisRow.unblock();
      },
      error: function() {
        thisRow.unblock();
        flashMsg('error', "We're sorry, something went wrong. Please try again.");
      }
    });
    
    return false;
  });
});