var ECube = new Object();


ECube.__onLoadFunctions = $A();
/********************************************************************************************

 registerOnLoadFunction(function) : will cause function to be executed
 during the dom:loaded event.
 unregisterOnLoadFunction(function) : will cause function to not be
 executed during the dom:loaded event
 
********************************************************************************************/
ECube.registerOnLoadFunction = function(fn) {
    ECube.__onLoadFunctions[ECube.__onLoadFunctions.length] = fn;
}
ECube.unregisterOnLoadFunction = function(fn) {
    var newFunctions = $A();
    ECube.__onLoadFunctions.each(function(item){
        if(item != fn){
            newFunctions[newFunctions.length] = item;
        };
    });
    ECube.__onLoadFunctions = newFunctions;
}


/********************************************************************************************

 formValidator(formObject) : an object that allows validation of forms using regular
 expressions in the mustmatch attribute of input fields. If the input field has an
 attribute errordisplay that holds the id of an element, that id will be shown if the
 input field value does not match the regular expression in its mustmatch attribute/ If
 the input field also has an attribute errormessage, the contents of this attribute will
 be shown in the element of which the id is in the attribute errordisplay.

 Note that *all* forms on the page will be validated on submit.
 
 customFormValidators : this is a hash that holds custom form validators for specific
 forms. The form name serves as the key. The value is the function that will be bound to
 the submit event for the form. Quite possibly you will want to use the formValidator
 object in your custom validator. To do this, use the following code:

 var validator = new ECube.formValidator(this);
 if(validator.hasErrors()) {
     window.event? event.returnValue = false : eventObject.preventDefault();
     validator.markErrors();
 };

 
********************************************************************************************/
ECube.formValidator = function(formObject) {
    var errors = $A();
    formObject.getElements().each(function(formElement){
        var mustMatch = formElement.readAttribute('mustmatch');
        if(mustMatch) {
            var matchingElem = $(mustMatch);
            if(matchingElem) {
                if(formElement.value != matchingElem.value) {
                    errors[errors.length] = formElement;
                }
            } else {
                if(formElement.readAttribute('errordisplay')){
                    var errorDisplay = $(formElement.readAttribute('errorDisplay'));
                    if(errorDisplay) {
                        errorDisplay.hide();
                    };
                };
                var mustMatchRE = new RegExp(mustMatch);
                if((formElement.readAttribute('type') == 'radio')  ||
                    (formElement.readAttribute('type') == 'radio')  ||
                    (formElement.readAttribute('type') == 'radio')) {
                    // radios, checkboxes and select-multiple don't work simply by looping through the form elements. if we
                    // encounter them, use old-fashioned form element looping to get their "value"
                    var value = '';
                    var inputName = formElement.readAttribute('name');
                    for(var i = 0, len = formObject.elements.length ; i < len ; ++i) {
                        var inputElement = formObject.elements[i];
                        if(inputElement.name == inputName) {
                            var inputType = inputElement.type;
                            if(inputType == 'radio') {
                                if(inputElement.checked) {
                                    value=inputElement.value;
                                };
                            };
                            if(inputType == 'checkbox') {
                                if(inputElement.checked) {
                                    value=inputElement.value;
                                };
                            };
                            if(inputType == 'select-multiple') {
                                value=inputElement.value;
                            };
                        }
                    };
                    if(! value.match(mustMatchRE)){
                        errors[errors.length] = formElement;
                    };
                } else {
                    if(! formElement.value.match(mustMatchRE)){
                        errors[errors.length] = formElement;
                    };
                };
            };
        };
    });
    this.hasErrors = function() {
        if(errors.length) {
            return true;
        } else {
            return false;
        };
    };
    this.getErrors = function() {
        return errors;
    };
    this.markErrors = function() {
        errors.each(function(errorElement) {
            // console.log(errorElement);
            if(errorElement.readAttribute('errordisplay')){
                var errorDisplay = $(errorElement.readAttribute('errordisplay'));
                if(errorDisplay) {
                    if(errorElement.readAttribute('errormessage')) {
                        errorDisplay.innerHTML = errorElement.readAttribute('errormessage');
                    };
                    errorDisplay.show();
                } else {
                    console.log('invalid error display object requested', errorElement.readAttribute('errordisplay'));
                };
            } else {
                if(errorElement.onErrorFunction) {
                    errorElement.onErrorFunction(formObject);
                };
            };
            errorElement.focus();
            throw $break;
        });
    };
}

