//
// functions.js
// ------------


// change button text colour when hovered over

function btnClassicOver(btn){
    $(btn).addClassName("btnClassicOver");
}

function btnClassicOut(btn){
    $(btn).removeClassName("btnClassicOver");
}

// open popup windows

function makeWindow(strUrl, strChrome){
    var objWindow = window.open(strUrl, "", strChrome);
    if (navigator.appVersion.charAt(0) == "2" && navigator.appName == "Netscape") {
        objWindow = window.open(strUrl, "", strChrome)
    }
}

function makeKiosk(strURL){
    makeWindow(strURL, 'width=790,height=540,x=0,y=0,top=0,left=0,scrollbars=yes');
}

function makeSmallKiosk(strURL){
    makeWindow(strURL, 'width=500,height=360,x=0,y=0,top=0,left=0,scrollbars=yes');
}


// form data entry validation

function allowChars(strValue, strChars, blnCaseSense){
    strResult = "";
    if (blnCaseSense) {
        for (var i = 0; i < strValue.length; i++) {
            strChar = strValue.substr(i, 1);
            if (strChars.indexOf(strChar) > -1) {
                strResult += strChar;
            }
        }
    }
    else {
        strChars = strChars.toUpperCase();
        for (var i = 0; i < strValue.length; i++) {
            strChar = strValue.substr(i, 1);
            if (strChars.indexOf(strChar.toUpperCase()) > -1) {
                strResult += strChar;
            }
        }
    }
    return strResult;
}

function denyChars(strValue, strChars, blnCaseSense){
    strResult = "";
    if (blnCaseSense) {
        for (var i = 0; i < strValue.length; i++) {
            strChar = strValue.substr(i, 1);
            if (strChars.indexOf(strChar) == -1) {
                strResult += strChar;
            }
        }
    }
    else {
        strChars = strChars.toUpperCase();
        for (var i = 0; i < strValue.length; i++) {
            strChar = strValue.substr(i, 1);
            if (strChars.indexOf(strChar.toUpperCase()) == -1) {
                strResult += strChar;
            }
        }
    }
    return strResult;
}

function validEmail(emailStr){
    var emailPat = /^(.+)@(.+)$/ // check user@domain pattern
    var specialChars = "\\(\\)<>@,;:\\\\\\\"\\.\\[\\]" // check banned special chars
    var validChars = "\[^\\s" + specialChars + "\]" // check banned normal chars
    var quotedUser = "(\"[^\"]*\")" // check if username quoted
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/ // check ip format
    var atom = validChars + '+' // series of non special chars
    var word = "(" + atom + "|" + quotedUser + ")" // a word
    var userPat = new RegExp("^" + word + "(\\." + word + ")*$") // structure of username
    var domainPat = new RegExp("^" + atom + "(\\." + atom + ")*$") // structure of domain
    var matchArray = emailStr.match(emailPat)
    if (matchArray == null) {
        return false
    }
    var user = matchArray[1];
    var domain = matchArray[2];
    if (user.match(userPat) == null) {
        return false
    }
    var IPArray = domain.match(ipDomainPat)
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return false
            }
        }
        return true
    }
    var domainArray = domain.match(domainPat);
    if (domainArray == null) {
        return false
    }
    var atomPat = new RegExp(atom, "g");
    var domArr = domain.match(atomPat);
    var len = domArr.length;
    // test for length of final part of domain - now need to allow up to 6 chars (.museum)
    if (domArr[domArr.length - 1].length < 2 || domArr[domArr.length - 1].length > 6) {
        return false
    }
    if (len < 2) {
        return false
    }
    return true;
}


/* INPUT FIELD FOCUS & BLUR ACTIONS */

var inputFieldBackgroundColor;

function inputFieldFocus(field){
    // amended by devAT 2007-04-11
    // because IE7 breaks the onfocus handler when there is a background
    // colour change on a SELECT element, we have to prevent this happening.
    if (document.getElementById) {
        if (field.nodeName == "SELECT") {
            if (navigator.appVersion.indexOf('MSIE 7.0') != -1) {
                return
            }
        }
        inputFieldBackgroundColor = field.style.backgroundColor;
        field.style.backgroundColor = "#faf8f6";
    }
}

