var beenHereBefore = {};
var originalText = {};
function getId (el) {
	 id = el.id;
	 if (!id) id = el.name;
	 return id;
}

function makeNew(id) {
	var els = $('#'+id);
	if (els) {
		beenHereBefore[id] = null;
		els.val(originalText[id]);
	}
}

function clearIfNew(el) {
	 var id = getId(el);
	 clearIdIfNew(id);
}

function clearIfNewBySelector(sel) {
	$(sel).each(function(i, el) {
		clearIfNew(el);
	});
}

function isNew(id) {
	return !beenHereBefore[id];
}

function clearIdIfNew(id) {
	 if (isNew(id)) $('#'+id).val("");
}

function handleExampleBlur(event) {
	 var el = event.target;
	 var id = getId(el);
	 if (el.nodeName == 'INPUT' && el.value == '') {
		 el.value = originalText[id];
//		 if (id.indexOf("password") == 0) {
//			 el.type = 'text';
//		 }
		 $('none').add(el).addClass("dimmed");
		 beenHereBefore[id] = null;
	 }
}

function handleExampleFocus(event) {
	 // Get an id
	 var el = event.target;
	 var id = getId(el);
	 if (!beenHereBefore[id]) {
		 if (el.nodeName == 'INPUT') {
			 originalText[id] = el.value;
			 el.value = '';
		 }
		 beenHereBefore[id] = true;
		 
		 // Switch the input field to a password field
//		 if (id.indexOf("password") == 0) {
//			 el.type = 'password';
//		 }
		 $('none').add(el).removeClass("dimmed");
	 }
}

function addExampleHandler(id) {
  $("#"+id).blur(handleExampleBlur);
  $("#"+id).focus(handleExampleFocus);
}

function addExampleHandlers() {
  $(".example").blur(handleExampleBlur);
  $(".example").focus(handleExampleFocus);
}

$(document).ready(function() {
  addExampleHandlers();
  addPasswordHandlers();
});

function getEventFieldName(event) {
    var el = event.target;
	var id = getId(el);
	return id;
}

function addPasswordHandlers() {
  $(".passwordRaw").focus(function(ev) {
    // Find the raw password field's name
    var id = getEventFieldName(ev);
    
    // Strip the "Raw" from the end
    var idlen = id.length;
    if (id.substring(idlen-3) === "Raw") {
      id = id.substring(0, idlen-3);
    }
    $("#"+id+"Raw").toggle();
    $("#"+id).toggle();
    $("#"+id).focus();
    $("#"+id).val("");
  });
  $(".password").blur(function(ev) {
    // Find the cooked password field's name
    var id = getEventFieldName(ev);
    if (isNew(id)) {
      $("#"+id+"Raw").toggle();
      $("#"+id).toggle();
    }
  });
}

// Set the value of a sensitive form field
function setVal(id, value) {
	var where =	$('#'+id);
	
	if (!beenHereBefore[id]) {
		originalText[id] = where.val();
		beenHereBefore[id] = true;
	}
	where.val(value);
	where.removeClass("dimmed");
}