ECube.customFormValidators = new Object();


ECube.registerOnLoadFunction(function(){
    $A(document.getElementsByTagName('FORM')).each(function(form){
        var customValidator = ECube.customFormValidators[form.name];
        if(customValidator) {
            $(form).observe('submit', customValidator);
        } else {
            $(form).observe('submit', function(eventObject){
                var validator = new ECube.formValidator(this);
                if(validator.hasErrors()) {
                    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
                    validator.markErrors();
                };
                validator = null;
            })
        };
    })
});


// input elements with class validate_email_input get attached a must match that is the correct RE for
// an email addres. This prevents having to type the same complicated RE again and again
ECube.registerOnLoadFunction(function(){
    $$('input.validate_email_input').each(function(inputElement){
        $(inputElement).writeAttribute('mustmatch', "^[^\\@\\s]+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,4})(\\]?)$");
    });
});


/**********************************************************************************
    
    Disable a form for a short while. Optionally do something when
    the form is disabled or when it is found the form is disabled
    
**********************************************************************************/
ECube.canSubmitIfNotSubmittedInLast = function(formObject, numSeconds, onDisableFunction, onIsDisabledFunction) {
    formObject = $(formObject);
    var d = new Date();
    var now = d.getTime();
    // getTime returns unix time in *milliseconds*
    var threshold = now - ( numSeconds * 1000) + 1;
    if(formObject.readAttribute('lastSubmittedOn')) {
        var lastSubmitted = formObject.readAttribute('lastSubmittedOn') * 1;
        if(( lastSubmitted * 1) > (threshold * 1)) {
            if(onIsDisabledFunction) {
                onIsDisabledFunction();
            };
            return false;
        } else {
            formObject.writeAttribute('lastSubmittedOn', now);
            if(onDisableFunction) {
                onDisableFunction();
            };
            return true;
        }
    } else {
        formObject.writeAttribute('lastSubmittedOn', now);
        if(onDisableFunction) {
            onDisableFunction();
        };
        return true;
    }
};

/**********************************************************************************
    
    dateValidator
    
    ECube.dateValidator.validate(day, month, year) 
**********************************************************************************/
ECube.dateValidator = new Object();
// which dates are valid?
ECube.dateValidator['validDates'] = new Object();
ECube.dateValidator['validDates']['1'] = '31';
ECube.dateValidator['validDates']['01'] = '31';
ECube.dateValidator['validDates']['2'] = '29';
ECube.dateValidator['validDates']['02'] = '29';
ECube.dateValidator['validDates']['3'] = '31';
ECube.dateValidator['validDates']['03'] = '31';
ECube.dateValidator['validDates']['4'] = '30';
ECube.dateValidator['validDates']['04'] = '30';
ECube.dateValidator['validDates']['5'] = '31';
ECube.dateValidator['validDates']['05'] = '31';
ECube.dateValidator['validDates']['6'] = '30';
ECube.dateValidator['validDates']['06'] = '30';
ECube.dateValidator['validDates']['7'] = '31';
ECube.dateValidator['validDates']['07'] = '31';
ECube.dateValidator['validDates']['8'] = '31';
ECube.dateValidator['validDates']['08'] = '31';
ECube.dateValidator['validDates']['9'] = '30';
ECube.dateValidator['validDates']['09'] = '30';
ECube.dateValidator['validDates']['10'] = '31';
ECube.dateValidator['validDates']['11'] = '30';
ECube.dateValidator['validDates']['12'] = '31';

ECube.dateValidator.validate = function(day, month, year) {
    if(day && month && year) {
        if((day * 1) > (ECube.dateValidator['validDates'][month] * 1) ) {
            return false;
        };
        if((month == '2') || (month == '02')) {
            if((day * 1) > 28) {
                if((year *1) % 400) {
                    if((year *1) % 4) {
                        return false;
                    };
                    return true;
                } else {
                    return false;
                }; 
            };
        };
        return true;
    };
    return true;
};






