/* Author: 

*/

var FEATURED_HOME_ROTATION_TIME = 8000;

var featuredHomes;

// Set to -1 to correct a small bug causing the second featured home
// to display first...
var currentFeaturedHome = -1;
var featuredHomeRotationInterval;

function fixListingBook(e) {	
	var widgetHeight = $('.listing-book-widget div div').height();
	
	$('.listing-book-widget div div').css({
		top: 0, left:'0px', 
		'box-shadow':'2px 8px 10px black', 
		'opacity':0, 
		'position':'absolute'});
	
	console.log('set z-index');
	
	$('.listing-book-widget div div').animate({'opacity':1});
	$('.listing-book-widget div div div').remove();
}

function changeListingImage(src) {
	var images = $('.main-images img');
	
	// Loop through all main images.
	for(i=0; i<images.length; i++) {
		
		//Check to ensure there are images...
		if(images[i].src.indexOf(src)!= -1) {
			
			//Set all images opacity to 0.
			images.stop();
			images.css('opacity','0');
			
			//Set desired image opacity to 1.
			$(images[i]).css('opacity','0.75');
			$(images[i]).animate({opacity:'1'},800);
		}
	}
	
}

// Bind homepage events.
function bindHomePageEvents() {
	$('.featured-right-arrow').click(scrollFeaturedHomes);
	$('.featured-left-arrow').click(scrollFeaturedHomes);
}

function bindListingBookEvents() {
	//Bind ListingBook Widget Events
	$('.listing-book-widget div img').click(fixListingBook);
}

// Scrolls the featured homes on homepage.
function scrollFeaturedHomes(e) {
	var nextFeaturedHome		= currentFeaturedHome + 1;
	var previousFeaturedHome 	= currentFeaturedHome - 1;

	$(featuredHomes).css({'z-index':'0'});

	if(featuredHomes[nextFeaturedHome] == undefined){
		nextFeaturedHome = 0;
	}

	if(featuredHomes[previousFeaturedHome] == undefined){
		previousFeaturedHome = featuredHomes.length - 1;
	}

	// Animate the next featured home in.
	if(e.target.className == 'featured-right-arrow') {
		if($(featuredHomes[currentFeaturedHome]+':animated').length > 0) {
			return;
		} else {
			// Set z-index for link hovers.
			$(featuredHomes[nextFeaturedHome]).css({'z-index':'10'});
			
			clearTimeout(featuredHomeRotationInterval);
			
			featuredHomeRotationInterval = setTimeout(function() {
				$('.featured-right-arrow').click();
			}, FEATURED_HOME_ROTATION_TIME);
			
			animFeaturedHomeOut($(featuredHomes[currentFeaturedHome]));
			animFeaturedHomeIn($(featuredHomes[nextFeaturedHome]));
			
			currentFeaturedHome = nextFeaturedHome;
		}
	}

	//Animate the previous featured home in.
	if(e.target.className == 'featured-left-arrow') {
		if($(featuredHomes[currentFeaturedHome]+':animated').length > 0) {
			return;
		} else {
			// Set z-index for link hovers.
			$(featuredHomes[previousFeaturedHome]).css({'z-index':'10'});
		
			clearTimeout(featuredHomeRotationInterval);
			
			featuredHomeRotationInterval = setTimeout(function() {
				$('.featured-right-arrow').click();
			}, FEATURED_HOME_ROTATION_TIME);
		
			animFeaturedHomeOut($(featuredHomes[currentFeaturedHome]));
			animFeaturedHomeIn($(featuredHomes[previousFeaturedHome]));
			
			currentFeaturedHome = previousFeaturedHome;
		}
	}
}

function animFeaturedHomeIn(featuredHome) {
	var image = $(featuredHome.children('.featured-home-image-container'));
	var heading = $(featuredHome.children('.over-image-h3'));
	var description = $(featuredHome.children('.listing-description'));
	var price = $(featuredHome.children('.listing-price'));
	
	heading.css({width:'400px'});
	
	setTimeout(function() {
		image.animate({opacity:'1'}, 'slow');
		heading.animate({width:'551px', opacity:'1'}, 'fast');
		
		
		setTimeout(function() {
			price.animate({opacity:'1'}, 'slow');
		},600);
	
		setTimeout(function() {
			description.animate({opacity:'1'});
		},200);
	}, 300);
}

