
/* preload images function */
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preloadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);

/*
 * 	easyListSplitter 1.0.1 - jQuery plugin
 *	written by Andrea Cima Serniotti	
 *	http://www.madeincima.eu
 *
 *	Copyright (c) 2010 Andrea Cima Serniotti (http://www.madeincima.eu)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 *
 */
 
 /*
	To activate the plugin add the following code to your own js file:
	
	jQuery('.your-list-class-name').listColumnizer({ 
			colNumber: 3,
			direction: 'horizontal'
	});
	
 */

var j = 1;
 
(function(jQuery) {
	jQuery.fn.easyListSplitter = function(options) {
	
	var defaults = {			
		colNumber: 2, // Insert here the number of columns you want. Consider that the plugin will create the number of cols requested only if there are enough items in the list.
		direction: 'vertical'
	};
			
	this.each(function() {
		
		var obj = jQuery(this);
		var settings = jQuery.extend(defaults, options);
		var totalListElements = jQuery(this).find('li').size();
		var baseColItems = Math.ceil(totalListElements / settings.colNumber);
		var listClass = jQuery(this).attr('class');
		
		// -------- Create List Elements given colNumber ------------------------------------------------------------------------------
		
		for (i=1;i<=settings.colNumber;i++)
		{	
			if(i==1){
				jQuery(this).addClass('listCol1').wrap('<div class="listContainer'+j+'"></div>');
			} else if(jQuery(this).is('ul')){ // Check whether the list is ordered or unordered
				jQuery(this).parents('.listContainer'+j).append('<ul class="listCol'+i+'"></ul>');
			} else{
				jQuery(this).parents('.listContainer'+j).append('<ol class="listCol'+i+'"></ol>');
			}
				jQuery('.listContainer'+j+' > ul,.listContainer'+j+' > ol').addClass(listClass);
		}
		
		var listItem = 0;
		var k = 1;
		var l = 0;	
		
		if(settings.direction == 'vertical'){ // -------- Append List Elements to the respective listCol  - Vertical -------------------------------
			
			jQuery(this).find('li').each(function(){
				listItem = listItem+1;
				if (listItem > baseColItems*(settings.colNumber-1) ){
					jQuery(this).parents('.listContainer'+j).find('.listCol'+settings.colNumber).append(this);
				} 
				else {
					if(listItem<=(baseColItems*k)){
						jQuery(this).parents('.listContainer'+j).find('.listCol'+k).append(this);
					} 
					else{
						jQuery(this).parents('.listContainer'+j).find('.listCol'+(k+1)).append(this);
						k = k+1;
					}
				}
			});
			
			jQuery('.listContainer'+j).find('ol,ul').each(function(){
				if(jQuery(this).children().size() == 0) {
				jQuery(this).remove();
				}
			});	
			
		} else{  // -------- Append List Elements to the respective listCol  - Horizontal ----------------------------------------------------------
			
			jQuery(this).find('li').each(function(){
				l = l+1;

				if(l <= settings.colNumber){
					jQuery(this).parents('.listContainer'+j).find('.listCol'+l).append(this);
					
				} else {
					l = 1;
					jQuery(this).parents('.listContainer'+j).find('.listCol'+l).append(this);
				}				
			});
		}
		
		jQuery('.listContainer'+j).find('ol:last,ul:last').addClass('last'); // Set class last on the last UL or OL	
		j = j+1;
		
	});
	};
})(jQuery);

