var ua = navigator.userAgent.toLowerCase();
var isFirefox = ( (ua.indexOf('mozilla/5')!=-1) && ( (navigator.vendor=="Firefox") || (ua.indexOf('firefox')!=-1) ) ) ? true : false;
var isOpera = (ua.indexOf('opera') != -1) ? true : false;
var isSafari = (ua.indexOf('safari') != -1) ? true : false;
var isIE6 = (ua.indexOf('msie') != -1 && parseFloat(ua.split('msie')[1]) < 7) ? true : false;


addDOMLoadEvent = (function(){
   var load_events = [],
       load_timer,
       script,
       done,
       exec,
       old_onload,
       init = function () {
           done = true;
           clearInterval(load_timer);
           while (exec = load_events.shift())
               exec();
           if (script) script.onreadystatechange = '';
       };

   return function (func) {
       if (done) return func();

       if (!load_events[0]) {
           if (document.addEventListener) document.addEventListener("DOMContentLoaded", init, false);
           // for Internet Explorer
           /*@cc_on @*/
           /*@if (@_win32)
               document.write("<script id=__ie_onload defer src=//0><\/scr"+"ipt>");
               script = document.getElementById("__ie_onload");
               script.onreadystatechange = function() {
                   if (this.readyState == "complete")
                       init(); // call the onload handler
               };
           /*@end @*/

           // for Safari
           if (/WebKit/i.test(navigator.userAgent)) { // sniff
               load_timer = setInterval(function() {
                   if (/loaded|complete/.test(document.readyState))
                       init(); // call the onload handler
               }, 10);
           }
           // for other browsers set the window.onload, but also execute the old window.onload
           old_onload = window.onload;
           window.onload = function() {
               init();
               if (old_onload) old_onload();
           };
       }
       load_events.push(func);
   }
})();


if (!simonsen) var simonsen = {};

