/* =============================================================================
 * Constants for use in the site
 * ============================================================================= */
debug_mode                      = false; 
                                
/* ===========================================================================================================
 *                                LIVE VALUES                             TEST VALUES                        
 * =========================================================================================================== */
twf_paypal_html_host            = 'www.paypal.com';                    // 'www.sandbox.paypal.com';          
twf_paypal_email_address        = 'cassy@twilightwishfoundation.org';  // 'TWF_M_1273959333_biz@comcast.net';
                                                                                                             
one_time_donation_item_number   = '110';                               // '110';                             
one_time_donation_item_name     = 'Donation';                          // 'Donation';                        
                                                                                                             
comfort_wish_donation_title     = 'Comfort Wish Angel';                // 'Comfort Wish Angel';              
comfort_wish_donation_amount    = '11';                                // '11';                              
comfort_wish_hosted_button_id   = 'EAH6R8X9HZAQY';                     // 'GBEPJVKTZ68CG';                   
                                                                                                             
shining_moment_donation_title   = 'Shining Moment Angel';              // 'Shining Moment Angel';            
shining_moment_donation_amount  = '25';                                // '25';                              
shining_moment_hosted_button_id = '7YUAAU8CP9QXJ';                     // 'YQ8U5HG9RZ9YA';                   
                                                                                                             
big_dream_donation_title        = 'Big Dream Angel';                   // 'Big Dream Angel';                 
big_dream_donation_amount       = 'select';                            // 'select';                          
big_dream_hosted_button_id      = 'K9J484L9JRAR6';                     // 'YYVTCHP29SJRL';                   


/*
 * js function getElementsByClassName is not yet standard in all browsers (ie). 
 * If it is not present, add this function.
 */
if (!document.getElementsByClassName) {
  document.getElementsByClassName = function(given_class_name) {
    var retVal   = new Array();
    var elements = document.getElementsByTagName("*");
    for (var i = 0; i < elements.length; i++) {
      if (elements[i].className.indexOf(" ") >= 0) {
        var classes = elements[i].className.split(" ");
        for (var j = 0; j < classes.length; j++){
          if (classes[j] == given_class_name) {
            retVal.push(elements[i]);
          }
        }
      }
      else {
        if (elements[i].className == given_class_name) {
          retVal.push(elements[i]);
        }
      }
    }
    return retVal;
  };
}


/*
 * Attach your listener (a js function) to a specific event of a specific object.
 */
function addEvent(obj, evType, fn) {  
  if (obj.addEventListener) { 
    obj.addEventListener(evType, fn, false); 
    return true; 
  } 
  else {
    if (obj.attachEvent) { 
      var r = obj.attachEvent("on"+evType, fn); 
      return r; 
    } 
    else { 
      return false; 
    } 
  }
}

function replaceEntityCharsInString(given_string) {
  string_to_return = given_string;
  string_to_return = string_to_return.replace(/\u00a0/g, ' ');  // non breaking space
  return string_to_return;

}