/*
 * jquery.tools 1.1.2 - The missing UI library for the Web
 *
 * [tools.tabs-1.0.4, tools.tabs.slideshow-1.0.2, tools.tabs.history-1.0.2, tools.tooltip-1.1.2, tools.tooltip.slide-1.0.0, tools.tooltip.dynamic-1.0.1, tools.scrollable-1.1.2, tools.scrollable.circular-0.5.1, tools.scrollable.autoscroll-1.0.1, tools.scrollable.navigator-1.0.2, tools.scrollable.mousewheel-1.0.1, tools.overlay-1.1.2, tools.overlay.gallery-1.0.0, tools.overlay.apple-1.0.1, 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
 *
 * -----
 *
 * jquery.event.wheel.js - rev 1
 * Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
 * Liscensed under the MIT License (MIT-LICENSE.txt)
 * http://www.opensource.org/licenses/mit-license.php
 * Created: 2008-07-01 | Updated: 2008-07-14
 *
 * -----
 *
 * File generated: Wed Oct 07 12:05:57 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(b){var a=b.tools.tabs;a.plugins=a.plugins||{};a.plugins.slideshow={version:"1.0.2",conf:{next:".forward",prev:".backward",disabledClass:"disabled",autoplay:false,autopause:true,interval:3000,clickable:true,api:false}};b.prototype.slideshow=function(e){var f=b.extend({},a.plugins.slideshow.conf),c=this.length,d;e=b.extend(f,e);this.each(function(){var p=b(this),m=p.tabs(),i=b(m),o=m;b.each(e,function(t,u){if(b.isFunction(u)){m.bind(t,u)}});function n(t){return c==1?b(t):p.parent().find(t)}var s=n(e.next).click(function(){m.next()});var q=n(e.prev).click(function(){m.prev()});var h,j,l,g=false;b.extend(m,{play:function(){if(h){return}var t=b.Event("onBeforePlay");i.trigger(t);if(t.isDefaultPrevented()){return m}g=false;h=setInterval(m.next,e.interval);i.trigger("onPlay");m.next()},pause:function(){if(!h){return m}var t=b.Event("onBeforePause");i.trigger(t);if(t.isDefaultPrevented()){return m}h=clearInterval(h);l=clearInterval(l);i.trigger("onPause")},stop:function(){m.pause();g=true},onBeforePlay:function(t){return m.bind("onBeforePlay",t)},onPlay:function(t){return m.bind("onPlay",t)},onBeforePause:function(t){return m.bind("onBeforePause",t)},onPause:function(t){return m.bind("onPause",t)}});if(e.autopause){var k=m.getTabs().add(s).add(q).add(m.getPanes());k.hover(function(){m.pause();j=clearInterval(j)},function(){if(!g){j=setTimeout(m.play,e.interval)}})}if(e.autoplay){l=setTimeout(m.play,e.interval)}else{m.stop()}if(e.clickable){m.getPanes().click(function(){m.next()})}if(!m.getConf().rotate){var r=e.disabledClass;if(!m.getIndex()){q.addClass(r)}m.onBeforeClick(function(u,t){if(!t){q.addClass(r)}else{q.removeClass(r);if(t==m.getTabs().length-1){s.addClass(r)}else{s.removeClass(r)}}})}});return e.api?d:this}})(jQuery);
(function(d){var a=d.tools.tabs;a.plugins=a.plugins||{};a.plugins.history={version:"1.0.2",conf:{api:false}};var e,b;function c(f){if(f){var g=b.contentWindow.document;g.open().close();g.location.hash=f}}d.fn.onHash=function(g){var f=this;if(d.browser.msie&&d.browser.version<"8"){if(!b){b=d("<iframe/>").attr("src","javascript:false;").hide().get(0);d("body").append(b);setInterval(function(){var i=b.contentWindow.document,j=i.location.hash;if(e!==j){d.event.trigger("hash",j);e=j}},100);c(location.hash||"#")}f.bind("click.hash",function(h){c(d(this).attr("href"))})}else{setInterval(function(){var j=location.hash;var i=f.filter("[href$="+j+"]");if(!i.length){j=j.replace("#","");i=f.filter("[href$="+j+"]")}if(i.length&&j!==e){e=j;d.event.trigger("hash",j)}},100)}d(window).bind("hash",g);return this};d.fn.history=function(g){var h=d.extend({},a.plugins.history.conf),f;g=d.extend(h,g);this.each(function(){var j=d(this).tabs(),i=j.getTabs();if(j){f=j}i.onHash(function(k,l){if(!l||l=="#"){l=j.getConf().initialIndex}j.click(l)});i.click(function(k){location.hash=d(this).attr("href").replace("#","")})});return g.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(b){var a=b.tools.scrollable;a.plugins=a.plugins||{};a.plugins.circular={version:"0.5.1",conf:{api:false,clonedClass:"cloned"}};b.fn.circular=function(e){var d=b.extend({},a.plugins.circular.conf),c;b.extend(d,e);this.each(function(){var i=b(this).scrollable(),n=i.getItems(),k=i.getConf(),f=i.getItemWrap(),j=0;if(i){c=i}if(n.length<k.size){return false}n.slice(0,k.size).each(function(o){b(this).clone().appendTo(f).click(function(){i.click(n.length+o)}).addClass(d.clonedClass)});var l=b.makeArray(n.slice(-k.size)).reverse();b(l).each(function(o){b(this).clone().prependTo(f).click(function(){i.click(-o-1)}).addClass(d.clonedClass)});var m=f.children(k.item);var h=k.hoverClass;if(h){m.hover(function(){b(this).addClass(h)},function(){b(this).removeClass(h)})}function g(o){var p=m.eq(o);if(k.vertical){f.css({top:-p.position().top})}else{f.css({left:-p.position().left})}}g(k.size);b.extend(i,{move:function(s,r,p,q){var u=j+s+k.size;var t=u>i.getSize()-k.size;if(u<=0||t){var o=j+k.size+(t?-n.length:n.length);g(o);u=o+s}if(q){m.removeClass(k.activeClass).eq(u+Math.floor(k.size/2)).addClass(k.activeClass)}if(u===j+k.size){return self}return i.seekTo(u,r,p)},begin:function(p,o){return this.seekTo(k.size,p,o)},end:function(p,o){return this.seekTo(n.length,p,o)},click:function(p,r,q){if(!k.clickable){return self}if(k.size==1){return this.next()}var s=p-j,o=k.activeClass;s-=Math.floor(k.size/2);return this.move(s,r,q,true)},getIndex:function(){return j},setPage:function(p,q,o){return this.seekTo(p*k.size+k.size,q,o)},getPageAmount:function(){return Math.ceil(n.length/k.size)},getPageIndex:function(){if(j<0){return this.getPageAmount()-1}if(j>=n.length){return 0}var o=(j+k.size)/k.size-1;return o},getVisibleItems:function(){var o=j+k.size;return m.slice(o,o+k.size)}});i.onStart(function(p,o){j=o-k.size;return false});i.getNaviButtons().removeClass(k.disabledClass)});return d.api?c:this}})(jQuery);
(function(b){var a=b.tools.scrollable;a.plugins=a.plugins||{};a.plugins.autoscroll={version:"1.0.1",conf:{autoplay:true,interval:3000,autopause:true,steps:1,api:false}};b.fn.autoscroll=function(d){if(typeof d=="number"){d={interval:d}}var e=b.extend({},a.plugins.autoscroll.conf),c;b.extend(e,d);this.each(function(){var g=b(this).scrollable();if(g){c=g}var i,f,h=true;g.play=function(){if(i){return}h=false;i=setInterval(function(){g.move(e.steps)},e.interval);g.move(e.steps)};g.pause=function(){i=clearInterval(i)};g.stop=function(){g.pause();h=true};if(e.autopause){g.getRoot().add(g.getNaviButtons()).hover(function(){g.pause();clearInterval(f)},function(){if(!h){f=setTimeout(g.play,e.interval)}})}if(e.autoplay){setTimeout(g.play,e.interval)}});return e.api?c:this}})(jQuery);
(function(b){var a=b.tools.scrollable;a.plugins=a.plugins||{};a.plugins.navigator={version:"1.0.2",conf:{navi:".navi",naviItem:null,activeClass:"active",indexed:false,api:false,idPrefix:null}};b.fn.navigator=function(d){var e=b.extend({},a.plugins.navigator.conf),c;if(typeof d=="string"){d={navi:d}}d=b.extend(e,d);this.each(function(){var i=b(this).scrollable(),f=i.getRoot(),l=f.data("finder").call(null,d.navi),g=null,k=i.getNaviButtons();if(i){c=i}i.getNaviButtons=function(){return k.add(l)};function j(){if(!l.children().length||l.data("navi")==i){l.empty();l.data("navi",i);for(var m=0;m<i.getPageAmount();m++){l.append(b("<"+(d.naviItem||"a")+"/>"))}g=l.children().each(function(n){var o=b(this);o.click(function(p){i.setPage(n);return p.preventDefault()});if(d.indexed){o.text(n)}if(d.idPrefix){o.attr("id",d.idPrefix+n)}})}else{g=d.naviItem?l.find(d.naviItem):l.children();g.each(function(n){var o=b(this);o.click(function(p){i.setPage(n);return p.preventDefault()})})}g.eq(0).addClass(d.activeClass)}i.onStart(function(o,n){var m=d.activeClass;g.removeClass(m).eq(i.getPageIndex()).addClass(m)});i.onReload(function(){j()});j();var h=g.filter("[href="+location.hash+"]");if(h.length){i.move(g.index(h))}});return d.api?c:this}})(jQuery);

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

/**
* hoverIntent r5 // 2007.03.27 // jQuery 1.1.2+
* <http://cherne.net/brian/resources/jquery.hoverIntent.html>
*
* @param  f  onMouseOver function || An object with configuration options
* @param  g  onMouseOut function  || Nothing (use configuration options object)
* @author    Brian Cherne <brian@cherne.net>
*/
(function($){$.fn.hoverIntent=function(f,g){var cfg={sensitivity:7,interval:100,timeout:0};cfg=$.extend(cfg,g?{over:f,out:g}:f);var cX,cY,pX,pY;var track=function(ev){cX=ev.pageX;cY=ev.pageY;};var compare=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);if((Math.abs(pX-cX)+Math.abs(pY-cY))<cfg.sensitivity){$(ob).unbind("mousemove",track);ob.hoverIntent_s=1;return cfg.over.apply(ob,[ev]);}else{pX=cX;pY=cY;ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}};var delay=function(ev,ob){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);ob.hoverIntent_s=0;return cfg.out.apply(ob,[ev]);};var handleHover=function(e){var p=(e.type=="mouseover"?e.fromElement:e.toElement)||e.relatedTarget;while(p&&p!=this){try{p=p.parentNode;}catch(e){p=this;}}if(p==this){return false;}var ev=jQuery.extend({},e);var ob=this;if(ob.hoverIntent_t){ob.hoverIntent_t=clearTimeout(ob.hoverIntent_t);}if(e.type=="mouseover"){pX=ev.pageX;pY=ev.pageY;$(ob).bind("mousemove",track);if(ob.hoverIntent_s!=1){ob.hoverIntent_t=setTimeout(function(){compare(ev,ob);},cfg.interval);}}else{$(ob).unbind("mousemove",track);if(ob.hoverIntent_s==1){ob.hoverIntent_t=setTimeout(function(){delay(ev,ob);},cfg.timeout);}}};return this.mouseover(handleHover).mouseout(handleHover);};})(jQuery);

