/*
 * jquery.tools 1.1.2 - The missing UI library for the Web
 * 
 * [tools.tabs-1.0.4, tools.tooltip-1.1.2, tools.scrollable-1.1.2, tools.overlay-1.1.2, tools.overlay.gallery-1.0.0, tools.expose-1.0.5]
 * 
 * Copyright (c) 2009 Tero Piirainen
 * http://flowplayer.org/tools/
 *
 * Dual licensed under MIT and GPL 2+ licenses
 * http://www.opensource.org/licenses
 * 
 * -----
 * 
 * File generated: Wed Oct 07 12:03:02 GMT+00:00 2009
 */
(function(d){d.tools=d.tools||{};d.tools.tabs={version:"1.0.4",conf:{tabs:"a",current:"current",onBeforeClick:null,onClick:null,effect:"default",initialIndex:0,event:"click",api:false,rotate:false},addEffect:function(e,f){c[e]=f}};var c={"default":function(f,e){this.getPanes().hide().eq(f).show();e.call()},fade:function(g,e){var f=this.getConf(),j=f.fadeOutSpeed,h=this.getPanes();if(j){h.fadeOut(j)}else{h.hide()}h.eq(g).fadeIn(f.fadeInSpeed,e)},slide:function(f,e){this.getPanes().slideUp(200);this.getPanes().eq(f).slideDown(400,e)},ajax:function(f,e){this.getPanes().eq(0).load(this.getTabs().eq(f).attr("href"),e)}};var b;d.tools.tabs.addEffect("horizontal",function(f,e){if(!b){b=this.getPanes().eq(0).width()}this.getCurrentPane().animate({width:0},function(){d(this).hide()});this.getPanes().eq(f).animate({width:b},function(){d(this).show();e.call()})});function a(g,h,f){var e=this,j=d(this),i;d.each(f,function(k,l){if(d.isFunction(l)){j.bind(k,l)}});d.extend(this,{click:function(k,n){var o=e.getCurrentPane();var l=g.eq(k);if(typeof k=="string"&&k.replace("#","")){l=g.filter("[href*="+k.replace("#","")+"]");k=Math.max(g.index(l),0)}if(f.rotate){var m=g.length-1;if(k<0){return e.click(m,n)}if(k>m){return e.click(0,n)}}if(!l.length){if(i>=0){return e}k=f.initialIndex;l=g.eq(k)}if(k===i){return e}n=n||d.Event();n.type="onBeforeClick";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}c[f.effect].call(e,k,function(){n.type="onClick";j.trigger(n,[k])});n.type="onStart";j.trigger(n,[k]);if(n.isDefaultPrevented()){return}i=k;g.removeClass(f.current);l.addClass(f.current);return e},getConf:function(){return f},getTabs:function(){return g},getPanes:function(){return h},getCurrentPane:function(){return h.eq(i)},getCurrentTab:function(){return g.eq(i)},getIndex:function(){return i},next:function(){return e.click(i+1)},prev:function(){return e.click(i-1)},bind:function(k,l){j.bind(k,l);return e},onBeforeClick:function(k){return this.bind("onBeforeClick",k)},onClick:function(k){return this.bind("onClick",k)},unbind:function(k){j.unbind(k);return e}});g.each(function(k){d(this).bind(f.event,function(l){e.click(k,l);return false})});if(location.hash){e.click(location.hash)}else{if(f.initialIndex===0||f.initialIndex>0){e.click(f.initialIndex)}}h.find("a[href^=#]").click(function(k){e.click(d(this).attr("href"),k)})}d.fn.tabs=function(i,f){var g=this.eq(typeof f=="number"?f:0).data("tabs");if(g){return g}if(d.isFunction(f)){f={onBeforeClick:f}}var h=d.extend({},d.tools.tabs.conf),e=this.length;f=d.extend(h,f);this.each(function(l){var j=d(this);var k=j.find(f.tabs);if(!k.length){k=j.children()}var m=i.jquery?i:j.children(i);if(!m.length){m=e==1?d(i):j.parent().find(i)}g=new a(k,m,f);j.data("tabs",g)});return f.api?g:this}})(jQuery);
(function(c){var d=[];c.tools=c.tools||{};c.tools.tooltip={version:"1.1.2",conf:{effect:"toggle",fadeOutSpeed:"fast",tip:null,predelay:0,delay:30,opacity:1,lazy:undefined,position:["top","center"],offset:[0,0],cancelDefault:true,relative:false,oneInstance:true,events:{def:"mouseover,mouseout",input:"focus,blur",widget:"focus mouseover,blur mouseout",tooltip:"mouseover,mouseout"},api:false},addEffect:function(e,g,f){b[e]=[g,f]}};var b={toggle:[function(e){var f=this.getConf(),g=this.getTip(),h=f.opacity;if(h<1){g.css({opacity:h})}g.show();e.call()},function(e){this.getTip().hide();e.call()}],fade:[function(e){this.getTip().fadeIn(this.getConf().fadeInSpeed,e)},function(e){this.getTip().fadeOut(this.getConf().fadeOutSpeed,e)}]};function a(f,g){var p=this,k=c(this);f.data("tooltip",p);var l=f.next();if(g.tip){l=c(g.tip);if(l.length>1){l=f.nextAll(g.tip).eq(0);if(!l.length){l=f.parent().nextAll(g.tip).eq(0)}}}function o(u){var t=g.relative?f.position().top:f.offset().top,s=g.relative?f.position().left:f.offset().left,v=g.position[0];t-=l.outerHeight()-g.offset[0];s+=f.outerWidth()+g.offset[1];var q=l.outerHeight()+f.outerHeight();if(v=="center"){t+=q/2}if(v=="bottom"){t+=q}v=g.position[1];var r=l.outerWidth()+f.outerWidth();if(v=="center"){s-=r/2}if(v=="left"){s-=r}return{top:t,left:s}}var i=f.is(":input"),e=i&&f.is(":checkbox, :radio, select, :button"),h=f.attr("type"),n=g.events[h]||g.events[i?(e?"widget":"input"):"def"];n=n.split(/,\s*/);if(n.length!=2){throw"Tooltip: bad events configuration for "+h}f.bind(n[0],function(r){if(g.oneInstance){c.each(d,function(){this.hide()})}var q=l.data("trigger");if(q&&q[0]!=this){l.hide().stop(true,true)}r.target=this;p.show(r);n=g.events.tooltip.split(/,\s*/);l.bind(n[0],function(){p.show(r)});if(n[1]){l.bind(n[1],function(){p.hide(r)})}});f.bind(n[1],function(q){p.hide(q)});if(!c.browser.msie&&!i&&!g.predelay){f.mousemove(function(){if(!p.isShown()){f.triggerHandler("mouseover")}})}if(g.opacity<1){l.css("opacity",g.opacity)}var m=0,j=f.attr("title");if(j&&g.cancelDefault){f.removeAttr("title");f.data("title",j)}c.extend(p,{show:function(r){if(r){f=c(r.target)}clearTimeout(l.data("timer"));if(l.is(":animated")||l.is(":visible")){return p}function q(){l.data("trigger",f);var t=o(r);if(g.tip&&j){l.html(f.data("title"))}r=r||c.Event();r.type="onBeforeShow";k.trigger(r,[t]);if(r.isDefaultPrevented()){return p}t=o(r);l.css({position:"absolute",top:t.top,left:t.left});var s=b[g.effect];if(!s){throw'Nonexistent effect "'+g.effect+'"'}s[0].call(p,function(){r.type="onShow";k.trigger(r)})}if(g.predelay){clearTimeout(m);m=setTimeout(q,g.predelay)}else{q()}return p},hide:function(r){clearTimeout(l.data("timer"));clearTimeout(m);if(!l.is(":visible")){return}function q(){r=r||c.Event();r.type="onBeforeHide";k.trigger(r);if(r.isDefaultPrevented()){return}b[g.effect][1].call(p,function(){r.type="onHide";k.trigger(r)})}if(g.delay&&r){l.data("timer",setTimeout(q,g.delay))}else{q()}return p},isShown:function(){return l.is(":visible, :animated")},getConf:function(){return g},getTip:function(){return l},getTrigger:function(){return f},bind:function(q,r){k.bind(q,r);return p},onHide:function(q){return this.bind("onHide",q)},onBeforeShow:function(q){return this.bind("onBeforeShow",q)},onShow:function(q){return this.bind("onShow",q)},onBeforeHide:function(q){return this.bind("onBeforeHide",q)},unbind:function(q){k.unbind(q);return p}});c.each(g,function(q,r){if(c.isFunction(r)){p.bind(q,r)}})}c.prototype.tooltip=function(e){var f=this.eq(typeof e=="number"?e:0).data("tooltip");if(f){return f}var g=c.extend(true,{},c.tools.tooltip.conf);if(c.isFunction(e)){e={onBeforeShow:e}}else{if(typeof e=="string"){e={tip:e}}}e=c.extend(true,g,e);if(typeof e.position=="string"){e.position=e.position.split(/,?\s/)}if(e.lazy!==false&&(e.lazy===true||this.length>20)){this.one("mouseover",function(h){f=new a(c(this),e);f.show(h);d.push(f)})}else{this.each(function(){f=new a(c(this),e);d.push(f)})}return e.api?f:this}})(jQuery);
(function(b){b.tools=b.tools||{};b.tools.scrollable={version:"1.1.2",conf:{size:5,vertical:false,speed:400,keyboard:true,keyboardSteps:null,disabledClass:"disabled",hoverClass:null,clickable:true,activeClass:"active",easing:"swing",loop:false,items:".items",item:null,prev:".prev",next:".next",prevPage:".prevPage",nextPage:".nextPage",api:false}};var c;function a(o,m){var r=this,p=b(this),d=!m.vertical,e=o.children(),k=0,i;if(!c){c=r}b.each(m,function(s,t){if(b.isFunction(t)){p.bind(s,t)}});if(e.length>1){e=b(m.items,o)}function l(t){var s=b(t);return m.globalNav?s:o.parent().find(t)}o.data("finder",l);var f=l(m.prev),h=l(m.next),g=l(m.prevPage),n=l(m.nextPage);b.extend(r,{getIndex:function(){return k},getClickIndex:function(){var s=r.getItems();return s.index(s.filter("."+m.activeClass))},getConf:function(){return m},getSize:function(){return r.getItems().size()},getPageAmount:function(){return Math.ceil(this.getSize()/m.size)},getPageIndex:function(){return Math.ceil(k/m.size)},getNaviButtons:function(){return f.add(h).add(g).add(n)},getRoot:function(){return o},getItemWrap:function(){return e},getItems:function(){return e.children(m.item)},getVisibleItems:function(){return r.getItems().slice(k,k+m.size)},seekTo:function(s,w,t){if(s<0){s=0}if(k===s){return r}if(b.isFunction(w)){t=w}if(s>r.getSize()-m.size){return m.loop?r.begin():this.end()}var u=r.getItems().eq(s);if(!u.length){return r}var v=b.Event("onBeforeSeek");p.trigger(v,[s]);if(v.isDefaultPrevented()){return r}if(w===undefined||b.isFunction(w)){w=m.speed}function x(){if(t){t.call(r,s)}p.trigger("onSeek",[s])}if(d){e.animate({left:-u.position().left},w,m.easing,x)}else{e.animate({top:-u.position().top},w,m.easing,x)}c=r;k=s;v=b.Event("onStart");p.trigger(v,[s]);if(v.isDefaultPrevented()){return r}f.add(g).toggleClass(m.disabledClass,s===0);h.add(n).toggleClass(m.disabledClass,s>=r.getSize()-m.size);return r},move:function(u,t,s){i=u>0;return this.seekTo(k+u,t,s)},next:function(t,s){return this.move(1,t,s)},prev:function(t,s){return this.move(-1,t,s)},movePage:function(w,v,u){i=w>0;var s=m.size*w;var t=k%m.size;if(t>0){s+=(w>0?-t:m.size-t)}return this.move(s,v,u)},prevPage:function(t,s){return this.movePage(-1,t,s)},nextPage:function(t,s){return this.movePage(1,t,s)},setPage:function(t,u,s){return this.seekTo(t*m.size,u,s)},begin:function(t,s){i=false;return this.seekTo(0,t,s)},end:function(t,s){i=true;var u=this.getSize()-m.size;return u>0?this.seekTo(u,t,s):r},reload:function(){p.trigger("onReload");return r},focus:function(){c=r;return r},click:function(u){var v=r.getItems().eq(u),s=m.activeClass,t=m.size;if(u<0||u>=r.getSize()){return r}if(t==1){if(m.loop){return r.next()}if(u===0||u==r.getSize()-1){i=(i===undefined)?true:!i}return i===false?r.prev():r.next()}if(t==2){if(u==k){u--}r.getItems().removeClass(s);v.addClass(s);return r.seekTo(u,time,fn)}if(!v.hasClass(s)){r.getItems().removeClass(s);v.addClass(s);var x=Math.floor(t/2);var w=u-x;if(w>r.getSize()-t){w=r.getSize()-t}if(w!==u){return r.seekTo(w)}}return r},bind:function(s,t){p.bind(s,t);return r},unbind:function(s){p.unbind(s);return r}});b.each("onBeforeSeek,onStart,onSeek,onReload".split(","),function(s,t){r[t]=function(u){return r.bind(t,u)}});f.addClass(m.disabledClass).click(function(){r.prev()});h.click(function(){r.next()});n.click(function(){r.nextPage()});if(r.getSize()<m.size){h.add(n).addClass(m.disabledClass)}g.addClass(m.disabledClass).click(function(){r.prevPage()});var j=m.hoverClass,q="keydown."+Math.random().toString().substring(10);r.onReload(function(){if(j){r.getItems().hover(function(){b(this).addClass(j)},function(){b(this).removeClass(j)})}if(m.clickable){r.getItems().each(function(s){b(this).unbind("click.scrollable").bind("click.scrollable",function(t){if(b(t.target).is("a")){return}return r.click(s)})})}if(m.keyboard){b(document).unbind(q).bind(q,function(t){if(t.altKey||t.ctrlKey){return}if(m.keyboard!="static"&&c!=r){return}var u=m.keyboardSteps;if(d&&(t.keyCode==37||t.keyCode==39)){r.move(t.keyCode==37?-u:u);return t.preventDefault()}if(!d&&(t.keyCode==38||t.keyCode==40)){r.move(t.keyCode==38?-u:u);return t.preventDefault()}return true})}else{b(document).unbind(q)}});r.reload()}b.fn.scrollable=function(d){var e=this.eq(typeof d=="number"?d:0).data("scrollable");if(e){return e}var f=b.extend({},b.tools.scrollable.conf);d=b.extend(f,d);d.keyboardSteps=d.keyboardSteps||d.size;this.each(function(){e=new a(b(this),d);b(this).data("scrollable",e)});return d.api?e:this}})(jQuery);
(function(c){c.tools=c.tools||{};c.tools.overlay={version:"1.1.2",addEffect:function(e,f,g){b[e]=[f,g]},conf:{top:"10%",left:"center",absolute:false,speed:"normal",closeSpeed:"fast",effect:"default",close:null,oneInstance:true,closeOnClick:true,closeOnEsc:true,api:false,expose:null,target:null}};var b={};c.tools.overlay.addEffect("default",function(e){this.getOverlay().fadeIn(this.getConf().speed,e)},function(e){this.getOverlay().fadeOut(this.getConf().closeSpeed,e)});var d=[];function a(g,k){var o=this,m=c(this),n=c(window),j,i,h,e=k.expose&&c.tools.expose.version;var f=k.target||g.attr("rel");i=f?c(f):null||g;if(!i.length){throw"Could not find Overlay: "+f}if(g&&g.index(i)==-1){g.click(function(p){o.load(p);return p.preventDefault()})}c.each(k,function(p,q){if(c.isFunction(q)){m.bind(p,q)}});c.extend(o,{load:function(u){if(o.isOpened()){return o}var r=b[k.effect];if(!r){throw'Overlay: cannot find effect : "'+k.effect+'"'}if(k.oneInstance){c.each(d,function(){this.close(u)})}u=u||c.Event();u.type="onBeforeLoad";m.trigger(u);if(u.isDefaultPrevented()){return o}h=true;if(e){i.expose().load(u)}var t=k.top;var s=k.left;var p=i.outerWidth({margin:true});var q=i.outerHeight({margin:true});if(typeof t=="string"){t=t=="center"?Math.max((n.height()-q)/2,0):parseInt(t,10)/100*n.height()}if(s=="center"){s=Math.max((n.width()-p)/2,0)}if(!k.absolute){t+=n.scrollTop();s+=n.scrollLeft()}i.css({top:t,left:s,position:"absolute"});u.type="onStart";m.trigger(u);r[0].call(o,function(){if(h){u.type="onLoad";m.trigger(u)}});if(k.closeOnClick){c(document).bind("click.overlay",function(w){if(!o.isOpened()){return}var v=c(w.target);if(v.parents(i).length>1){return}c.each(d,function(){this.close(w)})})}if(k.closeOnEsc){c(document).unbind("keydown.overlay").bind("keydown.overlay",function(v){if(v.keyCode==27){c.each(d,function(){this.close(v)})}})}return o},close:function(q){if(!o.isOpened()){return o}q=q||c.Event();q.type="onBeforeClose";m.trigger(q);if(q.isDefaultPrevented()){return}h=false;b[k.effect][1].call(o,function(){q.type="onClose";m.trigger(q)});var p=true;c.each(d,function(){if(this.isOpened()){p=false}});if(p){c(document).unbind("click.overlay").unbind("keydown.overlay")}return o},getContent:function(){return i},getOverlay:function(){return i},getTrigger:function(){return g},getClosers:function(){return j},isOpened:function(){return h},getConf:function(){return k},bind:function(p,q){m.bind(p,q);return o},unbind:function(p){m.unbind(p);return o}});c.each("onBeforeLoad,onStart,onLoad,onBeforeClose,onClose".split(","),function(p,q){o[q]=function(r){return o.bind(q,r)}});if(e){if(typeof k.expose=="string"){k.expose={color:k.expose}}c.extend(k.expose,{api:true,closeOnClick:k.closeOnClick,closeOnEsc:false});var l=i.expose(k.expose);l.onBeforeClose(function(p){o.close(p)});o.onClose(function(p){l.close(p)})}j=i.find(k.close||".close");if(!j.length&&!k.close){j=c('<div class="close"></div>');i.prepend(j)}j.click(function(p){o.close(p)})}c.fn.overlay=function(e){var f=this.eq(typeof e=="number"?e:0).data("overlay");if(f){return f}if(c.isFunction(e)){e={onBeforeLoad:e}}var g=c.extend({},c.tools.overlay.conf);e=c.extend(true,g,e);this.each(function(){f=new a(c(this),e);d.push(f);c(this).data("overlay",f)});return e.api?f:this}})(jQuery);
(function(b){var a=b.tools.overlay;a.plugins=a.plugins||{};a.plugins.gallery={version:"1.0.0",conf:{imgId:"img",next:".next",prev:".prev",info:".info",progress:".progress",disabledClass:"disabled",activeClass:"active",opacity:0.8,speed:"slow",template:"<strong>${title}</strong> <span>Image ${index} of ${total}</span>",autohide:true,preload:true,api:false}};b.fn.gallery=function(d){var o=b.extend({},a.plugins.gallery.conf),m;b.extend(o,d);m=this.overlay();var r=this,j=m.getOverlay(),k=j.find(o.next),g=j.find(o.prev),e=j.find(o.info),c=j.find(o.progress),h=g.add(k).add(e).css({opacity:o.opacity}),s=m.getClosers(),l;function p(u){c.fadeIn();h.hide();s.hide();var t=u.attr("href");var v=new Image();v.onload=function(){c.fadeOut();var y=b("#"+o.imgId,j);if(!y.length){y=b("<img/>").attr("id",o.imgId).css("visibility","hidden");j.prepend(y)}y.attr("src",t).css("visibility","hidden");var z=v.width;var A=(b(window).width()-z)/2;l=r.index(r.filter("[href="+t+"]"));r.removeClass(o.activeClass).eq(l).addClass(o.activeClass);var w=o.disabledClass;h.removeClass(w);if(l===0){g.addClass(w)}if(l==r.length-1){k.addClass(w)}var B=o.template.replace("${title}",u.attr("title")||u.data("title")).replace("${index}",l+1).replace("${total}",r.length);var x=parseInt(e.css("paddingLeft"),10)+parseInt(e.css("paddingRight"),10);e.html(B).css({width:z-x});j.animate({width:z,height:v.height,left:A},o.speed,function(){y.hide().css("visibility","visible").fadeIn(function(){if(!o.autohide){h.fadeIn();s.show()}})})};v.onerror=function(){j.fadeIn().html("Cannot find image "+t)};v.src=t;if(o.preload){r.filter(":eq("+(l-1)+"), :eq("+(l+1)+")").each(function(){var w=new Image();w.src=b(this).attr("href")})}}function f(t,u){t.click(function(){if(t.hasClass(o.disabledClass)){return}var v=r.eq(i=l+(u?1:-1));if(v.length){p(v)}})}f(k,true);f(g);b(document).keydown(function(t){if(!j.is(":visible")||t.altKey||t.ctrlKey){return}if(t.keyCode==37||t.keyCode==39){var u=t.keyCode==37?g:k;u.click();return t.preventDefault()}return true});function q(){if(!j.is(":animated")){h.show();s.show()}}if(o.autohide){j.hover(q,function(){h.fadeOut();s.hide()}).mousemove(q)}var n;this.each(function(){var v=b(this),u=b(this).overlay(),t=u;u.onBeforeLoad(function(){p(v)});u.onClose(function(){r.removeClass(o.activeClass)})});return o.api?n:this}})(jQuery);
(function(b){b.tools=b.tools||{};b.tools.expose={version:"1.0.5",conf:{maskId:null,loadSpeed:"slow",closeSpeed:"fast",closeOnClick:true,closeOnEsc:true,zIndex:9998,opacity:0.8,color:"#456",api:false}};function a(){if(b.browser.msie){var f=b(document).height(),e=b(window).height();return[window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth,f-e<20?e:f]}return[b(window).width(),b(document).height()]}function c(h,g){var e=this,j=b(this),d=null,f=false,i=0;b.each(g,function(k,l){if(b.isFunction(l)){j.bind(k,l)}});b(window).resize(function(){e.fit()});b.extend(this,{getMask:function(){return d},getExposed:function(){return h},getConf:function(){return g},isLoaded:function(){return f},load:function(n){if(f){return e}i=h.eq(0).css("zIndex");if(g.maskId){d=b("#"+g.maskId)}if(!d||!d.length){var l=a();d=b("<div/>").css({position:"absolute",top:0,left:0,width:l[0],height:l[1],display:"none",opacity:0,zIndex:g.zIndex});if(g.maskId){d.attr("id",g.maskId)}b("body").append(d);var k=d.css("backgroundColor");if(!k||k=="transparent"||k=="rgba(0, 0, 0, 0)"){d.css("backgroundColor",g.color)}if(g.closeOnEsc){b(document).bind("keydown.unexpose",function(o){if(o.keyCode==27){e.close()}})}if(g.closeOnClick){d.bind("click.unexpose",function(o){e.close(o)})}}n=n||b.Event();n.type="onBeforeLoad";j.trigger(n);if(n.isDefaultPrevented()){return e}b.each(h,function(){var o=b(this);if(!/relative|absolute|fixed/i.test(o.css("position"))){o.css("position","relative")}});h.css({zIndex:Math.max(g.zIndex+1,i=="auto"?0:i)});var m=d.height();if(!this.isLoaded()){d.css({opacity:0,display:"block"}).fadeTo(g.loadSpeed,g.opacity,function(){if(d.height()!=m){d.css("height",m)}n.type="onLoad";j.trigger(n)})}f=true;return e},close:function(k){if(!f){return e}k=k||b.Event();k.type="onBeforeClose";j.trigger(k);if(k.isDefaultPrevented()){return e}d.fadeOut(g.closeSpeed,function(){k.type="onClose";j.trigger(k);h.css({zIndex:b.browser.msie?i:null})});f=false;return e},fit:function(){if(d){var k=a();d.css({width:k[0],height:k[1]})}},bind:function(k,l){j.bind(k,l);return e},unbind:function(k){j.unbind(k);return e}});b.each("onBeforeLoad,onLoad,onBeforeClose,onClose".split(","),function(k,l){e[l]=function(m){return e.bind(l,m)}})}b.fn.expose=function(d){var e=this.eq(typeof d=="number"?d:0).data("expose");if(e){return e}if(typeof d=="string"){d={color:d}}var f=b.extend({},b.tools.expose.conf);d=b.extend(f,d);this.each(function(){e=new c(b(this),d);b(this).data("expose",e)});return d.api?e:this}})(jQuery);


