// JavaScript Document
// global variables
var u= 1;
var server = top.location.host;
var recommendation_expanded = false;
var original_image = null;

function buildContactButton(ele,pos) {	
	// add contact button (top of page if pos=true)
	if(pos)
		$(ele).append('<div id="contact-btn"></div>');
	else 
		$(ele).prepend('<div id="contact-btn"></div>');
	
	$('#contact-btn').click(function() {
		window.location = 'http://' + top.location.host + '/contact';
	});
}

/**
 * jQuery lightBox plugin
 * This jQuery plugin was inspired and based on Lightbox 2 by Lokesh Dhakar (http://www.huddletogether.com/projects/lightbox2/)
 * and adapted to me for use like a plugin from jQuery.
 * @name jquery-lightbox-0.5.js
 * @author Leandro Vieira Pinho - http://leandrovieira.com
 * @version 0.5
 * @date April 11, 2008
 * @category jQuery plugin
 * @copyright (c) 2008 Leandro Vieira Pinho (leandrovieira.com)
 * @license CC Attribution-No Derivative Works 2.5 Brazil - http://creativecommons.org/licenses/by-nd/2.5/br/deed.en_US
 * @example Visit http://leandrovieira.com/projects/jquery/lightbox/ for more informations about this jQuery plugin
 */
(function($){$.fn.lightBox=function(settings){settings=jQuery.extend({overlayBgColor:'#000',overlayOpacity:0.8,fixedNavigation:false,imageLoading:'images/lightbox-ico-loading.gif',imageBtnPrev:'images/lightbox-btn-prev.gif',imageBtnNext:'images/lightbox-btn-next.gif',imageBtnClose:'images/lightbox-btn-close.gif',imageBlank:'images/lightbox-blank.gif',containerBorderSize:10,containerResizeSpeed:400,txtImage:'Image',txtOf:'of',keyToClose:'c',keyToPrev:'p',keyToNext:'n',imageArray:[],activeImage:0},settings);var jQueryMatchedObj=this;function _initialize(){_start(this,jQueryMatchedObj);return false;}
function _start(objClicked,jQueryMatchedObj){$('embed, object, select').css({'visibility':'hidden'});_set_interface();settings.imageArray.length=0;settings.activeImage=0;if(jQueryMatchedObj.length==1){settings.imageArray.push(new Array(objClicked.getAttribute('href'),objClicked.getAttribute('title')));}else{for(var i=0;i<jQueryMatchedObj.length;i++){settings.imageArray.push(new Array(jQueryMatchedObj[i].getAttribute('href'),jQueryMatchedObj[i].getAttribute('title')));}}
while(settings.imageArray[settings.activeImage][0]!=objClicked.getAttribute('href')){settings.activeImage++;}
_set_image_to_view();}
function _set_interface(){$('body').append('<div id="jquery-overlay"></div><div id="jquery-lightbox"><div id="lightbox-container-image-box"><div id="lightbox-container-image"><img id="lightbox-image"><div style="" id="lightbox-nav"><a href="#" id="lightbox-nav-btnPrev"></a><a href="#" id="lightbox-nav-btnNext"></a></div><div id="lightbox-loading"><a href="#" id="lightbox-loading-link"><img src="'+settings.imageLoading+'"></a></div></div></div><div id="lightbox-container-image-data-box"><div id="lightbox-container-image-data"><div id="lightbox-image-details"><span id="lightbox-image-details-caption"></span><span id="lightbox-image-details-currentNumber"></span></div><div id="lightbox-secNav"><a href="#" id="lightbox-secNav-btnClose"><img src="'+settings.imageBtnClose+'"></a></div></div></div></div>');var arrPageSizes=___getPageSize();$('#jquery-overlay').css({backgroundColor:settings.overlayBgColor,opacity:settings.overlayOpacity,width:arrPageSizes[0],height:arrPageSizes[1]}).fadeIn();var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]}).show();$('#jquery-overlay,#jquery-lightbox').click(function(){_finish();});$('#lightbox-loading-link,#lightbox-secNav-btnClose').click(function(){_finish();return false;});$(window).resize(function(){var arrPageSizes=___getPageSize();$('#jquery-overlay').css({width:arrPageSizes[0],height:arrPageSizes[1]});var arrPageScroll=___getPageScroll();$('#jquery-lightbox').css({top:arrPageScroll[1]+(arrPageSizes[3]/10),left:arrPageScroll[0]});});}
function _set_image_to_view(){$('#lightbox-loading').show();if(settings.fixedNavigation){$('#lightbox-image,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}else{$('#lightbox-image,#lightbox-nav,#lightbox-nav-btnPrev,#lightbox-nav-btnNext,#lightbox-container-image-data-box,#lightbox-image-details-currentNumber').hide();}
var objImagePreloader=new Image();objImagePreloader.onload=function(){$('#lightbox-image').attr('src',settings.imageArray[settings.activeImage][0]);_resize_container_image_box(objImagePreloader.width,objImagePreloader.height);objImagePreloader.onload=function(){};};objImagePreloader.src=settings.imageArray[settings.activeImage][0];};function _resize_container_image_box(intImageWidth,intImageHeight){var intCurrentWidth=$('#lightbox-container-image-box').width();var intCurrentHeight=$('#lightbox-container-image-box').height();var intWidth=(intImageWidth+(settings.containerBorderSize*2));var intHeight=(intImageHeight+(settings.containerBorderSize*2));var intDiffW=intCurrentWidth-intWidth;var intDiffH=intCurrentHeight-intHeight;$('#lightbox-container-image-box').animate({width:intWidth,height:intHeight},settings.containerResizeSpeed,function(){_show_image();});if((intDiffW==0)&&(intDiffH==0)){if($.browser.msie){___pause(250);}else{___pause(100);}}
$('#lightbox-container-image-data-box').css({width:intImageWidth});$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({height:intImageHeight+(settings.containerBorderSize*2)});};function _show_image(){$('#lightbox-loading').hide();$('#lightbox-image').fadeIn(function(){_show_image_data();_set_navigation();});_preload_neighbor_images();};function _show_image_data(){$('#lightbox-container-image-data-box').slideDown('fast');$('#lightbox-image-details-caption').hide();if(settings.imageArray[settings.activeImage][1]){$('#lightbox-image-details-caption').html(settings.imageArray[settings.activeImage][1]).show();}
if(settings.imageArray.length>1){$('#lightbox-image-details-currentNumber').html(settings.txtImage+' '+(settings.activeImage+1)+' '+settings.txtOf+' '+settings.imageArray.length).show();}}
function _set_navigation(){$('#lightbox-nav').show();$('#lightbox-nav-btnPrev,#lightbox-nav-btnNext').css({'background':'transparent url('+settings.imageBlank+') no-repeat'});if(settings.activeImage!=0){if(settings.fixedNavigation){$('#lightbox-nav-btnPrev').css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnPrev').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnPrev+') left 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage-1;_set_image_to_view();return false;});}}
if(settings.activeImage!=(settings.imageArray.length-1)){if(settings.fixedNavigation){$('#lightbox-nav-btnNext').css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'}).unbind().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}else{$('#lightbox-nav-btnNext').unbind().hover(function(){$(this).css({'background':'url('+settings.imageBtnNext+') right 15% no-repeat'});},function(){$(this).css({'background':'transparent url('+settings.imageBlank+') no-repeat'});}).show().bind('click',function(){settings.activeImage=settings.activeImage+1;_set_image_to_view();return false;});}}
_enable_keyboard_navigation();}
function _enable_keyboard_navigation(){$(document).keydown(function(objEvent){_keyboard_action(objEvent);});}
function _disable_keyboard_navigation(){$(document).unbind();}
function _keyboard_action(objEvent){if(objEvent==null){keycode=event.keyCode;escapeKey=27;}else{keycode=objEvent.keyCode;escapeKey=objEvent.DOM_VK_ESCAPE;}
key=String.fromCharCode(keycode).toLowerCase();if((key==settings.keyToClose)||(key=='x')||(keycode==escapeKey)){_finish();}
if((key==settings.keyToPrev)||(keycode==37)){if(settings.activeImage!=0){settings.activeImage=settings.activeImage-1;_set_image_to_view();_disable_keyboard_navigation();}}
if((key==settings.keyToNext)||(keycode==39)){if(settings.activeImage!=(settings.imageArray.length-1)){settings.activeImage=settings.activeImage+1;_set_image_to_view();_disable_keyboard_navigation();}}}
function _preload_neighbor_images(){if((settings.imageArray.length-1)>settings.activeImage){objNext=new Image();objNext.src=settings.imageArray[settings.activeImage+1][0];}
if(settings.activeImage>0){objPrev=new Image();objPrev.src=settings.imageArray[settings.activeImage-1][0];}}
function _finish(){$('#jquery-lightbox').remove();$('#jquery-overlay').fadeOut(function(){$('#jquery-overlay').remove();});$('embed, object, select').css({'visibility':'visible'});}
function ___getPageSize(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=window.innerWidth+window.scrollMaxX;yScroll=window.innerHeight+window.scrollMaxY;}else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){if(document.documentElement.clientWidth){windowWidth=document.documentElement.clientWidth;}else{windowWidth=self.innerWidth;}
windowHeight=self.innerHeight;}else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=xScroll;}else{pageWidth=windowWidth;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight);return arrayPageSize;};function ___getPageScroll(){var xScroll,yScroll;if(self.pageYOffset){yScroll=self.pageYOffset;xScroll=self.pageXOffset;}else if(document.documentElement&&document.documentElement.scrollTop){yScroll=document.documentElement.scrollTop;xScroll=document.documentElement.scrollLeft;}else if(document.body){yScroll=document.body.scrollTop;xScroll=document.body.scrollLeft;}
arrayPageScroll=new Array(xScroll,yScroll);return arrayPageScroll;};function ___pause(ms){var date=new Date();curDate=null;do{var curDate=new Date();}
while(curDate-date<ms);};return this.unbind('click').click(_initialize);};})(jQuery);