(function($){

	//Finding min and max values in array from http://snippets.dzone.com/posts/show/769
	Array.prototype.min = function(){ return Math.min.apply({},this) };
	Array.prototype.max = function(){ return Math.max.apply({},this) };

	$.fn.masonry = function() {
		this.each(function() {

			var wall = $(this);

			if ( wall.children().length > 0 ) { // check if the element has anything in it

				if( wall.children('.masonryWrap').length == 0 ) {      // checks if the masonryWrap div is already there
					wall.wrapInner('<div class=\"masonryWrap\"></div>');
				}
				var mWrap = wall.children('.masonryWrap');

				var brick = mWrap.children();
				var brickW = brick.outerWidth(true);
				var colCount = Math.floor( mWrap.width() / brickW ) ;

				var colH=new Array();
				for ( i=0; i < colCount; i++) {
					colH[ i ] =  0 ;
				}

				mWrap.css({ position: 'relative' });

				brick.css({
						float: 'none',
						position: 'absolute',
						display: 'block'
					})
					.each(function(){
						for ( i=colCount-1; i > -1; i-- ) {
							if ( colH[ i ] == colH.min() ) {
								var thisCol = i;
							}
						}
						$(this).css({
							top: colH[ thisCol ],
							left: brickW * thisCol
						});
						colH[ thisCol ] += $(this).outerHeight(true);
					});

				mWrap.height( colH.max() );
			}

			return this;
		});
	};
})(jQuery);

/*
 * Autocomplete - jQuery plugin 1.1pre
 *
 * Copyright (c) 2007 Dylan Verheul, Dan G. Switzer, Anjesh Tuladhar, J?rn Zaefferer
 *
 * 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.autocomplete.js 5785 2008-07-12 10:37:33Z joern.zaefferer $
 *
 */