function animFeaturedHomeOut(featuredHome) {
	var image = featuredHome.children('.featured-home-image-container');
	var heading = featuredHome.children('.over-image-h3');
	var description = featuredHome.children('.listing-description');
	var price = featuredHome.children('.listing-price');
	
	setTimeout(function() {
		image.animate({opacity:'0'}, 'slow');
		heading.animate({opacity:'0'}, 'slow');
		description.animate({opacity:'0'}, 'slow');
	},200);
	
	
	price.animate({opacity:'0'}, 'fast');
}

function animHomePageLoad(pause) {
	var smallListings = $('.small-listing');
	
	var i=0;
	var smallListingAnimTime = 200;
	var smallListingTotalAnimTime = smallListings.length * smallListingAnimTime;
	
	
	// Fade in the recently listed homes.
	setTimeout(function() {
		var interval = setInterval(function() {
			$(smallListings[i]).animate({opacity:'1'},'fast');
			i++;
			
			if(i >= 4 || i > smallListings.length) {
				clearInterval(interval);
			}
			
		},smallListingAnimTime);
		
			
	}, pause);
	
	// Animate contact info div.
	setTimeout(function() {
		$('.header-contact').animate({'top':'0px'},1000,'easeOutBounce');
	},pause+3000);
	
	// Start main homepage animation.
	setTimeout(function() {
	
		// Slide down featured homes.
		setTimeout(function() {
			$('.featured-home-container').slideDown(600);
			
			setTimeout(function() {
				$('.featured-right-arrow').fadeIn();
				$('.featured-left-arrow').fadeIn();
			},1000);
			
		},300);
	
		// Commence home rotation.
		setTimeout(function() {
			$('.featured-right-arrow').click();			
		},1000);

		setTimeout(function() {
			$('h2').animate({opacity:'1'},800);
			$('.small-listing').animate({opacity:'1'},'fast');
			$('.container-bg').animate({opacity:'1'},800);
			$('nav ul').animate({opacity:'1'},1000);
			$('.homepage-video').css({display:'block'}); // Fix ie and chrome bug that will not animate opacity of iframe.
		},1500)
		

	}, pause + (smallListingTotalAnimTime-200));
}

/*
function animateLogo(pause) {
	var logo = $('.logo');
	var tagline = $('.tagline');
	
	logo.animate({opacity:'1'},300);
	
	setTimeout(function() {
		tagline.animate({left:'176px',opacity:'1'}, 800, 'easeOutExpo');
	},5000);
}
*/





function blackOut() {
	var blackoutDiv = '<div class="blackout"></div>';
	$(document.body).append(blackoutDiv);
	$('.blackout').css({width: $(window).width(), height: $(window).height() });
}

function clearBlackOut(pause) {
	var animationTime = 400;
	$('.blackout').delay(pause).animate({'opacity':0},animationTime);
	
	setTimeout(function() {
		$('.blackout').remove();
	}, pause+animationTime)
}

function createAnimationElements(num) {
	// Create Logo
	
	$(document.body).append('<div class="intro-logo"></div>');
	
	var logoLeft = ($(window).width() - $('.intro-logo').width()) / 2;
	var logoTop = ($(window).height() - $('.intro-logo').height()) / 2;
	$('.intro-logo').css({left:logoLeft, top: logoTop});

	// Create Slices
	for(i=0; i<num; i++) {
		$(document.body).append('<div class="slices slice' + i + '"></div>');
		
		//Get the width of the slices.
		var sliceWidth 		= $('.slice' + i).width();
		var sliceHeight 	= $('.slice' + i).height();
		var slicesPadding 	= parseInt($('.slices').css('margin-left'), 10);
		
		// Calculate left.
		var slicesLeft 	= ($(window).width() - (sliceWidth + slicesPadding) * num) / 2;
		slicesLeft = slicesLeft + i * (sliceWidth + slicesPadding);
		
		// Calculate the top position.
		var slicesTop 	= ($(window).height() - sliceHeight) / 2;
		
		// Set the left, top, and opacity.
		$('.slice' + i).css({left:slicesLeft, top:slicesTop});
		
		// Offset each slice by 10px.
		if(i%2==0) {
			$('.slice' + i).css({top:slicesTop+10});
		} else {
			$('.slice' + i).css({top:slicesTop-10});
		}
		
	}
}

