// variables for popup windows
var profiles =
	{
		mapWindow:
		{
			height:550,width:750,toolbar:1,scrollbars:1,status:1,resizable:0,center:1
		},
		emailWindow:
		{
			height:380,width:430,toolbar:0,scrollbars:0,status:0,resizable:0,center:1
		},
		infoWindow:
		{
			height:380,width:750,toolbar:0,scrollbars:0,status:0,resizable:0,center:1
		}
	};



// document ready - let's roll!
$(document).ready(function() { 


// fire functions needing page load wait
buttonRoll();
getCounties();
getSubs();
getSize();
searchOptions();
shBox();
$('.obfuscated').defuscate();

// conditional functions
if ( $('div#test_vid').length ) {
	videoBut();
}

if ( $('div#videoPlay').length ) {
	showVideo();
	$('h4.search_properties').css('background','transparent url(/2.0/_images/b_search_properties.gif) no-repeat scroll left top');
	$('h4.search_properties').css('text-indent','-99999px');
	$('h4.search_properties').css('margin','0');
}

if ( $('.popupwindow').length ) {
	$('.popupwindow').popupwindow(profiles);
}

// launch external links in new window
$('a[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });

}); 


// function to play flash video
function showVideo(){
	$('h3.arrow').wait(2).then.animate({'left': '235px'}, 900, 'easeOutBounce');
	flowplayer('videoPlay', '/2.0/scripts/flowplayer-3.1.1.swf', { 
    clip: { 
    	url: '/media/marketers.flv',
        autoPlay: false,  
        autoBuffering: true  
    },
    plugins: { 
    controls: null 
	} 
});
}

// function to change hover states
function buttonRoll(){
 if ($('.btn') != null){
	$('.btn').hover(
      function () {
        $(this).not('.active').css('background-position','left bottom');
      }, 
      function () {
        $(this).not('.active').css('background-position','left top');
      }
    );
   }
}

// function to add video button overlays
function videoBut(){
	$('a.overlay').append('<img class="vid_over" src="/2.0/_images/overlay_play.png" /><img class="vid_over_roll" src="2.0/_images/overlay_play_o.png" />');
	$('.vid_over_roll').css({opacity:"0",display:"block"});
	$('a.overlay').hover(function () {
	    $(this).find('.vid_over_roll').stop().animate({'opacity': '1'}, 400);
	  }, function () {
	    $(this).find('.vid_over_roll').stop().animate({'opacity': '0'}, 400);
	  });
}

// function to load in the counties only for the current state
function getCounties(){
	$('#state').change(function () {
		//get the state id on change
          var state = $(this).val();
          $.post('/_sh_inc/process.php', { data_action: 'getCounties', stateID: state }, function(data){
   			$('#county').html(data);
			});
        });
}

// function to load in the subdivisions only for the current state and county
function getSubs(){
	$('#state,#county').change(function () {
		//get the state and county id on change
          var state = $('#state').val();
          var county = $('#county').val();
          $.post('/_sh_inc/process.php', { data_action: 'getSubs', stateID: state, countyName: county }, function(data){
   			$('#subdivision').html(data);
			});
        });
}

// function to load in the lot sizes if land type is selected
function getSize(){
	var size = $.jqURL.get('lotSize');
	if (size != undefined && size != '')
		$('#lots').css('display','block');
	if ($('#property').val() == 'Land/Farm')
		$('#lots').css('display','block');
	$('#property').change(function () {
          if ($(this).val() == 'Land/Farm') {
          $('#lots').show();
			}
		   else {
		   	$('#lots').hide();
		   	$('#lotSize').val('');
		   }
        });
}

// function to change search results based on drop down boxes
function searchOptions(){
	$('#direction').change(function(){
		var direction = $(this).val();
		var currentURL = $.jqURL.set({order:direction},$.jqURL.url());
		window.location = currentURL;
	});
	$('#sortby').change(function(){
		var number = $(this).val();
		var currentURL = $.jqURL.set({results:number},$.jqURL.url());
		window.location = currentURL;
	});
}

// function for opening a modal box with video/audio
function shBox(){
	$('.shBox,.property-image').click(function() {
		var text = $(this).html();
		if (text == '') {
			text = $(this).next('div').find('a.shBox').html('<strong>Loading Tour...</strong>').addClass('loaded');
			} else {
			$(this).html('<strong>Loading Tour...</strong>').addClass('loaded');
			}
		var home = $(this).parents('li').attr('id');
		var id = $(this).attr('href');
		var dir = $(this).attr('rel');
		if (id == undefined) {
			var id = $(this).next('div').find('a.shBox').attr('href');
			}
		if (dir == undefined) {
			var dir = $(this).next('div').find('a').attr('rel');
			$(this).next('div').find('a.shBox').html('<strong>Loading Tour...</strong>').addClass('loaded');
			}
		$('body').prepend('<div id="overlayBG"></div>');
		$('#overlayBG').before('<div id="shBox-contain"></div>');
		$('#shBox-contain').center();
		$('#overlayBG').css({opacity: 0, height: $(document).height()+'px', display: 'block'});
		$.post('_sh_inc/process.php', { homeID: id, data_action: 'getHouse' },
   		function(data){
   			setTimeout("$.scrollTo('body', 600, { easing:'', queue:true, axis:'y' })",1000);
   			//$('#loader').wait(3).then.remove();
     		$('#shBox-contain').html(data);
     		$('.popupwindow').popupwindow(profiles);
     		if ( $('.movie').length ) {
     			$('.movie').wait(3.5).then.html('<div id="loader2" style="width:100px;height:100px; margin-left:auto; margin-right:auto; margin-top:45px;"><img src="/2.0/_images/ajax-loader.gif" /></div>');
     			var movie = $('#media-big').attr('href');
     		} else {
     			$('#gallery-image').append('<div id="media-big" class="media-big" style="height:480px;"><div id="loader2" style="width:100px;height:100px; margin-left:auto; margin-right:auto; margin-top:145px;"><img src="/2.0/_images/ajax-loader.gif" /></div></div>');
				$('#gallery-image').animate({'height': '480px'},500);
				$('#gallery-menu').append('<li id="gm5" class="delay"><a class="btn" href="#" id="next">Next</a></li><li id="gm4" class="delay"><a class="btn" href="#" id="prev">Previous</a></li><li id="gm3" class="delay"><a class="btn" href="#" id="stop">Stop</a></li><li id="gm2" class="delay"><a class="btn" href="#" id="play">Play</a></li>');
		 		setTimeout(function(){getHousePics(dir,640,480,'#media-big');},2000);
				$('.delay').wait(6).then.slideDown(800);
				$('#close-slide').click(function() {
     			$('.loaded').html(text).removeClass('loaded');
     			$('.media-big,.media-small').remove();
     			$('#shBox-contain').animate({'height': '0px'}, 'slow').wait(2).then.remove();
     			$('#overlayBG').wait(1).then.animate({opacity: 0}, 500).wait(1.5).then.remove();
     			setTimeout(function(){scrollBack(home)},1000);
     			return false;
     			});
				return;
     		}
     		setTimeout(function(){getHousePics(dir,310,233,'.movie'); boxSwitch(movie,id,dir);},3000);
			$('.media-big').wait(3).then.media({preferMeta:0,width:640,height:545,bgColor:'#f6f6f6',autoplay:1,attrs: {allowchangedisplaysize:1,displaysize:0,showstatusbar:0},params: {allowchangedisplaysize:1,displaysize:0,showstatusbar:0}});
     		$('#close-slide').click(function() {
     			$('.loaded').html(text).removeClass('loaded');
     			$('.media-big,.media-small').remove();
     			$('#shBox-contain').animate({'height': '0px'}, 'slow').wait(2).then.remove();
     			$('#overlayBG').wait(2).then.animate({opacity: 0}, 500).wait(1.5).then.remove();
     			setTimeout(function(){scrollBack(home)},1000);
     			return false;
     			});
   			});
   		$('#overlayBG').wait(2).then.animate({opacity: .6}, 500);
   		$('#shBox-contain').wait(3).then.animate({'height': '1500px'}, 'slow');
		return false;
		});
}

function getHousePics(dir,w,h,div){
	$(div).wait(2).then.html('<img src="_sh_inc/image.php?src='+dir+'/image1.jpg&h='+h+'&w='+w+'&zc=1 width="'+w+'" height="'+h+'" /><img src="_sh_inc/image.php?src='+dir+'/image2.jpg&h='+h+'&w='+w+'&zc=1 width="'+w+'" height="'+h+'" />');
	$('#loader2').wait(2).then.fadeOut();
	$.post('_sh_inc/process.php', { location: dir, width:w, height:h, data_action: 'getHousePhotos' },
   		function(data){
   			$(div).wait(3.5).then.append(data);
   			setTimeout(function(){loadSlides(div)},3600);
   			});
}

function boxSwitch(movie,id,dir){
		$('#o-slider').append('<a href="#" id="slide-with" class="btn">Slider</a>').fadeIn();
		$('#slide-with').click(function(){
		$('#media-big embed,#media-big').animate({'width': '0px'},500).wait(1).then.empty();
		$('#slide-with').remove();
		$('.movie').cycle('stop').html('<div id="loader2" style="width:100px;height:100px; margin-left:auto; margin-right:auto; margin-top:45px;"><img src="2.0/_images/ajax-loader.gif" /></div>');
		$('#gallery-menu-left').empty();
		$('#gallery-image').animate({'height': '480px'},500);
		$('#gallery-menu').append('<li id="gm5" class="delay"><a class="btn" href="#" id="next">Next</a></li><li id="gm4" class="delay"><a class="btn" href="#" id="prev">Previous</a></li><li id="gm3" class="delay"><a class="btn" href="#" id="stop">Stop</a></li><li id="gm2" class="delay"><a class="btn" href="#" id="play">Play</a></li>');
		// the old switcharoo
		$('.movie').append('<a class="media-small" id="media-small" href="'+movie+'" />').wait(2).then.animate({'height': '297px'},500);
		$('#media-big').wait(2).then.html('<img src="'+dir+'/image1.jpg" />').animate({'width': '640px', 'height': '480px'},500);
		$('#loader2').wait(2).then.fadeOut();
		$('.media-small').wait(3).then.media({width:310,height:297,bgColor:'#f6f6f6',autoplay:1,params:{ wmode:'transparent',WindowlessVideo:'-1'}});
		$.post('_sh_inc/process.php', { location: dir, width:640, height:480, data_action: 'getHousePhotos' },
   		function(data){
   			$('#media-big').wait(3.5).then.append(data);
			setTimeout(function(){loadSlides('#media-big'); boxSwitchBack(movie,id,dir);},3700);
			$('.delay').wait(3.6).then.slideDown(800);
   			});
		return false;
	});
}

function boxSwitchBack(movie,id,dir){
	$('#o-slider').append('<a href="#" id="slide-with" class="btn">Slider</a>').fadeIn();
	$('#slide-with').click(function(){
		// the put things back the way they were yo
		$('.delay').remove();
		$('#media-big').cycle('stop').animate({'width': '0px'},500).wait(2).then.remove();
		$('#slide-with').remove();
		$('#media-small embed,#media-small').empty().remove();
		$('.movie').html('<div id="loader2" style="width:100px;height:100px; margin-left:auto; margin-right:auto; margin-top:45px;"><img src="2.0/_images/ajax-loader.gif" /></div>').animate({'height': '233px'},500);
		$('#gallery-menu-left').html('<li id="gm5" class="delay"><a class="btn" href="#" id="next">Next</a></li><li id="gm4" class="delay"><a class="btn" href="#" id="prev">Previous</a></li><li id="gm3" class="delay"><a class="btn" href="#" id="stop">Stop</a></li><li id="gm2" class="delay"><a class="btn" href="#" id="play">Play</a></li>');
		$('#gallery-image').animate({'height': '545px'},500);
		$('#gallery-image').append('<a class="media-big" id="media-big" href="'+movie+'" />').wait(2).then.animate({'height': '545px'},500);
		$('.media-big').wait(3).then.media({width:640,height:545,bgColor:'#f6f6f6',autoplay:1,params:{ wmode:'transparent',WindowlessVideo:'-1'}});
		setTimeout(function(){getHousePics(dir,310,233,'.movie'); boxSwitch(movie,id,dir);},3000);
		$('.delay').wait(5.5).then.slideDown(800);
		return false;
	});
}

function loadSlides(div){
	buttonRoll();
	 
    // start slideshow
    $(div).cycle({
        		timeout:  6000,
        		prev:    '#prev',
        		next:    '#next',
        		speed:       1
	});
	$(div).cycle('pause');
     		$('#stop').click(function() { 
    			$(div).cycle('pause');
    			return false;
			});
			$('#play').click(function() { 
    			$(div).cycle('resume');
    			return false;
			});
}

function scrollBack(data){
	$.scrollTo('#'+data, 600, { easing:'', queue:true, axis:'y' });
	searchOptions();
}

// method for chaining and pausing jquery events
var ChainCollector = function(base) {
var CLASS = arguments.callee;
this.then = this.and = this;
var queue = [], baseObject = base || {};
this.____ = function(method, args) {
queue.push({func: method, args: args});
};
this.fire = function(base) {
var object = base || baseObject, method, property;
for (var i = 0, n = queue.length; i < n; i++) {
method = queue[i];
if (object instanceof CLASS) {
object.____(method.func, method.args);
continue;
}
property = object[method.func];
object = (typeof property == 'function')
? property.apply(object, method.args)
: property;
}
return object;
};
};
ChainCollector.addMethods = function(object) {
var methods = [], property, i, n, name;
var self = this.prototype;
var reservedNames = [], blank = new this();
for (property in blank) reservedNames.push(property);
var re = new RegExp('^(?:' + reservedNames.join('|') + ')$j');
for (property in object) {
if (Number(property) != property)
methods.push(property);
}
if (object instanceof Array) {
for (i = 0, n = object.length; i < n; i++) {
if (typeof object[i] == 'string')
methods.push(object[i]);
}
}
for (i = 0, n = methods.length ; i < n; i++)
(function(name) {
if (re.test(name)) return;
self[name] = function() {
this.____(name, arguments);
return this;
};
})(methods[i]);
if (object.prototype)
this.addMethods(object.prototype);
};
jQuery.fn.wait = function(time) {
var collector = new ChainCollector(), self = this;
// Deal with scoping issues...
var fire = function() { collector.fire(self); };
setTimeout(fire, Number(time) * 1000);
return collector;
};
// Then extend ChainCollector with all jQuery's methods
ChainCollector.addMethods(jQuery);

jQuery.fn.center = function(params) {

		var options = {

			vertical: true,
			horizontal: true

		}
		op = jQuery.extend(options, params);

   return this.each(function(){

		//initializing variables
		var $self = jQuery(this);
		//get the dimensions using dimensions plugin
		var width = $self.width();
		var height = $self.height();
		//get the paddings
		var paddingTop = parseInt($self.css("padding-top"));
		var paddingBottom = parseInt($self.css("padding-bottom"));
		//get the borders
		var borderTop = parseInt($self.css("border-top-width"));
		var borderBottom = parseInt($self.css("border-bottom-width"));
		//get the media of padding and borders
		var mediaBorder = (borderTop+borderBottom)/2;
		var mediaPadding = (paddingTop+paddingBottom)/2;
		//get the type of positioning
		var positionType = $self.parent().css("position");
		// get the half minus of width and height
		var halfWidth = (width/2)*(-1);
		var halfHeight = ((height/2)*(-1))-mediaPadding-mediaBorder;
		// initializing the css properties
		var cssProp = {
			position: 'absolute'
		};

		if(op.vertical) {
			cssProp.height = height;
			cssProp.top = '50%';
			cssProp.marginTop = halfHeight;
		}
		if(op.horizontal) {
			cssProp.width = width;
			cssProp.left = '50%';
			cssProp.marginLeft = halfWidth;
		}
		//check the current position
		if(positionType == 'static') {
			$self.parent().css("position","relative");
		}
		//aplying the css
		$self.css(cssProp);


   });

};

jQuery.fn.center = function () {
    this.css("position","absolute");
    this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");
    return this;
}

;(function(h){var m=h.scrollTo=function(b,c,g){h(window).scrollTo(b,c,g)};m.defaults={axis:'y',duration:1};m.window=function(b){return h(window).scrollable()};h.fn.scrollable=function(){return this.map(function(){var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this})};h.fn.scrollTo=function(r,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};a=h.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(d)){d=n(d);break}d=h(d,this);case'object':if(d.is||d.style)l=(d=h(d)).offset()}h.each(a.axis.split(''),function(b,c){var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();if(l){e[f]=l[i]+(p?0:s-o.offset()[i]);if(a.margin){e[f]-=parseInt(d.css('margin'+g))||0;e[f]-=parseInt(d.css('border'+g+'Width'))||0}e[f]+=a.offset[i]||0;if(a.over[i])e[f]+=d[v]()*a.over[i]}else e[f]=d[i];if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));if(!b&&a.queue){if(s!=e[f])q(a.onAfterFirst);delete e[f]}});q(a.onAfter);function q(b){o.animate(e,j,a.easing,b&&function(){b.call(this,r,a)})};function u(b){var c='scroll'+b,g=k.ownerDocument;return p?Math.max(g.documentElement[c],g.body[c]):k[c]}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);


// grid overlay for devel
var gOverride = {
  urlBase: 'http://gridder.andreehansson.se/releases/latest/',
  gColor: '#333333',
  gColumns: 12,
  gOpacity: 0.35,
  gWidth: 10,
  pColor: '#C0C0C0',
  pHeight: 15,
  pOffset: 0,
  pOpacity: 0.55,
  center: true,
  gEnabled: true,
  pEnabled: true,
  setupEnabled: true,
  fixFlash: true,
  size: 960
};