/* Custom Fade Out quickly then Fade In function */
jQuery.fn.fadeOutIn = function(){

	this.fadeTo(20,0.15,function(){ // Fade out then fade in
		var jThis = $(this);
		if(jThis.css("display") != "block"){
			jThis.css("display","block");
		}
		jThis.fadeTo(500,1);
	});

};

$(document).ready(function(){
	$(".ajax_status").ajaxStart(function(){
		$(this).fadeIn();
	});

	$(".ajax_status").ajaxComplete(function(){
		$(this).fadeOut();
	});

	$("#verticalSteps").click(function(){
		window.location.href="/order.php";
	});

	var base_path = window.location.protocol + "//" + window.location.host;

	// Some pre-loading
	if(document.images){
		var img1 = new Image(1,1);
		img1.src = base_path + "/resources/images/steps/horizontalSteps.gif";
		var img2 = new Image(1,1);
		img2.src = base_path + "/resources/images/other/mervSm.jpg";
	}

	// Merv pop window
	$("p.merv a").bind("click",function(){
		try{
			var newWindow = window.open($(this).attr('href'),
				"Have questions on air filters? Merv has the answers","menubar=0,resizable=1,scrollbars=1,width=1025,height=700");

			newWindow.moveTo(0,0);
			return false;
		} catch(e){}
	});

	/* TOP NAV HOVER MENU */

	$("#nav .main > li > a").each(function(index){
		$(this).attr("alt",index);
	});

	$("#nav .main li a[alt]").bind('mouseover focus',function(){
		var me = $(this);
		var altv = me.attr("alt");
		//console.log("mouseover: "+altv);

		$(".subnav").each(function(i){
			if( $(this).hasClass('num'+altv) == false ){
				$(this).fadeOut("fast");
			}
		});

		var coords = me.parent().offset();
		$("#subnav_"+altv).css({ left:coords.left-5 }).fadeIn("fast");

	});

	$("#header,.stepsBlock,#horizontalSteps").bind('mouseenter',function(){
		$(".subnav").fadeOut("fast");
	});

	$(".subnav").bind('mouseleave',function(){
		$(".subnav").fadeOut("fast");
	});

});

