/*****************************************************
*   contribution.js
*   Javascript used on the public facing contribution
*   pages and in the Control Panel (page_edit.php)
*
*****************************************************/

<!-- 

BSD.namespace("BSD.contribution");

BSD.contribution.paypal_button_handler = function() {
    var cc_number = $("cc_number");
    var cc_expir_month = $("cc_expir_month");
    var cc_expir_year = $("cc_expir_year");
    var payment_options = $("payment_options");
    var paypal_notice = $("paypal_notice");

    if (this.id == "radio_paypal") {

        YAHOO.util.Dom.setStyle(payment_options, "display", "none");
        YAHOO.util.Dom.setStyle(paypal_notice, "display", "block");

        // disabled form items don"t get sent with the POST
        
        cc_number.disabled = true;
        cc_expir_month.disabled = true;
        cc_expir_year.disabled = true;
    } else {

        YAHOO.util.Dom.setStyle(payment_options, "display", "block");
        YAHOO.util.Dom.setStyle(paypal_notice, "display", "none");

        cc_number.disabled = false;
        cc_expir_month.disabled = false;
        cc_expir_year.disabled = false;
    }
};

YAHOO.util.Event.onDOMReady(function() {

    // This toggles the credit card number / expir fields if someone
    // selects the PayPal radio button -- Josh K

    var radios = YAHOO.util.Dom.getElementsByClassName("cc_type_cd", "input");

    for (var i = 0; i < radios.length; i++) {
        YAHOO.util.Event.addListener(radios[i], "click", 
                                     BSD.contribution.paypal_button_handler);
        if (radios[i].checked) {
            BSD.contribution.fireEvent(radios[i], "click");
        }
    }
    
    BSD.contribution.registerAmountListeners();

    // Custom Country Field

    var country = document.getElementById("country");
    if (country) {
        YAHOO.util.Event.addListener(
            country, 'change', 
            BSD.contribution.custom_country_field_toggle
        );
    }

    var error_banner = YAHOO.util.Selector.query(".contriberrorbanner");
    if (error_banner[0] == undefined) {
        spud_populate(
            {country: 'country'},
            BSD.contribution.custom_country_field_toggle);
    }

    BSD.contribution.custom_country_field_toggle();
});

/**
 * Toggles the custom country fields to visible or hidden
 */

BSD.contribution.custom_country_field_toggle = function() {

    var country = document.getElementById('country');
    var default_country = document.getElementById('default_country');

    var cust_is_enabled_flags = [
        document.getElementById('custom_country_field_enabled_1'),
        document.getElementById('custom_country_field_enabled_2')
    ];

    var cust_country_tables = [
        document.getElementById('custom_country_field_table_1'),
        document.getElementById('custom_country_field_table_2')
    ];
       
    if (country && default_country) {

        for (var i = 0; i < cust_country_tables.length; i++) {
            
            if (!cust_country_tables[i] || !cust_is_enabled_flags[i]) {
                continue;
            }

            if (cust_is_enabled_flags[i].value == 0 || 
                (cust_is_enabled_flags[i].value == 1 && 
                 country.value == default_country.value)) {
                
                hide(cust_country_tables[i].id);
            }  else {
                show(cust_country_tables[i].id);
            }
        }
    }
}

BSD.contribution.errorHighlightLabel = function  (obj) {
  // this little JS hack highlights the last <label> added to the page.  this works around a limitation of QuickForm error display
  if (document.getElementsByTagName) {
    var elements = document.getElementsByTagName("label");
    if (elements && elements.length > 0) {
      elements.item(elements.length - 1).className="error";
    }
  }
}

BSD.contribution.clearother = function () {
    document.contribution.amount_other.value = "";
}

BSD.contribution.find_obj = function (n, d) { 
    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 = BSD.contribution.find_obj(n,d.layers[i].document);
    if (!x && d.getElementById)
        x = d.getElementById(n);
    return x;
}

BSD.contribution.isFunction = function (a) {
    return typeof a == "function";
}

BSD.contribution.isObject = function (a){
     return (typeof a == "object" && !!a) || BSD.contribution.isFunction(a);
 }                  

BSD.contribution.round_decimals = function (original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return BSD.contribution.pad_with_zeros(result3, decimals)
}