;(function($) {

$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150
		}, options);

		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };

		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;

		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);

	var blockSubmit;

	// prevent form submit in opera when selecting with return key
	$.browser.opera && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});

	// only opera doesn't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind(($.browser.opera ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {

			case KEY.UP:
				event.preventDefault();
				if ( select.visible() ) {
					select.prev();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.DOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.next();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEUP:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEDOWN:
				event.preventDefault();
				if ( select.visible() ) {
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;

			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;

			case KEY.ESC:
				select.hide();
				break;

			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
		hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		if ( hasFocus++ > 1 && !select.visible() ) {
			onChange(0, true);
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});
	
	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;

		var v = selected.result;
		previousValue = v;

		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				v = words.slice(0, words.length - 1).join( options.multipleSeparator ) + options.multipleSeparator + v;
			}
			v += options.multipleSeparator;
		}

		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}

	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}

		var currentValue = $input.val();

		if ( !skipPrevCheck && currentValue == previousValue )
			return;

		previousValue = currentValue;

		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};

	function trimWords(value) {
		if ( !value ) {
			return [""];
		}
		var words = value.split( options.multipleSeparator );
		var result = [];
		$.each(words, function(i, value) {
			if ( $.trim(value) )
				result[i] = $.trim(value);
		});
		return result;
	}

	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		return words[words.length - 1];
	}

	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue){
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$.Autocompleter.Selection(input, previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else
							$input.val( "" );
					}
				}
			);
		}
		if (wasVisible)
			// position cursor at end of input field
			$.Autocompleter.Selection(input, input.value.length, input.value.length);
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data && data.length) {
			success(term, data);
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){

			var extraParams = {
				timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});

			$.ajax({
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				data: $.extend({
					q: lastWord(term),
					limit: options.max
				}, extraParams),
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			failure(term);
		}
	};

	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: false,
	cacheLength: 10,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { return row[0]; },
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;

	function matchSubset(s, sub) {
		if (!options.matchCase)
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (options.matchContains == "word"){
			i = s.toLowerCase().search("\\b" + sub.toLowerCase());
		}
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){
			length++;
		}
		data[q] = value;
	}

	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;

		// track all options for minChars = 0
		stMatchSets[""] = [];

		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( value === false )
				continue;

			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] )
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};

			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}

	// populate any existing data
	setTimeout(populate, 25);

	function flush(){
		data = {};
		length = 0;
	}

	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/*
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}
				return csub;
			} else
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};

	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body);

		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			// TODO provide option to avoid setting focus again after selection? useful for cleanup-on-focus
			input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});

		if( options.width > 0 )
			element.css("width", options.width);

		needsInit = false;
	}

	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};

	function movePosition(step) {
		active += step;
		if (active < 0) {
			active = listItems.size() - 1;
		} else if (active >= listItems.size()) {
			active = 0;
		}
	}

	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}

	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}

	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});

                if($.browser.msie && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }

            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.Autocompleter.Selection = function(field, start, end) {
	if( field.createTextRange ){
		var selRange = field.createTextRange();
		selRange.collapse(true);
		selRange.moveStart("character", start);
		selRange.moveEnd("character", end);
		selRange.select();
	} else if( field.setSelectionRange ){
		field.setSelectionRange(start, end);
	} else {
		if( field.selectionStart ){
			field.selectionStart = start;
			field.selectionEnd = end;
		}
	}
	field.focus();
};

})(jQuery);



// HTML Truncator for jQuery
// by Henrik Nyh <http://henrik.nyh.se> 2008-02-28.
// Free to modify and redistribute with credit.

(function($) {

  var trailing_whitespace = true;

  $.fn.truncate = function(options) {

    var opts = $.extend({}, $.fn.truncate.defaults, options);

    $(this).each(function() {

      var content_length = $.trim(squeeze($(this).text())).length;
      if (content_length <= opts.max_length)
        return;  // bail early if not overlong

      var actual_max_length = opts.max_length - opts.more.length - 3;  // 3 for " ()"
      var truncated_node = recursivelyTruncate(this, actual_max_length);
      var full_node = $(this).hide();

      truncated_node.insertAfter(full_node);

      findNodeForMore(truncated_node).append(' (<a href="#show more content">'+opts.more+'</a>)');
      findNodeForLess(full_node).append(' (<a href="#show less content">'+opts.less+'</a>)');

      truncated_node.find('a:last').click(function() {
        truncated_node.hide(); full_node.show(); return false;
      });
      full_node.find('a:last').click(function() {
        truncated_node.show(); full_node.hide(); return false;
      });

    });
  }

  // Note that the " (more)" bit counts towards the max length ��� so a max
  // length of 10 would truncate "1234567890" to "12 (��?more)".
  $.fn.truncate.defaults = {
    max_length: 100,
    more: 'more',
    less: 'less'
  };

  function recursivelyTruncate(node, max_length) {
    return (node.nodeType == 3) ? truncateText(node, max_length) : truncateNode(node, max_length);
  }

  function truncateNode(node, max_length) {
    var node = $(node);
    var new_node = node.clone().empty();
    var truncatedChild;
    node.contents().each(function() {
      var remaining_length = max_length - new_node.text().length;
      if (remaining_length == 0) return;  // breaks the loop
      truncatedChild = recursivelyTruncate(this, remaining_length);
      if (truncatedChild) new_node.append(truncatedChild);
    });
    return new_node;
  }

  function truncateText(node, max_length) {
    var text = squeeze(node.data);
    if (trailing_whitespace)  // remove initial whitespace if last text
      text = text.replace(/^ /, '');  // node had trailing whitespace.
    trailing_whitespace = !!text.match(/ $/);
    var text = text.slice(0, max_length);
    // Ensure HTML entities are encoded
    // http://debuggable.com/posts/encode-html-entities-with-jquery:480f4dd6-13cc-4ce9-8071-4710cbdd56cb
    text = $('<div/>').text(text).html();
    return text;
  }

  // Collapses a sequence of whitespace into a single space.
  function squeeze(string) {
    return string.replace(/\s+/g, ' ');
  }

  // Finds the last, innermost block-level element
  function findNodeForMore(node) {
    var $node = $(node);
    var last_child = $node.children(":last");
    if (!last_child) return node;
    var display = last_child.css('display');
    if (!display || display=='inline') return $node;
    return findNodeForMore(last_child);
  };

  // Finds the last child if it's a p; otherwise the parent
  function findNodeForLess(node) {
    var $node = $(node);
    var last_child = $node.children(":last");
    if (last_child && last_child.is('p')) return last_child;
    return node;
  };

})(jQuery);


/**
 * jQuery.fn.rewImgSizer
 * version 1.2
 * COPYRIGHT 2010
 *
 * Usage: $('img').rewImgSizer({});
 *
 * Options: 
 *
 * scale : Ratio (e.g 1.25)
 * align: 'top left', 'top center', 'top right', 'center', 'center right', 'center left', 'bottom right', 'bottom center' or 'bottom left'
 * scale: 'scale', 'crop', 'fit' or 'none'
 * noUpscale: bollean (true or false)
 * onBeforeShow:
 * onAfterShow:
 *
**/
jQuery.fn.rewImgSizer = function(options) {

	var $self = this;

	var defaults = {
		method: 'crop',
		scale: 1,
		align: 'center',
		effect: 'fadeIn',
		noUpScale: false,
		onBeforeShow: function(){},
		onAfterShow: function(){}
	};

	var options = $.extend(defaults, options);

	$self.resize = function ($img) {

		/* photo
		----------------------------------------------------------- */

		var pho_vsize = 1;
		var pho_hsize = 1;
		var pho_width = $img.width();
		var pho_heigh = $img.height();

		if (pho_width > pho_heigh) {
			pho_vsize = Math.round((pho_width / pho_heigh) * 100) / 100;
		} else{
			pho_hsize = Math.round((pho_heigh / pho_width) * 100) / 100;
		}

		/* canvas
		----------------------------------------------------------- */

		$can = $img.parent();
		
		var can_vsize = 1;
		var can_hsize = 1;
		var can_width = $can.width();
		var can_heigh = $can.height();

		if (can_width > can_heigh) {
			can_vsize = Math.round((can_width / can_heigh) * 100) / 100;
		} else{
			can_hsize = Math.round((can_heigh / can_width) * 100) / 100;
		}

		/* store in case we want to revert */
		oldmethod = options.method;

		if (options.noUpScale) {
			if(pho_width < can_width && pho_heigh < can_heigh) {
				options.method = 'none';
			}

		}

		/* ect.
		----------------------------------------------------------- */

		//$img.attr('title', 'photo height=' + pho_hsize + '; photo width=' + pho_vsize + '; canvas height=' + can_hsize + '; canvas width=' + can_vsize);

		if (options.method == 'crop') {

			if (pho_hsize > can_hsize) {
				$img.width(can_width);
				$img.height($img.width() * pho_hsize);
			} else if (pho_vsize > can_vsize) {
				$img.height(can_heigh);
				$img.width($img.height() * pho_vsize);
			} else {
				// square 1:1
				$img.width(can_width);
				$img.height($img.width() * pho_hsize);
			}

		} else if (options.method == 'fit') {
		
			$img.height(can_heigh);
			$img.width(can_width);

		} else if (options.method == 'scale') {
		
			if (pho_hsize > can_hsize) {
				$img.height(can_heigh);
			} else if (pho_vsize > can_vsize) {
				$img.width(can_width);
			} else {
				// square 1:1
				if (can_hsize > can_vsize) {
					$img.width(can_width);
				} else {
					$img.height(can_heigh);
				}
			}

		} else {

			/* no resize */

		}

		/* SCALE OPTION */
		if (options.scale) {
			sImgH = $img.height() * options.scale;
			sImgW = $img.width() * options.scale;
			$img.width(sImgW); $img.height(sImgH);
		}

		$img.css({position:'absolute', left: ''});

		switch (options.align) {
		    
			case 'center':
    			$img.css('top', -($img.height() - can_heigh) / 2 + 'px');
    			$img.css('left', -($img.width() - can_width) / 2 + 'px');
			break;
			
			case 'top left':
    			$img.css({'top': 0, 'left': 0});
			break;
			
			case 'top center':
    			$img.css('top', 0);
    			$img.css('left', -($img.width() - can_width) / 2 + 'px');
			break;
			
			case 'top right':
    			$img.css('top', 0);
    			$img.css('right', 0);
			break;
			
			case 'center right':
    			$img.css('top', -($img.height() - can_heigh) / 2 + 'px');
    			$img.css('right', 0);
			break;
			
			case 'center left':
    			$img.css('top', -($img.height() - can_heigh) / 2 + 'px');
    			$img.css('left', 0);
			break;
			
			case 'bottom right':
    			$img.css('bottom', 0);
    			$img.css('right', 0);
			break;
			
			case 'bottom center':
    			$img.css('bottom', 0);
    			$img.css('left', -($img.width() - can_width) / 2 + 'px');
			break;
			
			case 'bottom left':
    			$img.css('bottom', 0);
    			$img.css('left', 0);
			break;
			
		}

		$img.hide();
	
		//showImage();

		//function showImage() {
			options.onBeforeShow.call(this);
			$img.fadeIn('slow', options.onAfterShow.call(this));
		//}
		
		options.method = oldmethod;

	};

    jQuery(this).each(function (i) {

		$img = $(this);
		$img.css({position: 'absolute', left: '-999em'});

		var orgSrc = this.src;
		if (!$.browser.msie) {
			this.src = ""; //ie will do funky things if this is here (show the image as an X, only show half of the image, etc)
		}
		$(this).bind('load', function(){
		    $(this).unbind('load');
			$self.resize($(this));
		});
		if (!$.browser.msie) {
			this.src = orgSrc; //needed for potential cached images
		} else if (this.complete || this.complete === undefined) {
			this.src = orgSrc;
			$(this).trigger('load');
		}
		
	});

	// allow jQuery chaining 
	return this;

};


