/*******************************************************************************

	CSS on Sails Framework
	Title: Bayberry 
	Author: XHTMLized (http://www.xhtmlized.com/)
	Date: March 2011

*******************************************************************************/

$.fn.extend({
	hrefHash: function(){
		return $(this).attr('href').substr($(this).attr('href').indexOf('#'));
	}
});

var Engine = {
	enhancements: {

		mainNav: function(){
			$('#navigation > ul > li').has('ul').hover(function(){
				$(this).addClass('sub-nav');
			},function(){
				$(this).removeClass('sub-nav');
			});
		},
		
		sideNav: function(){
			$('#side-nav > ul > li').has('ul').addClass('menuparent');	
			$('#side-nav ul li li:last a').addClass('last');
		},
		
		slideShow: 	function() {
			if($('#slideshow-container').length) {	
				$('#slide0').cycle({
					cssFirst: {  
							display: 'none' 
					}, 
					speed: 700,
					timeout: 9900,
					delay:-9900
				});
				$('#slide1').cycle({
					cssFirst: {  
						display: 'none' 
					}, 				
					speed: 700,
					delay: -9200,
					timeout: 9900		
					});
				$('#slide2').cycle({
					cssFirst: {  
						display: 'none' 
					}, 				
					speed: 700,
					delay: -8500,
					timeout: 9900			
					});			
				$('#slide3').cycle({
					cssFirst: {  
						display: 'none' 
					}, 				
					speed: 700,
					delay: -7800,
					timeout: 9900			
					});
				$('#slide4').cycle({
					cssFirst: {  
						display: 'none' 
					}, 				
					speed: 700,
					delay: -7100,
					timeout: 9900			
					});
				$('#slide5').cycle({
					cssFirst: {  
						display: 'none' 
					}, 				
					speed: 700,
					delay: -6400,
					timeout: 9900			
					});			
				$('#slide6').cycle({
					cssFirst: {  
						display: 'none' 
					}, 				
					speed: 700,
					delay: -5700,
					timeout: 9900			
					});	
			}
		},
		
		tabs: function(container) {
			var tabs = container ? container : '.tabs';
		
			$(tabs).each(function(){
				var nav = $('.nav', this),
					content = $('.tab-content', this),
					id = '';

				if(content.length > 1) {
					$('a', nav).click(function(){
						if(!$(this).is('.current')) {
							id = $(this).hrefHash();
							
							content.hide().filter(id).show();
							$('.current', nav).removeClass('current');
							$(this).addClass('current');
						}		

						return false;
					});					
				} else {
					$('a:first', nav).addClass('current');
				}
				
				$('a:first', nav).click();
			});
		},
		
		scrollablePortfolio: function() {
			$('.portfolio-homes').each(function(){
				var list = $('.items-container > ul', this);
				
				if($('.item', list).length > 3) {
					$('.items-container', this).addClass('items-container-scroll');

					var items = $('.item', list),
						sampleItem = items.filter(':last'),
						itemWidth = parseInt(sampleItem.css('width')) + parseInt(sampleItem.css('paddingLeft')) + parseInt(sampleItem.css('paddingRight')),
						itemHeight = parseInt(sampleItem.css('height')) + parseInt(sampleItem.css('paddingTop')) + parseInt(sampleItem.css('paddingBottom')) + 19,
						itemMargin = parseInt(sampleItem.css('marginLeft')),
						totalWidth = items.length * (itemWidth + itemMargin) - itemMargin;
						
					list.parent('.items-container').css('height', itemHeight);
					list.width(totalWidth);
				}
				
				/* IE spacing issue */
				if($.browser.msie && $.browser.version == '6.0') {
					setTimeout(function() {
						items.filter(':first').css('display', 'block');
					}, 1500);
				}
			});
		},
		
		mapTips: function() {
			if($('.area-map').length){
				$(".trigger, .lot, .featured-area a").tooltip({ 
				   effect: 'slide',
				   relative: true,
				   position: 'top center'
				   
				}).dynamic({ bottom: { direction: 'down', bounce: true }});	
			
				$("a.tooltip-close").click(function() {
					$(this).parent().hide();
					return false;
				});	
				
				// set zindex on header
				$('#header').hover(
					function(){
						$(this).css('z-index','12');	
					},
					function() {
						$(this).css('z-index','10');				
					}
				);
			}
		},
		
		popups: {
			init: function() {
				//Engine.enhancements.popups.myPortfolio();
				//Engine.enhancements.popups.register();
				//Engine.enhancements.popups.loginForm();
				Engine.enhancements.popups.communityMapZoom();
				Engine.enhancements.popups.homepageGallery();
			},
			/*
			myPortfolio: function() {
				$('.top-navigation .portfolio a').click(function(){
					if(!$('#my-portfolio').size()){
						$('<div class="hide"></div>')
							.appendTo('body')
							.load($(this).attr('href') + ' #my-portfolio',function(data){
								
								$('#my-portfolio',this).dialog({
									autoOpen: false,
									dialogClass: 'dialog-window portfolio-window portfolio-window-registered',
									draggable: false,
									resizeable: false,
									modal: true,
									closeText: 'Close',
									create: function() {
										Engine.enhancements.scrollablePortfolio();
										Engine.enhancements.tabs(this);
									}
								});
								$('#my-portfolio').dialog('open');
							});
					} else {
						$('#my-portfolio').dialog('open');
					}
				
					return false;
				});
			},
			*/
			/*
			register: function() {
				$('.top-navigation .register a').click(function(){
					if(!$('#register-account').size()){
						$('<div class="hide"></div>')
							.appendTo('body')
							.load($(this).attr('href') + ' #register-account',function(data){
								
								$('#register-account',this).dialog({
									autoOpen: false,
									dialogClass: 'dialog-window portfolio-window',
									draggable: false,
									resizeable: false,
									modal: true,
									closeText: 'Close',
									create: function() {
										Engine.enhancements.tabs(this);
										Engine.enhancements.popups.loginForm();
									},
									open: function() {
										$('input:first',  this).focus();
									}
								});
								$('#register-account').dialog('open');
							});
					} else {
						$('#register-account').dialog('open');
					}
				
					return false;
				});
			},
			*/
			/*
			loginForm: function() {
				$('.sign-in a').live('click', function(){

					if(!$('#login-form').size()){
						$('<div class="hide"></div>')
							.appendTo('body')
							.load($(this).attr('href') + ' #login-form',function(data){
								
								$('#login-form',this).dialog({
									autoOpen: false,
									dialogClass: 'dialog-window portfolio-window account-form',
									draggable: false,
									resizeable: false,
									modal: true,
									closeText: 'Close',
									create: function() {
										Engine.enhancements.popups.forgotPassword();
									}
								});
								$('#register-account').dialog('close');
								$('#login-form').dialog('open');
							});
					} else {
						$('#register-account').dialog('close');
						$('#login-form').dialog('open');
					}

					return false;
				});
			},
			*/
			forgotPassword: function(form) {
				$('.forgot-credentials').click(function(){
					if(!$('#forgot-password').size()){
						$('<div class="hide"></div>')
							.appendTo('body')
							.load($(this).attr('href') + ' #forgot-password',function(data){
								
								$('#forgot-password',this).dialog({
									autoOpen: false,
									dialogClass: 'dialog-window portfolio-window account-form',
									draggable: false,
									resizeable: false,
									modal: true,
									closeText: 'Close'
								});
								$('#login-form').dialog('close');
								$('#forgot-password').dialog('open');
							});
					} else {
						$('#login-form').dialog('close');
						$('#forgot-password').dialog('open');
					}
				
					return false;
				});
			},
			
			communityMapZoom: function() {
				if(!$('.map-large').length) {
					return;
				}
				
				var popup = $('.map-large').hide(),
					//trigger = $('.community-map-container .zoom'),
					trigger = $('.community-map-container .zoom, .community-map-container .map'),
					step1 = $('.step-1', popup),
					step2 = $('.step-2', popup).hide(),
					back = $('<a href="#" class="back"><span>Go Back</span></a>').appendTo(step2.find('.area-map')),
					//close = $('<a href="#" class="tooltip-close">Close</a>').appendTo(popup),
					close = $('<a href="#" class="tooltip-close"></a>').appendTo(popup),
					featuredArea = $('.featured-area', popup),
					
					// created by GL
					trigger_qdh = $('a.view');
					
				featuredArea
					.hover(
						function(){ $(this).addClass('hover'); },
						function(){ $(this).removeClass('hover'); }
					)
					.click(function(){
						step1.hide();
						step2.show();
					
						return false;
					});
					
				// featured-area-new is modified feature-area
				// created by GL
				$('.community-map-container .map').mouseover(function(e){
					$(this).css({'cursor':'pointer'});
				});
				$('.community-map-container .map-large .step-1 .area-map .featured-area-new img').mouseover(function(e){
					$(this).css({'cursor':'pointer'});
				});
				/*
				$('.featured-area-new a').mouseover(function(e){
					$('.featured-area-new img').css({'display':'none'});
					$(this).next().show();
					$(this).next().next().show();
				});
				$('.featured-area-new img, .featured-area-new div.tooltip').mouseleave(function(e){
					$(this).css({'display':'none'});
					$('.featured-area-new img').css({'display':'none'});
					$('.featured-area-new div.tooltip').css({'display':'none'});
				});
				*/
				$('.featured-area-new')
					.click(function(){
						
						var lot_map_id_in_db = $(this).children('a').attr('id');
						/*
						var dataString = 'lot_map_id_in_db=' + lot_map_id_in_db;
						$.getJSON('/about-bayberry/lot-map?jsoncallback=?',
							dataString,
 							function(json_object) {
			    				if (json_object.status == "success") {
									$('.step-2 .area-map img').attr('src', json_object.filename);
									$('.step-2 .area-map ul').css({'visibility':'hidden'});
									$('.step-2 .area-map #lot-map-' + lot_map_id_in_db).css({'visibility':'visible'});
									
									step1.hide();
									step2.show();
								}
						});
						*/
						
						$('.step-2 .area-map img').css({'display':'none', 'visibility':'hidden'});
						$('.step-2 .area-map ul').css({'visibility':'hidden'});
						$('.step-2 .area-map #lot-map-' + lot_map_id_in_db).prev().css({'display':'block', 'visibility':'visible'});
						$('.step-2 .area-map #lot-map-' + lot_map_id_in_db).css({'visibility':'visible'});
						
						step1.hide();
						step2.show();
						
						return false;
					});	
				
				$('.tooltip', featuredArea).click(function(){
					$(this).prev('a').click();
				
					return false;
				});
				
				back.click(function(){
					step2.hide();
					step1.show();
				
					return false;
				});
				
				close.click(function(){
					popup.hide();
				
					return false;
				});
				
				trigger.click(function(){
					popup.show();
					
					// to make sure every time when the overview map icon/zoom icon is clicked,
					// always pop up the large overview map, and not the detailed lot map
					// created by GL
					step1.show();
					step2.hide();
					
					return false;
				});
				
				// trigger for 'View on Lot Map'
				// created by GL
				trigger_qdh.live('click', function(e){
					e.preventDefault();
					popup.show();
					step1.hide();
					step2.show();
					
					var home_id = $(this).attr('id');
					$('#lot-' + home_id).show();
					setTimeout("$('#lot-" + home_id + "').hide();", 2000);
					
					var map_top_pos = $(this).offset().top;
					$('div.map-large').css('top', map_top_pos - 550);
					$('div.map-large').css('left', 55);
					
					var tooltip_top_pos = $('#lot-' + home_id).prev('a').css('top');
					tooltip_top_pos = parseInt(tooltip_top_pos) - 130;
					var tooltip_left_pos = $('#lot-' + home_id).prev('a').css('left');
					tooltip_left_pos = parseInt(tooltip_left_pos) - 102;
					
					$('#lot-' + home_id).attr('style', 'display:block;top:' + tooltip_top_pos +'px;left:' + tooltip_left_pos + 'px;');
					
					return false;
				});
			},
			
			homepageGallery: function() {
				$('#related-links .gallery a').click(function(){
					if(!$('#gallery').size()){
						$('<div class="hide"></div>')
							.appendTo('body')
							//.load($(this).attr('href') + ' #gallery',function(data){
							.load('/homepage/gallery', function(data){
								$('#gallery',this).dialog({
									autoOpen: false,
									dialogClass: 'dialog-window gallery-window',
									draggable: false,
									resizeable: false,
									modal: true,
									closeText: 'Close',
									create: function() {
										Engine.enhancements.scrollableGallery();
										Engine.enhancements.tabs(this);
									}
								});
								$('#gallery').dialog('open');
							});
					} else {
						$('#gallery').dialog('open');
					}
				
					return false;
				});
			}			
		},
		scrollableGallery: function() {
			if($('#image_wrap').length) {
					$(".scrollable").scrollable();

					$(".items img").click(function() {
						var test1 = $(this).parents("div.tab-content").children("#image_wrap");
						$(this).parents("div.tab-content").children("#image_wrap").children("p.visit").remove();
						//$('#image_wrap p.visit').remove();
						
						var visit = $(this).next().clone();
						$(this).parents("div.tab-content").children("#image_wrap").append(visit);
						//visit.appendTo('#image_wrap');
	
						// see if same thumb is being clicked
						if ($(this).hasClass("active")) { return;  }
	
						// calclulate large image's URL based on the thumbnail URL (flickr specific)
						var url = $(this).attr("src").replace("_t", "");
	
						// get handle to element that wraps the image and make it semi-transparent
						var wrap = $(this).parents("div.tab-content").children("#image_wrap").fadeTo("medium", 0.5);
						//var wrap = $("#image_wrap").fadeTo("medium", 0.5);
	
						// the large image from www.flickr.com
						var img = new Image();
	
						// call this function after it's loaded
						img.onload = function() {
	
							// make wrapper fully visible
							wrap.fadeTo("fast", 1);
	
							// change the image
							wrap.find("img").attr("src", url);
							
						};
	
						// begin loading the image from www.flickr.com
						img.src = url;
	
						// activate item
						$(".items img").removeClass("active");
						$(this).addClass("active");

					// when page loads simulate a "click" on the first image
					}).filter(":first").click();

					//$('.scrollable .items div img:last').css('display','none');
					$('.scrollable .items div').each(
						function() { 
						$(this).last('img').css('margin','0'); 
					});		
			}
		}/*,
		
		scrollableGallery: function() {
			if($('#image_wrap').length) {
					$(".scrollable").scrollable();

					$(".items img").click(function() {

					$('#image_wrap p.visit').remove();
					
					var visit = $(this).next().clone();
					visit.appendTo('#image_wrap');

					// see if same thumb is being clicked
					if ($(this).hasClass("active")) { return;  }

					// calclulate large image's URL based on the thumbnail URL (flickr specific)
					var url = $(this).attr("src").replace("_t", "");

					// get handle to element that wraps the image and make it semi-transparent
					var wrap = $("#image_wrap").fadeTo("medium", 0.5);

					// the large image from www.flickr.com
					var img = new Image();

					// call this function after it's loaded
					img.onload = function() {

						// make wrapper fully visible
						wrap.fadeTo("fast", 1);

						// change the image
						wrap.find("img").attr("src", url);
						
					};

					// begin loading the image from www.flickr.com
					img.src = url;

					// activate item
					$(".items img").removeClass("active");
					$(this).addClass("active");

					// when page loads simulate a "click" on the first image
					}).filter(":first").click();

					//$('.scrollable .items div img:last').css('display','none');
					$('.scrollable .items div').each(
						function() { 
						$(this).last('img').css('margin','0'); 
					});		
			}
		},
		*/
		/*
		validateForm: function() {
			if($('#realtors-form').length) {
				// adds an effect called "wall" to the validator
				$.tools.validator.addEffect("wall", function(errors, event) {
				
					// get the message wall
					var wall = $(this.getConf().container).fadeIn();
					
					// remove all existing messages
					wall.find("p").remove();
					
					// add new ones
					$.each(errors, function(index, error) {
						wall.append(
							"<p><strong>" +error.input.attr("name")+ "</strong> " +error.messages[0]+ "</p>"
						);		
					});
					
				// the effect does nothing when all inputs are valid	
				}, function(inputs)  {
					
				});
			
			
				// initialize validator with the new effect
				$("#realtors-form").validator({
				   effect: 'wall', 
				   container: '#errors',
				   
				   // do not validate inputs when they are edited
				   errorInputEvent: null
				   
				// custom form submission logic  
				}).submit(function(e)  { 
				   
				   // when data is valid 
				   if (!e.isDefaultPrevented()) {
					  
					  // tell user that everything is OK
					  $("#errors").html("<h2>All good</h2>");
					  
					  // prevent the form data being submitted to the server
					  e.preventDefault();
				   } 
				   
				});
			}
		}
		*/
		
	}
};

$(document).ready(function() {
	$('body').addClass('js');

	Engine.enhancements.mainNav();
	Engine.enhancements.sideNav();
	Engine.enhancements.scrollablePortfolio();
	Engine.enhancements.tabs();
	Engine.enhancements.mapTips();	
	Engine.enhancements.scrollableGallery();		
	// Engine.enhancements.slideShow();
	Engine.enhancements.popups.init();
	// Engine.enhancements.validateForm();	

});


// DD_belatedPNG fix for IE6
if (typeof DD_belatedPNG !== 'undefined') {
	var PNG_fix_selectors = [
		'#header',
		'.shadow',
		'.section-form .btn-submit-large span',
		'.dialog-window .btn-close',
		'#image_wrap .visit',
		'#image_wrap .visit a',
		'.dialog-window .btn-close',
		'.map-large .lot',
		'.map-large .legend li',
		'.map-large'
	];
	DD_belatedPNG.fix(PNG_fix_selectors.join(','));
}