(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);

/*
 * jQuery infinitecarousel plugin
 * @author admin@catchmyfame.com - http://www.catchmyfame.com
 * @version 1.2.2
 * @date August 31, 2009
 * @category jQuery plugin
 * @copyright (c) 2009 admin@catchmyfame.com (www.catchmyfame.com)
 * @license CC Attribution-Share Alike 3.0 - http://creativecommons.org/licenses/by-sa/3.0/
 */

(function($){
	$.fn.extend({ 
		infiniteCarousel: function(options)
		{
			var defaults = 
			{
				transitionSpeed : 1500,
				displayTime : 6000,
				textholderHeight : .2,
				displayProgressBar : 1,
				displayThumbnails: 1,
				displayThumbnailNumbers: 0,
				displayThumbnailBackground: 1,
				thumbnailWidth: '20px',
				thumbnailHeight: '20px',
				thumbnailFontSize: '.7em',
				thumbnailBorder: '#676767',
				img_dir: '/template_3/ic-images'
			};
		var options = $.extend(defaults, options);
	
    		return this.each(function() {
    			var randID = Math.round(Math.random()*100000000);
				var o=options;
				var obj = $(this);
				var curr = 1;

				var numImages = $('img', obj).length; // Number of images
				var imgHeight = $(obj).height();
				var imgWidth = $('img', obj).width();
				var autopilot = 1;
		
				$('p', obj).hide(); // Hide any text paragraphs in the carousel
				$(obj).width(imgWidth).height(imgHeight);
			
				// Build progress bar
				if(o.displayProgressBar)
				{
					$(obj).append('<div id="progress'+randID+'" style="position:absolute;bottom:0;background:#bbb;left:'+$(obj).css('paddingLeft')+'"></div>');
					$('#progress'+randID).width(imgWidth).height(5).css('opacity','.5');
				}
			
				// Move last image and stick it on the front
				$(obj).css({'overflow':'hidden','position':'relative'});
				$('li:last', obj).prependTo($('ul', obj));
				$('ul', obj).css('left',-imgWidth+'px');
				$('ul',obj).width(9999);

				$('ul',obj).css({'list-style':'none','margin':'0','padding':'0','position':'relative'});
				$('li',obj).css({'display':'inline','float':'left'});
			
				// Build textholder div thats as wide as the carousel and 20%-25% of the height
				$(obj).append('<div id="textholder'+randID+'" class="textholder" style="position:absolute;bottom:0px;margin-bottom:'+-imgHeight*o.textholderHeight+'px;left:'+$(obj).css('paddingLeft')+'"></div>');
				var correctTHWidth = parseInt($('#textholder'+randID).css('paddingTop'));
				var correctTHHeight = parseInt($('#textholder'+randID).css('paddingRight'));
				$('#textholder'+randID).width(imgWidth-(correctTHWidth * 2)).height((imgHeight*o.textholderHeight)-(correctTHHeight * 2)).css({'backgroundColor':'#FFF','opacity':'0.5'});
				showtext($('li:eq(1) p', obj).html());
			
				// Prev/next button(img) 
				html = '<div id="btn_rt'+randID+'" style="position:absolute;right:0;top:'+((imgHeight/2)-15)+'px"><a href="javascript:void(0);"><img style="border:none;margin-right:2px" src="'+o.img_dir+'/rt.png" /></a></div>';
				html += '<div id="btn_lt'+randID+'" style="position:absolute;left:0;top:'+((imgHeight/2)-15)+'px"><a href="javascript:void(0);"><img style="border:none;margin-left:2px" src="'+o.img_dir+'/lt.png" /></a></div>';
				$(obj).append(html);
			
				// Pause/play button(img)	
				html = '<a href="javascript:void(0);"><img id="pause_btn'+randID+'" src="'+o.img_dir+'/pause.png" style="position:absolute;top:3px;right:3px;border:none" alt="Pause" /></a>';
				html += '<a href="javascript:void(0);"><img id="play_btn'+randID+'" src="'+o.img_dir+'/play.png" style="position:absolute;top:3px;right:3px;border:none;display:none;" alt="Play" /></a>';
				$(obj).append(html);
				$('#pause_btn'+randID).css('opacity','.5').hover(function(){$(this).animate({opacity:'1'},250)},function(){$(this).animate({opacity:'.5'},250)});
				$('#pause_btn'+randID).click(function(){
					autopilot = 0;
					$('#progress'+randID).stop().fadeOut();
					clearTimeout(clearInt);
					$('#pause_btn'+randID).fadeOut(250);
					$('#play_btn'+randID).fadeIn(250);
					showminmax();
				});
				$('#play_btn'+randID).css('opacity','.5').hover(function(){$(this).animate({opacity:'1'},250)},function(){$(this).animate({opacity:'.5'},250)});
				$('#play_btn'+randID).click(function(){
					autopilot = 1;
					anim('next');
					$('#play_btn'+randID).hide();
					clearInt=setInterval(function(){anim('next');},o.displayTime+o.transitionSpeed);
					setTimeout(function(){$('#pause_btn'+randID).show();$('#progress'+randID).fadeIn().width(imgWidth).height(5);},o.transitionSpeed);
				});
				
				// Left and right arrow image button actions
				$('#btn_rt'+randID).css('opacity','.75').click(function(){
					autopilot = 0;
					$('#progress'+randID).stop().fadeOut();
					anim('next');
					setTimeout(function(){$('#play_btn'+randID).fadeIn(250);},o.transitionSpeed);
					clearTimeout(clearInt);
				}).hover(function(){$(this).animate({opacity:'1'},250)},function(){$(this).animate({opacity:'.75'},250)});
				$('#btn_lt'+randID).css('opacity','.75').click(function(){
					autopilot = 0;
					$('#progress'+randID).stop().fadeOut();
					anim('prev');
					setTimeout(function(){$('#play_btn'+randID).fadeIn(250);},o.transitionSpeed);
					clearTimeout(clearInt);
				}).hover(function(){$(this).animate({opacity:'1'},250)},function(){$(this).animate({opacity:'.75'},250)});

				if(o.displayThumbnails)
				{
					// Build thumbnail viewer and thumbnail divs
					$(obj).after('<div id="thumbs'+randID+'" style="position:relative;overflow:auto;text-align:left;padding-top:5px;"></div>');
					$('#thumbs'+randID).width(imgWidth);
					for(i=0;i<=numImages-1;i++)
					{
						thumb = $('img:eq('+(i+1)+')', obj).attr('src');
						//$('#thumbs'+randID).append('<div class="thumb" id="thumb'+randID+'_'+(i+1)+'" style="cursor:pointer;background-position: center center;background-image:url('+thumb+');display:inline;float:left;width:'+o.thumbnailWidth+';height:'+o.thumbnailHeight+';line-height:'+o.thumbnailHeight+';padding:0;overflow:hidden;text-align:center;border:2px solid #ccc;margin-right:4px;font-size:'+o.thumbnailFontSize+';font-family:Arial;color:#000;text-shadow:0 0 3px #fff">'+(i+1)+'</div>');
						$('#thumbs'+randID).append('<div class="thumb" id="thumb'+randID+'_'+(i+1)+'" style="cursor:pointer;background-position: center center;background-image:url('+thumb+');display:inline;width:'+o.thumbnailWidth+';height:'+o.thumbnailHeight+';line-height:'+o.thumbnailHeight+';padding:0;overflow:hidden;text-align:center;border:2px solid #ccc;margin-right:4px;font-size:'+o.thumbnailFontSize+';font-family:Arial;color:#000;text-shadow:0 0 3px #fff">'+(i+1)+'</div>');
						if(i==0) $('#thumb'+randID+'_1').css({'border-color': o.thumbnailBorder });
					}
					// Next two lines are a special case to handle the first list element which was originally the last
					thumb = $('img:first', obj).attr('src');
					$('#thumb'+randID+'_'+numImages).css({'background-image':'url('+thumb+')'});
					$('#thumbs'+randID+' div.thumb:not(:first)').css({'opacity':'.65'}); // makes all thumbs 65% opaque except the first one
					$('#thumbs'+randID+' div.thumb').hover(function(){$(this).animate({'opacity':.99},150)},function(){if(curr!=this.id.split('_')[1]) $(this).animate({'opacity':.65},250)}); // add hover to thumbs

					// Assign click handler for the thumbnails. Normally the format $('.thumb') would work but since it's outside of our object (obj) it would get called multiple times
					$('#thumbs'+randID+' div').bind('click', thumbclick); // We use bind instead of just plain click so that we can repeatedly remove and reattach the handler
				
					if(!o.displayThumbnailNumbers) $('#thumbs'+randID+' div').text('');
					if(!o.displayThumbnailBackground) $('#thumbs'+randID+' div').css({'background-image':'none'});
				}
				function thumbclick(event)
				{
					target_num = this.id.split('_'); // we want target_num[1]
					if(curr != target_num[1])
					{
						$('#thumb'+randID+'_'+curr).css({'border-color':'#ccc'});
						$('#progress'+randID).stop().fadeOut();
						clearTimeout(clearInt);
						//alert(event.data.src+' '+this.id+' '+target_num[1]+' '+curr);
						$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended
						autopilot = 0;
						setTimeout(function(){$('#play_btn'+randID).fadeIn(250);},o.transitionSpeed);
					}
					if(target_num[1] > curr)
					{
						diff = target_num[1] - curr;
						anim('next',diff);
					}
					if(target_num[1] < curr)
					{
						diff = curr - target_num[1];
						anim('prev', diff);
					}
				}

				function showtext(t)
				{
					// the text will always be the text of the second list item (if it exists)
					if(t != null)
					{
						$('#textholder'+randID).html(t).animate({marginBottom:'0px'},500); // Raise textholder
						showminmax();
					}
				}
				function showminmax()
				{
						if(!autopilot)
						{
							html = '<img style="position:absolute;top:2px;right:18px;display:none;cursor:pointer" src="'+o.img_dir+'/down.png" title="Minimize" alt="minimize" id="min" /><img style="position:absolute;top:2px;right:18px;display:none;cursor:pointer" src="'+o.img_dir+'/up.png" title="Maximize" alt="maximize" id="max" />';
							html += '<img style="position:absolute;top:2px;right:6px;display:none;cursor:pointer" src="'+o.img_dir+'/close.png" title="Close" alt="close" id="close" />';
							$('#textholder'+randID).append(html);
							$('#min').fadeIn(250).click(function(){$('#textholder'+randID).animate({marginBottom:(-imgHeight*o.textholderHeight)-(correctTHHeight * 2)+24+'px'},500,function(){$("#min,#max").toggle();});});
							$('#max').click(function(){$('#textholder'+randID).animate({marginBottom:'0px'},500,function(){$("#min,#max").toggle();});});
							//$('#close').fadeIn(250).click(function(){$('#textholder'+randID).animate({marginBottom:(-imgHeight*o.textholderHeight)-(correctTHHeight * 2)+'px'},500);});
						}
				}
				function borderpatrol(elem)
				{
					$('#thumbs'+randID+' div').css({'border-color':'#ccc'}).animate({opacity: 0.65},500);
					setTimeout(function(){elem.css({'border-color': o.thumbnailBorder }).animate({'opacity': .99},500);},o.transitionSpeed);
				}
				function anim(direction,dist)
				{
					// Fade left/right arrows out when transitioning
					$('#btn_rt'+randID).fadeOut(500);
					$('#btn_lt'+randID).fadeOut(500);
					
					// animate textholder out of frame
					$('#textholder'+randID).animate({marginBottom:(-imgHeight*o.textholderHeight)-(correctTHHeight * 2)+'px'},500);					

					//?? Fade out play/pause?
					$('#pause_btn'+randID).fadeOut(250);
					$('#play_btn'+randID).fadeOut(250);

					if(direction == "next")
					{
						if(curr==numImages) curr=0;
						if(dist>1)
						{
							borderpatrol($('#thumb'+randID+'_'+(curr+dist)));
							$('li:lt(2)', obj).clone().insertAfter($('li:last', obj));
							$('ul', obj).animate({left:-imgWidth*(dist+1)},o.transitionSpeed,function(){
								$('li:lt(2)', obj).remove();
								for(j=1;j<=dist-2;j++)
								{
									$('li:first', obj).clone().insertAfter($('li:last', obj));
									$('li:first', obj).remove();
								}
								$('#btn_rt'+randID).fadeIn(500);
								$('#btn_lt'+randID).fadeIn(500);
								$('#play_btn'+randID).fadeIn(250);
								showtext($('li:eq(1) p', obj).html());
								$(this).css({'left':-imgWidth});
								curr = curr+dist;
								$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
							});
						}
						else
						{
							borderpatrol($('#thumb'+randID+'_'+(curr+1)));
							$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended
							// Copy leftmost (first) li and insert it after the last li
							$('li:first', obj).clone().insertAfter($('li:last', obj));	
							// Update width and left position of ul and animate ul to the left
							$('ul', obj)
								.animate({left:-imgWidth*2},o.transitionSpeed,function(){
									$('li:first', obj).remove();
									$('ul', obj).css('left',-imgWidth+'px');
									$('#btn_rt'+randID).fadeIn(500);
									$('#btn_lt'+randID).fadeIn(500);
									if(autopilot) $('#pause_btn'+randID).fadeIn(250);
									showtext($('li:eq(1) p', obj).html());
									if(autopilot)
									{
										$('#progress'+randID).width(imgWidth).height(5);
										$('#progress'+randID).animate({'width':0},o.displayTime,function(){
											$('#pause_btn'+randID).fadeOut(50);
											setTimeout(function(){$('#pause_btn'+randID).fadeIn(250)},o.transitionSpeed)
										});
									}
									curr=curr+1;
									$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
								});
						}
					}
					if(direction == "prev")
					{
						if(dist>1)
						{
							borderpatrol($('#thumb'+randID+'_'+(curr-dist)));
							$('li:gt('+(numImages-(dist+1))+')', obj).clone().insertBefore($('li:first', obj));
							$('ul', obj).css({'left':(-imgWidth*(dist+1))}).animate({left:-imgWidth},o.transitionSpeed,function(){
								$('li:gt('+(numImages-1)+')', obj).remove();
								$('#btn_rt'+randID).fadeIn(500);
								$('#btn_lt'+randID).fadeIn(500);
								$('#play_btn'+randID).fadeIn(250);
								showtext($('li:eq(1) p', obj).html());
								curr = curr - dist;
								$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
							});
						}
						else
						{
							borderpatrol($('#thumb'+randID+'_'+(curr-1)));
							$('#thumbs'+randID+' div').css({'cursor':'default'}).unbind('click'); // Unbind the thumbnail click event until the transition has ended
							// Copy rightmost (last) li and insert it after the first li
							$('li:last', obj).clone().insertBefore($('li:first', obj));
							// Update width and left position of ul and animate ul to the right
							$('ul', obj)
								.css('left',-imgWidth*2+'px')
								.animate({left:-imgWidth},o.transitionSpeed,function(){
									$('li:last', obj).remove();
									$('#btn_rt'+randID).fadeIn(500);
									$('#btn_lt'+randID).fadeIn(500);
									if(autopilot) $('#pause_btn'+randID).fadeIn(250);
									showtext($('li:eq(1) p', obj).html());
									curr=curr-1;
									if(curr==0) curr=numImages;
									$('#thumbs'+randID+' div').bind('click', thumbclick).css({'cursor':'pointer'});
								});
						}
					}
				}

				var clearInt = setInterval(function(){anim('next');},o.displayTime+o.transitionSpeed);
				$('#progress'+randID).animate({'width':0},o.displayTime+o.transitionSpeed,function(){
					$('#pause_btn'+randID).fadeOut(100);
					setTimeout(function(){$('#pause_btn'+randID).fadeIn(250)},o.transitionSpeed)
				});
  		});
    	}
	});
})(jQuery);