(function($){

	/* rewIDX_SLIDES */

	$.fn.rewIDX_SLIDES = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
            'speed':            'slow',
            'timeout':          5000,
            'order':			'sequential'
        };
        if (options) $.extend(settings, options);

        var elements = $(container).children();

        if (elements.length > 1) {
            $(container).css('position', 'relative');
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
			setTimeout(function() {
				$.innerfade.next(elements, settings, 1, 0);
			}, settings.timeout);
			$(elements[0]).show();
        }
    };

    $.innerfade.next = function(elements, settings, current, last) {

		if(settings.order == 'random') { elements[current] = elements.get(Math.random()*elements.length())}

		$(elements[last]).fadeOut(settings.speed);
		$(elements[current]).fadeIn(settings.speed, function(){});
		$(elements[current]).find('img').not('.resized').rewIDX_IMGCANVAS({'method':'crop'});

		if ((current + 1) < elements.length) {
			current = current + 1;
			last = current - 1;
		} else {
			current = 0;
			last = elements.length - 1;
		}

        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };









	/* rewIDX_IMGCANVAS */

	jQuery.fn.rewIDX_IMGCANVAS = function(options) {

		var $self = $(this);

		var defaults = {
			method: 'crop',
			align: 'center'
		};
	
		var options = $.extend(defaults, options);


		jQuery(this).each(function(i) {

			$self.resize = function ($img) {

				/* the canvas */
				$imgCanvas 	= $img.parent();
				$imgCanvasW	= $imgCanvas.width();
				$imgCanvasH	= $imgCanvas.height();

				if($imgCanvasW > $imgCanvasH) {
					$imgCanvasAspect = 'landscape';
					$imgCanvasRatioH = 1;
					$imgCanvasRatioV = Math.round(($imgCanvasW / $imgCanvasH) * 100) / 100;
				} else {
					$imgCanvasAspect = 'portrait';
					$imgCanvasRatioV = 1;
					$imgCanvasRatioH = Math.round(($imgCanvasH / $imgCanvasW) * 100) / 100;
				}

				/* the image */
				$img		= $('img', $imgCanvas);
				$imgW		= $img.width();
				$imgH		= $img.height();
				if($imgW > $imgH) {
					$imgAspect = 'landscape';
					$imgRatioH = 1;
					$imgRatioV = Math.round(($imgW / $imgH) * 100) / 100;
				} else {
					$imgAspect = 'portrait';
					$imgRatioH = 1;
					$imgRatioV = Math.round(($imgW / $imgH) * 100) / 100;
				}

				if(options.method == 'crop'){
			
						if($imgRatioV > $imgCanvasRatioV) {
			
							$img.height($imgCanvasH);
							$img.width($img.height() * $imgRatioV);
			
						} else {
			
							$img.width($imgCanvasW);
							$img.height($img.width() * Math.round(($imgH / $imgW) * 100) / 100);
			
						}
			
			
						/* recheck and adjust size. easiest this way */
						if($img.height() < $imgCanvasH) {
							$img.height($imgCanvasH);
							$img.width($imgCanvasH * $imgRatioV);
						}
	
				} else if (options.method == 'scale') {
	
						if($imgRatioV > $imgCanvasRatioV) {
			
							$img.width($imgCanvasW);
							$img.height($img.width() * Math.round(($imgH / $imgW) * 100) / 100);
			
						} else {
			
							$img.height($imgCanvasH);
							$img.height($img.width() * Math.round(($imgH / $imgW) * 100) / 100);
			
						}
	
						/* recheck and adjust size. easiest this way */
						if($img.width() > $imgCanvasW) {
							$img.width($imgCanvasW);
							$img.height($imgCanvasW * Math.round(($imgH / $imgW) * 100) / 100);
						}
	
				}
	
	
				/* SCALE OPTION */
				if (options.scale) {
					sImgH = $img.height() * options.scale;
					sImgW = $img.width() * options.scale;
					$img.width(sImgW); $img.height(sImgH);
				}
	
	
				$imgCanvas.css({position: 'relative'});
				$img.css({position: 'absolute'});
	
				/* ALIGN OPTION */
				switch (options.align) {

					case 'center':
						$img.css('top', -($img.height() - $imgCanvasH) / 2 + 'px');
						$img.css('left', -($img.width() - $imgCanvasW) / 2 + 'px');
					break;
					
					case 'top left':
						$img.css({'top': 0, 'left': 0});
					break;
					
					case 'top center':
						$img.css('top', 0);
						$img.css('left', -($img.width() - $imgCanvasW) / 2 + 'px');
					break;
					
					case 'top right':
						$img.css('top', 0);
						$img.css('right', 0);
					break;
					
					case 'center right':
						$img.css('top', -($img.height() - $imgCanvasH) / 2 + 'px');
						$img.css('right', 0);
					break;
					
					case 'center left':
						$img.css('top', -($img.height() - $imgCanvasH) / 2 + 'px');
						$img.css('left', 0);
					break;
					
					case 'bottom right':
						$img.css('bottom', 0);
						$img.css('right', 0);
					break;
					
					case 'bottom center':
						$img.css('bottom', 0);
						$img.css('left', -($img.width() - $imgCanvasW) / 2 + 'px');
					break;
					
					case 'bottom left':
						$img.css('bottom', 0);
						$img.css('left', 0);
					break;

				}
				
				$img.addClass('resized');
				
			}

			jQuery(this).each(function (i) {

				$img = $(this);

				var orgSrc = this.src;

				if (!$.browser.msie) {
					this.src = ""; //ie will do funky things if this is here (show the image as an X, only show half of the image, etc)
				}
				$(this).bind('load', function(){
					$(this).unbind('load');
					if($(this).parent().height() > 0) {
						$self.resize($(this));
					}
				});
				if (!$.browser.msie) {
					this.src = orgSrc; //needed for potential cached images
				} else if (this.complete || this.complete === undefined) {
					this.src = orgSrc;
					$(this).trigger('load');
				}

			});

			return this;

		});

	};



})(jQuery);

/**
 * jQuery Facebox Plugin (Redux)
 */
