$(document).ready(function() {
	
	initAutoComplete();
	
	initNestedModels();
	
	$("#mailinglistform").validate({
		rules: {
			first_name: {
				required: true
			},
			last_name: {
				required: true
			},
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			first_name: "Please enter your name",
			last_name: "Please enter your name",
			email: "Please enter a valid email address"
		}
	
	});
	
	$("input.type_text").focus(function() {
		if($(this).attr("title")==$(this).val())
			$(this).val("");
	});
	
	$("input.type_text").blur(function() {
		if($(this).val()=="")
			$(this).val($(this).attr("title"));
	});
	
});


/* autocomplete setup */
function initAutoComplete(){//autocomplete
	$('input.autocomplete').each(function(){
		var input = $(this);
		input.autocomplete(input.attr('autocomplete_url'),{
			onItemSelect:fillExtraInputs,
			matchContains:1, //also match inside of strings when caching
			//mustMatch:1, //allow only values from the list
			//selectFirst:1, //select the first item on tab/enter
			removeInitialValue:0 //when first applying $.autocomplete
		});
	});
}

/* Used with autocomplete - fills out additional product data when selecting by sku */
function fillExtraInputs(data, input) {
	for (var i=0; i < data.extra.length; i++) {
		var keyvalue = data.extra[i].split(":");
		if (keyvalue.length > 1) {
			input.closest(".item").find("input." + keyvalue[0]).val(keyvalue[1]);
		}
	}
}


/* Nested models addition and removal */
function initNestedModels() {
	$('.add_nested_item').bind('click', addNestedItem);
	$('.add_nested_item_lvl2').bind('click', addNestedItemdLvl2);
	$('.remove').bind('click', removeItem);
}

replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}

var addNestedItem = function(e) {
	itemName = $(this).attr("href").replace(/.*#/, '');
	template = eval(itemName);
	$("" + replace_ids(template) + "").hide().appendTo('#' + itemName).fadeIn();
	
	if (itemName == "wish_list_item") {
		$('div.item:visible:odd').addClass('odd');
		initAutoComplete();
	}
	
	initNestedModels();
	return false;
};

var addNestedItemdLvl2 = function(e) { alert("addNestedItemdLvl2!"); };

var removeItem = function(e) {
	itemName = $(this).attr("href").replace(/.*#/, '');
	$(this).closest('.' + itemName).fadeOut("normal", function() {
		$('div.item:visible:even').removeClass('odd');
		$('div.item:visible:odd').addClass('odd');
	});
	
	if ($(this).prev("input").length > 0) {
		$(this).prev("input").val('1');
	}
	
	initNestedModels();
	return false;
}