function inputFieldBlur(field){
    // amended by devAT 2007-04-11
    // see above - if we haven't changed the colour onfocus because of
    // the IE7 select bug, we shouldn't change it onblur either.
    if (document.getElementById) {
        if (field.nodeName == "SELECT") {
            if (navigator.appVersion.indexOf('MSIE 7.0') != -1) {
                return
            }
        }
        field.style.backgroundColor = inputFieldBackgroundColor;
    }
}


/* FORM BUTTON MOUSE ACTIONS */

function btnClassicOver(btn){
    btn.style.color = "#ff7717";
}

function btnClassicOut(btn){
    btn.style.color = "#0b3090";
}


/* FORM INITIAL FOCUS ACTION */

/* rewritten 2007-08-21 by devAT to avoid using element IDs */
/* the first element on the page with a className of "focusHere" */
/* will be given focus. if there is no such element, no error results. */
/* remember elements can have multiple space-separated class names  ;) */

function checkForFocus(){
    /* dependent on prototype 1.5.1.1 or better */
    if (document.getElementsByClassName('focusHere').length >= 1) {
        document.getElementsByClassName('focusHere').first().focus();
    }
}


/* POPUP WINDOWS */

function makeWindow(strUrl, strChrome){
    var objWindow = window.open(strUrl, "", strChrome);
    if (navigator.appVersion.charAt(0) == "2" && navigator.appName == "Netscape") {
        objWindow = window.open(strUrl, "", strChrome)
    }
}

function makeKiosk(strURL){
    makeWindow(strURL, 'width=780,height=540,x=0,y=0,top=0,left=0,scrollbars=yes');
}

function makeSmallKiosk(strURL){
    makeWindow(strURL, 'width=500,height=360,x=0,y=0,top=0,left=0,scrollbars=yes');
}




/* AJAX VALIDATION */

function highlightLabel(id){
    $(id).className = 'ajaxAlert';
}

function unHighlightLabel(id){
    $(id).className = 'ajaxLabel';
}

function validate(formName, field){
    var url = '/ajaxvalidator.do';
    var currentPage = document.forms[formName].currentPage.value;

    // construct an object with parameters
    var params = {
        f: formName,
        cp: currentPage,
        p: field.name,
        v: field.value
    }

    // convert parameters to hashmap and then to a URL encoded query string
    var pars = $H(params).toQueryString();

    //var pars = 'f=' + formName + '&cp=' + currentPage + '&p=' + field.name + '&v=' + field.value;
    var myAjax = new Ajax.Request(url, {
        method: 'post',
        parameters: pars,
        onComplete: showResponse
    });
}

function showResponse(originalRequest){
    //
    // get the response from the Ajax request
    // should be in the form 'field,message'
    //
    var strResponse = originalRequest.responseText;
    //
    // extract  the field name that it refers to
    //
    var strField = strResponse.substring(0, strResponse.indexOf(','));
    //
    // extract the message returned
    //
    var strMessage = strResponse.substring(strResponse.indexOf(',') + 1, strResponse.length);
    //
    // put the message in the alert div
    //
    $('id_' + strField).innerHTML = strMessage;
    //
    // and now change the class of the label div accordingly
    // this is new code added by devAT 2007-03-08
    //
    if (strMessage.length >= 1) {
        highlightLabel('id_label_' + strField);
    }
    else {
        unHighlightLabel('id_label_' + strField);
    }
}

