var t;

$(function(){
	// placeholders for forms 
	$(":input").each(function(index){if($(this).attr("title")){infieldLabel(this)}});
	// expand toggles
	$(".expand").live("click",function(event){event.preventDefault();expandToggle(this)});
	// confirm links
	$(".confirm-link").live("click",function(event){confirmAlert(this,event)});
	// login revealers
	$("a.reveal-login").live("click",function(event){if($.browser.msie && parseInt($.browser.version) < 8){}else{event.preventDefault();loginToggle(this)}});
	$("#login-wrapper").mouseenter(loginClear)
	$("#login-wrapper").mouseleave(loginClose)
	$("#login-wrapper input").focus(loginClear)
	// date picker
	$(".datepicker").datepicker({
		showOn: "button",
		buttonImage: "/img/icons/calendar.gif",
		buttonImageOnly: true,
		dateFormat: 'dd/mm/yy',
		buttonText:"Select a date",
		firstDay:1,
		minDate:0,
		onSelect:function(dateText,inst){$("#"+inst.id).removeClass("inactive").addClass("active")}
	});
	
	
	
	
	
	
	
	/*$(function() {
		$.datepicker.setDefaults( $.datepicker.regional[ "" ] );
		$( "#datepicker" ).datepicker( $.datepicker.regional[ "fr" ] );
		$( "#locale" ).change(function() {
			$( "#datepicker" ).datepicker( "option",
				$.datepicker.regional[ $( this ).val() ] );
		});
	});*/
	
	
	
	
	
	
	
	// capture auto-populate fields
	$("select.populate-field").change(function(){populateField(this)});
	// search preferred settings
	$("#search_preferred_only").live("click",function(){togglePreferred()});
	// search features
	$("#search-feature-show a").click(function(event){event.preventDefault();revealFeatures()})
	// my destination form 
	$("#my-destination-form").submit(function(event){event.preventDefault();destinationSubmit(this)});
	// destination deletes
	$("a.delete-destination").live("click",function(event){event.preventDefault();destinationDelete(this,event)})
	// upload tabs
	$("#member-video-tabs a").live("click",function(event){event.preventDefault();uploadTab(this)});
	// sliders
	$("div.slider-track-left").each(function(){sliders(this)})
	// house view tabs
	$("a.house-map-tab").click(function(event){event.preventDefault();houseTab(this)})
	// capture flash writers
	$("a.flash").live("click",function(event){event.preventDefault();elementFlash(this)});
	// close overlays
	$("a.close-overlay").live("click",function(event){event.preventDefault();closeOverlay()});
	$('#overlay-body').bind("clickoutside",function(event){event.preventDefault();closeOverlay()});
	$(document).keypress(function(event){if(event.keyCode==27)closeOverlay()})
	// comment forms 
	$("#comment-form").submit(function(event){event.preventDefault();commentSubmit(this)})
	// reporting links
	$("a.site-report").live("click",function(event){event.preventDefault();reportCreate(this)});
	// favourite a house
	$("a.house-favourite").live("click",function(event){event.preventDefault();favouriteAdd(this)});
	// faq
	$("a.faq-selection-cat").click(function(event){event.preventDefault();faqCategory(this)});
	$("a.faq-selection-qus").click(function(event){event.preventDefault();faqQuestion(this)})
	// footer country event
	$("#country_search_country_id").change(function(){searchCountry(this)});
	// missing town form
	$("a.missing-town").click(function(event){event.preventDefault();requestTown()})
})

// infield label for forms 
function infieldLabel(el){$(el).addClass('inactive');if(el.value==''){$(el).attr('value',el.title)}else if(el.value != el.title){$(el).removeClass('inactive')}$(el).focus(function(){if(el.value==el.title){$(el).attr('value','');$(el).removeClass('inactive')}});$(el).blur(function(){if(el.value==''){$(el).attr('value',el.title);$(el).addClass('inactive')}});$(el).parents("form").submit(function(event){if(el.value==el.title){$(el).attr('value','')}});}

