// JavaScript Document

$(function() {
    
	//Show form when placefield is clicked
	$(document).on('click','.placefield',function(){
		var fieldId = $(this).attr('id');
		//If the place div is available, then just show that, else, load a new div content
		if($('#'+fieldId+'__div').length > 0)
		{
			$('#'+fieldId+'__div').fadeIn('fast');
		} 
		else 
		{
			$('#'+fieldId).after("<div id='"+fieldId+"__div' class='callout'></div>");
			$('#'+fieldId+'__div').css('min-width',$(this).outerWidth());
			
			updateFieldLayer(getBaseURL()+"/Page/address_field_form/field_id/"+fieldId,'','',fieldId+'__div','');
		}
		
		var offsetTop = $('#'+fieldId).offset().top - $('#'+fieldId+'__div').outerHeight() - 10;
		var offsetLeft = $('#'+fieldId).offset().left;
		$('#'+fieldId+'__div').offset({ top: offsetTop, left: offsetLeft });
	});


	// Close call out bubble if user clicks outside
	$(document).mouseup(function (e)
	{
    	var calloutContainer = $(".callout");
		var calloutContainerDiv = calloutContainer.children('div');
		
		//If the target of the click isn't the container... nor a descendant of the container, hide it
   		if (!calloutContainer.is(e.target) && calloutContainer.has(e.target).length === 0 && !calloutContainerDiv.is(e.target) && calloutContainerDiv.has(e.target).length === 0) 
    	{
       	 	calloutContainerDiv.hide('fast');
			calloutContainer.hide('fast');
    	}
	});
	
	
	//Activate form submission if the required fields are filled in
	$('.addressform').on('change', 'input', function(e){
		var activate = true;
		$('.addressform').find('input').each(function(){
			if(!$(this).hasClass('optional') && $(this).val().length < 3){
				activate = false; 
				return false;
			}
		});
		
		if(activate){
			var formBtn = $('.addressform').find('button').first();
			formBtn.attr('type','submit');
			formBtn.removeClass('greybtn').addClass('btn');
		}
	});
	
	// What to do when the form is posted
	$('.addressform').on('click','button',function(){
		
	});
});

	
	
	
	



