$(document).ready(function(){

	$('a[rel*=external]').attr('target', '_blank');

	function megaHoverOver(){
		$(this).find(".sub").stop().fadeTo('fast', 1).show();

		//Calculate width of all ul's
		(function($) { 
			jQuery.fn.calcSubWidth = function() {
				rowWidth = 0;
				//Calculate row
				$(this).find("ul").each(function() {					
					rowWidth += $(this).width(); 
				});	
			};
		})(jQuery); 

		if ( $(this).find(".row").length > 0 ) { //If row exists...
			var biggestRow = 0;	
			//Calculate each row
			$(this).find(".row").each(function() {							   
				$(this).calcSubWidth();
				//Find biggest row
				if(rowWidth > biggestRow) {
					biggestRow = rowWidth;
				}
			});
			//Set width
			$(this).find(".sub").css({'width' :biggestRow});
			$(this).find(".row:last").css({'margin':'0'});

		} else { //If row does not exist...

			$(this).calcSubWidth();
			//Set Width
			$(this).find(".sub").css({'width' : rowWidth});

		}
	}

	function megaHoverOut(){ 
	  $(this).find(".sub").stop().fadeTo('fast', 0, function() {
		  $(this).hide(); 
	  });
	}


	var config = {    
		 sensitivity: 2, // number = sensitivity threshold (must be 1 or higher)    
		 interval: 100, // number = milliseconds for onMouseOver polling interval    
		 over: megaHoverOver, // function = onMouseOver callback (REQUIRED)    
		 timeout: 100, // number = milliseconds delay before onMouseOut    
		 out: megaHoverOut // function = onMouseOut callback (REQUIRED)    
	};

	$("ul#topnav li .sub").css({'opacity':'0'});
	$("ul#topnav li").hoverIntent(config);

});

$(document).ready(function () {
    var $div = $('#city');
    var height = $div.height();
    $div.hide().css({ height : 0 });

    $('a#city-click').click(function () {
        if ($div.is(':visible')) {
            $div.animate({ height: 0 }, { duration: 200, complete: function () {
                $div.hide();
            } });
        } else {
            $div.show().animate({ height : height }, { duration: 200 });
        }

        return false;
    });
});


//innerfade
$(document).ready(
	function(){
		$('#slideshow').innerfade({
		speed: 1000,
		timeout: 8000,
		type: 'sequence',
		containerheight: '340px'
	});

});

$(function() {
	// set opacity to nill on page load
	$("ul#navigation span").css("opacity","0");
	// on mouse over
	$("ul#navigation span").hover(function () {
		// animate opacity to full
		$(this).stop().animate({
			opacity: 1
		}, 'fast');
	},
	// on mouse out
	function () {
		// animate opacity to nill
		$(this).stop().animate({
			opacity: 0
		}, 'slow');
	});
});