function checkForAjaxAlerts(){
    //
    // function called on page load, to check for any prefilled Ajax alerts.
    // if it finds any, it sets the class of the corresponding label field
    // so that the label is highlighted as well.
    // added 2007-03-08 by devAT
    //
    var allDivs = document.getElementsByTagName('div');
    var divID = null;
    var div = null;
    for (var i = 0; i < allDivs.length; i++) {
        thisDiv = allDivs[i];
        thisDivID = thisDiv.id;
        if (thisDiv.id.indexOf('id_') == 0) {
            //
            // we have a div called 'id_*'
            //
            if (thisDiv.id.indexOf('id_label_') == -1) {
                //
                // and it's not called 'id_label_*'
                //
                if (thisDiv.innerHTML != '') {
                    //
                    // create the matching label name
                    //
                    thisLabelDivName = 'id_label_' + thisDivID.substr(3);
                    //
                    // and set the class so it goes red
                    //
                    highlightLabel(thisLabelDivName);
                }
            }
        }
    }
}


/* PASSWORD INPUT MATCHING - devAT, updated 2007-05-11 */

function MM_findObj(n, d){
    //v4.01
    var p, i, x;
    if (!d)
        d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all)
        x = d.all[n];
    for (i = 0; !x && i < d.forms.length; i++)
        x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++)
        x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById)
        x = d.getElementById(n);
    return x;
}

function checkForDifferentPasswords(strFieldName1, strFieldName2, strHelpDivID, strSecondLabelDivID){
    var strPassword1 = "";
    var strPassword2 = "";
    var inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++) {
        var strFieldName = inputs[i].name;
        if (strFieldName == strFieldName1) {
            strPassword1 = inputs[i].value;
        }
        if (strFieldName == strFieldName2) {
            strPassword2 = inputs[i].value;
        }
    }
    var objHelp = MM_findObj(strHelpDivID);
    if (strPassword1 != strPassword2) {
        if ((strPassword1 != "") && (strPassword2 != "")) {
            objHelp.innerHTML = strDifferentPasswordsMessage;
            highlightLabel(strSecondLabelDivID);
        }
        else {
            objHelp.innerHTML = strDefaultMessage;
            unHighlightLabel(strSecondLabelDivID);
        }
    }
    else {
        objHelp.innerHTML = strDefaultMessage;
        unHighlightLabel(strSecondLabelDivID);
    }
}

/* PERSONAL INFO CHECKBOX AUTOMATION - AJT 2007-04-02 */

function initialiseCheckBox(strID){
    if (document.getElementById) {
        if (document.getElementById(strID).value == "true") {
            document.getElementById(strID).checked = true;
        }
        else {
            document.getElementById(strID).checked = false;
        }
    }
}

function updateCheckBox(objElement){
    var strID = objElement.id;
    if (document.getElementById) {
        if (document.getElementById(strID).checked) {
            document.getElementById(strID).value = "true";
            //alert("control_" + strID + " now equals true");
        }
        else {
            document.getElementById(strID).value = "false";
            //alert("control_" + strID + " now equals false");
        }
    }
}


/* PERSONAL INFO PHONE COUNTRY CODE RELOADER - AJT 2007-04-09 */

function reloadPhoneCountryCode(arrayIndex, fieldID){
    if (!(phoneCountryLookup[arrayIndex] == undefined)) {
        //$(fieldID).value = phoneCountryLookup[arrayIndex];
        document.getElementById(fieldID).value = phoneCountryLookup[arrayIndex];
    }
    else {
        //$(fieldID).value = '';
        document.getElementById(fieldID).value = "";
    }
}

/* REVISED SPINNER CONTROL - AJT 2007-04-17 */

var blnNewSpinnerActivated = false;

function showNewSpinner(){
    if (document.getElementById) {
        if (document.getElementById("divNewSpinner")) {
            document.getElementById("divNewSpinner").style.visibility = "visible";
            // image reload required to show animation in IE7
            if (navigator.appVersion.indexOf('MSIE 7.0') != -1) {
                setTimeout('showNewSpinnerReload()', 50);
            }
            blnNewSpinnerActivated = true;
        }
    }
}

function showNewSpinnerReload(){
    if (document.images) {
        document.images["imgNewSpinner"].src = imgNewSpinner;
    }
}