/**********************************************************************************
    
    input elements that have an attribute valuedefault 
    
**********************************************************************************/
ECube.registerOnLoadFunction(function(e) {
    var inputs = $A(document.getElementsByTagName('INPUT'));
    inputs.each(function(inputElem) {
        inputElem = $(inputElem);
        if(inputElem.readAttribute('valuedefault')) {
            inputElem.observe('click', function(eventObject){
                var value = this.value;
                var defaultValue = this.readAttribute('valuedefault');
                if(value == defaultValue) {
                    this.value = '';
                };
            });
        };
    });
})



/**********************************************************************************
    
    mouse over images. replace the source
    with the source appended with _hover onmouseover and _hover removed onmouseout
    works for all image types
    
**********************************************************************************/
ECube.setMouseOvers = function(item){
    if(item.src){
        item.observe('mouseover', function(eventObject){
            this.src = this.src.replace(/\.([a-z0-9A-Z]+)$/, '_hover.$1');
        });
        item.observe('mouseout', function(eventObject){
            this.src = this.src.replace(/_hover\.([a-z0-9A-Z]+)$/, '.$1');
        });
    }
}
// images that have a class hashover get their mouseovers set on page load
ECube.registerOnLoadFunction(function(e){
    $$('img.hashover').each(function(imgObject){
        ECube.setMouseOvers(imgObject);
    });
})




/**********************************************************************************

    selects met class onsubmitgotovalue gaan onsubmit naar de gekozen value.
    werkt ook met checkboxes (onclick)

**********************************************************************************/
ECube.registerOnLoadFunction(function(e){
    $$('select.onsubmitgotovalue').each(function(selectObj){
        selectObj.observe('change', function(eventObject){
            if(this.value) {
                location.href = this.value;
            }
        })
    })
    $$('input.onsubmitgotovalue').each(function(inputObj){
        if((inputObj['type'] == 'checkbox') || (inputObj['type'] == 'radio')){
            inputObj.observe('click', function(eventObject){
                if(this.value){
                    location.href = this.value;
                }
            })
        };
    })
})

/**********************************************************************************

    links met class alertonclick tonen een alert met de inhoud van het attribuut message

**********************************************************************************/
ECube.registerOnLoadFunction(function(e){
    $$('a.alertonclick').each(function(aObj){
        if(aObj.readAttribute('message')){
            aObj.observe('click', function(eventObject){
                window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
                alert(this.readAttribute('message'));
            });
        };
    })
})


/**********************************************************************************

    links met class showonclick en met class closeonclick. de ids ztten in
    attributen showonclick en hideonclick. eventueel kan er een functie
    worden meegegeven die wordt uitgevoerd met de div als parameter
    in showonclick_function en hideonclick_function

**********************************************************************************/
ECube.showAndCloseOnClick = new Object();
ECube.showAndCloseOnClick.showOnClick = function(eventObject){
    var idStringToShow = this.readAttribute('showonclick');
    if(! idStringToShow) {
        return true;
    };
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    var linkObj = this;
    $w(idStringToShow).each(function(idToShow){
        var divToShow = $(idToShow);
        // console.log('div to show is ', divToShow);
        if(divToShow) {
            // showonclick_function from the div itself overrules that of the link object
            var showFunction = linkObj['showonclick_function'];
            if(divToShow['showonclick_function']){
                showFunction = divToShow['showonclick_function'];
            };
            if(showFunction){
                showFunction(linkObj, divToShow);
            } else {
                divToShow.show();
            }
        };
    });
};
ECube.showAndCloseOnClick.closeOnClick = function(eventObject){
    var idStringToHide = this.readAttribute('closeonclick');
    if(! idStringToHide) {
        return true;
    };
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    var linkObj = this;
    // console.log('trying to hide ', idToHide);
    $w(idStringToHide).each(function(idToHide){
        var divToHide = $(idToHide);
        // console.log('div to hide is ', divToHide);
        if(divToHide) {
            var closeFunction = linkObj['hideonclick_function'];
            if(divToHide['hideonclick_function']){
                closeFunction = divToHide['hideonclick_function'];
            };
            if(closeFunction){
                closeFunction(linkObj, divToHide);
            } else {
                divToHide.hide();
            }
        };
    });
}