/* Save current data and go back 1 step */
function stepBack(oForm){
	var theForm = $(oForm);

	if(!theForm){ return; }

	var curStep = theForm.find("input[name=step]").val();
	curStep -= 1;
	var action = "step" + curStep;

	var dataStr = theForm.serialize() + "&goback";
	if(theForm.find("input[name=action][value=store]").length < 1){
		dataStr += "&action=store";
	}

	$.ajax({
		type:"POST",
		url: "order.php",
		data: dataStr,
		success: function(rText){
			// alert("Success");
			window.location.href = "order.php?action="+action; // Browse to prev step without posting
		}

	});
}

/* Update Delivery Cost up to this point */
function calcDeliveryCost(theForm){

	var oForm = $(theForm);
	var updateDiv = $(".bottom_section .alertBot .alertTop span");

	if( oForm.length < 1 || updateDiv.length < 1){
		return false;
	}

	var dataString = oForm.serialize();

	dataString += "&getcost=1";

	// Post the form using AJAX so we don't have to worry about
	// the user going back or refreshing the page which would re-submit the data
	$.ajax({
		type:"POST",
		url: "/order.php",
		data:dataString,
		success: function(rText){
			updateDiv.css({opacity:0.33});
			updateDiv.html(rText);
			updateDiv.fadeTo("normal",1.0);
		}

	});
}