function monthlyDonationButtonHTML(given_donation_title, given_donation_amount, given_donation_hosted_button_id) {
  given_donation_title = replaceEntityCharsInString(given_donation_title);

  html_to_return = '';
  html_to_return = html_to_return + "<strong>" + given_donation_title + "</strong><br />";
  html_to_return = html_to_return + "<form action='https://" + twf_paypal_html_host + "/cgi-bin/webscr' method='post'>";
  //                                   <!-- PayPal 'Technical HTML Variables' -->
  //                                   <!--   cmd:               REQUIRED:  specifies action to be taken.  The button is either protected from tampering by using encryption, or the is saved in the merchant’s PayPal account. PayPal determines which kind of button was clicked by decoding the encrypted code or by looking up the saved button in the merchant’s account.  -->
  //                                   <!--   notify_url:        optional:  The URL to which PayPal posts information about the transaction, in the form of Instant Payment Notification messages. -->
  //                                   <!--   bn:                optional:  An identifier of the source that built the code for the button that the payer clicked, sometimes known as the build notation -->
  //                                   <!--   hosted_button_id:  SPECIAL:  Required for buttons that have been saved in PayPal accounts; otherwise, not allowed., The identifier of a button that was saved in a merchant’s PayPal account.  -->
  html_to_return = html_to_return +   "<input name='cmd'              type='hidden' value='_s-xclick'/>";
  html_to_return = html_to_return +   "<input name='bn'               type='hidden' value='PP-DonationsBF:btn_donateCC_LG.gif:NonHostedGuest' />";
  html_to_return = html_to_return +   "<input name='hosted_button_id' type='hidden' value='" + given_donation_hosted_button_id + "' />";
  if (given_donation_amount == 'select') {
    html_to_return = html_to_return +   "<table>";
    html_to_return = html_to_return +     "<tr><td><input type='hidden' name='on0' value=''/></td></tr>";
    html_to_return = html_to_return +     "<tr><td>$<select name='os0'>";
    html_to_return = html_to_return +       "<option value='30' >30</option>";
    html_to_return = html_to_return +       "<option value='45' >45</option>";
    html_to_return = html_to_return +       "<option value='50' >50</option>";
    html_to_return = html_to_return +       "<option value='75' >75</option>";
    html_to_return = html_to_return +     "</select> per month</td></tr>";
    html_to_return = html_to_return +   "</table>";
    html_to_return = html_to_return +   "<input type='hidden' name='currency_code' value='USD'/>";
  }
  else {
    html_to_return = html_to_return +   "<table>";
    html_to_return = html_to_return +     "<tr><td>$" + given_donation_amount + " per month</td></tr>";
    html_to_return = html_to_return +   "</table>";
  }
  html_to_return = html_to_return +   "<br />";
  html_to_return = html_to_return +   "<input name='submit'           type='image'  src='/storage/images/buttons/monthly-donation-button.png' style='border: 0px solid #000; background: transparent;' alt='PayPal - The safer, easier way to pay online!' />";
  html_to_return = html_to_return +   "<img alt='' border='0' src='https://" + twf_paypal_html_host + "/en_US/i/scr/pixel.gif' width='1' height='1'/>";
  html_to_return = html_to_return + "</form>";

  if (debug_mode) {
    alert(html_to_return);
  }

  return html_to_return;
}