function formCheck(formobj){
	
	var l_Msg = alertMsg.length;
	
	for (var i = 0; i < fieldRequired.length; i++){
		var obj = formobj.elements[fieldRequired[i]];
		if (obj){
			switch(obj.type){
			case "select-one":
				if (obj.selectedIndex == -1 || obj.options[obj.selectedIndex].text == ""){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "select-multiple":
				if (obj.selectedIndex == -1){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			case "text":
			case "textarea":
				if (obj.value == "" || obj.value == null){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
				break;
			default:
			}
			if (obj.type == undefined){
				var blnchecked = false;
				for (var j = 0; j < obj.length; j++){
					if (obj[j].checked){
						blnchecked = true;
					}
				}
				if (!blnchecked){
					alertMsg += " - " + fieldDescription[i] + "\n";
				}
			}
		}
	}

	if (alertMsg.length == l_Msg){
		return true;
	}else{
		alert(alertMsg);
		return false;
	}
	
}

//property thumbnail fading magic stuff
function propertyPictures(){
	
	$(function(){
	
		var thumbButtons = $('ul.prop-img-menu li');
		thumbButtons.filter(function(i){ return (i > 0)}).css('opacity', 0.2);
		
		thumbButtons.click(function(){
			
			$clicked = $(this);
			
			// if the button is not already "transformed" AND is not animated
			if($clicked.css("opacity") != "1" && $clicked.is(":not(animated)")) {
				
				$clicked.animate({
					opacity: 1
				}, 600 );
				
				// each button div MUST have a "xx-button" and the target div must have an id "xx" 
				var idToLoad = $clicked.attr("id").split('-');
				
				//we search trough the content for the visible div and we fade it out
				$("#feature-content").find("div:visible").fadeOut("fast", function(){
					$(this).parent().find("#"+idToLoad[0]).fadeIn();
				})
			}
			
			//we reset the other buttons to default style
			$clicked.siblings(".node").animate({
				opacity: 0.2
			}, 600 );
			
		});
	});
	
}

function marketplace_initSearch(){
	
	$(document).ready(function(){
	
		//search for
		options = $('ul.searchfor li a');
		options.click(function(e){
		
			clickd = $(this);
			if(!clickd.hasClass('active')){
				
				li = clickd.parent();
				
				options.removeClass('active');
				clickd.addClass('active');
				
				$('#searchtype').attr('value', li.attr('class'));
				
			}
			
			e.preventDefault();
			return false;
			
		});
		
		//sort by
		sorters = $('div.sortby a');
		sorters.click(function(e){
			
			$(this).parent('div').toggleClass('high');
			
			//e.preventDefault();
			//return false;
			
		});
		
	});
	
}

function form_ambassadors_init(){
	
	$(document).ready(function(){
		
		formNotificationField();
		formValidateTextfields();
		
	});
	
}

function form_apartments_init(){
	
	$(document).ready(function(){
		
		formNotificationField();
		formValidateTextfields();
		
		var x = $("input[name=Date]").datepicker({
			minDate: 			new Date()
		});
		$('img.icon').click(function(e){
			x.datepicker('show');
		});
		
	});
	
}

function form_landlords_init(){
	
	$(document).ready(function(){
		
		formValidateTextfields();
		
	});
	
}

function form_regular_init(){
	
	$(document).ready(function(){
		
		formNotificationField();
		formValidateTextfields();
		
	});
	
}


function formNotificationField(){
	
	$('select#notification').change(function(e){
	
		if($(this).attr('value') == 'other' || $(this).attr('value') == 'ambassador'){	
			$('input[name=notification_other]').removeClass('hide');
		}else{
			$('input[name=notification_other]').addClass('hide');
		}
		
	});
}

function formValidateTextfields(){
	
	form = $('.form-holder form');
	form.submit(function(e){
	
		var errorTxt = 'Please fill out all required fields:\n';
		var error = false;
	
		fields = $('.form-holder input[type=text], .form-holder textarea');
		fields.each(function(i, el){
		
			field = $(el);
			if(field.attr('value').length == 0 && !field.hasClass('ignore')){
			
				errorTxt += '- '+ field.attr('name') +'\n';
				error = true;
			
			}
		
		});
	
		if(error){
		
			alert(errorTxt);
		
			e.preventDefault();
			e.stopImmediatePropagation();
			
			return false;
		
		}
		
	});
	
}

function marketPlace_detailInit(){
	
	jQuery(document).ready(function(){
		$("#contactbutton").fancybox({
			"width":  			494,
			"height": 			405,
			"autoScale": 		false,
			"autoDimensions": 	false,
			"padding": 			0,
			"overlayColor": 	'#fff',
			"overlayOpacity": 	0.8,
			"scrolling": 		false,
			"ajax":{
				type: "GET"
			}						
		});
	});
	
}

function marketplace_contactPopup(submiturl){
	
	jQuery(document).ready(function(){
	
		$('#contactform').submit(function(e){

			email = $(this).find('input[name=email]').val();

			var filter= /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
			if(filter.test(email)){

				dataString = $(this).serialize();
			
				button = $(this).find('button');
				button.css('opacity', 0.8);
				button.text('Please Wait...');

				$.ajax({
					type: 	"POST",
					url: 	submiturl,
					data: 	dataString,
					success: function(){
						$.fancybox.close();
					}
				});
				
			}else{
				
				alert('Please fill out a valid email address');
				
			}
		
			e.preventDefault();
			e.stopImmediatePropagation();
			
		});
		
	});
	
}

function maps_init(baseurl){
	
	jQuery(document).ready(function(){
	
		$('#neighborhoodselect').change(function(e){
		
			document.location.href = baseurl +'?neighborhood='+ $(this).val();
			
		});
	
	});
}