(function($) {

    /* jQuery.fn.facebox */
    $.facebox = function(options) {
        
        /* Instance */
        var $self = this;

        /* Facebox Defaults */
        $self.defaults = {
            opacity      : 0.3,
            overlay      : true,
            modal        : true,
            noclose      : false,
            //
            div          : false,
            ajax         : false,
            image        : false,
            data         : false,
            iframe       : false,
            //
            title        : '&nbsp;',
            css_top      : 'auto', // auto or number of pixels
            css_left     : 'auto', // auto or number of pixels
            loadingImage : '/img/facebox/loading.gif',
            closeImage   : '/img/facebox/closelabel.gif',
            imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
            faceboxHtml  : '\
                <div id="facebox" style="display:none;"> \
                    <div class="popup"> \
                        <table> \
                          <tbody> \
                            <tr> \
                              <td class="tl"/><td class="b"/><td class="tr"/> \
                            </tr> \
                            <tr> \
                              <td class="b"/> \
                              <td class="body"> \
                                <div class="titlebar"> \
                                  <span class="title">&nbsp;</span> \
                                  <a href="#" class="close">Close</a> \
                                </div> \
                                <div class="content"> \
                                </div> \
                              </td> \
                              <td class="b"/> \
                            </tr> \
                            <tr> \
                              <td class="bl"/><td class="b"/><td class="br"/> \
                            </tr> \
                          </tbody> \
                        </table> \
                      </div> \
                </div>'
        };

        /* Instance Options */
        $self.options = $.extend($self.defaults, options);

        /* Initilized Boolean */
        $self.initilized = false;

        /* $.facebox.makeCompatible */
        $self.makeCompatible = function () {
            $self.options.loadingImage = $self.options.loading_image || $self.options.loadingImage;
            $self.options.closeImage   = $self.options.close_image   || $self.options.closeImage;
            $self.options.imageTypes   = $self.options.image_types   || $self.options.imageTypes;
            $self.options.faceboxHtml  = $self.options.facebox_html  || $self.options.faceboxHtml;
        }

        /* $facebox.close */
        $self.close = function () {
            $(document).unbind('close.facebox');
            $(document).unbind('keydown.facebox');
            $('#facebox').fadeOut(function() {
                $('#facebox .content').removeClass().addClass('content');
                $self.hideOverlay();
                $('#facebox .loading').remove();
            }).remove();
            return false;
        }

        /* $facebox.skipOverlay */
        $self.skipOverlay = function () {
            return $self.options.overlay == false || $self.options.opacity === null;
        }

        /* $facebox.showOverlay */
        $self.showOverlay = function () {
            if ($self.skipOverlay()) return;
            if ($('#facebox_overlay').length == 0) {
                $("body").append('<div id="facebox_overlay" class="facebox_hide"></div>');
            }
            $('#facebox_overlay').hide().addClass("facebox_overlayBG").css('opacity', $self.options.opacity).click(function() {
                if ($self.options.modal != true) {
                    $self.close();
                }
            }).fadeIn(200);
            return false;
        }

        /* $facebox.hideOverlay */
        $self.hideOverlay = function () {
            if ($self.skipOverlay()) return;
            $('#facebox_overlay').fadeOut(200, function() {
                $("#facebox_overlay").removeClass("facebox_overlayBG");
                $("#facebox_overlay").addClass("facebox_hide");
                $("#facebox_overlay").remove();
            });
            return false;
        }

        /* $facebox.fillFaceboxFromHref */
        $self.fillFaceboxFromHref = function (href) {

            // div
            if (href.match(/#/)) {
                var url    = window.location.href.split('#')[0];
                var target = href.replace(url, '');
                if (target == '#') return;
                $self.reveal($(target).html());

            // image
            } else if (href.match($self.options.imageTypesRegexp)) {
                $self.fillFaceboxFromImage(href);

            // ajax
            } else {
                $self.fillFaceboxFromAjax(href);

            }

        }

        /* $facebox.fillFaceboxFromImage */
        $self.fillFaceboxFromImage = function (href) {
            var image = new Image();
            image.onload = function () {
                $self.reveal('<div class="image"><img src="' + image.src + '" /></div>');
            }
            image.src = href;
        }

        /* $facebox.fillFaceboxFromAjax */
        $self.fillFaceboxFromAjax = function (href) {
            $.get(href, function(data) {
                $self.reveal(data);
            });
        }

        /* $facebox.fillFaceboxFromIFrame */
        $self.fillFaceboxFromIFrame = function (href) {
            
            /* Append facebox_Frame=true to URL Query */
            var href = (href.indexOf('?') != -1) ? href + '&facebox_Frame=true' : href + '?facebox_Frame=false';

            /* Remove Existing IFrame */
            $('#facebox-iframe').remove();
            
            /* Build IFrame */
            href = href.replace(/\"/g, "'");
            var iframe = $('<iframe id="facebox-iframe" src="' + href + '" width="100%" height="100" frameborder="0" scrolling="no" style="overflow-x: hidden;" />');
            
            /*
            iframe.load(function () {
                var height = this.contentWindow.document.body.scrollHeight;
                $(this).css('height', height + 'px');
            });
            */
            
            $self.reveal(iframe);

        }

        /* $facebox.reveal */
        $self.reveal = function (data) {
            $('#facebox .content').append(data);
            $('#facebox .loading').remove();
            $('#facebox .body').children().fadeIn('normal');
            if ($self.options.noclose == true) {
                $('#facebox .titlebar a.close').hide();
            } else {
                $('#facebox .titlebar a.close').show();
            }
            $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2));
        }

        /* $facebox.getPageScroll */
        $self.getPageScroll = function () {
            var xScroll, yScroll;
            if (self.pageYOffset) {
                yScroll = self.pageYOffset;
                xScroll = self.pageXOffset;
            } else if (document.documentElement && document.documentElement.scrollTop) {     // Explorer 6 Strict
                yScroll = document.documentElement.scrollTop;
                xScroll = document.documentElement.scrollLeft;
            } else if (document.body) {// all other Explorers
                yScroll = document.body.scrollTop;
                xScroll = document.body.scrollLeft;
            }
            return new Array(xScroll, yScroll);
        }

        /* $facebox.getPageHeight */
        $self.getPageHeight = function () {
            var windowHeight;
            if (self.innerHeight) { // all except Explorer
                windowHeight = self.innerHeight;
            } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
                windowHeight = document.documentElement.clientHeight;
            } else if (document.body) { // other Explorers
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }

        /* $.facebox.init */
        $self.init = function () {

            /* Return if Already Initilized */
            if ($self.initilized) {
                return true;
            } else {
                $self.initilized = true;
            }

            /* Make Compatible */
            $self.makeCompatible();

            var imageTypes = $self.options.imageTypes.join('|');
            $self.options.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i');

            /* Append Facebox Content to Document Body */
            $('body').append($self.options.faceboxHtml);

            /* Preload Close & Loading Images */
            var preload = [ new Image(), new Image() ];
            preload[0].src = $self.options.closeImage;
            preload[1].src = $self.options.loadingImage;

            /* Preload Images */
            $('#facebox').find('.b:first, .bl').each(function() {
                preload.push(new Image());
                preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1');
            });

            /* Close Button */
            $('#facebox .close').click($self.close);
            $('#facebox .close_image').attr('src', $self.options.closeImage);

        }

        /* $.facebox.loading */
        $self.loading = function() {

            $self.init();

            if ($('#facebox .loading').length == 1) return true;

            $self.showOverlay();

            $('#facebox .content').empty();
            $('#facebox .body').children().hide().end().
            append('<div class="loading"><img src="' + $self.options.loadingImage + '"/></div>')

            $('#facebox').css({
                top:    $self.options.css_top  != 'auto' ? $self.options.css_top  : $self.getPageScroll()[1] + ($self.getPageHeight() / 10),
                left:   $self.options.css_left != 'auto' ? $self.options.css_left : $(window).width() / 2 - 205
            }).show()

            if (typeof($self.options.title) != 'undefined') {
                $('#facebox .titlebar span.title').html($self.options.title);
            }

            if (typeof($self.options.width) != 'undefined') {
                $('#facebox .body').width($self.options.width);
            }

            if (typeof($self.options.height) != 'undefined') {
                $('#facebox .body').height($self.options.height);
            }

            $(document).bind('keydown.facebox', function(e) {
                if ($self.options.modal != true) {
                    if (e.keyCode == 27) {
                        $self.close();
                    }
                }
                return true;
            });
            
            $(document).bind('close.facebox', function(e) {
                $self.close();
            });

        }

        /* Initilize Facebox */
        $self.init();

        /* Loading */
        $self.loading();

        /* AJAX */
        if ($self.options.ajax) {
            $self.fillFaceboxFromAjax($self.options.ajax);

        /* IFrame */
        } else if ($self.options.iframe) {
            $self.fillFaceboxFromIFrame($self.options.iframe);

        /* Image */
        } else if ($self.options.image) {
            $self.fillFaceboxFromImage($self.options.image);

        /* Container */
        } else if ($self.options.div) {
            $self.fillFaceboxFromHref($self.options.div);

        /* Load Data */
        } else {
            $self.reveal($self.options.data);

        }

        /* Return Facebox Instance */
        return $self;

    };

})(jQuery);
$(document).ready(function() {

    $.preloadImages('/img/no-bookmarks.png');

	if($('body').hasClass('enablesuckerfish')) {
		/* do nothing */
	} else {
		$('#nav ul ul, #nav ul div').remove();
	}

    $('.rewbtn').each(function(){
        $button = $(this);
        $button.mousedown(function(){$(this).addClass('active'); });
        $button.mouseleave(function(){$(this).removeClass('active');});
    });

    $('body').append('<div class="tooltip"></div>');

    $('#content .tabset li').bind('click', function(event) {
        if ($(event.target).is('li')) {
            $('a', event.target).trigger('click');
            return false;
        } else if ($(event.target).is('a')) {
            window.location.href = $(event.target).attr('href');
        }
    });

	$('.communities-nav ul').easyListSplitter({'colNumber':3});
	$('.communities-nav ul').each(function(){
		$('li:odd', this).addClass('odd');
	});

    $("form").attr("autocomplete", "off");
    $('.set .photos img').rewImgSizer({method:'crop','scale':1.25});
    $('#idx-detail .description p').truncate({'max_length': 760})

    $('#idx-detail .photos').each(function() {
        $(this).wrap('<div class="gallery"></div>');
        $(this).parent('.gallery').prepend('<div id="image_wrap"></div>');
        $(this).wrapInner('<div class="slides"></div>');
        $('img', this).wrap('<div class="slide"></div>');
        var $num = $('.slide', this).length;
        var photosurl = window.location + 'photos.html';
        $(this).after('<div class="controls"><a href="javascript:void(0);" class="prev">&laquo; Previous</a><a href="javascript:void(0);" class="next">Next &raquo;</a></div>');
    });

    //$('#feature img.panel-img').rewImgSizer();
    
    $('#idx-detail .gallery img').rewImgSizer();

    $('.agent .photos img, .office .photos img').rewImgSizer({method:'crop'});

    var hoverConfig = {
        'over' : function() {
            // mouseover
            $(this).trigger('hoverIntent');
        },
        'out' : function () {
            // mouseout
        }
    };

    /* Ok, let's prep colorbox stuff */
    $('#idx-detail .gallery').each(function(){
        $gallery = $(this);
        $gallery.prepend('<div id="colorbox_gallery"></div>');
    });

    var $wrap = $("#image_wrap");

    $("#content .slides .slide").each(function(i){

        $slide = $(this);
        var $slideImg = $('img', $slide);
        var $si_src = $slideImg.attr('src');
        var $si_rel = 'imgnum_' + i;
        $slideImg.attr('rel', $si_rel);

        $nImg = $('<img src="' + $si_src  + '" id="'+ $si_rel +'" />').appendTo($wrap).hide();


        /* colorbox */
        $imgLink = $('<a href="' + $si_src + '" rel="colorbox" class="' + $slideImg.attr('rel') + '">View Large Images</a>');
        $imgLink.appendTo('#colorbox_gallery');

        $slide.bind('mouseover',function(){
            if ($(this).is(":not(.active)")) {
                $rel = $('img',this).attr('rel');
                $showImg = $('img#'+ $rel);
                $showImg.siblings('img').fadeOut(); 
                $showImg.rewImgSizer({method:'scale'});
                $(this).addClass('active').siblings().removeClass('active');
                $("a[rel='colorbox']").hide().filter('.' + $rel).show();
            }
        });

        $("#content .slides .slide").filter(":first").trigger('hover').addClass('active');

    });

	$('#imgnum_0').rewImgSizer({method:'scale'});

    //$("#content .slides .slide").filter(":first").trigger('hover');
    
    $("a[rel='colorbox']").each(function(i) {
        $(this).colorbox({
            photo: true,
            slideshow: false,
            opacity: 0.8,
            initialWidth: 60,
            initialHeight: 60
        });
        if (i > 0) {
            $(this).hide();
        }
    });

    $('#idx-detail .photos.disabled').hide();

    $('#idx-detail .photos').scrollable({
        size: 5,
        next: '',
        prev: '',
        nextPage: '.next',
        prevPage: '.prev'
    });

    $('#refine-form dl.panel, #quick-search dl.panel').each(function(i){
        $('dt', this).append('<span class="ico-panel-trigger"></span>');
        $('dt', this).click(function(){
            $(this).next('dd').slideToggle('slow',function(){
                $(this).parent('dl').toggleClass('open');
            });
        });
    });

    $("#content div.item").wrap('<div class="dialog">'+'<div class="bd">'+'<div class="c">'+'<div class="s">'+'</div>'+'</div>'+'</div>'+'</div>');

    $('div.dialog').prepend('<div class="hd">'+'<div class="c"></div>'+'</div>').append('<div class="ft">'+'<div class="c"></div>'+'</div>');


    $('#nav .nav.primary li div').css({'left':'-1px'}).hide();

    $('#nav .nav.primary li').hoverIntent(function() {
        $('div', this).show();
    }, function() {
        $('div', this).hide();
    });


    $('#content hr').wrap('<div class="hr"></div>');

    $('#content legend').each( function() {
        val = $(this).html();
        $(this).after('<h5 class="legend"><span>' + val + '</span></h5>');
        $(this).html('');
    });

});