ECube.registerOnLoadFunction(function(e){
    $$("a.showonclick").each(function(linkObj){
        $(linkObj).observe("click", ECube.showAndCloseOnClick.showOnClick);
    });
    $$("a.closeonclick").each(function(linkObj){
        $(linkObj).observe("click", ECube.showAndCloseOnClick.closeOnClick);
    })
    
})

/**********************************************************************************
    
    Links that submit forms. Nasty as these are, designers like them. So:
    - links that have class "submitform" and the name of an existing form in
    an attribute formtosubmit submit the named form on click
    
**********************************************************************************/
ECube.formSubmitOnLinkClick = function(eventObject){
    window.event? event.returnValue = false : eventObject.preventDefault(); /* IE : standards */
    var formName = this.readAttribute('formtosubmit');
    if(! formName) {
        return false;
    };
    var formObj = document.forms[formName];
    if(! formObj) {
        return false;
    };
    var functionToCall = this.formsubmitfunction;
    if(functionToCall){
        functionToCall(formObj, eventObject);
    } else {
        formObj.submit();
    }
};
ECube.__register__formSubmitOnLinkClick = function(elementObj) {
    elementObj.observe('click', ECube.formSubmitOnLinkClick);
};
ECube.registerOnLoadFunction(function(e){
    $$('a.submitform').each(ECube.__register__formSubmitOnLinkClick);
});
// submitform


/**********************************************************************************
    
    Cookies . Code nicked from http://www.quirksmode.org/js/cookies.html
    
**********************************************************************************/

// document.cookie =
//  'ppkcookie1=testcookie; expires=Thu, 2 Aug 2001 20:47:11 UTC; path=/'
ECube.cookies = function(){
    var cookies = document.cookie.split(/;\s*/);
    for(var i = 0; i < cookies.length;i++){
        var pair = cookies[i].split("=");
        var name = pair[0];
        var value = pair[1];
        if(name != 'read' && name != 'create' && name != 'erase' && name != 'remove'){
            ECube.cookies[name] = value;
        };
    };
};
ECube.cookies.create = function(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

ECube.cookies.read = function(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

ECube.cookies.erase = function(name) {
	ECube.cookies.create(name,"",-1);
}
ECube.cookies.remove = ECube.cookies.erase;
ECube.cookies();

/**********************************************************************************
    
 Query variable fetching
    
**********************************************************************************/

ECube.queryVars = function(){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        var name = pair[0];
        var value = pair[1];
        if(name != 'read'){
            ECube.queryVars[name] = value;
        };
    };
};  
    
ECube.queryVars.read = function(name){
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
        var pair = vars[i].split("=");
        if (pair[0] == name) {
            return pair[1];
        }
    }
    return null;
}
ECube.queryVars();

/**********************************************************************************
    
    Done. Call the on load functions
    
**********************************************************************************/
document.observe("dom:loaded", function(e) {
    try {
        if(ECube.onLoadFunctionsMustWait){
           if(ECube.onLoadFunctionsCanRun) {
               ECube.__onLoadFunctions.invoke('call');
           } else {
               ECube.__onLoadTimeoutSafety = 0;
               ECube.__onLoadAttempt = function(){
                   if(ECube.onLoadFunctionsCanRun || ECube.__onLoadTimeoutSafety > 100){
                       ECube.__onLoadFunctions.invoke('call');
                   } else {
                       ECube.__onLoadTimeoutSafety++;
                       window.setTimeout(ECube.__onLoadAttempt, 50);
                   };
               };
               ECube.__onLoadAttempt();
           }
        } else {
            ECube.__onLoadFunctions.invoke('call');
        };
    } catch(err){
        console.log('An error occurred trying to invoke the on load functions : ', err);
        ECube.__onLoadFunctions.invoke('call');
    };
});