/* added 2007-06-20, updated 2007-07-23 and 2007-08-28 by devAT */
function updateLandingCurrencyFees(){
    // get value of selected Option
    // set span to value of Array with selected Option as key
    strCurrency = '';
    if ($('prefCurrency')) {
        strCurrency = $('prefCurrency').options[$('prefCurrency').selectedIndex].value;
        if (feeLookup) {
            $('spnPrefCurrencyPayin').innerHTML = feeLookup[strCurrency + '_LOAD'];
            $('spnPrefCurrencyPayout').innerHTML = feeLookup[strCurrency + '_VIRTUAL_PAYOUT'];
            // if either is undefined, hide the row else show it
            if (!feeLookup[strCurrency + '_VIRTUAL_PAYOUT']) {
                $('rowPrefCurrencyPayout').hide();
            }
            else {
                $('rowPrefCurrencyPayout').show();
            }
            if (!feeLookup[strCurrency + '_LOAD']) {
                $('rowPrefCurrencyPayin').hide();
            }
            else {
                $('rowPrefCurrencyPayin').show();
            }
        }
    }
}

function getCheckedValues(checkObj){
    if (!checkObj) {
        return false;
    }
    var checkObjLength = checkObj.length;
    var values = new Array();
    if (checkObjLength == undefined) {
        return false;
    }
    for (var i = 0; i < checkObjLength; i++) {
        if (checkObj[i].checked) {
            if (checkObj[i].value != '') {
                values[i] = checkObj[i].value;
            }
        }
    }
    return values;
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj){
    if (!radioObj)
        return "";
    var radioLength = radioObj.length;
    if (radioLength == undefined)
        if (radioObj.checked)
            return radioObj.value;
        else
            return "";
    for (var i = 0; i < radioLength; i++) {
        if (radioObj[i].checked) {
            return radioObj[i].value;
        }
    }
    return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue){
    if (!radioObj)
        return;
    if (!newValue)
        return;
    var radioLength = radioObj.length;
    if (radioLength == undefined) {
        radioObj.checked = (radioObj.value == newValue.toString());
        return;
    }
    for (var i = 0; i < radioLength; i++) {
        radioObj[i].checked = false;
        if (radioObj[i].value == newValue.toString()) {
            radioObj[i].checked = true;
        }
    }
}

