/*******************************************************************************
 * Slow home test Javascript implementation.
 *
 * This javascript implementation calculates slow home scores, packages them up
 * into a comment submission as well as submitting them to a google spreadsheet
 * for the purposes of more easily analyzing the results afterwards.
 * 
 * Author: Lakin Wecker, Structured Abstraction Inc.
 * Copyright: © 2010 Slow Home
 * 
 ******************************************************************************/

/*******************************************************************************
 * Configuration:
 *  form_id: Set this to the id of the form - must not start with a '#'
 *                   Default: "commentform"
 *  comment_form_url: The url of the place where comments are posted.
 *  google_form_url: The url of the place where google results are posted.
 *  form_weights: An object that maps input names to score values.
 *  form_names: An object that maps input names to label names.
 *  required_fields: An object that maps input names to their required
 *                           status.
 *  google_field_mapping: A mapping of field names from the slowhome
 *                                form to the google form.
 ******************************************************************************/

var sh_test_config = {
  form_id: "commentformtest",
  comment_form_url: "/wp-comments-post.php",
 // google_form_url: "/wp-content/themes/slowhome2010/google-form-submit.php?google_form_url=http://spreadsheets.google.com/formResponse?formkey=dHp1S0ZvYnlWY2tzVDZ5YV9YNVJrMGc6MA&ifq",
  google_form_url: "/wp-content/themes/slowhome2010/slowform_submit.php",
  form_weights: {
    Location: { "Y": 3, "N": 0 },
    Orientation: { "Y": 3, "N": 0 },
    Organization: { "Y": 2, "N": 0 },
    Circulation: { "Y": 2, "N": 0 },
    Entry: { "Y": 1, "N": 0 },
    Living: { "Y": 1, "N": 0 },
    "Outdoor Living": { "Y": 1, "N": 0 },
    Kitchen: { "Y": 1, "N": 0 },
    Dining: { "Y": 1, "N": 0 },
    Bedrooms: { "Y": 1, "N": 0 },
    Bathrooms: { "Y": 1, "N": 0 },
    Study: { "Y": 1, "N": 0 },
    Laundry: { "Y": 1, "N": 0 },
    Parking: { "Y": 1, "N": 0 }
  },
  form_names: {
    project_name: "Project Name",
    size: "Size",
    project_url: "Project URL",
    group1: "1 Location",
    group2: "2 Orientation",
    group3: "3 Organization",
    group4: "4 Circulation",
    group5: "5 Entry",
    group6: "6 Living",
    group7: "7 Outdoor Living",
    group8: "8 Kitchen",
    group9: "9 Dining",
    group10: "10 Bedrooms",
    group11: "11 Bathrooms",
    group12: "12 Study",
    group13: "13 Laundry",
    group14: "14 Parking",
    project_address: "Project Address"
	 },
  required_fields: {
    author: false,
    email: false,
    project_name: false,
    size: false,
    project_url: false,
    group1: false,
    group2: false,
    group3: false,
    group4: false,
    group5: false,
    group6: false,
    group7: false,
    group8: false,
    group9: false,
    group10: false,
    group11: false,
    group12: false,
    group13: false,
    group14: false
  },
  google_field_mapping: {
    Project: "Project",
    Size: 'Size',
    URL: 'URL',
    "Location": 'Location',
    "City": 'City',
    "Email": 'Email',
    "House Type": 'House Type',
    Orientation: 'Orientation',
    Organization: 'Organization',
    Circulation: 'Circulation',
    Entry: 'Entry',
    Living: 'Living',
    "Outdoor Living": 'Outdoor Living',
    Kitchen: 'Kitchen',
    Dining: 'Dining',
    Bedrooms: 'Bedrooms',
    Bathrooms: 'Bathrooms',
    Study: 'Study',
    Laundry: 'Laundry',
    Parking: 'Parking',
    "Additional Comments": 'Additional Comments',
    Score: 'Score',
    Author: 'Author',
    Address: 'Address'
  }
};

/*******************************************************************************
 * Comment Template: This template is used to format the comment that is
 *                   submitted to wordpress. 
 ******************************************************************************/
var slow_home_comment_template = '';
slow_home_comment_template += '<b>#{project_name_label}:</b> #{project_name}<br/>\n\n';
slow_home_comment_template += '<b>#{size_label}:</b> #{size}<br/>\n\n';
slow_home_comment_template += '<b>#{project_address_label}:</b> #{project_address}<br/>\n\n';
slow_home_comment_template += '<b>#{project_url_label}:</b> #{project_url}<br/>\n\n';
slow_home_comment_template += '<b>Slow Home Test Score:</b> #{total}<br/>\n\n';
slow_home_comment_template += '<br/>';
slow_home_comment_template += '<br/>';
slow_home_comment_template += '<b>Comment:</b> #{comment}<br/>\n\n';


/*******************************************************************************
 * For debugging - set this to true, and run with firebug and this app will
 * log a bunch of stuff to the firebug console. Keep this at false otherwise.
 ******************************************************************************/
var debug = false;

/*******************************************************************************
 * Handles Errors
 * The response is the full response from the server. If you want to put it
 * in a jQuery popup/lightbox, this is the place to do it.
 * One small issue is that response is a FULL HTML response - so you may
 * want to display it in an iframe or parse it to pull out just the body.
 ******************************************************************************/