BSD.contribution.pad_with_zeros = function (rounded_value, decimal_places) {

    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if (decimal_location == -1) {
        
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else {

        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if (pad_total > 0) {
        
        // Pad the string with 0s
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }
    return value_string
}

BSD.contribution.total_tickets = function (intl_currency_symbol) {
    
    // do we have the currency data loaded already?  if not, load it and then recall this function
    var currency_data = BSD.utils.currency_manager.get_currency(intl_currency_symbol);
    
    if(currency_data == undefined) {
        BSD.utils.currency_manager.load_currency(
            intl_currency_symbol,
            {
                success: function() {
                    BSD.contribution.total_tickets(intl_currency_symbol);
                },
                failure: function() {
                    // do nothing
                }
            }
        );
        return;
    }
    var currency = BSD.utils.currency(currency_data);

    var total_cost = 0;
    var total_tickets = 0;
    var q = BSD.contribution.find_obj("t_q");
    var amountfield = BSD.contribution.find_obj("amount");
    var quantity = false;
    var x = 0;
    while(quantity = BSD.contribution.find_obj("q_"+x)){

        if(quantity.value != "" && !isNaN(quantity.value) && Math.floor(quantity.value) > 0){
            var amount = BSD.contribution.find_obj("c_"+x);
    
        
            total_cost = total_cost + (Math.floor(quantity.value)*amount.value)
            total_tickets += parseInt(Math.floor(quantity.value));
            quantity.value = Math.floor(quantity.value);
        }
        if(isNaN(quantity.value) || Math.floor(quantity.value) < 0) { quantity.value = "" }
        x++;
    }

    amountfield.value = BSD.contribution.round_decimals(total_cost,2);
    if(total_tickets > 1 || total_tickets == 0) {
        q.innerHTML = total_tickets + ' ' + total_label.pluralize() + " , " + currency.format_number(total_cost, "%n");
    } else {
        q.innerHTML = total_tickets + ' ' + total_label.pluralize().singularize() + " , " + currency.format_number(total_cost, "%n");
    }
}

BSD.contribution.fireEvent = function(elem, event) {
    if (elem.fireEvent) {
        // If IE, use the builtin fireEvent
        elem.fireEvent("on" + event);
    } else {
        // Othwerwise use the DOM Level 2 method of doing it
        var e;
        if (event == "click") {
            e = document.createEvent("MouseEvents");
            e.initMouseEvent("click", true, true, window,
                             0, 0, 0, 0, 0, false, false, false, false,
                             0, null);
        } else {
            e = document.createEvent("HTMLEvents");
            e.initEvent(event, true, true);
        }
        elem.dispatchEvent(e);
    }
}

BSD.contribution.registerAmountListeners = function() {
    var amount_total = document.getElementById("amount_total");
    if (amount_total) {
        var form = YAHOO.util.Dom.getAncestorByTagName(amount_total, "form");
        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i].name.search(/^amount.*/) >= 0) {
                YAHOO.util.Event.addListener(form.elements[i], "change", BSD.contribution.updateAmountTotal);
            }
        }
        BSD.contribution.updateAmountTotal();
    }
}

BSD.contribution.updateAmountTotal = function() {
    var amount_total = document.getElementById("amount_total");
    var form = YAHOO.util.Dom.getAncestorByTagName(amount_total, "form");
    var total = 0;
    var other_amount = 0;
    var other_checked = false;
    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];
        if (element.name.search(/^amount\[[0-9]*\]$/) >= 0 && element.checked) {
            total += parseFloat(element.value);
        } else if (element.name.search(/^amount_other_checkbox$/) >= 0 && element.checked) {
            other_checked = element.checked;
        } else if (element.name.search(/^amount_other$/) >= 0) {
            other_amount = element.value;
        }
    }
    if (other_checked) {
        total += BSD.contribution.parseAmount(other_amount);
    }
    amount_total.innerHTML = module_text.total_contribution_label+" $" + total.toFixed(2);
}

BSD.contribution.parseAmount = function(str) {
    str = str.replace(/[^0-9,.]/g);
    if (str.length >= 3) {
        var decimal = str.search(/[,.]\d\d?$/);
        if (decimal > 0) {
            cents = str.substr(decimal);
            str = str.substr(0, decimal).replace(/[^0-9]/g, "") + "." + cents.substr(1);
        } else {
            str = str.replace(/[^0-9]/g, "");
        }
    } else if (str.length == 0) {
        str = "0";
    }
    return parseFloat(str);
}

//-->