/* REWFW: FORMS */

$(document).ready(function(){

    function rewForm(rewform) {
        rewform.each(function(){
             var dform = $(this);
             $(dform).wrapInner('<div class="form-wrap"></div>');
             $('.field input:text,.field input:password', dform).wrap('<span class="input-wrap"></span>');
             $('.field select', dform).wrap('<span class="select-wrap"></span>');
             $('.field textarea', dform).not('.richtext').wrap('<span class="textarea-wrap"></span>');
             $('.field', dform).wrapInner('<span class="field-iwrap"></span>');
             $('.token', dform).wrapInner('<span class="token-iwrap"></span>');
             $('legend', dform).each(function() {
                var content = $(this).html();
                $(this).after('<h4 class="legend">'+ content +'</h4>').hide();
                $(this).remove();
             });

        });
    }

    rewForm($('form.rewfw'));

    $('#content .actions a.button').each(function(){
        $button = $(this);
        $label = $(this).html();
        $classes = $(this).attr('class').replace('button','');
        $(this).wrap('<div class="button link ' + $classes + '"></div>').after('<span class="label">' + $label + '</span>');
        $('.button', this).live('click', function() {
            document.location = $('a', this).attr('href');
        });
    });

});

/* IDX STUFF */

$(document).ready(function(){

    $('#navi-favorites').hoverIntent(
        function(){
            if ($('#favs-menu').hasClass('loaded')) {
            } else {
                $('#favs-menu').load('/idx/inc/php/ajax/favourites.php', function () {
                    $(this).addClass('loaded');
                });
            }
            $('#favs-menu').fadeIn();
            $(this).addClass('hover');
        },
        function(){
            $('#favs-menu').hide();
            $(this).removeClass('hover');
            }
    );

    /* IDX Saved Searches */
    $('#navi-searches').hoverIntent(
        function(){
            if ($('#searches-menu').hasClass('loaded')) {
                $('#searches-menu').show();
            } else {
                $('#searches-menu').load('/idx/inc/php/ajax/saved_searches.php', function () {
                    $(this).addClass('loaded').show();
                });
            }
            $('#searches-menu').fadeIn();
            $(this).addClass('hover');
        },
        function(){
            $('#searches-menu').hide();
            $(this).removeClass('hover');
    });

    $('#navi-searches').live('mouseout', function() {
        $('#searches-menu').hide();
    });

    /* IDX Save this Search */
    $('body').append('<div id="form-save"></div>');
    $('#navi-save').bind('mouseover', function() {
        $savemenuoffset      = $('#navi-save').offset();
        $savemenuoffset.top  = $savemenuoffset.top  + $('#navi-save').outerHeight();
        $('#form-save').show().css({
            left: $savemenuoffset.left + 'px',
            top: $savemenuoffset.top + 'px'
        });
    });
    $('#form-save').hide().addClass('menu');

    /* Save this Search Form */
    $('#form-save').html('<form action="' + window.location.href + '" onsubmit="this.action += ((this.action.indexOf(\'?\') != -1) ? \'&\' : \'?\') + \'search_title=\' + this.search_title.value;" method="post" class="rewfw">'
                           + '<input id="search_title" name="search_title" type="text" value="Search Title"'
                           + ' onfocus="this.value = this.value == \'Search Title\' ? \'\' : this.value;"'
                           + ' onblur="this.value = this.value == \'\' ? \'Search Title\' : this.value;"'
                           + ' />'
                           + '<div class="buttonset"><button type="submit" class="positive" value="Save">Save</button>'
                       + '</form>').css('width', '140px');

    /* IDX Nav Toolbar */
    $('#nav-supplementary li a').mouseover(function(){closeAllMenus();})
    $('.menu').hover(function(){},function(){closeAllMenus();})

    function closeAllMenus() {
        $('.menu').hide();
    }

    $('.compact .listing').live('mouseover',function(){$(this).addClass('hover');});
    $('.compact .listing').live('mouseout',function(){$(this).removeClass('hover');});
    $('.compact .listing').live('click',function(){
        document.location = $('a:first', this).attr('href');
    });

    $closeLink = $('<a href="javascript:void(0)" title="Click to Hide" class="action-close">close</a>');
    $('#login .errors').append($closeLink);
    $closeLink.click(function() {
        $(this).parent().hide();
    });

});