function ajax_get(url, callbackFunction, extra_vars){
    var request = new XMLHttpRequest(callbackFunction);
    request.open("GET", url, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    request.onreadystatechange = function(){
        var done = 4, ok = 200;
        if (request.readyState == done && request.status == ok) {
            if (request.responseText) {
                if (extra_vars) {
                    callbackFunction(request.responseText, extra_vars);
                }
                else {
                    callbackFunction(request.responseText);
                }
            }
        }
    };
    request.send(null);
}

function ajax_post(url, vars, callbackFunction){
    var request = new XMLHttpRequest();
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    request.onreadystatechange = function(){
        var done = 4, ok = 200;
        if (request.readyState == done && request.status == ok) {
            if (request.responseText) {
                callbackFunction(request.responseText);
            }
        }
    };
    request.send(vars);
}

function showDiv(divID){
    if (!divID)
        return;
    /*
     var elementList = document.getElementsByClassName("funding_type");
     for(var i=0;i<elementList.length;i++) {
     alert(divID +" == " + elementList[i].id);
     if(elementList[i].id.toUpperCase() == divID.toUpperCase())
     {
     alert("test"+elementList[i].id);
     elementList[i].style.display='block';
     }
     else
     {
     elementList[i].style.display='none';
     }
     }
     */
    switch (divID) {

        case '6':
            document.getElementById("card").style.display = "none";
            document.getElementById("easybuy_voucher").style.display = "none";
            document.getElementById("giropay").style.display = "block";
            break;

        case '5':
            document.getElementById("card").style.display = "none";
            document.getElementById("giropay").style.display = "none";
            document.getElementById("easybuy_voucher").style.display = "block";
            break;

        case '1':
        case '2':
        case '3':
        case '4':
        default:
            document.getElementById("card").style.display = "block";
            document.getElementById("easybuy_voucher").style.display = "none";
            document.getElementById("giropay").style.display = "none";
            break;
    }
}

function showMessage(message_div_id, message){
    if (!message || !message_div_id)
        return false;

    document.getElementById(message_div_id).innerHTML = message;
}

function toggle_div_visibility(id){
    var element = document.getElementById(id);

    if (element.style.display == 'block') {
        element.style.display = 'none';
    }
    else {
        element.style.display = 'block';
    }
}

function showDivById(groupName, divID) {
    if (!divID || !groupName)
        return false;
    var elementList = document.getElementsByName(groupName);

    for (var i = 0; i < elementList.length; i++) {
        if (elementList[i].id.toUpperCase() == divID.toUpperCase()) {
            elementList[i].style.display = 'block';
        }
        else {
            elementList[i].style.display = 'none';
        }
    }
}

function confirmAction(url, message) {
    if (confirm(message)) {
        location.href = url;
    }
}

function submitForm() {
	$(function() {
	   $('form').each(function() {
		   $(this).submit();
	      })
	   });
}

function disableForm() {
    var btnText;
    $(function() {
       $('form').each(function() {
          var $that = $(this);
          $(this).submit(function(){
	             var submitButton = $that.find("input[type='submit']");
	             btnText = $(submitButton).attr("value");
	             $(submitButton).attr("value", translations['please_wait'] + '...');
	             $(submitButton).attr("disabled", "true");
          });
       });
    });
}

function number_format(number, decimals, dec_point, thousands_sep){
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57

    var i, j;

    // input sanitation & defaults
    if (isNaN(decimals = Math.abs(decimals))) {
        decimals = 2;
    }
    if (dec_point == undefined) {
        dec_point = ".";
    }
    if (thousands_sep == undefined) {
        thousands_sep = " ";
    }

    i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

    if ((j = i.length) > 3) {
        j = j % 3;
    }
    else {
        j = 0;
    }

    return (j ? i.substr(0, j) + thousands_sep : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep) + (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
}

function round_float(float_num, dec_digits){
    if (dec_digits < 0) {
        return float_num;
    }

    var helper_float = Math.pow(10, dec_digits);

    return number_format(Math.round(float_num * helper_float) / helper_float, 2);
}

// * START admin_manage_security_constraints.tpl

//function insertOption(select_field, text, value) {
//  var elSel = document.getElementById(select_field);
//  if (elSel.selectedIndex >= 0) {
//    var elOptNew = document.createElement('option');
//    elOptNew.text = text;
//    elOptNew.value = value;
//    var elOptOld = elSel.options[elSel.selectedIndex];
//    try {
//      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
//    }
//    catch(ex) {
//      elSel.add(elOptNew, elSel.selectedIndex); // IE only
//    }
//  }
//}

function removeOptionSelected(select_field){
    var elSel = document.getElementById(select_field);
    var i;
    for (i = elSel.length - 1; i >= 0; i--) {
        if (elSel.options[i].selected) {
            elSel.remove(i);
        }
    }
}

function appendOptionFirst(select_field, text, value){
    var elOptNew = document.createElement('option');
    elOptNew.text = text;
    elOptNew.value = value;
    var elSel = document.getElementById(select_field);

    try {
        elSel.add(elOptNew, 0); // standards compliant; doesn't work in IE
    }
    catch (ex) {
        elSel.add(elOptNew, 0); // IE only
    }
}

function move_options_between_selects(select_field_from, select_field_to){
    var elSelFrom = document.getElementById(select_field_from);
    var elSelTo = document.getElementById(select_field_to);

    var i;
    for (i = elSelFrom.length - 1; i >= 0; i--) {
        if (elSelFrom.options[i].selected) {
            var elOptNew = document.createElement('option');
            elOptNew.text = elSelFrom.options[i].text;
            elOptNew.value = elSelFrom.options[i].value;

            try {
                elSelTo.add(elOptNew, elSelTo.options[0]); // standards compliant; doesn't work in IE
            }
            catch (ex) {
                elSelTo.add(elOptNew, 0); // IE only
            }

            elSelFrom.remove(i);
        }
    }
}

function compareText(option1, option2){
    return option1.text < option2.text ? -1 : option1.text > option2.text ? 1 : 0;
}

function sortlist(list_id){
    var select = document.getElementById(list_id);
    if (select == null) {
        return false;
    }
    var options = new Array(select.options.length);
    for (var i = 0; i < options.length; i++)
        options[i] = new Option(select.options[i].text, select.options[i].value, select.options[i].defaultSelected, select.options[i].selected);

    options.sort(compareText);
    select.options.length = 0;
    for (var i = 0; i < options.length; i++)
        select.options[i] = options[i];
}

//function removeOptionLast()
//{
//  var elSel = document.getElementById('selectX');
//  if (elSel.length > 0)
//  {
//    elSel.remove(elSel.length - 1);
//  }
//}
//-->

function select_check_all(select_field){
    var elSel = document.getElementById(select_field);
    var i;
    for (i = elSel.length - 1; i >= 0; i--) {
        elSel.options[i].selected = 1;
    }
}

// * END admin_manage_security_constraints.tpl

// * START admin_manage_consumers.tpl
function setMaxLength(){
    var x = document.getElementsByTagName('textarea');
    var counter = document.createElement('div');
    counter.className = 'counter';
    for (var i = 0; i < x.length; i++) {
        if (x[i].getAttribute('maxlength')) {
            var counterClone = counter.cloneNode(true);
            counterClone.relatedElement = x[i];
            counterClone.innerHTML = '<span>0</span>/' + x[i].getAttribute('maxlength');
            x[i].parentNode.insertBefore(counterClone, x[i].nextSibling);
            x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

            x[i].onkeyup = x[i].onchange = checkMaxLength;
            x[i].onkeyup();
        }
    }
}

function checkMaxLength(){
    var maxLength = this.getAttribute('maxlength');
    var currentLength = this.value.length;
    if (currentLength > maxLength)
        this.relatedElement.className = 'toomuch';
    else
        this.relatedElement.className = '';
    this.relatedElement.firstChild.nodeValue = currentLength;
    // not innerHTML
}

// * END admin_manage_consumers.tpl

// * START consumer_signup_payment.tpl
function showDiv_signup(divID){
    if (!divID)
        return;
    /*
     var elementList = document.getElementsByClassName("funding_type");
     for(var i=0;i<elementList.length;i++) {
     alert(divID +" == " + elementList[i].id);
     if(elementList[i].id.toUpperCase() == divID.toUpperCase())
     {
     alert("test"+elementList[i].id);
     elementList[i].style.display='block';
     }
     else
     {
     elementList[i].style.display='none';
     }
     }
     */
    switch (divID) {

        case '6':
            document.getElementById("card").style.display = "none";
            document.getElementById("easybuy_voucher").style.display = "none";
            document.getElementById("giropay").style.display = "block";
            document.getElementById("funding_type_text").innerHTML = 'Giropay Transfer';
            document.getElementById("funding_type_note").innerHTML = 'a Credit/Debit Card,&nbsp;<a href="#" onclick="javascipt:showDiv_signup(\'1\'); show_new_rates(\'1\');"><b>click here</b></a>&nbsp;';
            document.getElementById("funding_type_note_2").innerHTML = 'an EasyBuy Voucher,&nbsp;<a href="#" onclick="javascipt:showDiv_signup(\'5\'); show_new_rates(\'5\');"><b>click here</b></a>&nbsp;';
            setCheckedValue(document.forms['consumer_signup_payment_form'].elements['funding_type_id'], '6');
            break;

        case '5':
            document.getElementById("card").style.display = "none";
            document.getElementById("giropay").style.display = "none";
            document.getElementById("easybuy_voucher").style.display = "block";
            document.getElementById("funding_type_text").innerHTML = 'EasyBuy Voucher';
            document.getElementById("funding_type_note").innerHTML = 'a Credit/Debit Card,&nbsp;<a href="#" onclick="javascipt:showDiv_signup(\'1\'); show_new_rates(\'1\');"><b>click here</b></a>&nbsp;';
            document.getElementById("funding_type_note_2").innerHTML = 'an Giropay Transfer,&nbsp;<a href="#" onclick="javascipt:showDiv_signup(\'6\'); show_new_rates(\'6\');"><b>click here</b></a>&nbsp;';
            setCheckedValue(document.forms['consumer_signup_payment_form'].elements['funding_type_id'], '5');
            break;

        case '1':
        case '2':
        case '3':
        case '4':
        default:
            document.getElementById("easybuy_voucher").style.display = "none";
            document.getElementById("giropay").style.display = "none";
            document.getElementById("card").style.display = "block";
            document.getElementById("funding_type_text").innerHTML = 'Credit/Debit Card';
            document.getElementById("funding_type_note").innerHTML = 'an EasyBuy Voucher,&nbsp;<a href="#" onclick="javascipt:showDiv_signup(\'5\'); show_new_rates(\'5\');"><b>click here</b></a>&nbsp;';
            document.getElementById("funding_type_note_2").innerHTML = 'an Giropay Transfer,&nbsp;<a href="#" onclick="javascipt:showDiv_signup(\'6\'); show_new_rates(\'6\');"><b>click here</b></a>&nbsp;';
            setCheckedValue(document.forms['consumer_signup_payment_form'].elements['funding_type_id'], '1');
            break;
    }
}

function show_new_rates(divID){
    var message = '';

    switch (divID) {
        case '6':
            message = $('#id_message_container_3').text();
            break;

        case '5':
            message = $('#id_message_container_1').text();
            break;

        case '1':
        case '2':
        case '3':
        case '4':
        default:
            message = $('#id_message_container_2').text();
            break;
    }

    show_alert_msg(message, false);
}

// * END consumer_signup_payment.tpl


function utf8_string_compare(a, b) {
    var index = 0;
    while(a[index] && b[index] && a[index] == b[index]) {
        index++;
    }

    if (! b[index]) {
        return 1;
    } else if (! a[index]) {
        return -1;
    } else if (a[index] != b[index]) {
        return char_compare(a[index], b[index]);
    } else {
        return 0;
    }
}

function char_compare(a, b) {
    if (a == b) {
        return 0;
    }

    if ((a <= 'z' && a >= 'A') && (b >= 'A' && b <= 'z')) {
            if (a < b) return -1;
            if (a > b) return 1;
        } else if ((a >= 'A' && a <= 'z') && (b.toLowerCase() == 'ä' ||
                b.toLowerCase() == 'ö' || b.toLowerCase() == 'ü' || b == 'ß')) {
            if ((a.toLowerCase() <= 'a')) {
                return -1;
            } else if ((a.toLowerCase() <= 'o') && (b.toLowerCase() == 'ä')) {
                return 1;
            } else if ((a.toLowerCase() <= 'o') && (b.toLowerCase() != 'ä')) {
                return -1;
            } else if ((a.toLowerCase() <= 's') && (b.toLowerCase() == 'ä' ||
                b.toLowerCase() == 'ö')) {
                return 1;
            } else if ((a.toLowerCase() <= 's') && (b.toLowerCase() != 'ä' &&
                b.toLowerCase() != 'ö')) {
                return -1;
            } else if ((a.toLowerCase() <= 'u') && (b.toLowerCase() == 'ä' ||
                b.toLowerCase() == 'ö' || b == 'ß')) {
                return 1;
            } else if ((a.toLowerCase() <= 'u') && (b.toLowerCase() != 'ä' &&
                b.toLowerCase() != 'ö' && b != 'ß')) {
                return -1;
            } else {
                return 1;
            }
        } else if ((b >= 'A' && b <= 'z') && (a.toLowerCase() == 'ä' ||
                a.toLowerCase() == 'ö' || a.toLowerCase() == 'ü' || a == 'ß')) {
            if ((b.toLowerCase() <= 'a')) {
                return 1;
            } else if ((b.toLowerCase() <= 'o') && (a.toLowerCase() == 'ä')) {
                return -1;
            } else if ((b.toLowerCase() <= 'o') && (a.toLowerCase() != 'ä')) {
                return 1;
            } else if ((b.toLowerCase() <= 's') && (a.toLowerCase() == 'ä' ||
                a.toLowerCase() == 'ö')) {
                return -1;
            } else if ((b.toLowerCase() <= 's') && (a.toLowerCase() != 'ä' &&
                a.toLowerCase() != 'ö')) {
                return 1;
            } else if ((b.toLowerCase() <= 'u') && (a.toLowerCase() == 'ä' ||
                a.toLowerCase() == 'ö' || a == 'ß')) {
                return -1;
            } else if ((b.toLowerCase() <= 'u') && (a.toLowerCase() != 'ä' &&
                a.toLowerCase() != 'ö' && a != 'ß')) {
                return 1;
            } else {
                return -1;
            }
        } else {
            if ((a.toLowerCase() == 'ä') && (b != 'ä')) {
                return -1;
            } else if ((a.toLowerCase() == 'ä' || a.toLowerCase() == 'ö' ) && (b.toLowerCase() != 'ä' && b.toLowerCase() != 'ö')) {
                return -1;
            } else if ((a.toLowerCase() == 'ä' || a.toLowerCase() == 'ö' || a == 'ß') &&
                    (b.toLowerCase() != 'ä' && b.toLowerCase() != 'ö' && b != 'ß')) {
                return -1;
            } else {
                return 1;
            }
        }
}




function sort_countries(select_id) {
    var country_select = document.getElementById(select_id);
    selectedIndexValue = country_select.options[country_select.selectedIndex].value;

    var delimiters_array = new Array();

    for(i=0; i<country_select.length; i++){
        if (country_select.options[i].value.substring(0,1) == '-') delimiters_array[delimiters_array.length] = i;
    }

    delimiters_array[delimiters_array.length] = country_select.length;

    prev_delimiter = 0;

    for(i=0; i<delimiters_array.length; i++){
        scope_count = delimiters_array[i] - prev_delimiter - 1;
        scope_start = (prev_delimiter+1);
        scope_end = (delimiters_array[i]-1);
        prev_delimiter = delimiters_array[i];
        if (scope_count > 1) {
            partial_select_sort(country_select, scope_start, scope_end);
        }
    }

    for(i=0; i<country_select.length; i++){
        if (country_select.options[i].value == selectedIndexValue) {
            country_select.options[i].selected = true;
        }
        else {
            country_select.options[i].selected = false;
        }
    }

    function partial_select_sort(sort_select, sort_start, sort_end, selectedIndexValue) {
        tmp_arr = new Array();
        for (j=sort_start; j<sort_end+1; j++) {
            tmp_arr[tmp_arr.length] = sort_select.options[j].text+'|'+sort_select.options[j].value;
        }

        tmp_arr.sort(function(a, b) {return utf8_string_compare(a, b)});

        for(k=0; k<tmp_arr.length; k++){
            tmpsplitarr = tmp_arr[k].split("|");
            select_index = sort_start+k;
            sort_select.options[select_index].text = tmpsplitarr[0];
            sort_select.options[select_index].value = tmpsplitarr[1];
        }
    }
}

//Change card image by Card type id
var getCardTypeImageUrl  = 'common/ajax.php?main_object=consumer&action=get_card_type_image&card_type_id=';

function setCardTypeImage(selectElement, cardTypeId) {
	if (!cardTypeId){
		cardTypeId = $(selectElement).val();
	}

    var url = getCardTypeImageUrl + cardTypeId;
    var img_url = '';
    
    if (!cardTypeId) return;
    
    $.get(url, function(img) {
        if (img) {
            img_url = img;
            $('#card_preview_image').attr('src', img_url);
        }
    });
}