function oneTimeDonationButtonHTML(given_item_name, given_item_number, given_include_amount_choices) {
  if (!given_item_name) {
    given_item_name = one_time_donation_item_name;
  }
  given_item_name = replaceEntityCharsInString(given_item_name);
  if (!given_item_number) {
    given_item_number = one_time_donation_item_number;
  }


  html_to_return = '';
  html_to_return = html_to_return + "<form action='https://" + twf_paypal_html_host + "/cgi-bin/webscr' method='post'>";
  //                                   <!-- PayPal 'Technical HTML Variables' -->
  //                                   <!--   cmd:           REQUIRED:  specifies action to be taken ("Buy Now" button) -->
  //                                   <!--   notify_url:    optional:  The URL to which PayPal posts information about the transaction, in the form of Instant Payment Notification messages. -->
  //                                   <!--   bn:            optional:  An identifier of the source that built the code for the button that the payer clicked, sometimes known as the build notation -->
  html_to_return = html_to_return +   "<input name='cmd'           type='hidden' value='_xclick' />";
  html_to_return = html_to_return +   "<input name='bn'            type='hidden' value='PP-DonationsBF:btn_donateCC_LG.gif:NonHostedGuest' />";
  //                                   <!-- Paypal 'HTML Variables for Displaying PayPal Checkout Pages' -->  
  //                                   <!--   image_url:     optional:  The URL of the 150x50-pixel image displayed as your logo in the upper left corner of the PayPal checkout pages. -->
  //                                   <!--   cn:            optional:  Label that appears with "NOTE" field in PayPal -->
  //                                   <!--   no_shipping:   optional:  Do not prompt payers for shipping address. Allowable values: 0 – prompt for an address, but do not require one, 1 – do not prompt for an address, 2 – prompt for an address, and require one -->
  //                                   <!--   lc:            optional:  Pre-populates payment form, sets the payer’s language for the billing information/log-in page only. The default is US. -->
  //                                   <!--   cancel_return: optional:  A URL to which the payer’s browser is redirected if payment is cancelled. -->
  //                                   <!--   return:        optional:  The URL to which the payer’s browser is redirected after completing the payment -->
  //                                   <!--   rm:            optional:  Return method. The FORM METHOD used to send data to the URL specified by the return variable after payment completion. Allowable values: 0 – all shopping cart transactions use the GET method   1 – the payer’s browser is redirected to the return URL by the GET method, and no transaction variables are sent  2 – the payer’s browser is redirected to the return URL by the POST method, and all transaction variables are also posted  -->
  html_to_return = html_to_return +   "<input name='image_url'     type='hidden' />";
  html_to_return = html_to_return +   "<input name='cn'            type='hidden' value='Comments' />";
  html_to_return = html_to_return +   "<input name='no_shipping'   type='hidden' value='0' />";
  html_to_return = html_to_return +   "<input name='lc'            type='hidden' value='US' />";
  html_to_return = html_to_return +   "<input name='cancel_return' type='hidden' value='http://www.twilightwish.org/paypal-cancel-return' />";
  html_to_return = html_to_return +   "<input name='return'        type='hidden' value='http://www.twilightwish.org/paypal-return' />";
  html_to_return = html_to_return +   "<input name='rm'            type='hidden' value='2' />";
  //                                   <!-- Paypal Transaction-scope variables -->
  //                                   <!--   business:      REQUIRED:  Your PayPal ID or an email address associated with your PayPal account. Email addresses must be confirmed. -->                                                             
  //                                   <!--   custom:        optional:  User-defined field which will be passed through the system and returned in your merchant payment notification email. This field will not be shown to your subscribers. --> 
  //                                   <!--   currency_code: optional:  Currency of prices\amounts provided in these variables. -->                                                                                                                
  html_to_return = html_to_return +   "<input name='business'      type='hidden' value='" + twf_paypal_email_address + "' />";
  html_to_return = html_to_return +   "<input name='custom'        type='hidden' value='0' />";
  html_to_return = html_to_return +   "<input name='currency_code' type='hidden' value='USD' />";
  //                                   <!-- Paypal 'HTML Variables for Individual Items' -->
  //                                   <!--   item_name:    optional:  Description of item. If omitted, payers enter their own name at the time of payment. -->
  //                                   <!--   item_number:  optional: Pass-through variable for you to track product or service purchased or the contribution made. The value you specify passed back to you upon payment completion. -->
  //                                   <!--   amount:       optional:  Line Item extended value. -->  
  //                                   <!--   on0, os0:     optional:  custom option for item.  on0 is NAME\LABEL of option, os0 is corresponding VALUE --> 
  html_to_return = html_to_return +   "<input name='item_name'     type='hidden' value='" + given_item_name + "' />";
  html_to_return = html_to_return +   "<input name='item_number'   type='hidden' value='" + given_item_number + "' />";
  html_to_return = html_to_return +   "<table class='form_table'>";
  if (given_include_amount_choices) {
    html_to_return = html_to_return +   "<tr>";
    html_to_return = html_to_return +     "<td>Please select an amount to donate</td>";
    html_to_return = html_to_return +     "<td>";
    html_to_return = html_to_return +       "<select name='amount'>";
    html_to_return = html_to_return +         "<option selected='selected' value='25'>$25</option>";
    html_to_return = html_to_return +         "<option value='40'>$40</option>";
    html_to_return = html_to_return +         "<option value='100'>$100</option>";
    html_to_return = html_to_return +         "<option value='250'>$250</option>";
    html_to_return = html_to_return +         "<option value='500'>$500</option>";
    html_to_return = html_to_return +         "<option value='1000'>$1000</option>";
    html_to_return = html_to_return +         "<option value='5000'>$5000</option>";
    html_to_return = html_to_return +         "<option value='0'>Other</option>";
    html_to_return = html_to_return +       "</select>";
    html_to_return = html_to_return +     "</td>";
    html_to_return = html_to_return +   "</tr>";
  }
  html_to_return = html_to_return +     "<tr>";
  html_to_return = html_to_return +       "<td><input name='on0' type='hidden' value='List your name? ' />";
  html_to_return = html_to_return +         "Do you want your name displayed with your donation?</td>";
  html_to_return = html_to_return +       "<td>";
  html_to_return = html_to_return +         "<table>";
  html_to_return = html_to_return +           "<tr>";
  html_to_return = html_to_return +             "<td>";
  html_to_return = html_to_return +               "<input checked='checked' name='os0' type='radio' value='Yes' />";
  html_to_return = html_to_return +             "</td>";
  html_to_return = html_to_return +             "<td>Yes - List me as a Generous Donor</td>";
  html_to_return = html_to_return +           "</tr>";
  html_to_return = html_to_return +           "<tr>";
  html_to_return = html_to_return +             "<td>";
  html_to_return = html_to_return +               "<input name='os0' type='radio' value='No' />";
  html_to_return = html_to_return +             "</td>";
  html_to_return = html_to_return +             "<td>No - List my donation as from an Anonymous Donor</td>";
  html_to_return = html_to_return +           "</tr>";
  html_to_return = html_to_return +         "</table>";
  html_to_return = html_to_return +       "</td>";
  html_to_return = html_to_return +     "</tr>";
  html_to_return = html_to_return +   "</table>";
  html_to_return = html_to_return +   "<div style='text-align: center;'>";
  html_to_return = html_to_return +     "<input alt='PayPal - The safer, easier way to pay online!' name='submit' src='https://" + twf_paypal_html_host + "/en_US/i/btn/btn_donateCC_LG.gif' type='image' />";
  html_to_return = html_to_return +   "</div>";
  html_to_return = html_to_return +   "<img src='https://" + twf_paypal_html_host + "/en_US/i/scr/pixel.gif' border='0' alt='' width='1' height='1' />";
  html_to_return = html_to_return + "</form>";

  if (debug_mode) {
    alert(html_to_return);
  }

  return html_to_return;
}