function handler_form_submission_error(response) {
  if (debug) console.log("Error: ", response);
  alert(
"We're sorry, an error occured during your submission. Your comment may or may not have been received.\n\nPlease refresh this page. If you comment does not appear please submit it again.");
}

/*******************************************************************************
 * Submits the form
 ******************************************************************************/
function submit_form(event) {
  //event.preventDefault();
  var form = document.getElementById('sh_slowform');
  if (debug) console.log("Using form: ", form);

  for (var name in sh_test_config.required_fields) {
    var required = sh_test_config.required_fields[name];
    if (required) {
      var element = dojo.query('[name='+name+']')[0];
      if (dojo.attr(element, 'type') == 'radio') {
        var value = !!dojo.query("[name="+name+"]:checked").length;
      } else {
        var value = element.value;
      }
      if(debug) console.log(name, value);
      if (!value) {
        alert(sh_test_config.form_names[name] + " was left blank.\nPlease fill out all of the required fields.");
        return false;
      }
    }
  }

  submit_to_google(form);
  submit_to_slowhome(form);
  return false;
}

/*******************************************************************************
 * Calculates the score of the form based on the weightings.
 * Arguments:
 *  form: a javascript object as returned from dojo.formToObject()
 * Returns: Integer total of the score for this home.
 ******************************************************************************/
function calculate_score(form) {
  var total = 0;
  for (name in form) {
    var value = form[name];
    var weight = sh_test_config.form_weights[name];
    if (weight) {
      var score = weight[value];
      total += score;
    }
  }
  return total;
}

/*******************************************************************************
 * Submits the form to google
 ******************************************************************************/
function submit_to_google(form) {
  if(debug) console.log("Submitting to google:", form);

  var object = dojo.formToObject(form);
  //object['total'] = calculate_score(object);
  object['Score'] = calculate_score(object);

  var google_POST = {};
  for (var our_post_name in sh_test_config.google_field_mapping) {
    if(debug) console.log(our_post_name);
    google_POST[sh_test_config.google_field_mapping[our_post_name]] = object[our_post_name];
  }
  if(debug) console.log(google_POST);

  dojo.xhrPost({
    url: sh_test_config.google_form_url,
    content: google_POST
  });
}

/*******************************************************************************
 * Submits the form to slowhome
 ******************************************************************************/
function submit_to_slowhome(form) {
  if(debug) console.log("Submitting to slowhome:", form);

  var form_values = dojo.formToObject(form);
  var template_context = {};
  for (name in form_values) {
    var value = form_values[name];
    var score_property = name + "_score";
    var label_property = name + "_label";

    // Put the actual value in the context.
    template_context[name] = value;

    // Put the label in the context
    template_context[label_property] = sh_test_config.form_names[name];

    var weight = sh_test_config.form_weights[name];
    if (weight) {
      var score = weight[value];
      // Put the label in the context
      template_context[score_property] = score;
    }
  }
  template_context['total'] = calculate_score(form_values);


  var comment_text = basic_template(slow_home_comment_template, template_context);
  var comment_post = {
    author: dojo.byId('author').value,
    email: dojo.byId('email').value,
    comment: form_values['Additional Comments'],
    submit: "Submit Comment",
    //comment_post_ID: dojo.byId('comment_post_ID').value,
    comment_post_ID: 3869,
    comment_parent: 0,
    "_wp_unfiltered_comment": "8cb29b0bb5"
    //subscribe: dojo.byId('subscribe').checked
  }
  if (debug) console.log(comment_post);

  dojo.xhrPost({
    url: sh_test_config.comment_form_url,
    content: comment_post,
    error: handler_form_submission_error,
    load: function(response, ioArgs) {
        window.location.reload(true);
    }
  });

  if(debug) {
    dojo.place(comment_text, dojo.byId("debug"), "only");
  }
}

/*
 * Basic template integration based on:
 * jQuery Simple Templates plugin 1.1.1
 * But ported to dojo.
 *
 * http://andrew.hedges.name/tmpl/
 * http://docs.jquery.com/Plugins/Tmpl
 *
 * Copyright (c) 2008 Andrew Hedges, andrew@hedges.name
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */

function basic_template(template, values) {
  var regex, repr;
        
  // default to doing no harm
  template = template   || '';
  values = values || {};
        
  // regular expression for matching our placeholders; e.g., #{my-cLaSs_name77}
  regex = /#\{([^{}]*)}/g;
        
  // function to making replacements
  repr = function (str, match) {
    return typeof values[match] === 'string' || typeof values[match] === 'number' ? values[match] : str;
  };
      
  return template.replace(regex, repr);
}

/*******************************************************************************
 * Hooks into the necessary html form to process it on submit.
 ******************************************************************************/
function setup_callbacks() {
  if(debug) console.log("Setting up the initial callbacks for: ", sh_test_config.form_id);
  var form = dojo.byId(sh_test_config.form_id);
  if(debug) console.log("Found comment form: ", form);
  dojo.connect(form, 'onsubmit', submit_form);
}

dojo.addOnLoad(setup_callbacks);