// expand toggles
function expandToggle(el){var reveal="#"+$(el).attr("data-expand_id"),accordian=$(el).attr("data-accordian"),accordian_class=$(el).attr("data-accordian_class");if(accordian==undefined)accordian=0;if(accordian){$("."+accordian_class).slideUp("fast")}if(!$(reveal).is(":visible")){$(reveal).slideDown("fast",function(){$(el).addClass("expand-showing");if(reveal=="#search-features"){$("#search-feature-show").show()}})}else{$(reveal).slideUp("fast",function(){$(el).removeClass("expand-showing");if(reveal=="#search-features"){$("#search-feature-show").hide()}})}}

// confirm dialogs
function confirmAlert(el,ev){if(confirm($(el).attr("data-confirm"))){return true}else{ev.preventDefault();return false}}

// display ajax errors
function getErrorcount(json){var cnt=0;$.each(json,function(key,value){cnt=cnt+1});return cnt}
function showErrors(json){$.each(json,function(key,value){var str=key.replace(".","_").toLowerCase();$("#"+str).show()});$("#page-errors").show("fast")}
function hideErrors(){$("#page-errors").hide("fast")}
function resetErrors(){$("#page-errors li").hide()}

// write to the flash layer (deprecated, need to make AJAX call to load flash template if re-used) 
function elementFlash(el){var content={title:$(el).attr("data-title"),body:$(el).attr("data-body")};writeFlash(content.title,content.body);}
function writeFlash(title,body){$("#overlay-body").load("/"+language_id+"/overlay/flash/",function(){$("#flash-title").text(title);$("#overlay-text").html(body);$("#overlay-toggle").show()})}

// reveal features on left pane
function revealFeatures(){
	$("#search-features").css("height","auto");
	$("#search-feature-show").hide();
}

// footer country search
function searchCountry(field){
	var val=$(field).val();
	location.href="/"+language_id+"/search/get/?search.country_id="+val;
}

// comment form
function commentSubmit(form){
	var serilaized=$(form).serializeArray();
	$("#comment-indicator").show();
	$.post("/"+language_id+"/comments/create.json?cache="+Math.random(),serilaized,function(data){
		var errors=parseInt(getErrorcount(data.errors));
		$("#comment-indicator").hide();
		if(!errors){
			$("#comment-none").slideUp("fast")
			commentShowsingle(data.comment.ID);
			hideErrors();
			$("#comment_body").val("")				
		}else{showErrors(data.errors)}
	});
}
function commentShowsingle(id){
	$.get("/"+language_id+"/comments/single/"+id+"/?hide=1&cache="+Math.random(),function(data){
		$("#comments-all").append(data);
		setTimeout(function(){$("#comment"+id).slideDown("fast")},30);
	});

}

// overlays
function closeOverlay(){$("#overlay-toggle").hide()}
function showOverlay(){$("#overlay-toggle").show()}

// request a new town form 
function requestTown(){
	$("#overlay-body").load("/"+language_id+"/overlay/missing-town/",showOverlay)
}

// toggle the preferred destination fields 
function togglePreferred(){var checked=$("#search_preferred_only").is(":checked");if(!checked){$("#search-locations").slideDown("fast")}else{$("#search-locations").slideUp("fast")}}

// reveal login
function loginToggle(el){
	if(!$("#login-wrapper").is(":visible")){
		$("#login-wrapper").slideDown(200,function(){
			loginClose();
			//$('#login-wrapper').bind("clickoutside",function(event){$("#login-wrapper").slideUp(200)});
		});
	}else{
		$("#login-wrapper").slideUp(200)
	}
}
function loginClose(){if(!$("#login-wrapper input").is(":focus")){t=setTimeout(function(){$("#login-wrapper").slideUp(200)},6000)}}
function loginClear(){clearTimeout(t)}

