$(document).ready(function() {

	if(document.domain == "localhost") {
		var domain = $("base").attr('href');
	} else {
		var domain = "http://" + document.domain;
	}
	
	$("a.trash").bind('click',function(){
		if(!confirm("Are you sure you want to delete this element?")) {
			return false;
		}
	});
	
	$("ul:first").children("li").children(".expander").addClass('expanded');
	
	$("ul li .expander").click(function(){
		if($(this).hasClass('expanded')) {
			$(this).siblings("ul").slideUp(200);
			$(this).removeClass('expanded');
		} else {
			$(this).siblings("ul").slideDown(200)
			$(this).addClass('expanded');
		}
		$(this).find("img").toggle();
		return false;
	});
	
	$(".visibility_toggle").click(function(){
		var $this = $(this);
		var current = $this.find("span:visible").attr('class');
		var visible = (current == 'visible') ? 0 : 1;
		var id = $this.closest("li").attr('id').replace(/\w*?_/,"");
		var model = $this.closest("ul").attr('id').replace(/\w*?_/,"");
		$.ajax({
			url: domain + '/' + model + '/toggle',
			type: 'POST',
			data: "id="+id+"&visible="+visible,
			dataType: 'text',
			complete: function(feedback) {
				$this.find("span").toggle();
			}
		});
		return false;
	});
	
	$("ul.sortable").bind('mousedown',function(e){
		e.stopPropagation();
	});
	
	$("ul.sortable").sortable({
//		connectWith: '.connected',
		axis: 'y',
		update: function(e, ui) {
			var id = $(ui.item).closest("ul").attr('id');
			var model = id.replace(/\w*_/,"");
			var parent = id.replace(/_\w*/,"");
			var mKey = model + '[]';
			$.ajax({
				url: domain + '/' + model + '/sort',
				type: 'POST',
				data: "parent_id=" + parent + "&" + $(this).sortable('serialize', {key:mKey}),
				dataType: 'script',
				complete: function(feedback) {
					
				}
			});
		}
	});
	
	$(".edit img").mouseenter(function(){
		$(".hint").text($(this).attr('alt'));
	}).mouseleave(function(){
		$(".hint").text('');
	});
	
	$("select#datatypeField").change(function(e){
		$this = $(this);
		if(e.target.value == 'Text'){
			$this.after('<span id="rteInputContainer"> rte: <input name="rte" id="rteInput" type="checkbox" /></span>');
		} else {
			$("#rteInputContainer").remove();
		}
	});
	
	$("textarea.rte").aWYSIWYG({imgPath:domain+"/imgs/static/aWYSIWYG",extStyles:domain+"/css/editorStyles.css",icons:true});
	
});