function animateSlices(pause) {
	var slices = $('.slices');
	var endTop;

	for(i=0; i<slices.length; i++) {
		// Get jQuery object for slice.
		var slice = $('.slice' + i);
		
		// Get the slice's current (ending) top position.
		endTop = parseInt(slice.css('top'), 10);
		var sliceHeight = parseInt($('.slice' + i).height(), 10);
		
		// Move slices off screen.
		if(i%2==0) {
			slice.css({'top':-sliceHeight});		
		} else {
			slice.css({'top':$(window).height()});
		}
		
		// Animate slices in.
		slice.delay(pause).animate({'top':endTop, 'opacity':1}, 2000, 'easeOutSine');
		
		// Animate slices out.
		if(i%2==0) {
			slice.delay(pause).animate({'top':$(window).height(), 'opacity':0}, 1200, 'easeInSine');		
		} else {
			slice.delay(pause).animate({'top':-sliceHeight, 'opacity':0}, 1200, 'easeInSine');
		}
	}
}

function animateLogo(pause) {
	$('.intro-logo').delay(pause).animate({'opacity':1},'slow');
	$('.intro-logo').delay(pause/4).animate({'opacity':0},'slow');
}

function homeAnim(slices) {
	
	createAnimationElements(slices);
	
	animateSlices(1200);
	animateLogo(5000);

	clearBlackOut(7300);
}

/*
 * Email Functions
 */

var defBorderColor, defBGColor;
var errorBorderColor = '#C1292E';
var errorBGColor = '#FFF2F3';

var defName, defPhoneNumber, defMessage, defEmail;

function bindEmailFormEvents() {
	$('#emailFormName').bind('blur', validateName);
	$('#emailFormPhoneNumber').bind('blur', validatePhone);
	$('#emailFormEmail').bind('blur', validateEmail);
	$('#emailFormMessage').bind('blur', validateMessage);
	$('#emailFormSelect').bind('blur', validateSelect);
	
	$('#emailFormName').bind('focus', defColors);
	$('#emailFormPhoneNumber').bind('focus', defColors);
	$('#emailFormEmail').bind('focus', defColors);
	$('#emailFormMessage').bind('focus', defColors);
	$('#emailFormSelect').bind('focus', defColors);
	
	// Get default values.
	defName = $('#emailFormName').val();
	defPhoneNumber = $('#emailFormPhoneNumber').val();
	defMessage = $('#emailFormMessage').val();
	defEmail = $('#emailFormEmail').val();
}

function defColors(e) {
	if (e.currentTarget) { e = e.currentTarget; }

	if(!defBorderColor && !defBGColor) {
		defBorderColor = $(e).css('border-top-color');
		defBGColor = $(e).css('background-color');
	}
	
	// Clear the default values
	if(e.id == 'emailFormName' && e.value == defName) 
		e.value = '';
	
	if(e.id == 'emailFormPhoneNumber' && e.value == defPhoneNumber) 
		e.value = '';
	
	if(e.id == 'emailFormEmail' && e.value == defEmail) 
		e.value = '';
	
	if(e.id == 'emailFormMessage' && e.value == defMessage) 
		e.value = '';
	
	e.style.borderColor = defBorderColor;	
	e.style.backgroundColor = defBGColor;
}