/*
 *  Create and return a FORM with hidden information and a single button.
 *  When submitted, the form takes the user to PayPal to make a donation
 *  of the amount they choose referring to this specific wish.
 */
function createWishSpecificDonationButton(wish_id, wish_title) {
  var newdiv = document.createElement('div');
  newdiv.innerHTML = oneTimeDonationButtonHTML(wish_title, wish_id, false);
  return newdiv;
}

/*
 *  To be called at load of pages listing open wishes,
 *  create a button for each wish allowing people to make a 
 *  donation (through PayPal) to that specific wish.
 * 
 *  Each wish is assumed to be represented as a SquareSpace 
 *  journal entry.
 */
function createWishSpecificDonationButtons() {
  // Find all journal entries on the page.
  journal_entries = document.getElementsByClassName('journal-entry-text');
  // For each journal entry (that is, each wish):
  // (1) Collect information from the wish (title, wish_id)
  // (2) Create PayPal single-button form to make a donation toward this wish
  // (3) Add that button to the bottom of the wish body.
  var a_list;
  for (i = 0; i < journal_entries.length; i++) {
    wish = journal_entries[i];

    wish_title    = null;    // Text title of the wish
    title_element = null;    // DOM element containing the title (H2 within journal-entry-text)
    a_list = wish.getElementsByTagName('h2');
    if (a_list.length > 0) {
      title_element = a_list[0];
      wish_title = title_element.getElementsByTagName('a')[0].innerHTML;
    }


    wish_id      = null;     // ID for the wish
    body_element = null;     // DOM element containing the wish description (including the ID)
    a_list = wish.getElementsByTagName('div');
    if (a_list.length > 0) {
      body_element = a_list[0];
      // The wish_id is in the "id" attribute of one of the "span" elements within the body_element.
      //  -- the one whose value begins with the text "wish_id_".
      a_list = body_element.getElementsByTagName('span');
      for (j = 0; j < a_list.length; j++) {
        a_span_element = a_list[j];
        an_attribute = a_span_element.attributes.getNamedItem("id");
        if (an_attribute && (an_attribute.value.search(/^wish_id_/) >= 0)) {
          wish_id = an_attribute.value.substring(8);
        }
      }
    }

    if (!!wish_title && !!wish_id) {
      button = createWishSpecificDonationButton(wish_id, wish_title);
      body_element.appendChild(button);
    }
  }
}


if (location.pathname.toLowerCase().search(/^\/open-wishes\/?/) >= 0) {
  if (!(addEvent(window, 'load', createWishSpecificDonationButtons))) {
    if (debug_mode) {
      alert('Unable to create donation buttons on this page:  addEvent returns false.');
    }
  }
}