$(document).ready(function(){ 
						   
	/* remove captcha if JS is present */
	$('#captcha_container').remove();
	
	$('#hdr_info').find('a').defuscate();
	
	// watch for print request
	var printUrl = window.location.href.split(/\//);
	for(i=0;i<=printUrl.length-1;i++) {
		if(printUrl[i]=='print') {
			print();
		}
	}
	
	/****************************************************/
	/*				NAVIGATION					
	*****************************************************/
	/*>>> Sub Navigation - Browse Listings Pagination  <<<*/
	$('.paginate-links ul').addClass('js-enabled');
	$('.paginate-links ul li.this-page').wrapInner('<span class="pgnum"></span>');
	$('.paginate-links ul li a, .paginate-links ul li.this-page').append('<span class="arrow"> </span>');
	
	$('#hdr #logo #company_name').prependTo($('#navigation_wrapper'));
	
	/****************************************************/
	/*				HOME PAGE LISTINGS					
	*****************************************************/
	if(jQuery.support.cssFloat) {
		$('#featured-listing .listing, #listing-list .listing').wrap('<div class="outerListing"></div>');
		$('#featured-listing .listing, #listing-list .listing').corner("20px").parent().css('padding', '1px').corner("20px");
	}
	$('#featured-listing .listing, #listing-list .listing').each(function() {
		txt = $(this).find('img').attr('alt');
		$(this).find('.list_img').prepend('<div class="img_info noprint">'+ txt +'</div>');
	});
		
	$('#featured-listing .listing, #listing-list .listing').click(function() {
		mls = $(this).find('.overview_more').attr('href');
		edit = '';
		if(getURLParam('edit'))
			edit = '/true';
		
		window.location = 'http://' + top.location.host + mls+edit;
		return false;
	});

	$('#featured-listing .top_info_1, #listing-list .top_info_1').each(function() {
		var move_dt = $(this).find('dt.top_mls');
		var move_dd = $(this).find('dt.top_mls + dd');
		
		$(move_dt).remove();
		$(move_dd).remove();
		
		$(this).find('dt.top_price + dd').after(move_dd);
		$(this).find('dt.top_price + dd').after(move_dt);		
		
	});		
		
	$('#featured-listing .listing dt.top_addy + dd, #listing-list .listing dt.top_addy + dd').each(function() {
		var txt = $(this).html();
		txt = txt.replace('<br>',' ');
		$(this).html(txt);
	});	
	
	/****************************************************/
	/*				HOME PAGE						
	*****************************************************/
		
	if($('#home-listings').length > 0) {		
		$.ajax({
			type: 'POST',
			url: 'http://'+server+'/modules.php',
			data: 'func=home-gallery',
			success: function(response){
				$('#home-listings').html(response);
				buildContactButton($('#home-listings'),true);	
				//prep image list for gallery (this is used on the home page too!)
				var imgArr = new Array();
			
				$('#img_list li').each(function(index, domEle) {
					imgArr.push(domEle);
				});
				
				$('#img_gallery').empty();
				
				$('#img_gallery').append('<div id="slider"><div class="scrollButtons left">&nbsp;</div><div style="overflow: hidden;" class="scroll"><div class="scrollContainer"></div><div id="left-shadow"></div><div id="right-shadow"></div></div><div class="scrollButtons right">&nbsp;</div>');
				str = '';
				ctr = 1;
				$(imgArr).each(function(index, domEle) {
					str += '<div class="panel" id="panel_'+ ctr +'"><div class="inside">'+ $(domEle).html() +'</div></div>';
					
					ctr++;
				});
				
				$('.scrollContainer').append(str);				
				
				create_3_Panel_Carousel();
				
			}
		});
	}	
	
	var activestate = false;
	if($("#home-content #featured-listing").size() > 0 ) {
		activestate = 0 ;
	}
	if($("#home-content").hasClass('is_admin')) { 
		//do nothing 
	}
	else {
		$(function() {
			$("#home-content").accordion({ collapsible: true, active: activestate,autoHeight: false, icons: { 'header': 'ui-icon-circle-arrow-e', 'headerSelected': 'ui-icon-circle-arrow-s' } });
		});
	}
	/*>> END Home Page <<*/
	
	/* Tools ans Resources list */
	var maxitm = 5;
	
	$('#resources').append('<div class="clear"></div">');
	$('#resources .category').each(function(i) {
		var list = new Array();
		var tw = parseInt(100/$('#resources .category').size());
		$(this).css({ float: 'left', width: tw+'%' });
			
		if($(this).find('ul').children('li').size() > maxitm) {
			var orig = $(this).find('ul');
			containers = parseInt($(this).find('ul').children('li').size() / maxitm);
			size = $(this).find('ul').children('li').size();
			var lw = parseInt(96/containers);
		
			for(var cnt = 1; cnt <= containers; cnt++) {
				$(this).append('<div class="list_split"></div">');
				$(this).find('.list_split:last').css({ float: 'left', width: lw+'%' });
				$(this).find('.list_split:last').append('<ul></ul>');
			}
			
			cont = $(this);
			ctr = 1;
			idx = 0;
			$(cont).find('ul').children('li').each(function(i) { 
				if((ctr<=maxitm)) {
					$(cont).find('.list_split:eq('+idx+') > ul').append($(this));
					ctr++;
				}
				else {
					ctr = 1;
					idx++;
					$(cont).find('.list_split:eq('+idx+') > ul').append($(this));						
				}
			});
				
			$(orig).remove();
		}
	});
/****************************************************/
/*				LISTINGS PAGE						
*****************************************************/

/*>> Make the contact button on the browse page <<*/
	buildContactButton($('#listing-list'),false);
	
/*>> Listing Detail Scripts <<*/
	if($('#listing-detail').length > 0) {
		
		
		$('#do_slideshow').click(function() { createSlideshow(); });
		$('#do_carousel_view').click(function() { createCarousel(); });
		$('#do_gallery_view').click(function() { createGallery(); });
		
		
		var original_image = $('#img_gallery li a').clone();
		
		if($('#img_gallery').not('.imgEdit').length > 0) {
			createCarousel();
		}
		
	}
	function createSlideshow(e) {
		$(original_image).lightBox({
								fixedNavigation:		true,
								imageLoading:			'/template_3/lightbox/images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
								imageBtnPrev:			'/template_3/lightbox/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
								imageBtnNext:			'/template_3/lightbox/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
								imageBtnClose:			'/template_3/lightbox/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
								imageBlank:				'/template_3/lightbox/images/lightbox-blank.gif'			// (string) Path and the name of a blank image (one pixel)
				});	
		
		$(original_image[0]).trigger('click');
	}

	function createCarousel() {
		if($('#do_carousel_view').hasClass('active_view')) {
			return false;
		}
		else {
			$('#img_gallery').addClass('hide');
			$('#img_gallery_js').remove();
			$('#do_slideshow').removeClass('active_view');
			$('#do_gallery_view').removeClass('active_view');
			$('#do_carousel_view').addClass('active_view');
			
			
			if($('#img_gallery_js').length == 0) {
				$('#img_gallery').clone().appendTo('#detail_listing_img').attr('id','img_gallery_js').show();
			}
			$('#img_gallery_js').empty();
			$('#img_gallery_js').append('<div id="carousel"></div>');
			
			// create the gallery effect
			var imgArr = new Array();
		
			$('#img_gallery #img_list li').each(function(index, domEle) {
				imgArr.push(domEle);
			});		
			
			str = '';
			$(imgArr).each(function(index, domEle) {
				txt = $(domEle).find('img').attr('title');
				if(txt.length > 0) 
					txt = '<p>'+txt+'</p>';
					
				ele = '<img src="'+$(domEle).find('a').attr('href')+'">'+ txt;
				str += '<li>'+ ele +'</li>';
			});
			
			$('#carousel').addClass('noprint').append('<ul>'+str+'</ul>');
			
			if($(imgArr).length <= 1) {
				$('#carousel').addClass('single-img');
			}
			else {
				$('#carousel').infiniteCarousel();
			
				var ctr= $('.thumb').length;
				var container_w = $('#img_gallery_js').width() - 20;
				var img_h = $('#carousel').height() - 20;
				var img_w = $('#carousel').find('img').width();
				var col_w = (Math.ceil((container_w - img_w)/2));
				
				var thumb_container = $('#carousel').siblings('div');
				var item_cnt = $(thumb_container).children('div').size('div');		
				var item_per =  Math.ceil(item_cnt/2) ;
				
				var area = col_w * img_h;
				var factor = (0.9/item_per);
				var img_area = area * factor;
				var side_len = (Math.sqrt(img_area)) / 1.25;
				
						
				$('#img_gallery_js').prepend('<div id="thumb_col_1" class="noprint"></div>').prepend('<div id="thumb_col_2" class="noprint"></div>').append('<div class="clear"></div>');
				$('#thumb_col_1').css({width: col_w});
				//col_w = col_w-7;
				$('#thumb_col_2').css({width: col_w});
				
				$('.thumb').each(function(i,ele) {
					itm = $(this).clone(true);
					if(i<item_per) {
						$('#thumb_col_1').append(itm);
					}
					else {
						$('#thumb_col_2').append(itm);
					}
					$(this).remove();
				});
				
				$(thumb_container).remove();
				$('#carousel').css({margin:'0px 10px'});
				
				$('.thumb').each(function() {
					$(this).css({ width: side_len, height: side_len, marginBottom: '3px' });
				});
			
			}		
		}
	}
	
	function createGallery() {
		$('#img_gallery_js').remove();
		
		$('#do_slideshow').removeClass('active_view');
		$('#do_gallery_view').addClass('active_view');
		$('#do_carousel_view').removeClass('active_view');
		
		$('#img_gallery').removeClass('hide');
		
		// create the gallery effect
		var imgArr = new Array();
	
		$('#img_gallery #img_list li').each(function(index, domEle) {
			imgArr.push(domEle);
		});	
		$('#img_gallery #img_list li a').lightBox({
								fixedNavigation:		true,
								imageLoading:			'/template_3/lightbox/images/lightbox-ico-loading.gif',		// (string) Path and the name of the loading icon
								imageBtnPrev:			'/template_3/lightbox/images/lightbox-btn-prev.gif',			// (string) Path and the name of the prev button image
								imageBtnNext:			'/template_3/lightbox/images/lightbox-btn-next.gif',			// (string) Path and the name of the next button image
								imageBtnClose:			'/template_3/lightbox/images/lightbox-btn-close.gif',		// (string) Path and the name of the close btn
								imageBlank:				'/template_3/lightbox/images/lightbox-blank.gif'			// (string) Path and the name of a blank image (one pixel)
				});		
		
	}
	// Handle the print request
	$('#detail-print-icon').click(function() { print(); return false; });
	$('#detail-friend-icon').click(function() { $('#list_email').trigger('click');  });
	$('#detail-map-icon').click(function() { $('#list_map').trigger('click'); });
	// rearrange the Price and MLS fields
	$('#listing-detail .top_info_1').each(function() {
		var move_dt = $(this).find('dt.top_mls');
		var move_dd = $(this).find('dt.top_mls + dd');
		
		$(move_dt).remove();
		$(move_dd).remove();
		
		$(this).find('dt.top_price + dd').after(move_dd);
		$(this).find('dt.top_price + dd').after(move_dt);		
		
	});		
	
	// removes the bullet from the last list element
	$('#listing-detail #prop_det li').not(':last-child').addClass('delim');
	
	
	/*>> Detail Page 'List Tools' <<*/
	if($('#list_tools').length > 0) {
		
		setTool('#list_map');
		initMap();
			
		$('#list_map').click( function () {
			setTool($(this));
			initMap();
			return false;
		});	
		
		$('#list_calc').click( function () {
			setTool($(this));
			makeToolWindow();		
			makeCalc();
			return false;
		});	
	
		
		$('#list_email').click( function () {
			setTool($(this));
			makeToolWindow();		
			makeReferMail();
			return false;
		});	
		$('#list_print').click( function () {
			print();
			return false;
		});	
	}
	
	// shared amongst 'List Tools' 
	function closeTools() {
		$('#tool_window').remove();
	}
	function setTool(e) {
		$('#list_tools li').removeClass('current');
		$(e).parent().addClass('current');
	}
	function makeToolWindow() {
		if($('#tool_window').length == 0) {
			$('.listing').append('<div id="tool_window" class="noprint"></div>');
			loadingTool();		
		}
		else {
			$('#tool_window').empty();
			loadingTool();					
		}
	}
	function loadingTool() {
		$('#tool_window').html('<div id="loading"><img src="/i/Shared/loadingAnimation.gif" /></div>"');
	}
	
	/*>> GOOGLE MAP <<*/
	function initMap() {
		var key = googleKey;
		
		
		var script = document.createElement("script");
		script.src = "http://www.google.com/jsapi?key="+key+"&callback=loadMaps";
		script.type = "text/javascript";
		document.getElementsByTagName("head")[0].appendChild(script);		
		
		// the default address to show - change to something more dynamic
		showAddress('1600 Amphitheatre Pky, Mountain View, CA');
		
		// create the map container and map
		makeMap();
	}
	function makeMap() {
		var addy = $('#list_map').attr('href').replace('http://','');
		//var address = getURLParam('q',addy);
		closeTools(); // closes window if previously open, which causes an error with Google Maps API		
		makeToolWindow();
		
		$('#tool_window').html('<div id="map"><center><br /><br /><br /><br /><img src="/i/Shared/loadingAnimation.gif" /></center></div><div id="map_links"><a id="full_map" href="http://'+addy+'" target="_blank">Full Screen</a></div>');
	}
	
	/*>>  Mortgage Calculator <<*/
	function makeCalc() {
		
		var price = 0;
		
		if($('.top_price + dd').length > 0){
			var price = $('.top_price + dd').text();
			price = price.substr(1);
			if(!isNumeric(price)) {
				price = 0;
			}
		}
		
		$.ajax({
			type: 'POST',
			url: 'http://'+server+'/modules.php',
			data: 'func=calc',
			success: function(msg){
				$('#tool_window').html('<div id="calc-form">' + msg +'<div id="result"></div><small>All values are an approximation and should be used for informational purposes only.</small><div class="clear"></div></div>');
				
				$('#calc-form p').remove();
				
				defaultVal = new Array();

				defaultVal['PRICE'] = price;
				defaultVal['DWN'] = 5;
				defaultVal['INT'] = 5;
				defaultVal['YEARS'] = 30;
				defaultVal['TERM'] = 5;
				
				$("#calc-price").append('<div id="slide-price"></div>');
				$("#calc-dwn").append('<div id="slide-dwn"></div>');
				$("#calc-int").append('<div id="slide-int"></div>');
				$("#calc-amort").append('<div id="slide-years"></div>');
				$("#calc-term").append('<div id="slide-term"></div>');
				
				$("#PRICE").val('$ ' + defaultVal['PRICE']);
				$("#DWN").val(defaultVal['DWN'] + ' %');
				$("#INT").val(defaultVal['INT'] + ' %');
				$("#YEARS").val(defaultVal['YEARS'] + ' years');
				$("#TERM").val(defaultVal['TERM'] + ' years');
				
				if(price == 0) {
					price = 400000;  // note - the value is doubled below!
				}
				$('#slide-price').slider({
					min: 50000,
					max: price * 2,
					value: defaultVal['PRICE'],
					slide: function(event, ui) { $("#PRICE").val('$ ' +ui.value); },
					stop: function() {	updateResult(); }
				});	
				$('#slide-dwn').slider({
					value: defaultVal['DWN'],
					max: 50,
					min: 0,
					slide: function(event, ui) { $("#DWN").val(ui.value + ' %'); },
					stop: function() {	updateResult(); }
				});	
				$('#slide-int').slider({
					min: 2,
					max: 8,
					value: defaultVal['INT'],
					step: 0.25,
					slide: function(event, ui) { $("#INT").val(ui.value + ' %'); },
					stop: function() {	updateResult(); }
				});	
				$('#slide-years').slider({
					min: 5,
					max: 50,
					value: defaultVal['YEARS'],
					step: 5,
					slide: function(event, ui) { $("#YEARS").val(ui.value + ' years'); },
					stop: function() {	updateResult(); }
				});	
				$('#slide-term').slider({
					min: 3,
					max: 15,
					value: defaultVal['TERM'],
					step: 1,
					slide: function(event, ui) { $("#TERM").val(ui.value + ' years'); },
					stop: function() {	updateResult(); }
				});
				
				updateResult();
				
				ht = $('#calc-form').height();
				$('#tool_window').css('height', ht+'px');				
		
			}
		});
	}
	
	function updateResult() {
		var result = calculate();
		str = '<dl><dt>Down Payment</dt><dd>$' + result['Down Payment'] + '</dd><dt>Mortgage Amount</dt><dd>$' + result['Mortgage Amount'] +'</dd><dt>Monthly Payment</dt><dd>$' + result['Monthly Payment'] + '<dt>Owing After Term</dt><dd>$' + result['Owing After Term'] + '</dd></dl>';
		$('#result').html(str);
		$('#result').find('dd').corner();
	}
		
	function calculate() {								 
		var price = $("#PRICE").val().substr(2)
		var dwn = $("#DWN").val().replace(' %','');
		var percent = $("#INT").val().replace(' %','');
		var years = $("#YEARS").val().replace(' years','');
		var term = $("#TERM").val().replace(' years','');
		
		/* Mortgage Calculation */
		var irate, mi, cmi, years, tprinc, princ, paym, cpaym, osp,v,downp,downr;
		tprinc = round2d(parseFloat(price));
		downp = .01*parseFloat(dwn);
		downr = ceil2d(downp*tprinc);
		princ = tprinc-downr;
		res_princ = fmt2d(princ,0);
		res_dwn = fmt2d(downr,0);
		irate = .01*parseFloat(percent);
		years=parseFloat(years);
		term = parseFloat(term);
		if(term > years) term=years;
		if (term==0 || years==0||irate<.0001||princ<1||tprinc<1)
		{
			res_mnthly = 0; 
			res_owed = 0;
		}
		else
		{
			mi = Math.pow(1+ irate/2,1/6)
			mi = 1+(irate/12);
		   v = 1/mi;
		   paym = ceil2d(princ*(mi-1)/(1-Math.pow(mi,-(years*12))));
		   osp = (princ-(v*paym*(1-Math.pow(v,12*term)))/(1-v))/Math.pow(v,12*term);
		   res_mnthly=fmt2d(paym,0);
		   if(osp<0)osp = 0;
		   res_owed = fmt2d(osp,0);
		   }
		
		function round2d(n){return(.01* Math.round(100*n));}
		function floor2d(n){return(.01* Math.floor(100*n));}
		function ceil2d(n){return(.01* Math.ceil(100*n));}
		// format number n as string width w with 2 decimal places
		function fmt2d(n,w)
		{
		   var work,dp,sl,dl;
		   work = ""+floor2d(n); // force only 2 decimals
		   sl=work.length;
		   if(-1 == (dp = work.indexOf(".")))work=work+".00";
		   else if(3 > sl-dp)work = work+".00".substring(sl-dp,3);
		   sl = work.length;
		   if(0 != w && w !=sl)
			  if(w<sl){work = "*";for(sl=1;sl<w;sl++)work=work+"*";}
			  else for(;sl<w;sl++)work=" "+work;
		   return work;
		}
		
		var results = new Array();
		results['Down Payment'] = Math.floor(res_dwn);
		results['Mortgage Amount'] = Math.floor(res_princ);
		results['Monthly Payment'] = Math.floor(res_mnthly);
		results['Owing After Term'] = Math.floor(res_owed);
		
		return results;
	}	
	/*>> END Mortgage Calculator <<*/
	
	
	/*>>  Email Functions <<*/
	
	// resets the fields in the supplied form, and applies the HINT function to them
	function resetForm(form) {
		$(form).find('input[alt!=""], textarea[alt!=""]').each(function() {
			$(this).val($(this).attr('alt'));
			$(this).removeClass('valid').addClass('blur');
			$(this).hint();
		});
		$(form).find('input[alt=""], textarea[alt=""]').not('#submit').each(function() {
			$(this).val('');
			$(this).removeClass('valid');
		});
	}
	// apply the HINT functions to input fields
	if($('.frm').length > 0) {		
		$('.frm').each(function() {
			// find all the input elements with title attributes
			$(this).find('input[alt!=""], textarea[alt!=""]').hint();
		});		
	}
	// removes the labels from the lead email
	$('#lead-email li').each(function() {
		$(this).find('label').remove();
	});	
	// adds the nocmx class to contact form elements - then hides 'em
	$('#contact-info label').each(function() {
		$(this).addClass('nocmx');
	});
	// creates the Referal form on the detail page
	function makeReferMail() {
		var address = $('.top_addy + dd').text();
		var params = window.location.href.split(/\//);
		var mls = params[5];
		$.ajax({
			type: 'POST',
			url: 'http://'+server+'/modules.php',
			data: 'func=refer&mls='+ mls,
			success: function(msg){
				$('#tool_window').html(msg);
				$('#refer-form .list_info').append('<p> '+ window.location.href +'</p>');
				$('#refer-form fieldset fieldset legend').wrapInner('<p></p>');
				ht = $('#refer-form').height();
				$('#tool_window').css('height', ht+'px');
				
				submitBtn = $('#refer-form').find('#submit');
				$(submitBtn).val('Send this message to your friend').bind('click',function() { sendReferMail(submitBtn); } );	
				
			}
		});
	}
 	// submits/ sends the Referal form on the detail page
	function sendReferMail(btn) {
		form = $(btn).parents('form');
		var REFER = $(form).find('#REFER').val();
		var EML = $(form).find('#EML').val();
		var MSG = $(form).find('#MSG').val();
		var MLS = $(form).find('#MLS').val();
		var src = $(form).find('#src').val();		
		
		$(form).validate({
		   rules: {
			   REFER: { required: true },
			   EML: { required: true, email: true },
			   MSG: { required: true }
		   },
		   messages: { REFER: {required:'', email: ''}, EML: {required:'', email: ''}, MSG : '' },
		   submitHandler: function() {
   				$.ajax( {
					url 		: 'http://'+server+'/modules.php',
					type		: 'POST',
					data		: ({ EML: EML, REFER: REFER, MSG: MSG, src: src, MLS: MLS, func: 'sendrefermail' }),
					success	: function(msg) {
								$(msg).dialog( {
										width: 500,
										title: 'Your Email Has Been Sent',
									modal: true,
									buttons: { "Ok": function() { $(this).dialog("close"); } },
									open: function(event, ui) { 
										title =  $(ui).find('h3');
										$(title).remove();										
										 }		  
											  
								});
								
								$(form).find('#REFER').attr('readonly','readonly');
								$(form).find('#EML').attr('readonly','readonly');
								$(form).find('#MSG').attr('readonly','readonly');
								
								lnk = $(form).find('#submit');
								$(lnk).val('Click To Print This Message');
								mid_url = $('#printer').attr('href');
								mid = getURLParam('mid',mid_url);
								$(lnk).click(function() {
									window.location = 'http://' + top.location.host + '/message/'+ mid +'/print';
									return false;
								});
								
								$(form).append('<div id="resetForm"><span class="trigger">Reset Form</span></div>');
								$('#resetForm').bind('click',function() { $('#list_email').trigger('click'); });
								ht = $('#refer-form').height();
								$('#tool_window').css('height', ht+'px');		
								return false;
							}	
					   });
				},
			ignoreTitle: true			
	   });
	}
	
	//submits the lead form
	$('#lead-email #frm_lead #submit').click(function () {
		form = $(this).parents('form');
		var EML = $(form).find('#EML').val();
		var NAME = $(form).find('#NAME').val();
		var PHONE = $(form).find('#PHONE').val();
		var MSG = $(form).find('#MSG').val();
		var MLS = $(form).find('#MLS').val();
		var src = $(form).find('#src').val();		
		
		$(form).validate({
		   rules: {
			   NAME: { required: true },
			   EML: { required: true, email: true },
			   PHONE: { required: true },
			   MSG: { required: true }
		   },
		   submitHandler: function() {
   				$.ajax( {
					url 		: 'http://'+server+'/modules.php',
					type		: 'POST',
					data		: ({ EML: EML, NAME: NAME, PHONE: PHONE, MSG: MSG, src: src, MLS: MLS, func: 'sendleadmail' }),
					success	: function(msg) {								
								$(msg).dialog( {
									width: 500,
									title: 'Your Email Has Been Sent',
									modal: true,
									buttons: { "Ok": function() { $(this).dialog("close"); } },
									open: function(event, ui) { 
										title =  $(ui).find('h3');
										$(title).remove();
									}										
											  
								});
								
								$(form).find('#EML').attr('readonly','readonly');
								$(form).find('#NAME').attr('readonly','readonly');
								$(form).find('#PHONE').attr('readonly','readonly');
								$(form).find('#MSG').attr('readonly','readonly');
								
								lnk = $(form).find('#submit');
								$(lnk).val('Click To Print This Message');
								mid_url = $('#printer').attr('href');
								mid = getURLParam('mid',mid_url);
								
								$(lnk).click(function() {
									window.location = 'http://' + top.location.host + '/message/'+ mid +'/print';
									return false;
								});
								
								var params = window.location.href.split(/\//);
								var mls = params[3] + params[4];
		
								$(form).append('<div id="resetForm"><a href="http://' + top.location.host + '/listings/'+ mls +'">Reset Form</a></div>');
								return false;
							}	
					   });
				},
			ignoreTitle: true
		   });
		
	});
	
	// manipulate the Contact form
	if($('#contact-time li').length > 0) {
		makeTimeSelectable();
	}
	function makeTimeSelectable() {
		if($('#CONTACTTIME').length > 0) {
			$('#frm_lead').prepend('<input type="hidden" id="CONTACTTIME" name="CONTACTTIME" value="Any-Time" />');
		}
		$('#contact-time li').each(function() {
			val = $(this).find('input').val();
			$(this).html(val);
			$(this).bind('click', function() {
				$('#CONTACTTIME').val($(this).text());
			});
		});
		
		$("#contact-time").selectable();
	}
	
	//submits/ sends the Contact form
	$('#contact-form #frm_lead #submit').click(function () {
		form = $(this).parents('form');
		var NAME = $(form).find('#NAME').val();
		var PHONE = $(form).find('#PHONE').val();
		var EML = $(form).find('#EML').val();
		var CONTACTTIME = $(form).find('#CONTACTTIME').val();
		var MSG = $(form).find('#MSG').val();
		var src = $(form).find('#src').val();
		
		
		$(form).validate({
		   rules: {
			   NAME: { required: true },
			   EML: { required: true, email: true },
			   MSG: { required: true }
		   },
		   messages: { EML: {required:'', email: ''}, NAME: '', MSG : '' },
		   submitHandler: function() {
   				$.ajax( {
					url 		: 'http://'+server+'/modules.php',
					type		: 'POST',
					data		: ({ EML: EML, NAME: NAME, PHONE: PHONE, CONTACTTIME: CONTACTTIME, MSG: MSG, src: src, func: 'contact' }),
					success	: function(msg) {								
								$(msg).dialog( {
									width: 500,
									title: 'Your Email Has Been Sent',
									modal: true,
									buttons: { "Ok": function() { $(this).dialog("close"); } },
									open: function(event, ui) { 
										title =  $('.ui-dialog').find('h3');
										$(title).remove();
										lnk = $(ui).find('.print');
										$(lnk).click(function() {
											//window.location = 'http://' + top.location.host + '/contact';
											return false;
											});
										 }		  
										 
										 	  
								});
								$('.ui-selectable').children().removeClass('ui-selected');																					
										
								resetForm(form);									
								return false;
							}	
					   });
				},
			ignoreTitle: true
		   });		
		
	});		
	
	/*>> Property Info form <<*/
	var rangeMin = 10000;
	var rangeMax = 2000000;
	var rangeStart = 100000;
	var rangeEnd = 500000;
	
	var beds = 2;
	var baths = 1;
	var age = 50;
	var sqftg = 500;
	
	var lotMin = 50;
	var lotMax = 5000;
	var lotStart = 200;
	var lotEnd = 1000;
	
	$('#hi-price').append('<div id="slide-price"></div>');
	$('#hi-beds').append('<div id="slide-beds"></div>');
	$('#hi-baths').append('<div id="slide-baths"></div>');
	$('#hi-age').append('<div id="slide-age"></div>');
	$('#hi-sqftg').append('<div id="slide-sqftg"></div>');
	$('#hi-lot').append('<div id="slide-lot"></div>');
	
	$("#PRICERANGE").val('$' + rangeStart + ' - $' + rangeEnd);
	$("#BEDROOMS").val(beds);
	$("#BATHROOMS").val(baths);
	$("#AGE").val(age + ' yrs');
	$("#SQFTG").val(sqftg + " '");
	$("#LOTSIZE").val(lotStart + " ' by " + lotEnd + " '");
	
	$('#slide-price').slider({
		range: true,
		min: rangeMin,
		max: rangeMax,
		values: [rangeStart, rangeEnd],
		slide: function(event, ui) { $("#PRICERANGE").val('$' + ui.values[0] + ' - $' + ui.values[1]); }
	});	
	$('#slide-beds').slider({
		value: beds,
		max: 10,
		slide: function(event, ui) { $("#BEDROOMS").val(ui.value); }
	});	
	$('#slide-baths').slider({
		value: baths,
		max: 5,
		step: 0.5,
		slide: function(event, ui) { $("#BATHROOMS").val(ui.value); }
	});	
	$('#slide-age').slider({
		value: baths,
		max: 200,
		slide: function(event, ui) { $("#AGE").val(ui.value + ' yrs'); }
	});	
	$('#slide-sqftg').slider({
		value: sqftg,
		max: 10000,
		slide: function(event, ui) { $("#SQFTG").val(ui.value + " '"); }
	});	
	
	$('#slide-sqftg').slider({
		value: sqftg,
		max: 10000,
		slide: function(event, ui) { $("#SQFTG").val(ui.value + " '"); }
	});		
	$('#slide-lot').slider({
		range: true,
		min: lotMin,
		max: lotMax,
		values: [lotStart, lotEnd],
		slide: function(event, ui) { $("#LOTSIZE").val(ui.values[0] + " ' by " + ui.values[1] + " '"); }
	});	
	
	if($('#btype li').length > 0) {
		$('#frm_lead').append('<input type="hidden" id="PROPTYPE" name="PROPTYPE" value="House" />');
	}
	if($('#bstyle li').length > 0) {
		$('#frm_lead').append('<input type="hidden" id="STYLE" name="STYLE" value="Detached" />');
	}
	$('#btype li').each(function() {
		val = $(this).find('input').val();
		$(this).html(val);
		$(this).bind('click', function() {
			$('#PROPTYPE').val($(this).text());
		});
	});
	$('#bstyle li').each(function() {
		val = $(this).find('input').val();
		$(this).html(val);
		$(this).bind('click', function() {
			$('#STYLE').val($(this).text());
		});
	});
	$("#btype, #bstyle").selectable();
	
	// submits/ sends the Property Info form
	$('#selling-form #frm_lead #submit').click(function () {
		form = $(this).parents('form');
		var NAME = $(form).find('#NAME').val();
		var PHONE = $(form).find('#PHONE').val();
		var EML = $(form).find('#EML').val();
		var PRICERANGE = $(form).find('#PRICERANGE').val();
		var BEDROOMS = $(form).find('#BEDROOMS').val();
		var BATHROOMS = $(form).find('#BATHROOMS').val();
		var PROPTYPE = $(form).find('#PROPTYPE').val();
		var STYLE = $(form).find('#STYLE').val();
		var AGE = $(form).find('#AGE').val();
		var SQFTG = $(form).find('#SQFTG').val();
		var LOTSIZE = $(form).find('#LOTSIZE').val();
		var MISC = $(form).find('#MISC').val();
		var src = $(form).find('#src').val();
		
		$(form).validate({
		   rules: {
			   NAME: { required: true },
			   EML: { required: true, email: true }
		   },
		  messages: { EML: {required:'', email: ''}, NAME: '' },
		  submitHandler: function() {
   				$.ajax( {
					url 		: 'http://'+server+'/modules.php',
					type		: 'POST',
					data		: ({ NAME: NAME, PHONE: PHONE, EML: EML, PRICERANGE: PRICERANGE, BEDROOMS: BEDROOMS, BATHROOMS: BATHROOMS, PROPTYPE: PROPTYPE, STYLE: STYLE, AGE: AGE, SQFTG: SQFTG, LOTSIZE: LOTSIZE, MISC: MISC, src: src, func: 'sendsellingmail' }),
					success	: function(msg) {								
								$(msg).dialog( {
									width: 500,
									title: 'Your Email Has Been Sent',
									modal: true,
									buttons: { "Ok": function() { $(this).dialog("close"); } },
									open: function(event, ui) { 
										title =  $('.ui-dialog').find('h3');
										$(title).remove();
									}										
								});
								lnk = $(form).find('#submit');
								$(lnk).val('Click To Print This Message');
								mid_url = $('#printer').attr('href');
								mid = getURLParam('mid',mid_url);
								$(lnk).click(function() {
									window.location = 'http://' + top.location.host + '/message/'+ mid +'/print';
									return false;
								});
								
								$(form).append('<div id="resetForm"><a href="http://' + top.location.host + '/sell-your-property">Reset Form</a></div>');
								return false;
							}				
								
					   });
				},
			ignoreTitle: true
		   });		
		
	});	
	
	/****************************************************/
	/*				RECOMMENDATIONS WIDGET						
	*****************************************************/
	
	// define elements
	var c = $('#recommendation');			// id of widget container
	var l = $('#recommendation-items');// id of item wrapper
	var default_container_height = 460;				// height of the wrapper element
	var default_panel_height = 330; 				// height of the text panel
	var ftr_ht = 150;								// height of the navigation and submission tools
	// expand/collapse stuff
	var tid = 'expand-item';  				// id (or class) of trigger
	var more_text = 'Show More';					// link text - can be html
	var less_text = 'Show Less';					// link text - can be html
	// prev next stuff	
	var prev_btn = 'Prev';							// link text - can be html
	var next_btn = 'Next'; 							// link text - can be html
	
	// NO NEED TO EDIT BELOW THIS LINE	
	var t = '#'+tid;
	function calculateRealHeight(e) {
		h = 0;
		$(e).children().each(function() {
			h = h + $(this).outerHeight();
		});		
		return h;
	}
	function expandItem(e) {		
		h = calculateRealHeight(e);
		container_diff = $(c).outerHeight() - h;
		container_ht = $(c).outerHeight() + container_diff;
		item_ht = $(l).outerHeight() + container_diff;			
		
		$(e).css( { height: item_ht+'px'} );
		$(c).css( { height: container_ht+'px'} );
		$(l).css( { height: item_ht+'px'} );
		
		$(t).html(less_text).removeClass('collapsed').addClass('expanded').unbind();
		$(t).bind('click',function() {
			collapseItem(e);
			$(t).html(more_text).removeClass('expanded').addClass('collapsed');
		});
	}
	function collapseItem(e) {
		$(c).css( { height: default_container_height+'px'} );
		$(e).css( { height:  default_panel_height+'px'} );
		$(l).css( { height: default_panel_height+'px'} );
		$(t).html('&nbsp;').removeClass();
		$(t).bind('click',function() {
			expandItem(e);
		});
	}	
	function expandCollapse(e) {		
		// reset all the panels
		$(e).siblings().each(function() {
			collapseItem(this);
		});
		ht = calculateRealHeight(e);
		if(ht > default_panel_height) {
			if($(t).length == 0)
				$('#panel-nav').before('<span id="'+tid+'" class="collapsed">'+more_text+'</span>');
			else 
				$(t).html(more_text).removeClass('expanded').addClass('collapsed');
			
			$(t).unbind();
			$(t).bind('click',function() {
				expandItem(e,ht);
			});
		}
		else {
			collapseItem(e);
		}
	}
	function initCarousel() {
		//add in navigation and submission tools
		if($(c).find('li').size() > 1) {
			$(c).append('<div id="panel-nav" class="noprint"><span id="panel-title">Browse: </span> <span class="panel-prev">'+prev_btn+'</span> <span class="panel-next">'+next_btn+'</span></div>');
		}
		
		//get the max height of sibling elements and set this container to that height
		sibling_ht = 0;
		$(c).siblings().each(function() {
			if($(this).outerHeight() > sibling_ht)
				sibling_ht = $(this).outerHeight();
		});
		
		//size the panels
		default_container_height = sibling_ht;
		default_panel_height = default_container_height - ftr_ht; 
		$(c).height(default_container_height);				
		
		//reset the container
		curr = $(l).find('li:first');
		expandCollapse(curr);	
		
		// start the animation using plugin
		$(l).jCarouselLite({
			btnNext: ".panel-next",
			btnPrev: ".panel-prev",
			vertical: true,
			circular: true,
			visible: 1,
			start: 0,
			afterEnd: function(a) {		
				//reset the container
				expandCollapse(a);				
			}								 
		});
	}
	
	initCarousel();
	
	//fix pngs for IE6
	$('#contact-btn').ifixpng('i/Shared/blank.gif');

	//setFooter();
	
	
});

function setFooter() {
	// move the footer to the bottom of the page if there isn't enough content to fill it
	$(function() {
		ttl_ht = $(window).height() + 5;
		page_ht  = $('#page').outerHeight(true);
		ftr_ht = $('#ftr').outerHeight(true);
		
		off_ht = ftr_ht + page_ht;
		if(off_ht < ttl_ht) {
			new_ht = page_ht + (ttl_ht - off_ht);
			$('#page').height(new_ht);
			
			// adjust the content area to fit
			ftr_pos = $('#ftr').position();			
			content_pos = $('#content').position();
			content_ht = $('#content').height();			
			content_bottom = content_pos.top + content_ht;			
			
			if(ftr_pos.top > content_bottom + 1) {
				ht_calc = ftr_pos.top - content_bottom;				
				
				$('#content').height($('#content').height() + ht_calc);				
			}				
				
		}
	}); 
}

function create_3_Panel_Carousel() {
		
		var totalPanels			= $(".scrollContainer").children().size();		
		var factor				= 50;	
		
		var $panels				= $('#slider .scrollContainer > div');
		var $container			= $('#slider .scrollContainer');
		
		var autoroll = true;
		
		if($panels.size() <= 1) {
			autoroll = false;
		}
		if($container.length == 0) { }
		else {	
			
			var panelHalf = $("#slider").width()/2;
				
			$('#slider .scrollContainer > div').each(function() { $(this).css({'float' : 'left','position' : 'relative'}); });
			
			$("#slider").data("currentlyMoving", false);
		
			$container
				.css('width', ($panels[0].offsetWidth * $panels.length) + 150 )
				.css('left', "-350px");
		
			var scroll = $('#slider .scroll').css('overflow', 'hidden');
			
			function returnToNormal(element) {
				$(element)
					.animate({ height: '-='+factor+'px', width: '-='+factor+'px' })
					.find("img")
					.animate({ height: '-='+factor+'px', width: '-='+factor+'px' })
					.end();
				
				$(element + ' .image-descr').remove();
				
				$(element).removeClass('active-img');
			};
			
			function showDescr() {
				element = $('.active-img');
				txt = $(element).find("img").attr('title').split('::');
				txt[1] = txt[1].replace(/, /gi,'<br />');
				padValue    = parseFloat($(element).css("paddingLeft"), 0)+2;
				$(element).append('<div class="image-descr"><span class="image-addy"></span><span class="image-price"></span><div class="clear"></div></div>');
				
				wide = $(element).find("img").width();
				//get the max height of sibling elements and set this container to that height
				
				$('.image-addy').html(txt[1]);
				$('.image-price').html(txt[0]);
				
				$('.image-descr').width(wide);
				
				$('.image-descr').slideDown();
			}
			function growBigger(element) {
				//alert($(element).attr('id'));
				var r_panel = $(element).next('.panel');
				var l_panel = $(element).prev('.panel');
				
				$(element).addClass('active-img');
				
				$(element)
					.animate({ height: '+='+factor+'px', width: '+='+factor+'px', opacity: 1},1000)
					.find("img")
					.animate({ height: '+='+factor+'px', width: '+='+factor+'px' },1000)
					.end();
				
				
				mls = $(element).find('a').attr('href');	
				$(element).unbind();
				$(element).bind('click', function() {
					window.location = mls;
					return false;
				});
				
				setTimeout(showDescr,1000);
				
				$('.panel').not($(r_panel)).not($(l_panel)).not($(element)).animate({opacity:0}).end();
				$(l_panel).css('opacity',.8);
				$(r_panel).css('opacity',.8);
				
				
			}
			
			//direction true = right, false = left
			function change(direction,start) {
				 
				//if at the last panel
				if(direction && !(curPanel < totalPanels)) {
					// Set up "Current" panel and next and prev
					curPanel = 1;
					next     = 1;
					
					var curPos = $('#panel_'+curPanel).position();
					var curImgWidth = $('#panel_'+curPanel).width();
					
					var leftValue    = $(".scrollContainer").css("left");
					var movingDistance =  Math.abs(curPos.left) - panelHalf + (curImgWidth - factor);
					var movement	 = 0 - parseFloat(movingDistance);
				
					moveWindow(movement,totalPanels,1,true);
					curPanel = next;
					
					
				}
				//if at the first panel
				else if (!direction && (curPanel <= 1)) {
					// Set up "Current" panel and next and prev
					curPanel = Math.floor($('.panel').length-1);
					
					next     = totalPanels;
					
					var curPos = $('#panel_'+curPanel).position();
					var curImgWidth = $('#panel_'+curPanel).width();
					var leftValue    = $(".scrollContainer").css("left");
					var movingDistance =  Math.abs(curPos.left) - panelHalf + (curImgWidth*2 - factor);
					var movement	 = 0 - movingDistance;
							
					moveWindow(movement,1,totalPanels,true);
					curPanel = next;
					
					
				}
				else {
					//if not currently moving
					if (($("#slider").data("currentlyMoving") == false)) {
						
						$("#slider").data("currentlyMoving", true);
						
						nextPanel =  direction ? curPanel+1 : curPanel-1;
						
						if(start) {
							// if this is the first load of the carousel - move to the starting point
							var curPos = $('#panel_'+curPanel).position();
							//var curPos = $("#slider").position();
							var curImgWidth = $('#panel_'+curPanel).width();
							
							var next         = direction ? curPanel + 1 : curPanel - 1;
							var leftValue    = $(".scrollContainer").css("left");
							var movingDistance =  220 - panelHalf + (curImgWidth*2 - factor);
							var movement	 = 0 - movingDistance;
							temp = curImgWidth*2 - factor;
							//alert(curPos.left);
							moveWindow(movement,curPanel,next);
							curPanel = next;
						}
						else {
							var thisHalf = $('#panel_'+curPanel).outerWidth()/2;
							var nextHalf = $('#panel_'+nextPanel).outerWidth()/2;
							
							var next         = direction ? curPanel + 1 : curPanel - 1;
							var leftValue    = $(".scrollContainer").css("left");
							var movingDistance = thisHalf + nextHalf - factor/2 ;
							
							var movement	 = direction ? parseFloat(leftValue, 10) - movingDistance : parseFloat(leftValue, 10) + movingDistance;
						
								
							moveWindow(movement,curPanel,next);
							curPanel = next;
						}
						
					}
				}
			}
			
			var moveWindow_firstrun = true;
			function moveWindow(movement,curPanel,next,fly) {
				
				$(".scrollContainer")
					.stop()
					.animate({
						"left": movement					
					},1000, function() {
						if(fly) {
							if(curPanel < next) {
								lft = parseInt($(".scrollContainer").css('left'));
								lft = lft + 50;
								$(".scrollContainer").css({ left: lft+'px'});
							}
						}
						else {
							$("#slider").data("currentlyMoving", false);
						}
					});
				if(moveWindow_firstrun) {
					returnToNormal("#panel_"+curPanel+1);
					moveWindow_firstrun = false;
				}
				else {
					returnToNormal("#panel_"+curPanel);
				}
				
				growBigger('#panel_'+next);
				
				//remove all previous bound functions
				$("#panel_"+(curPanel)).unbind();	
				
				//go forward
				$("#panel_"+(curPanel)).click(function(){ change(false,false); return false; });
				
				//remove all previous bound functions															
				$("#panel_"+(curPanel+2)).unbind();
				
				//go back
				$("#panel_"+(curPanel+2)).click(function(){ change(true,false); return false; }); 
				
				//remove all previous bound functions
				$("#panel_"+curPanel+1).unbind('click');	
				
			}
			
			// Set up "Current" panel and next and prev
			//var curPanel = Math.floor($('.panel').length/2);
			var curPanel = 0
			
			
			//growBigger("#panel_"+curPanel)
			change(true,true);
			
			$("#panel_"+(curPanel+1)).click(function(){ change(true,false); return false;});
			$("#panel_"+(curPanel-1)).click(function(){ change(false,false); return false; });
			
			mls = 	$("#panel_"+(curPanel)).find('a').attr('href');
			$("#panel_"+(curPanel)).click(function(){ window.location = 'http://' + top.location.host + mls; return false; });
			
			//when the left/right arrows are clicked
			$(".right").click(function(){ change(true,false); clearInterval(interval); return false;});	
			$(".left").click(function(){ change(false,false); clearInterval(interval); return false; });
			
			$(window).keydown(function(event){
			  switch (event.keyCode) {
					case 13: //enter
						$(".right").click();
						break;
					case 32: //space
						$(".right").click();
						break;
				case 37: //left arrow
						$(".left").click();
						break;
					case 39: //right arrow
						$(".right").click();
						break;
			  }
			});
			
			function runInterval() {
				change(true,false);
			}
			
			if(autoroll)
				var interval = setInterval(runInterval, 5000);
												
		}
	}
	// end MOVING BOXES