simonsen.widgets = {
	ZIP:"zip",
	EMAIL:"email",
	PHONE:"phone",
	NOTEMPTY:"notempty",
	patternButton: /\b(ncButton)\w*/,
	patternIcon: /\b(icon)\w*/,
	patternPhone: /^[4|9]{1}\d{7}$/,
	patternZip: /^\d{4}$/,
	patternEmail: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([,;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*/,
	patternNotEmpty: /^.+[ \t\n.]*/,
	fieldHeight: "20",
	buttonHeight: "20",
	activeSelect:null,
	init: function() {
		var classpattern = new RegExp('(^| )'+'ncWidget'+'( |$)');
		var i=0;
		// Clear float after all forms with the class ncWidget
		var forms = document.getElementsByTagName("form");
		for(i = 0; i < forms.length; i++) {
			var form = forms[i];
			if(classpattern.test(form.className)) {
				var clearboth = document.createElement("div");
				clearboth.className = "ncClearBoth";
				insertAfter(clearboth, form);
			}
		}
		
		/****** CUSTOM SELECT IMPLEMENTATION ******/
		var selects = document.getElementsByTagName("select");
		for(i = 0; i < selects.length; i++) {
			var select = selects[i];
			if(classpattern.test(select.className) && !select.multiple) {
				var selectbox = new simonsen.widgets.Selectbox(select);
			}
		}
		
		var inputs = document.getElementsByTagName("input");
		var span = Array();
		for(a = 0; a < inputs.length; a++) {
			if((inputs[a].type == "text" || inputs[a].type == "password") && classpattern.test(inputs[a].className)) {
				var field = inputs[a];
				var fw = getStyle(field, 'width');
				var left = document.createElement("span"); left.className = "textinputLeft";
				var right = document.createElement("span"); right.className = "textinputRight";
				var wrapper = document.createElement("span"); wrapper.className = "textinputWrapper";
				
				var iconresult = simonsen.widgets.patternIcon.exec(field.className);
				var icon = document.createElement("span");
				icon.className = (iconresult != null) ? "iconDefault " + iconresult[0] : "iconNone";

				insertAround(field, wrapper);
				field.parentNode.insertBefore(left, field);
				field.parentNode.insertBefore(icon, field);
				field.parentNode.insertBefore(right, field.nextSibling);
				field.className = "textinputField";
				field.defaultColor = getStyle(field, 'color');
				
				if(wrapper.nextSibling.nodeName == "BR") {
					wrapper.style.marginRight = "0px";
					var clearboth = document.createElement("div");
					clearboth.className = "ncSuperClear";
					wrapper.parentNode.replaceChild(clearboth, wrapper.nextSibling);
				}
				
				if(fw != null && fw != 'auto'){
					if(isIE6){
						field.style.width = parseInt(fw) - (iconresult != null ? 35 : 17) + 'px';
					}else{
						field.style.width = parseInt(fw) - (iconresult != null ? 35 : 14) + 'px';
					}
					wrapper.style.width = fw;
				}else if(field.size){
					wrapper.style.width = field.size * 10 + 'px';
				}else{
					field.style.width = '80px';
					wrapper.style.width = '100px';
				}

				if(navigator.userAgent.toLowerCase().indexOf('safari') > -1){
					field.style.paddingTop = "1px";
				}else if(navigator.userAgent.toLowerCase().indexOf('opera') > -1){
					field.style.paddingTop = "0px";
				}
				field.onfocus = function() {
					this.parentNode.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight + "px";
					this.nextSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight + "px";
					this.previousSibling.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight + "px";
					this.style.color = "#6b6b6b";
					hideErrorMessage();
				}
				field.onblur = function() {
					this.parentNode.style.backgroundPosition = "0 0";
					this.nextSibling.style.backgroundPosition = "0 0";
					this.previousSibling.previousSibling.style.backgroundPosition = "0 0";
				}
				field.onerror = function() {
					if(this.disabled != true){
						this.parentNode.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight*2 + "px";
						this.nextSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight*2 + "px";
						this.previousSibling.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight*2 + "px";
						this.style.color = "#e12813";
					}
				}
				field.enable = function(){
					this.disabled = false;
					this.style.color = "#6b6b6b";
					this.parentNode.style.backgroundPosition = "0 0";
					this.nextSibling.style.backgroundPosition = "0 0";
					this.previousSibling.style.backgroundPosition = "0 0";
					this.previousSibling.previousSibling.style.backgroundPosition = "0 0";
				}
				field.disable = function(){
					this.disabled = true;
					this.style.color = "#cccccc";
					this.parentNode.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight*3 + "px";
					this.nextSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight*3 + "px";
					this.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight + "px";
					this.previousSibling.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.fieldHeight*3 + "px";
				}
				if(field.disabled) field.disable();
			}else if((inputs[a].type == "submit" || inputs[a].type == "reset" || inputs[a].type == "button") && classpattern.test(inputs[a].className)) {
				var button = inputs[a];
				
				var arr = simonsen.widgets.patternButton.exec(button.className);
				var buttonClass = (arr != null) ? "ncButton " + arr[0] : "ncButton";
				var left = document.createElement("div"); left.className = (arr != null) ? "ncButtonLeft " + arr[0]+"Left" : "ncButtonLeft";
				var right = document.createElement("div"); right.className = (arr != null) ? "ncButtonRight " + arr[0]+"Right" : "ncButtonRight";
				
				button.parentNode.insertBefore(left, button);
				button.parentNode.insertBefore(right, button.nextSibling);
				button.className = (arr != null) ? "ncButton " + arr[0] : "ncButton";
				
				var ow = button.style.width;
				if(typeof(ow) != 'undefined' && ow != null && ow != 'auto' && ow != ''){
					var lw = getStyle(left, 'width');
					lw = (lw != null && lw != 'auto') ? parseInt(lw) : 0;
					var rw = getStyle(right, 'width');
					rw = (rw != null && rw != 'auto') ? parseInt(rw) : 0;
					button.style.width = parseInt(ow) - lw - rw + "px";
				}
				
			/*	if(right.nextSibling.nodeName == "BR") {
					right.style.marginRight = "0px";
					var clearboth = document.createElement("div");
					clearboth.className = "ncSuperClear";
					right.parentNode.replaceChild(clearboth, right.nextSibling);
				}
 */				
				button.onmouseover = function(){
					this.style.color = "#FFFFFF";
					this.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight + "px";
					this.nextSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight + "px";
					this.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight + "px";
				}
				button.onmouseout = function(){
					this.style.color = "#878787";
					this.style.backgroundPosition = "0 0";
					this.nextSibling.style.backgroundPosition = "0 0";
					this.previousSibling.style.backgroundPosition = "0 0";
				}
				button.onmousedown = function(){
					this.style.color = "#d4e0a7";
					this.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight*2 + "px";
					this.nextSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight*2 + "px";
					this.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight*2 + "px";
				}
				button.onmouseup = function(){
					this.style.color = "#FFFFFF";
					this.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight + "px";
					this.nextSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight + "px";
					this.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight + "px";
				}
				button.enable = function(){
					this.disabled = false;
					this.onmouseout();
					this.style.cursor = this.nextSibling.style.cursor = this.previousSibling.style.cursor = "pointer";
				}
				button.disable = function(){
					this.disabled = true;
					this.style.color = "#dbdbdb";
					this.style.backgroundPosition = this.nextSibling.style.backgroundPosition = this.previousSibling.style.backgroundPosition = "0 -" + simonsen.widgets.buttonHeight*3 + "px";
					this.style.cursor = this.nextSibling.style.cursor = this.previousSibling.style.cursor = "default";
				}
				
				if(button.disabled) button.disable();
				
				if(isSafari) button.style.paddingTop = "1px";
			}
		}
	},
	validate: function(value, type) {
		switch(type){
			case simonsen.widgets.PHONE: return simonsen.widgets.patternPhone.test(value);
			case simonsen.widgets.EMAIL: return simonsen.widgets.patternEmail.test(value);
			case simonsen.widgets.ZIP: return simonsen.widgets.patternZip.test(value);
			case simonsen.widgets.NOTEMPTY: return simonsen.widgets.patternNotEmpty.test(value);
		}
		return true;
	}
}

simonsen.widgets.Selectbox = function(o){
	
	/*** Methods ***/
	this.open = function(){
		if(typeof(console) != 'undefined') console.log('simonsen.widgets.Selectbox.open()');
		this.box.style.display = "block";
		if(simonsen.widgets.activeSelect != null) simonsen.widgets.activeSelect.wrapper.style.zIndex = 1;
		simonsen.widgets.activeSelect = this;
		this.wrapper.style.zIndex = 2;
		document.onmousedown = this.forceclose;
	};
	
	this.close = function(opt){
		if(typeof(console) != 'undefined') console.log('simonsen.widgets.Selectbox.close() => ' + opt.index + ' | ' + opt.value + ' | ' + opt.text);
		document.onmousedown = null;

		this.original.options[opt.index].selected = true;
		this.original.onchange();
		
		if(this.selected) this.selected.style.backgroundPosition = "-5000px 8px";
		this.selected = opt;
		
		this.box.style.display = "none";
		var offset = Math.abs(parseInt( this.content.style.top ));
		if(isNaN(offset) || offset <= 10){
			this.box.style.top = -10 - (opt.index*this.optionHeight) + "px";
		}else{
			this.box.style.top = -10 - (opt.index*this.optionHeight) + offset + "px";
		}
		opt.style.backgroundPosition = "9px 8px";
		this.select.firstChild.nextSibling.innerHTML = opt.text;
	};
	
	this.forceclose = function(e){
		var target = (e && e.target) || (event && event.srcElement);
		var outside = true;
		while(target.parentNode){
			if(target == simonsen.widgets.activeSelect.wrapper){
				outside = false;
				break;
			}
			target = target.parentNode;
		}
		if(outside){
			if(typeof(console) != 'undefined') console.log('simonsen.widgets.Selectbox.forceclose()');
			document.onmousedown = null;
			simonsen.widgets.activeSelect.box.style.display = "none";
		}
	};
	
	this.enable = function(){
		this.original.disabled = false;
		this.select.firstChild.style.backgroundPosition = "0 0";
		this.select.firstChild.nextSibling.style.color = "#878787";
		this.select.firstChild.nextSibling.nextSibling.style.backgroundPosition = "0 0";
		this.select.onmouseup = this.open.bind(this);
		this.select.style.cursor = "pointer";
		this.select.style.backgroundPosition = "0 0";
	};
	
	this.disable = function(){
		this.original.disabled = true;
		this.select.firstChild.style.backgroundPosition = "0 -21px";
		this.select.firstChild.nextSibling.style.color = "#a99e9a";
		this.select.firstChild.nextSibling.nextSibling.style.backgroundPosition = "0 -21px";
		this.select.onmouseup = null;
		this.select.style.cursor = "default";
		this.select.style.backgroundPosition = "0 -21px";
	};
	
	this.getText = function(){
		if(this.original.options.length > 0){
			if(this.original.selectedIndex > -1) return this.original.options[this.original.selectedIndex].text;
			return this.original.options[0].text;
		}
		return "";
	};
	
	this.startScroll = function(value){
		this.stopScroll();
		this.scrollId = setInterval(this.doScroll.bind(this, value), 100);
	};
	
	this.stopScroll = function(){
		if(this.scrollId != null) clearInterval(this.scrollId);
	};
	
	this.doScroll = function(value){
		var pos = parseInt(getStyle(this.content, 'top')) + value;
		if(pos > this.minScroll){ pos = this.minScroll; this.stopScroll(); }
		if(pos < this.maxScroll){ pos = this.maxScroll; this.stopScroll(); }
		this.content.style.height = (pos == this.minScroll) ? this.boxHeight + Math.abs(pos) - this.minScroll + "px" : this.boxHeight + Math.abs(pos) + "px";
		this.content.style.top = pos + "px";
	};
	
	/*** Properties ***/
	this.selected = null;
	this.scrollId = null;
	this.optionHeight = 30;
	this.original = o;
	this.original.disable = this.disable.bind(this);
	this.original.enable = this.enable.bind(this);
	this.original.style.display = "none";
	this.wrapper = createStyledElement('div', 'ncSelectWrapper');
	this.select = createStyledElement('div', 'ncSelect', '<div class="ncSelectLeft"></div><p>' + this.getText()  +'</p><div class="ncSelectRight"></div>');
	this.select.onmouseup = this.open.bind(this);
	this.box = createStyledElement('div', 'ncOptionBox', '<div class="ncOptionBox_topright"><div class="ncOptionBox_topleft"></div></div><div class="ncOptionBox_content"><div class="ncOptionBox_scrollup"></div><div class="ncOptionBox_inner"></div><div class="ncOptionBox_scrolldown"></div></div>');
	this.content = this.box.childNodes[1].childNodes[1];
	this.scrollup = this.box.childNodes[1].childNodes[0];
	this.scrolldown = this.box.childNodes[1].childNodes[2];
	
	this.wrapper.appendChild(this.select);
	this.wrapper.appendChild(this.box);
	
	insertAfter(this.wrapper, this.original);
	var ow = getStyle(this.original, 'width');
	if(ow != null && ow.indexOf('px') != -1){
		this.selectWidth = parseInt(ow);	
	}else{
		this.selectWidth = 250;
	}
	if(typeof(console) != 'undefined') console.log("this.selectWidth: " + this.selectWidth);
	
	this.wrapper.style.width = this.selectWidth + "px";
	this.content.style.width = this.selectWidth - 6 + "px";
	
	var i=0;
	for(i = 0; i < this.original.options.length; i++) {
		var opt = createStyledElement('div', 'ncOption', this.original.options[i].text);
		opt.index = i;
		opt.value = this.original.options[i].value;
		opt.text = this.original.options[i].text;
		opt.onmouseup = this.close.bind(this, opt);
		opt.onmouseover = function(){
			this.style.color = "#FFFFFF";
			this.style.backgroundColor = "#a5c526";
		}
		opt.onmouseout = function(){
			this.style.color = "#878787";
			this.style.backgroundColor = "#FFFFFF";
		}
		
		if(!isFirefox) opt.style.padding = "4px 23px 5px 23px";
		
		if(i == this.original.selectedIndex && this.original.selectedIndex != 0){
			opt.style.backgroundPosition = "9px 8px";
			this.selected = opt;
		}
		this.content.appendChild(opt);
	}
	
	// Getting and checking height setting
	this.maxSelectHeight = 10 + this.original.options.length*this.optionHeight + 16;	
	var oh = getStyle(this.original, 'height');
	if(oh != null && oh.indexOf('px') != -1){
		this.selectHeight = parseInt(oh);
	}else{
		if(this.original.size){
			this.selectHeight = 10 + parseInt(this.original.size)*this.optionHeight + 16;
		}else{
			this.selectHeight = this.maxSelectHeight;
		}	
	}
	// Catch for if the height wasn't found properly as is the case for Safari
	if(this.selectHeight < 40) this.selectHeight = 250;
	
	if(this.selectHeight > this.maxSelectHeight) this.selectHeight = this.maxSelectHeight;
	if(this.selectHeight > 800) this.selectHeight = 800;
	
	if(typeof(console) != 'undefined') console.log("this.selectHeight: " + this.selectHeight);
	
	this.boxHeight = this.selectHeight - 16;
	this.contentHeight = this.original.options.length*this.optionHeight;
	this.minScroll = 10;
	this.maxScroll = this.boxHeight - this.contentHeight;
	
	this.content.style.height = this.boxHeight + "px";
	this.content.parentNode.style.height = this.selectHeight - 8 + "px";
	
	if(this.contentHeight > this.boxHeight){
		this.scrollup.onmouseover = this.startScroll.bind(this, this.optionHeight);
		this.scrollup.onmouseout = this.stopScroll.bind(this);
		this.scrolldown.onmouseover = this.startScroll.bind(this, this.optionHeight*-1);
		this.scrolldown.onmouseout = this.stopScroll.bind(this);
	}else{
		this.scrollup.style.display = "none";
		this.scrolldown.style.display = "none";
	}
	
	// position selected item and box
	if(this.selected != null){
		if(this.contentHeight > this.boxHeight){
			var pos = this.boxHeight/2 - (this.original.selectedIndex*this.optionHeight);
			if(pos > 10) pos = 10;
			this.content.style.top = pos + "px";
			this.content.style.height = (pos < 10) ? this.boxHeight + Math.abs(pos) + "px" : this.boxHeight + "px";
		}
		
		var offset = Math.abs(parseInt( this.content.style.top ));
		if(isNaN(offset) || offset <= 10){
			this.box.style.top = -10 - (this.original.selectedIndex*this.optionHeight) + "px";
		}else{
			this.box.style.top = -10 - (this.original.selectedIndex*this.optionHeight) + offset + "px";
		}
		
	}
	
	// Fix for extra padding on top of elements in ie6
	if(isIE6) this.box.firstChild.firstChild.style.padding = "0 0 0 4px";
	if(this.original.disabled) this.disable();
	
	return this;
}

function showErrorMessage(message){
	var elm = document.getElementById('errormessage');
	if(typeof(elm) != 'undefined' && elm != null){
		elm.innerHTML = "<p>" + message + "</p>";
		elm.style.display = "block";
	}
}
			
function hideErrorMessage(){
	var elm = document.getElementById('errormessage');
	if(typeof(elm) != 'undefined' && elm != null){
		elm.style.display = "none";
	}
}

function getStyle(elm, styleProp){
	if(elm.currentStyle){
		return elm.currentStyle[styleProp];
	}else if(window.getComputedStyle){
		return document.defaultView.getComputedStyle(elm, null).getPropertyValue(styleProp);
	}
	return null;
}

function getSelectText(select){
	if(select.options.length > 0){
		if(select.selectedIndex > -1) return select.options[select.selectedIndex].text;
		return select.options[0].text;
	}
	return "";	
}


function createStyledElement(type, style, inner){
	var elm = document.createElement(type);
	if(typeof(style) == "string") elm.className = style;
	if(typeof(inner) == "string") elm.innerHTML = inner;
	return elm;
}

function insertAround(elt, newelt){
	var parent = elt.parentNode;							// get parent
	parent.replaceChild(newelt, elt);					// new replaces old
	newelt.appendChild(elt);								// old becomes child
}

function insertAfter(node, reference) {
	var parent = reference.parentNode;
	parent.insertBefore(node, reference.nextSibling);
}

Function.prototype.bind = function(obj) {
	var method = this;
	var args = Array.prototype.slice.call(arguments, 1, arguments.length);
	var temp = function() {
		return method.apply(obj, args);
	};
	return temp;
}


// Make sure we call the init method as soon as the dom is loaded
addDOMLoadEvent(simonsen.widgets.init);