/**
 * yourfleece.com - global.js
 *
 * @author      Mooner <michael {at} g-fighter.com>
 * @copyright   2011 Michael Shamoon
 */
 
window.onload = init;

function init() {
    var formInputs = document.getElementsByTagName('input');
    for (var i = 0; i < formInputs.length; i++) {
        var theInput = formInputs[i];
        
        if (theInput.type == 'text' && theInput.className.match(/\bcleardefault\b/)) {
            addEvent(theInput, 'focus', clearDefaultText, false);
            addEvent(theInput, 'blur', replaceDefaultText, false);
            if (theInput.value != '') {
                theInput.defaultText = theInput.value;
            }
        }
        
        if (theInput.type == 'text' && theInput.className.match(/\bqty\b/)) {
            addEvent(theInput, 'blur', onQtyBlur, false);
            addEvent(theInput, 'keypress', onQtyEnter, false);
        }
    }
}
	
function addEvent(element, eventType, lamdaFunction, useCapture) {
	if (element.addEventListener) {
		element.addEventListener(eventType, lamdaFunction, useCapture);
		return true;
	} else if (element.attachEvent) {
		var r = element.attachEvent('on' + eventType, lamdaFunction);
		return r;
	} else {
		return false;
	}
}

function clearDefaultText(e) {
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	if (!target) return;
	
	if (target.value == target.defaultText) {
		target.value = '';
	}
}

function replaceDefaultText(e) {
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	if (!target) return;
	
	if (target.value == '' && target.defaultText) {
		target.value = target.defaultText;
	}
}

function onQtyBlur(e) {
	var target = window.event ? window.event.srcElement : e ? e.target : null;
	if (!target) return;
	clamp(target);
}

function onQtyEnter(e){
	var key = e.keyCode || e.which;
	if (key == 13) clamp(e.target);
}

function clamp(inputField) {
	if (Number(inputField.value) % 1 != 0) {
		var converted = parseFloat(inputField.value); // Make sure we have a number 
		var decimal = (converted - parseInt(converted, 10)); 
		decimal = Math.round(decimal * 10);
		var newValue;
		if (decimal == 5) newValue = (parseInt(converted, 10) + 0.5);
		if ( (decimal < 3) || (decimal > 7) ) newValue = Math.round(converted); 
		else newValue = (parseInt(converted, 10) + 0.5);
		if (newValue == 0) newValue = .5;
		inputField.value = newValue;
	}
}
