/*
	echonet Javascript Library
	Version: 1.0 light
	Date: 16.08.2007
	Content: 
		No More IE6 Background Flicker - http://www.hedgerwow.com/360/bugs/dom-fix-ie6-background-image-flicker.html
		addEvent function - http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
		JSTarget by Roger Johansson - www.456bereastreet.com
		focusLabels - Wenn label geklickt wird entsprechendes input feld in den focus gebracht, erweiterung da nicht von allen browsern unterstützt.
		insertAfter - wie insertBefore 

*/


// No More IE6 Background Flicker - http://www.hedgerwow.com/360/bugs/dom-fix-ie6-background-image-flicker.html
(function(){ /*Use Object Detection to detect IE6*/ var m = document.uniqueID /*IE*/ && document.compatMode /*>=IE6*/ && !window.XMLHttpRequest /*<=IE6*/ && document.execCommand ; try{ if(!!m){ m("BackgroundImageCache", false, true) /* = IE6 only */ } }catch(oh){}; })();
// Load Function on DOM.Contentload - crossbrowser
function onContent(f){//(C)webreflection.blogspot.com
var b=navigator.userAgent,d=document,w=window,
c="__onContent__",e="addEventListener",o="opera",r="readyState",
s="<scr".concat("ipt defer src='//:' on",r,"change='if(this.",r,"==\"complete\"){this.parentNode.removeChild(this);",c,"()}'></scr","ipt>");
w[c]=(function(o){return function(){w[c]=function(){};f(o?o():o)}})(w[c]);
if(d[e])d[e]("DOMContentLoaded",w[c],false);
if(/WebKit|Khtml/i.test(b)||(w[o]&&parseInt(w[o].version())<9))
(function(){/loaded|complete/.test(d[r])?w[c]():setTimeout(arguments.callee,1)})();
else if(/MSIE/i.test(b))d.write(s);
};


/*
addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
*/
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

/*
JSTarget function by Roger Johansson, www.456bereastreet.com
*/
var JSTarget = {
	init: function(att,val,warning) {
		if (document.getElementById && document.createElement && document.appendChild) {
			var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'rel' : att;
			var strVal = ((typeof val == 'undefined') || (val == null)) ? 'external' : val;
//			var strWarning = ((typeof warning == 'undefined') || (warning == null)) ? ' (opens in a new window)' : warning;
//			var oWarning;
			var arrLinks = document.getElementsByTagName('a');
			var oLink;
			var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
			for (var i = 0; i < arrLinks.length; i++) {
				oLink = arrLinks[i];
				if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
//					oWarning = document.createElement("em");
//					oWarning.appendChild(document.createTextNode(strWarning));
//					oLink.appendChild(oWarning);
					oLink.onclick = JSTarget.openWin;
				}
			}
			oWarning = null;
		}
	},
	openWin: function(e) {
		var event = (!e) ? window.event : e;
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
		else {
		    var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) oWin.focus();
				return false;
			}
			oWin = null;
			return true;
		}
	}
};

function focusLabels() {
  if (!document.getElementsByTagName) return false;
  var labels = document.getElementsByTagName("label");
  for (var i=0; i<labels.length; i++) {
    if (!labels[i].getAttribute("for")) continue;
    labels[i].onclick = function() {
      var id = this.getAttribute("for");
      if (!document.getElementById(id)) return false;
      var element = document.getElementById(id);
      element.focus();
    }
  }
}

function resetFields(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.type == "submit") continue;
    if (!element.defaultValue) continue;
    element.onfocus = function() {
    if (this.value == this.defaultValue) {
      // this.value = "";
     }
    }
    element.onblur = function() {
      if (this.value == "") {
        this.value = this.defaultValue;
      }
    }
  }
}

function validateForm(whichform) {
  for (var i=0; i<whichform.elements.length; i++) {
    var element = whichform.elements[i];
    if (element.className.indexOf("required") != -1) {
      if (!isFilled(element)) {
        alert("Please fill in the "+element.name+" field.");
        return false;
      }
    }
    if (element.className.indexOf("email") != -1) {
      if (!isEmail(element)) {
        alert("The "+element.name+" field must be a valid email address.");
        return false;
      }
    }
  }
  return true;
}

function isFilled(field) {
  if (field.value.length < 1 || field.value == field.defaultValue) {
    return false;
  } else {
    return true;
  }
}

function isEmail(field) {
  if (field.value.indexOf("@") == -1 || field.value.indexOf(".") == -1) {
    return false;
  } else {
    return true;
  }
}

function prepareForms() {
  focusLabels();
  for (var i=0; i<document.forms.length; i++) {
    var thisform = document.forms[i];
//    resetFields(thisform);
    thisform.onsubmit = function() {
      return validateForm(this);
    }
  }
}

addEvent(window,'load',JSTarget.init);
addEvent(window,'load',prepareForms);



/**
* Add this script to document that use <input autofocus type="text" />
* or <input type="text" placeholder="username" /> and it'll plug support for browser
* without these attributes
* modified version of http://gist.github.com/330318
*/
function extendInputs() {
  if (!document.getElementsByTagName) return false;
	var i = document.createElement('input'), inputs = $$('input');
	if (inputs.length < 0) return false;
	if (!('placeholder' in i)) {
		// placeholder fix
		inputs.each(function (el) {
			// note - we're using el instead of this across the board because it compresses better
			var lastValue = el.value, placeholder = el.getAttribute('placeholder');
			if(placeholder) {
				el.addClassName('placeholder');			
				var focus = function () {
					if (el.value == placeholder) {
						el.value = '';
						el.removeClassName('placeholder');
					}
				};
		 
				var blur = function () {
					if (el.value == '') {
						el.value = placeholder;
						el.addClassName('placeholder');
					}
				};
				
				Event.observe(el,'focus', focus);
				Event.observe(el,'blur', blur);
				
				// remove the placeholder if the page is reload or the form is submitted
				Event.observe(el.form,'submit', function () { focus.call(el); });
				Event.observe(window, 'unload', function () { focus.call(el); });
				
				// set the default state
				if (el.value == '') {
					blur.call(el);
				}
			}
		});
	}
	if (!('autofocus' in i)) {
		// auto focus
		inputs.each(function (el) {
			if (el.getAttribute('autofocus') != null) {
				el.focus();
				return false; // "there can only be one"
			}
		});
	}
}

window.onload=function() {
extendInputs();
}