function getWindowSize(){
	var obj = {};

	obj.width = $(window).width();
	obj.height = $(window).height();

	return obj;
}

function validateEmail(str){
	return str.match(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i);
}

function validatePassword(str){
	//return str.match(/^[A-Z0-9_!?@#$%^&*]+$/i);
	return str.match(/^[-A-Z0-9_!?@#$^%&*]{6,18}$/i);
}

/* Luhn algorithm number checker - (c) 2005-2009 - planzero.org            *
 * This code has been released into the public domain, however please      *
 * give credit to the original author where possible.                      */

function luhn_check(number) {


  // Strip any non-digits (useful for credit card numbers with spaces and hyphens)
  var number=number.replace(/\D/g, '');

  // Set the string length and parity
  var number_length=number.length;
  var parity=number_length % 2;

  // Loop through each digit and do the maths
  var total=0;
  for (i=0; i < number_length; i++) {
    var digit=number.charAt(i);
    // Multiply alternate digits by two
    if (i % 2 == parity) {
      digit=digit * 2;
      // If the sum is two digits, add them together (in effect)
      if (digit > 9) {
        digit=digit - 9;
      }
    }
    // Total up the digits
    total = total + parseInt(digit);
  }

  // If the total mod 10 equals 0, the number is valid
  if (total % 10 == 0) {
    return true;
  } else {
    return false;
  }


}

function showFilterInfo(oSelect){
	var chosenNum = $(oSelect).val();
	var actualNum = $("#filterInputs div").length;

	if(chosenNum <= 0 || chosenNum == actualNum){
		return;
	}

	var filterInputs = $("#filterInputs");
	var copyStr = filterInputs.find("div:last").html();
	var lastDiv;

	while(actualNum < chosenNum){
		filterInputs.append( "<div>" + copyStr + "</div>" );
		actualNum += 1;

		lastDiv = filterInputs.find("div:last");
		lastDiv.find("var").html(actualNum);
		lastDiv.find("select")[0].selectedIndex = 0;
		lastDiv.find("input").css("color","black")[0].value = "";
	};
	while(actualNum > chosenNum){
		filterInputs.find("div:last").remove();
		actualNum -= 1;
	}


	$(".filter_info").fadeIn("fast");
}

function moveFloatingBox(){
	var wheight = $(window).height();
	var scrollTop = $(window).scrollTop();
	var y = (wheight + scrollTop - 300);

	buttonYvalue = $(".bottom_section .buttons").position().top;

	y = Math.min( y, buttonYvalue );

	// alertBot.css({ top:y });
	alertBot.animate( { top: y }, 100 );

	// console.log("window: " + wheight + " scrollTop: " + scrollTop);
}


/* Step 3 Validation */
function validateStep3(ssl_url,sess_id){
	error = "";

//	$(".schedule select").each(function(i){
//		if( $(this).val() < 1 ){
//			error += "Please select a frequency for Filter " + (i+1) + "<br />";
//		}
//	});

	var em = $("#error_message");
	if(error != ""){
		em.find("var").html( error );
		em.fadeOutIn();
	} else {
		// submit form
		em.fadeOut();

		var dataString = $("#step3form").serialize();

		// Disable the Prev/Next Button
		$(".buttons input[type=image]")
			.attr("onclick","")
			.bind("click",function(){ return false; });

		// Post the form using AJAX so we don't have to worry about
		// the user going back or refreshing the page which would re-submit the data
		$.ajax({
			type:"POST",
			url: "order.php",
			data:dataString,
			success: function(rText){
				// alert("Success");
				window.location.href = ssl_url + "order.php?PHPSESSID="+sess_id+"&action="+next_action; // Browse to next step without posting
			}

		});
	}
}


function toggleSameAddress(){

	var elForm = $("#step4form")[0];

	var t = setTimeout(function(){
		if( $("#cbox_1")[0].checked ){
			$("ol.billing span.required").hide();
			elForm["bill_address[name]"].value = elForm["ship_address[name]"].value;
			elForm["bill_address[address1]"].value = elForm["ship_address[address1]"].value;
			elForm["bill_address[address2]"].value = elForm["ship_address[address2]"].value;
			elForm["bill_address[city]"].value = elForm["ship_address[city]"].value;
			elForm["bill_address[zip]"].value = elForm["ship_address[zip]"].value;
			elForm["bill_address[phone1]"].value = elForm["ship_address[phone1]"].value;

			elForm["bill_address[state]"].selectedIndex = elForm["ship_address[state]"].selectedIndex;
			elForm["bill_address[country]"].selectedIndex = elForm["ship_address[country]"].selectedIndex;

			$(".addresses ol.billing input[type=text], .addresses ol.billing select").each(function(i){
				this.disabled = true;
			});
		} else {
			$("ol.billing span.required").show();
			$(".addresses ol.billing input[type=text], .addresses ol.billing select").each(function(i){
				this.disabled = false;
			});
		}

		swapCountry();
	},50);
}

function togglePaymentMethod(){
	var t = setTimeout(function(){
		if( $("#rchoice_paypal")[0].checked ){
			$(".paymentInfo > ol span.required").hide();
			$(".paymentInfo > ol input[type=text], .paymentInfo > ol select").each(function(i){
				this.disabled = true;
			});

		} else {
			$(".paymentInfo > ol span.required").show();
			$(".paymentInfo > ol input[type=text], .paymentInfo > ol select").each(function(i){
				this.disabled = false;
			});
		}

		if($("#rchoice_2").length > 0){
			if( $("#rchoice_2")[0].checked ){
				$(".paymentOptions .prepay .price").fadeOut();
			} else {
				$(".paymentOptions .prepay .price").fadeIn();
			}
		}
	},100);
}

function validateStep4(hasPaypalToken){
	var error = "";

	var jForm = $("#step4form");
	var elForm = jForm[0];

//	if( jForm.find(".paymentOptions input[type=radio]:checked").length < 1 ){
//		error += "Please select a payment plan at the top.<br />";
//	}

	if($("#rchoice_9")[0].checked){
		var expDate = new Date();

		expDate.setFullYear( $("#csp1_y").val(), $("#csp1_m").val() - 1 , 28 );

		var today = new Date();
		if( expDate < today ){
			error += "The start date must be no earlier than today. <br />";
		}
	}

	if($("#id_bill_method").val() == "prepay12" && $("#id_partner_id").val() == ""){
		error += "Please enter your NAMB Member #.<br />";
	}

	if(elForm["ship_address[name]"].value.length < 2){
		error += "Please enter a shipping name.<br />";
	}
	if(elForm["ship_address[address1]"].value.length < 2){
		error += "Please enter a shipping address line 1.<br />";
	}
	if(elForm["ship_address[city]"].value.length < 1){
		error += "Please enter a shipping city.<br />";
	}
	if(elForm["ship_address[state]"].selectedIndex < 1){
		error += "Please choose a shipping state/province.<br />";
	}
	if(elForm["ship_address[zip]"].value.length < 5){
		error += "Please enter a valid shipping zip/postal code.<br />";
	}

	if( !validateEmail( elForm["bill_address[email]"].value ) ){
		error += "Please enter a valid e-mail address.<br />";
	} else if( $("#email_result span.ui-icon-closethick").length > 0 ){
		error += "The e-mail address you entered is already in use. Please try another.<br />";
	}

	if( jForm.find(".paymentInfo input[type=radio]:checked").length < 1 ){
		error += "Please select a payment method on the right.<br />";
	}

	if( $("#cbox_1")[0].checked == false ){
		// Shipping Info diff than billing
		if(elForm["bill_address[name]"].value.length < 2){
			error += "Please enter a billing name.<br />";
		}
		if(elForm["bill_address[address1]"].value.length < 2){
			error += "Please enter a billing address line 1.<br />";
		}
		if(elForm["bill_address[city]"].value.length < 1){
			error += "Please enter a billing city.<br />";
		}
		if(elForm["bill_address[state]"].selectedIndex < 1){
			error += "Please choose a billing state/province.<br />";
		}
		if(elForm["bill_address[zip]"].value.length < 5){
			error += "Please enter a valid billing zip/postal code.<br />";
		}
	}

	if( $("#rchoice_cc")[0].checked == true ){
		// Validate CC Info
		if(elForm["payment[card_num]"].value.length < 15){
			error += "The credit card number entered is invalid. Please re-enter.<br />";
		} else if( luhn_check( elForm["payment[card_num]"].value ) == false ){
			// Check Luhn Algorithm
			error += "The credit card number entered is invalid. Please re-enter.<br />";
		}
		if(elForm["payment[name]"].value.length < 2){
			error += "Please enter the name on the credit card.<br />";
		}
		if(elForm["payment[ccv]"].value.length < 3){
			error += "Please enter the credit card's security code (3 or 4 digit).<br />";
		}

		var expDate = new Date();

		expDate.setFullYear( $(elForm["payment[exp_year]"]).val(), $(elForm["payment[exp_month]"]).val() - 1 , 28 );

		var today = new Date();
		if( expDate < today ){
			error += "This credit card is expired. Please check the expiration. <br />";
		}
	}
/*
	if(elForm["login[password]"].value.length < 6){
		error += "Password should be at least 6 characters long.<br />";
	}
	else if( !validatePassword( elForm["login[password]"].value ) ){
		error += "Invalid password. Please only use letters, numbers, or ! ? @ # $ ^ &amp; *. No spaces or quotes.<br />";
	}
	else if(elForm["login[password]"].value != elForm["login[retype_password]"].value){
		error += "Passwords entered do not match. Please re-type.<br />";
	}
*/

	if($("#cbox_accept")[0].checked != true){
		error += "Your order cannot be processed unless you accept the Terms of Use by clicking the checkbox above.<br />";
	}

	var em = $("#error_message");
	if(error != ""){
		em.find("var").html( error );
		em.fadeOutIn();
	} else {
		// submit form
		em.fadeOut();
		var has_paypal_token = hasPaypalToken;

		// Disable the Prev/Next Button
		$(".buttons input[type=image]")
			.attr("onclick","")
			.bind("click",function(){ return false; });

		$(".ajax_status").show();

		if( $("#rchoice_paypal")[0].checked == true && !has_paypal_token){
			// Redirect To Paypal Site to Get Paypal Token
			var type = $(".paymentOptions input[name=bill_method]:checked").val();

			var dataString = "";

			dataString += "action2=geturl";
			dataString += "&" + $("#step4form").serialize();

			$.ajax({
				type:"POST",
				url: "/ajax.paypal.php",
				data:dataString,
				success: function(rText){
					// console.log(rText);
					window.location.href = rText; // Browse to next step without posting
				}

			});
		} else {
			// Submit the form asynchronously

			var dataString = $("#step4form").serialize();

			// Post the form using AJAX so we don't have to worry about
			// the user going back or refreshing the page which would re-submit the data
			$.ajax({
				type:"POST",
				url: "order.php",
				data:dataString,
				success: function(rText){
					window.location.href = "order.php?action="+next_action; // Browse to next step without posting
				}

			});
		}
	}
}

function popWindow(a_tag){
	a_tag = $(a_tag);
	try{
		var newWindow = window.open(a_tag.attr('href'),
			a_tag.attr("title"),"menubar=0,resizable=1,scrollbars=1,width=1024,height=700");

		newWindow.moveTo(0,0);

		return false;
	} catch(e){

	}
}


var step4checkEmail = function(jEvent){
	var dataStr;

	dataStr = "email=" + $("#id_email").val();

	$.ajax({
		type: "POST",
		url: "ajax.checkemail.php",
		data:dataStr,
		success:function(rText){
			if(rText == "SUCCESS"){
				$("#email_result span").removeClass("ui-icon-closethick").addClass("ui-icon-check");
			} else {
				$("#email_result span").removeClass("ui-icon-check").addClass("ui-icon-closethick");
				$("#email_result var").html(rText);
			}
		}
	});
};


var saveCartForLater = function(jInput){
	var email = jInput.val();

	if(!validateEmail(email)){
		alert("Please enter a valid e-mail address to use this feature.");
		return false;
	}

	var dataStr = $("form.filters_form").serialize() + "&email=" + email;

	$.ajax({
		type: 'POST',
		url: 'ajax.saveorder.php',
		data: dataStr,
		success:function(rText){
			alert(rText);
		}

	});

	return false;
};

var swapCountry = function(switchType){
	ship_state_index = $("select.ship_state")[0].selectedIndex;
	bill_state_index = $("select.bill_state")[0].selectedIndex;

	if(switchType == 'ship'){
		ship_state_index = 0;
	} else if(switchType == 'bill'){
		bill_state_index = 0;
	}

	if($(".ship_country").val() == "CA"){
		$(".shipping label.state").html( $(".shipping label.state").html().replace("State","Prov.") );
		$(".shipping label.zip").html( $(".shipping label.zip").html().replace("Zip","Post Code") );
		$("select.ship_state").html(ca_state_array);
	} else if($(".ship_country").val() == "US"){
		$(".shipping label.state").html( $(".shipping label.state").html().replace("Prov.","State") );
		$(".shipping label.zip").html(   $(".shipping label.zip").html().replace("Post Code","Zip") );
		$("select.ship_state").html(us_state_array);
	}

	if($(".bill_country").val() == "CA"){
		$(".billing label.state").html( $(".billing label.state").html().replace("State","Prov.") );
		$(".billing label.zip").html( $(".billing label.zip").html().replace("Zip","Post Code") );
		$("select.bill_state").html(ca_state_array);
	} else if($(".bill_country").val() == "US"){
		$(".billing label.state").html( $(".billing label.state").html().replace("Prov.","State") );
		$(".billing label.zip").html(   $(".billing label.zip").html().replace("Post Code","Zip") );
		$("select.bill_state").html(us_state_array);
	}

	$("select.ship_state")[0].selectedIndex = ship_state_index;
	$("select.bill_state")[0].selectedIndex = bill_state_index;


};

var enableNambPartner = function(){
	previousBillHtml = $("#bill_information").html();

	$("#id_bill_method").val("prepay12");

	$(".paymentOptions span.price").html("$"+prepay_amt);
	$("#bill_information").html('<strong>One time prepayment lasting 1 year</strong> ('+shipments_per_year+' shipments)');

	$(".notnamb").hide();
	$(".namb").fadeIn();

	return false;
};

var disableNambPartner = function(){
	$("#bill_information").html( previousBillHtml );

	$("#id_bill_method").val("per_shipment");
	$(".paymentOptions span.price").html("$"+per_shipment_amt);

	$(".namb").hide();
	$(".notnamb").fadeIn();

	return false;
}