/**

    Process all FORM <INPUT> elements with id pattern "jsHint_*".
    If of type `text` OR `textarea` massign hint from `hintvalue` attribute
    and attach mouse events

*/

var jsHint_hintColor = '#aaaaaa';
var jsHint_normalColor = '';  // keep default


function cmtProcessJSHints() {
	var re = /^jsHint_\w+$/;
	cmtProcessJSHintsInternal(document.getElementsByTagName("input"), re);
	cmtProcessJSHintsInternal(document.getElementsByTagName("textarea"), re);

}

function cmtProcessJSHintsInternal(inputs, re){
    var aform = null, cform = null;

    for (var i = 0; i < inputs.length; ++i) {
        if (re.test(inputs[i].id)
            && inputs[i].hintvalue != ''){
            // set value:
            // alert(inputs[i].hintvalue);
            var hintVal = util_getCustomAttribute(inputs[i], 'hintvalue');
            if (inputs[i].value == ''){
                inputs[i].value = hintVal
	            // set hint text color:
	            inputs[i].style.color = jsHint_hintColor;

                // change password field to text:
                /*if (inputs[i].type == 'password'){
                	inputs[i].type = 'text';
                	inputs[i].oldType = 'password';
                }
                */
            }

            // register events:
            inputs[i].onfocus = cmtClearJsHintText;
            inputs[i].onblur = cmtRestoreJsHintText;

            cform = inputs[i].form;
            if (aform != cform){
                if (typeof(cform.onsubmit) != 'function'
                    || cform.onsubmit.toString().indexOf('cmtResetJSHintForm') == -1 ){
                    util_registerForOnsubmitExec(cform, cmtResetJSHintForm);
                }
                aform = cform;
            }
        }
    }
}

function cmtClearJsHintText(e){
    var source = util_getEventSource(e);
    if (source.value != '' && source.value == util_getCustomAttribute(source, 'hintvalue')){
	    source.value = '';
	    source.style.color = jsHint_normalColor;
        /*if (source.oldType == 'password'){
        	source.type = 'password';
        	source.oldType = null;
        }*/
    }
}

function cmtRestoreJsHintText(e){
    var source = util_getEventSource(e);
    if (source.value == ''){
        source.value = util_getCustomAttribute(source, 'hintvalue');
        source.style.color = jsHint_hintColor;
        /*if (source.type == 'password'){
        	source.type = 'text';
        	source.oldType = 'password';
        }*/
    }
}

function cmtResetJSHintForm(e){
    var form = util_getEventSource(e);
    if (!form.elements){
        return;
    }
    var elts = form.elements;
    for (var i = 0; i < elts.length; ++i){
        var hintVal = util_getCustomAttribute(elts[i], 'hintvalue');
        if (hintVal != null && hintVal.length > 0 && elts[i].value == hintVal){
            elts[i].value = '';
        }
    }
}


// register for onload
util_registerForOnloadExec(cmtProcessJSHints);

