// 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();
shBox();


// conditional functions
if ( $('form.ajaxform').length ) {
	$('.sign_in').click(function() {
		$('form.ajaxform').removeClass('current');
		$(this).parents('form').addClass('current');
		});
	$('form.ajaxform').ajaxForm({
		beforeSubmit: validate, 
        success: showResponse 
    }); 
}

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

if ( $('#test_vid').length ) {
	testVids();
}

if ( $('div#splash-content').length ) {
	divSwitcher();
}

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 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');
      }
    );
   }
}

// show/hide divs on mouseover for products page
function divSwitcher(){
		$('#splash-content #premier').addClass('show');
		$('#sm1').addClass('active');
		$('ul#splash-menu li').mouseover(
      		function () {
      			$('ul#splash-menu li').css('background-position','left top');
      			$(this).css('background-position','left bottom');
        		$('div.splash-box').removeClass('show');
        		$('#'+$(this).attr('title')).addClass('show');
      			});
}

// 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: 'http://glidetour.com/media/marketers.flv',
        autoPlay: false,  
        autoBuffering: true  
    },
    plugins: { 
    controls: null 
	} 
});
}

function testVids(){
	$('.overlay').click(function() {
		var movie = $(this).attr('href');
		var html = '<div id="testMovie" style="width:310px; height:233px;"></div>';
		$(document).bind('reveal.facebox', function() {
			flowplayer('testMovie', '2.0/scripts/flowplayer-3.1.1.swf', { 
    		clip: { 
    		url: movie,
        	autoPlay: true,  
        	autoBuffering: true  
    		},
    		plugins: { 
    		controls: null 
			} 
		});
		});
		$.facebox(html);
		return false;	
		});
}

// functions for login form submission
function showResponse(responseText, statusText)  {
	if (responseText == 'Logged In!') {
		$('form.current .sign_in').val(responseText);
		setTimeout("window.location = 'home.php'",1000);
	} else
	if (responseText == 'Email Ok!') {
		$('form.current .sign_in').val(responseText);
		var password = $('form.current #password').val();
		var email = $('form.current #email').val();
		setTimeout("window.location = 'order_a_tour_signup.php?email="+email+"&pass="+password+"'",2000);
	} else
	if (responseText == 'error') {
		jAlert('Sorry, this email already exists - please call 770-560-9658', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
	} else 
	if (responseText == 'accepted') {
		jAlert('Welcome to GlideMLS.com! <br />Click OK to login now', 'Congratulations!',function(){ window.location = "index.php" });
		$('form.current .sign_in').val('Accepted');
	} else 
	if (responseText == 'insert error') {
		jAlert('Oops, something went wrong with our server. Please try again or call 770-560-9658 for help.','Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
	}
	else {
		jAlert(responseText, 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
	}
} 

// some simple email validation
function echeck(str) {
	var at='@';
	var dot='.';
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	if (str.indexOf(' ')!=-1){
		jAlert('Invalid E-mail Address', 'Submission Problem Found');
		$('form.current .sign_in').val('Sign Up');
		return false;
	}
	return true;			
}

function validate(formData, jqForm, options) {
	$('form.current .sign_in').val('Sending...');
	var formID = $('form.current').attr('id');
	if (formID != 'final_sign_up'){
    	for (var i=0; i < formData.length; i++) { 
        	if (!formData[i].value) { 
            	jAlert('Username and Password Required','Errors Found!'); 
            	$('form.current .sign_in').val('Sign In');
            	return false; 
        		} 
    		}
    } else {
    	for (var i=0; i < formData.length; i++) { 
        	if (!formData[i].value && formData[i].name != 'website') {
        		var fieldName = formData[i].name;
        		fieldName = fieldName.replace(/_/, ' ');
        		fieldName = stCap(fieldName);
            	jAlert(fieldName+' is required!','Errors Found!'); 
            	$('form.current .sign_in').val('Sign Up');
            	return false; 
        		} 
		}
    }
    if (formID == 'sign_up'){
    	var email = $('form.current #email').val();
		if (echeck(email)==false){
		$('form.current #email').val('');
		$('form.current #email').focus();
		jAlert('Invalid Email Address','Errors Found!'); 
		return false;
		}
	}
    return true; 
}

// function for capitalizing the first letter of words
function stCap(strObj){
return(strObj.charAt(0).toUpperCase()+strObj.substr(1).toLowerCase());
}

// function for opening a modal box with video/audio
function shBox(){
	$('.shBox,.property-image').click(function() {
		var home = $(this).parents('li').attr('id');
		var id = $(this).attr('href');
		var dir = $(this).attr('rel');
		$('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'});
		var text = $(this).html();
		$(this).html('<strong>Loading Tour...</strong>').addClass('loaded');
		$.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({width:640,height:545,bgColor:'#f6f6f6',autoplay:1});
     		$('#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){
	if ( $('#gallery-image').length ) {
		$('#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});
		$.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});
		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' });
}

// 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 () {
    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
};