/****
THIS FILE MAY ONLY CONTAIN NON_SPECIFIC FUNCTIONS
FUNCTIONS THAT CAN BE USED ON ANY SITE OR PAGE
WITH NO REFERENCE TO, OR USAGES FOR SPECIFIC ELEMENTS
****/

/**
 * This function makes it easier to addEvent withou overwriting allready attached events to an element
 *
 * @param $element The element to which the event gets attached
 * @param $type The event type, without 'on-' so it's just 'click' or 'change', etc.
 * @param $function The function that gets attached, which can be passed inline
 * @param $bubbling Wether the event bubbles down to underlaying elements, I thought .. not sure though
 */
function addEvent($element, $type, $function, $bubbling) {
    $bubbling = $bubbling || false;
    if (window.addEventListener) { // Standard
        $element.addEventListener($type, $function, $bubbling);
        return true;
    } else if (window.attachEvent) { // IE
        $element.attachEvent('on' + $type, $function);
        return true;
    } else {
        return false;
    }
}

// checks an array(haystack) for the presence of 1 item(needle)
function in_array(needle, haystack) {
    var found = false;
    for (key in haystack) {
        if (haystack[key] == needle) {
            found = true;
            break;
        }
    }
    return found;
}

/** REQUIRES PROTOTYPE **/
// populates a select with an array of options
// if selected value exists in $arrOptions, option remains selected
function select_setOptions($el, $arrOptions, $reset) {
    var $el = $($el);
    if (($reset == undefined) || ($reset != false)) {
        // get selected value
        var $selectedValue = $F($el);
        // save first item if it's got no value (because that would be something like '-- select --')
        if (($el.childElements()[0] != undefined) && (($el.childElements()[0].value == '') || ($el.childElements()[0].value == '0'))) {
            var $firstEl = $el.childElements()[0];
        }
        $el.childElements().invoke('remove');
        if ($firstEl != undefined) {
            // put back first item
            $el.insertBefore($firstEl, null);
        }
    }
    // insert all new options
    for ($key in $arrOptions) {
        if (typeof($arrOptions[$key]) != 'object') {
            if ($key == $selectedValue) {
                var $option = new Element('option', {'value': $key, 'selected': 'selected'});
            } else {
                var $option = new Element('option', {'value': $key});
            }
            $option.update($arrOptions[$key]);
            $el.insertBefore($option, null);
        }
    }
}

// sets the value in a select
function select_setValue($el, $selected) {
    var options = $el.options;
    var value;
    for (i=0; i<options.length; i++) {
        value = options[i].value;
        if (value==$selected) {
            options[i].selected = true;
        }
    }
}

/**
* Returns the value of the selected radio button in the radio group, null if
* none are selected, and false if the button group doesn't exist
*
* @param {radio Object} or {radio id} el
* OR
* @param {form Object} or {form id} el
* @param {radio group name} radioGroup
*/
function $RF(el, radioGroup) {
    if($(el).type && $(el).type.toLowerCase() == 'radio') {
        var radioGroup = $(el).name;
        var el = $(el).form;
    } else if ($(el).tagName.toLowerCase() != 'form') {
        return false;
    }

    var checked = $(el).getInputs('radio', radioGroup).find(
        function(re) {return re.checked;}
    );
    return (checked) ? $F(checked) : null;
}

function convertFloat(input, replacement) {
    rExpIn = /,/;
    rExpOut = /\./;
    switch (replacement) {
        case ".":
            regExp = rExpIn;
            var parse = true;
            break;
        case ",":
            regExp = rExpOut;
            var parse = false;
            break;
    }
    var output = new String(input);
    output = output.replace(regExp, replacement);
    if (parse) {
        output = parseFloat(output);
    }
    return output;
}

function roundFloat(input) {
    rExpIn = /,/;
    var output = new String(input);
    output = output.replace(rExpIn, ".");

    output = output * Math.pow(10, 2);
    output = Math.round(output);
    output = output / Math.pow(10, 2);

    rExpOut = /\./;
    var output = new String(output);
    output = output.replace(rExpOut, ",");

    output = new String(output);
    var position = output.indexOf(","); //Find the comma or point
    if (position<0) {
        output = output+",00";
    }
    else {
        if (output.substr(position+1).length == 1) {
            output = output+"0";
        }
    }
    return output;
}

function trim(value) {
    value = value.replace(/^\s+/,'');
    value = value.replace(/\s+$/,'');
    return value;
}

/**
*   Toggles an element in a fancy way (BlindUp/BlindDown)
*   @param  The element that is clicked (this)
*   @param  The element that is to be toggled
*   @param  The amount of miliseconds used to Blind
*/
function fancyToggle($clickElement, $toggleElement, $duration) {
    $clickElement = $($clickElement);
    $toggleElement = $($toggleElement);
    // don't toggle whilst toggling
    if ($toggleElement.readAttribute('toggling') == '1') {
        return false;
    }
    // calculate duration / timeout
    var $timeout = $duration;
    $duration = $duration/1000;
    // save and unset the onclick to avoid interuptions
    if ($toggleElement.visible()) {
        if (!isClientIE7()) {
            // set element to status toggling
            $toggleElement.writeAttribute('toggling', '1');
            // do the fancy toggle
            Effect.BlindUp($toggleElement, {duration: $duration});
            // unset the status toggling
            setTimeout('$("'+$toggleElement.id+'").writeAttribute("toggling");', $timeout);
        }
        else {
            $toggleElement.hide();
        }
    }
    else {
        if (!isClientIE7()) {
            // set element to status toggling
            $toggleElement.writeAttribute('toggling', '1');
            // do the fancy toggle
            Effect.BlindDown($toggleElement, {duration: $duration});
            // unset the status toggling
            setTimeout('$("'+$toggleElement.id+'").writeAttribute("toggling");', $timeout);
        }
        else {
            $toggleElement.show();
        }
    }
    return false;
}

function isClientIE7() {
    var isIE7 = false;
    //Test for IE 7
    if (Prototype.Browser.IE) {
        var ieVersion = navigator.appVersion.toLowerCase()
        if (ieVersion.indexOf("msie 7.")>0) {
            //Browser is version 7.X
            isIE7 = true;
        }
    }
    return isIE7;
}

function sanitizeForURL($value, $seperator) {
    if ($seperator == undefined) {
        $seperator = '-';
    }
    $value = trim($value.toLowerCase());
    $regex = new RegExp('[^a-z0-9]+', 'g');
    $value = $value.split($regex).join($seperator);
    $regexLTrimSeperator = new RegExp('^\\' + $seperator + '+');
    $value = $value.replace($regexLTrimSeperator,'');
    $regexRTrimSeperator = new RegExp('\\' + $seperator + '+$');
    $value = $value.replace($regexRTrimSeperator,'');
    return $value;
}

function urlencode(str) {
    // http://kevin.vanzonneveld.net
    str = (str+'').toString();
    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
        replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+').replace(/%2f/gi, '%252f');
}