// populate select fields (AJAX) 
// supply the following HTML5 attrs:
// data-populate_category=The category to be sent to the server so we know what to send back (e.g. region, town etc)
// data-populate_id=The id of the select field to populate with the new content
// data-populate_unselected_value=If a unselected value is passed, this will be its default value
// data-populate_unselected_title=Text for the unselected title (if wanted)
function populateField(el){
	var field={
		populate_category:$(el).attr("data-populate_category"),
		populate_id:"#"+$(el).attr("data-populate_id"),
		populate_unselected_value:$(el).attr("data-populate_unselected_value"),
		populate_unselected_title:$(el).attr("data-populate_unselected_title"),
		populate_callback:$(el).attr("data-populate_callback")
	}
	if(field.populate_unselected_value==undefined)field.populate_unselected_value="";
	if(field.populate_unselected_title==undefined)field.populate_unselected_title="";
	if(field.populate_callback==undefined)field.populate_callback="";
	$(field.populate_id).load("/"+language_id+"/ajax/populate/",{populate_category:field.populate_category,populate_unselected_value:field.populate_unselected_value,populate_unselected_title:field.populate_unselected_title,populate_value:$(el).val()},function(){
		if(field.populate_callback.length){eval(field.populate_callback)}
	});
}
function toggleSearchfield(id){
	var id="#"+id;
	$(id).show("fast")
}

// reporting 
function reportCreate(el){
	params={
		type:$(el).attr("data-type"),
		related_id:$(el).attr("data-related_id")
	}
	$("#overlay-body").load("/"+language_id+"/report/new/",params,function(){
		showOverlay()
	})
}

// favourite a house
function favouriteAdd(el){
	var id=$(el).attr("data-id"),
			replace=$(el).attr("data-replace");
	$.post("/"+language_id+"/my-favourites/add/"+id,function(){
		writeFlash("House Favourited","This house has been successfully added to your <a href=\"/"+language_id+"/my-favourites/\">favourites</a>.");
		$(el).text(replace);
		$(el).removeClass("house-favourite");
		$(el).attr("href","/"+language_id+"/my-favourites/");
	})
}

// my destination form submit
function destinationSubmit(form){$("#ajax-indicator-dest").show();$.post("/"+language_id+"/member/my-destinations/",$(form).serializeArray(),function(data){$("#ajax-indicator-dest").hide();if(data==""){hideErrors();$("#my-destinations").load("/"+language_id+"/member/my-destinations-list/?cache="+Math.random())}else{showErrors(data)}})}	
// my destination delete
function destinationDelete(el,ev){if(confirmAlert(el,ev)){$.post("/"+language_id+"/member/my-destinations-delete/"+$(el).attr("data-id")+"/?cache="+Math.random(),function(){$(el).parents("tr").fadeOut(300)})}}

// tabs
function uploadTab(el){var type=$(el).attr("data-type");$("#member-video-tabs a").removeClass("selected");$("div.member-video-sec").hide(0,function(){$(el).addClass("selected");$("#video-"+type).show()})}
function houseTab(el){var id=$(el).attr("data-id");$("a.house-map-tab").removeClass("selected");$("div.house-map-stat").hide(0,function(){$(el).addClass("selected");$("#"+id).show()})}

// sliders
function sliders(el){
	var field_id="#"+$(el).attr("data-field");
	$(el).slider({
		value:parseInt($(field_id).val()),
		min:parseInt($(el).attr("data-min")),
		max:parseInt($(el).attr("data-max")),
		step:parseInt($(el).attr("data-step")),
		change:function(event,ui){
			$(field_id).val(ui.value);
		}
	});
}

// FAQ: Category
function faqCategory(el){
	var category_id=$(el).attr("data-category_id"),category_string="#faq-questions-"+category_id;
	$("div.faq-questions").slideUp("fast");
	if($(category_string).is(":visible")){
		$(category_string).slideUp("fast")
	}else{
		$(category_string).slideDown("fast")
	}
}
// FAQ: Question
function faqQuestion(el){
	var question_id=$(el).attr("data-question_id"),question_string="#faq-answer-"+question_id;
	$("div.faq-answer").slideUp("fast");
	if($(question_string).is(":visible")){
		$(question_string).slideUp("fast")
	}else{
		$(question_string).slideDown("fast")
	}
}