/* IDX Auto Complete */
$(document).ready(function () {
    $('form.rewfw input.autocomplete').each(function () {
        var multiple = $(this).hasClass('single') ? false : true;
        $(this).autocomplete('/idx/inc/php/ajax/json.php?search=' + $(this).attr('name'), {
            extraParams : {
                'search_city' : function () {
                    return $('select[name="search_city"]').val();
                }
            },
            cacheLength: 0,
            multiple: multiple,
            dataType: 'json',
            parse: function (data) {
                var parsed = [];
                var rows   = data.options;
                for (var i=0; i < rows.length; i++) {
                    var row = $.trim(rows[i].title);
                    if (row) {
                        row = row.split("|");
                        parsed[parsed.length] = {
                            data: row,
                            value: row[0],
                            result: row
                        };
                    }
                }
                return parsed;
            }
        });
    });
});

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}

/* IDX Bookmarking */
function bookmarkListing (mls_number, container) {

    /* POST HTTP Request, Expect JSON */
    $.ajax({
        'url'      : '/idx/inc/php/ajax/json.php?bookmarkListing',
        'type'     : 'POST',
        'dataType' : 'json',
        'data'     : {
            'mls_number' : mls_number
        },
        'error'    : function (XMLHttpRequest, textStatus, errorThrown) {
            alert('An error has occurred. Listing could not be saved.');
            return;
        },
        'success'  : function (json, textStatus) {

            /* Return Code */
            if (json.returnCode == 200) {

                /* Success - Saved */
                if (json.added) {
                    $(container).addClass('saved');
                }

                /* Success - Removed */
                if (json.removed) {
                    $(container).removeClass('saved');
                }

                /* reload favs menu */
                $('#favs-menu').load('/idx/inc/php/ajax/favourites.php', function () {
                    $(this).addClass('loaded');
                });

            } else {

                /* Require Registration */
                if (json.register) {

                    /* Registration Form Overlay */
                    openPage(json.register);

                } else {

                    /* Error Occurred */
                    alert('An error has occurred. Listing could not be saved.');

                }
            }
            return;
        }
    });

}

$(function() {
    if ($.browser.msie) {
        $('select[name="minimum_price"],select[name="maximum_price"]')
            .bind('mousedown', function() {
                if ($(this).css('width') != 'auto') {
                    $(this).data('origWidth', $(this).css('width')).css('width', 'auto');
                }
            })
            .bind('blur', function() {
                $(this).css('width', $(this).data('origWidth'));
            })
            .bind('change', function() {
                $(this).css('width', $(this).data('origWidth'));
            });
    }
});

/**
 * Global Javascript Functions
 */

/* Open Facebox Iframe */
var openPage = function openPage (href) {
    $.facebox({'iframe' : href});
};

/* Global Facebox Close Function */
var closeFacebox = function () {
    $(document).trigger('close.facebox');
};

/* Re-Load User Search Tools */
var reloadUserTools = function () {
    $.ajax({
        'url' : '?',
        'success' : function (data) {
            var data = $('#login', data).html();
            if (typeof(data) != 'undefined') {
                $('#login', window.parent.document.body).html(data);
                Cufon.refresh();
            }
        }
    });
};