function validateName(e) {
	
	if (e.currentTarget) { e = e.currentTarget; }
	
	if(!defBorderColor && !defBGColor) {
		defBorderColor = $(e).css('border-top-color');
		defBGColor = $(e).css('background-color');
	}
	
	var regex = /^['&,\.a-zA-Z\d\s]+$/;
	if (e.value == '' || e.value == defName) {
		e.style.borderColor = errorBorderColor;	
		e.style.backgroundColor = errorBGColor;
		
		e.value = defName;
		
		return false;
	} else {
		if (e.value.match(regex)) {
			e.style.borderColor = defBorderColor;	
			e.style.backgroundColor = defBGColor;
			return true;	
		} else {
			e.style.borderColor = errorBorderColor;	
			e.style.backgroundColor = errorBGColor;
			return false;
		}
	}
}

function validatePhone(e) {
	var regex = /^1?[\.\s\-]?\(?[\d]{3}\)?[\.\s\-]?[\d]{3}[\.\s\-]?[\d]{4}$/;
	
	if(!defBorderColor && !defBGColor) {
		defBorderColor = $(e.currentTarget).css('border-top-color');
		defBGColor = $(e.currentTarget).css('background-color');
	}
	
	if (e.currentTarget) {
		e = e.currentTarget;
	}
	
	if (e.value == '' || e.value == defPhoneNumber) {
		e.style.borderColor = errorBorderColor;	
		e.style.backgroundColor = errorBGColor;
		
		e.value = defPhoneNumber;
		
		return false;
	} else {
		if (e.value.match(regex)) {
			
			var num = e.value;
			
			num = num.replace(/[\-|\.|\(|\)|\s]/ig, '');
			num = num.slice(num.length - 10, 11);
			//123 456 7890
			//619 756 1954
			num = '(' + num.substr(0,3) + ') ' + num.substr(3,3) + '-' + num.substr(6,4);
			
			e.value = num;
			
			e.style.borderColor = defBorderColor;	
			e.style.backgroundColor = defBGColor;
			
			return true;	
		} else {
			e.style.borderColor = errorBorderColor;	
			e.style.backgroundColor = errorBGColor;
			return false;
		}
	}
}

function validateEmail(e) {
	var regex = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
	
	if (e.currentTarget) { e = e.currentTarget; }
	
	if(!defBorderColor && !defBGColor) {
		defBorderColor = $(e).css('border-top-color');
		defBGColor = $(e).css('background-color');
	}
	
	
	if (e.value == '' || e.value == defEmail) {
		e.style.borderColor = errorBorderColor;	
		e.style.backgroundColor = errorBGColor;
		
		e.value = defEmail;
		
		return false;
	} else {
		if (e.value.match(regex)) {
			e.style.borderColor = defBorderColor;	
			e.style.backgroundColor = defBGColor;
			return true;
		} else {
			e.style.borderColor = errorBorderColor;	
			e.style.backgroundColor = errorBGColor;
			return false;
		}
	}
}

function validateMessage(e) {
	var regex = /^[\s\w\.\-\?,\(\)\$\*!:;`~@#%\^&=+"']+$/;
	
	if (e.currentTarget) { e = e.currentTarget; }
	
	if(!defBorderColor && !defBGColor) {
		defBorderColor = $(e).css('border-top-color');
		defBGColor = $(e).css('background-color');
	}
	
	
	
	if (e.value == '' || e.value == defMessage) {
		e.style.borderColor = errorBorderColor;	
		e.style.backgroundColor = errorBGColor;
				
		e.value = defMessage;
		
		return false;
	} else {
		if (e.value.match(regex)) {
			e.style.borderColor = defBorderColor;	
			e.style.backgroundColor = defBGColor;
			return true;
		} else {
			e.style.borderColor = errorBorderColor;	
			e.style.backgroundColor = errorBGColor;
			return false;
		}
	}
}

function validateSelect(e) {
	if (e.currentTarget) { e = e.currentTarget; }
	
	if(!defBorderColor && !defBGColor) {
		defBorderColor = $(e).css('border-top-color');
		defBGColor = $(e).css('background-color');
	}
	
	if(e.value == 'default') {
		e.style.borderColor = errorBorderColor;	
		e.style.backgroundColor = errorBGColor;
	} else {
		return true;
	}
}

function validateAndSendEmail() {
	var name = document.getElementById('emailFormName');
	var phone = document.getElementById('emailFormPhoneNumber');
	var email = document.getElementById('emailFormEmail');
	var message = document.getElementById('emailFormMessage');
	var select = document.getElementById('emailFormSelect');
	
	var validName = validateName(name);
	var validPhone = validatePhone(phone);
	var validEmail = validateEmail(email);
	var validMessage = validateMessage(message);
	var validSelect = validateSelect(select)
	
	console.log(select.value);
	
	if(validName && validPhone && validEmail && validMessage && validSelect) {
		sendEmail(name.value, phone.value, email.value, select.value, message.value);
		
		blackout();
		sendingEmailMessage();
		
		setTimeout( function() {
			clearBlackout();
			//hideEmailForm();
			document.getElementById('emailForm').reset();
		}, 2000);
	} 
}

function sendEmail(name, phone, email, select, message) {
	var request;
	var requestURL = '/mail.php?name=' + name + '&phone=' + phone + '&email=' + email + '&select=' + select + '&message=' + message;
	var response;
	
	if (window.XMLHttpRequest) {				//Check for XMLHttpRequest Support
		request = new XMLHttpRequest();
	} else {									//No support for XMLHttpRequest (IE < 7)
		request = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	request.open('GET', requestURL, true);
	
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			if (request.status == 200) {	
				response = request.responseXML;
			} else {
				//alert ('There was an error loading ' + requestURL + '.');
			}
		}
	};
	
	request.send(null);
}

function sendShowingRequest() {
	var name = $('.pp_inline .scheduleFormName').val();
	var phone = $('.pp_inline .scheduleFormPhoneNumber').val();
	var email = $('.pp_inline .scheduleFormEmail').val();
	var comments = $('.pp_inline .scheduleFormComments').val();
	var dateTime = $('.pp_inline .scheduleFormDateMonth').val() + " " + $('.pp_inline .scheduleFormDateDay').val() + " " + $('.pp_inline .scheduleFormTime').val();
	var plannedMoveDate = $('.pp_inline .scheduleFormMoveDate').val();
	
	blackout();
	
	$.prettyPhoto.close();
	
	
	sendingScheduleRequestMessage();
	
	setTimeout(function() {
		clearBlackout();
	},2000);
	
	var request;
	var requestURL = '/sendScheduleRequest.php?name=' + name + '&phone=' + phone + '&email=' + email + '&dateTime=' + dateTime + '&comments=' + comments + '&plannedMoveDate=' + plannedMoveDate;
	var response;
	
	if (window.XMLHttpRequest) {				//Check for XMLHttpRequest Support
		request = new XMLHttpRequest();
	} else {									//No support for XMLHttpRequest (IE < 7)
		request = new ActiveXObject('Microsoft.XMLHTTP');
	}
	
	request.open('GET', requestURL, true);
	
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			if (request.status == 200) {	
				response = request.responseXML;
			} else {
				//alert ('There was an error loading ' + requestURL + '.');
			}
		}
	};
	
	request.send(null);
}

function sendingEmailMessage() {
	$('<div id=\"sendingEmail\"><img src=\"/images/wait.gif\"/><h3>sending...</h3></div>').appendTo('body');
	
	var div = $('#sendingEmail');
	var h3 = $('#sendingEmail h3');
	var img = $('#sendingEmail img');
	var f = $('#email');
	
	div.css({ 
		"top":"0px", 
		"left":"0px",
		"background-color":"#000",
		"opacity":"0",
		"z-index":"103",
		"position":"fixed",
		"text-align":"center",
		"border-radius":"20px",
		"height":"140px",
		"width":"200px"
	});
	
	img.css({
		"margin-top":"25px"
	});
	
	h3.css({
		"color":"white",
		"font-size":"1.5em",
		"padding-top":"15px",
		"position":"absolute",
		"bottom":"30px",
		"text-align":"center",
		"width":"100%",
		"padding-left":"5px",
		"margin-bottom":"0px"
	});
	
	var x = ($(window).width()/2) - (div.width()/2);
	var y = ($(window).height()/2) - (div.height()/2);
	
	div.css('top',y);
	div.css('left',x);
	
	f.fadeTo(1000, 0.9);
	div.fadeTo(1000, 0.9);
	
	setTimeout( function(){
		$('#sendingEmail img').fadeTo(400, 0);
		div.animate({height: 80},1000, 'easeOutCubic');
		h3.css({"padding-left":"0px"});
		h3.text('message sent!');
		
		setTimeout(function() {
			div.fadeTo(1000, 0);
			f.fadeTo(1000, 1);
			setTimeout( function() {
				div.remove();
			},1000);
		},3000);
		
	},2000);
	
	return div;
}


function sendingScheduleRequestMessage() {
	$('<div id=\"sendingEmail\"><img src=\"/images/wait.gif\"/><h3>sending...</h3></div>').appendTo('body');
	
	var div = $('#sendingEmail');
	var h3 = $('#sendingEmail h3');
	var img = $('#sendingEmail img');
	var f = $('#email');
	
	div.css({ 
		"top":"0px", 
		"left":"0px",
		"background-color":"#000",
		"opacity":"0",
		"z-index":"103",
		"position":"fixed",
		"text-align":"center",
		"border-radius":"20px",
		"height":"140px",
		"width":"300px"
	});
	
	img.css({
		"margin-top":"25px"
	});
	
	h3.css({
		"color":"white",
		"font-size":"1.5em",
		"padding-top":"15px",
		"position":"absolute",
		"bottom":"30px",
		"text-align":"center",
		"width":"100%",
		"padding-left":"5px",
		"margin-bottom":"0px"
	});
	
	var x = ($(window).width()/2) - (div.width()/2);
	var y = ($(window).height()/2) - (div.height()/2);
	
	div.css('top',y);
	div.css('left',x);
	
	f.fadeTo(1000, 0.9);
	div.fadeTo(1000, 0.9);
	
	setTimeout( function(){
		$('#sendingEmail img').fadeTo(400, 0);
		div.animate({height: 80},1000, 'easeOutCubic');
		h3.css({"padding-left":"0px"});
		h3.text('showing request sent!');
		
		setTimeout(function() {
			div.fadeTo(1000, 0);
			f.fadeTo(1000, 1);
			setTimeout( function() {
				div.remove();
			},1000);
		},3000);
		
	},2000);
	
	return div;
}


//Pass functional arguments, or not and use the constant definitions.
function blackout(div_id, fade_speed) {
	//-------------------------------------------------
	// Constant Definitions
	//-------------------------------------------------
	var DIV_ID = "blackout";		//Default DIV ID.
	var FADE_SPEED = 1000;			//Fade speed in miliseconds.
	var COLOR = "#000";				//DIV background color.
	var ZINDEX = "100";				//Z-Index of DIV.
	var OPACITY = 0.7;				//Ending opacity.
	
	//-------------------------------------------------
	// Constant Definitions
	//-------------------------------------------------
	
	var id = (typeof div_id == "undefined") ? DIV_ID : div_id;
	var spd = (typeof fade_speed == "undefined") ? FADE_SPEED : fade_speed;
	
	//Create the DIV and add to BODY.
	$('<div id='+ id + '></div').appendTo('body');
	var div = $('#' + id);
	
	//Apply CSS styles.
	div.css({ "position":"absolute", 
		"top":"0px", 
		"left":"0px",
		"background-color":COLOR,
		"opacity":"0",
		"z-index":ZINDEX,
		"height":$(document).height() + 'px',
		"width":$(document).width() + 'px'
	});
	
	//Fade-in DIV.
	div.fadeTo(spd, OPACITY);
	
	//Listen for window resize, and resize curtain accordingly.
	$(window).bind('resize', function() {
		div.css('width', '0px');
		div.css('width', $(document).width() + 'px');
	});
	
	//Returns reference to jQuery DIV object.
	return div;
}

function clearBlackout() {
	var div = $('#blackout');
	div.fadeTo(1000, 0);
	setTimeout(function() {div.remove();}, 1000);
}

function scrollToEmailForm() {	
	$('html, body').delay(50).animate({scrollTop:($(document).height()-$(window).height())},$(document).height(),'easeOutExpo');
}

function openChatWindow() {
	window.open('http://www.google.com/talk/service/badge/Start?tk=z01q6amlqv1kgkv3k1ft68flbcfkqc9tt2oh0rsmmru3gm3umpmvmhbt01hshi96r59q9e88endf8mc9j1pcncnecarskes8vqi3l1ratovpdo783fpveg7psh4640au3c7sm1d11enkcuss0l0botlbljm2rnadj7acrefkd','chat','height=400,width=300',false);
}
