var cache = {};
$(document).ready(function() {
    var copy = [];
    copy[0] = "<p>Dear SST,</p><p>My name is <%=cache.about.name%> and I represent <%=cache.about.company%>.</p>";
    copy[1] = "<p>We are in need of some help with <%=cache.project.project_type%>. <% if (cache.project.website_address) { %> My website address is: <%=cache.project.website_address%>.<% } %></p>";
    copy[2] = "<% if (cache.tasks) { %><p>In particular, we are looking for help with <% for ( var i = 0; i < cache.tasks.taskscheckbox.length; i++ ) { %> <%=cache.tasks.taskscheckbox[i]%><% if (i+1 < cache.tasks.taskscheckbox.length && cache.tasks.taskscheckbox.length !== i+2) { %>, <% } else if (cache.tasks.taskscheckbox.length === (i+2)) { %> and<% } else if (cache.tasks.taskscheckbox.length === 1) { %><% } %><% } %>.<% } %></p>";
    copy[3] = "<% if (cache.cost) { %><p>We would like this project finished in <%=cache.cost.time%> and our budget range is <%=cache.cost.budget%> depending on experience and strength of proposal.</p><% } %>";
    copy[4] = "<% if (cache.description) { %><p><%=cache.description.project_description%></p><% } %>";
    copy[5] = "<p>Thank you for your time and interest in our project. I can be reached by phone at <%=cache.contact.phone_number%> or via email at <%=cache.contact.email_address%></p><% if (cache.about) { %><p>Yours,<br><%= cache.about.name%></p><% } %>";
    copy[6] = "<% if (cache.found.who) { %>  <p>P.S. <%=cache.found.who%> liked me so much that they told me about Stone Soup. </p><% } else { %>  <p>P.S. <%=cache.found.found_us%> </p> <% } %>";


    // Banner animations
    jQuery.easing.def = "easeOutSine";

    if ($("#rfp").length !== 0) {
    // Move the RFP email along side the window position on the form
    $(window).scroll(function () { 
        scroll();
      });
    // Enable ajax submission of the form
	/*
    $('#new_pitch').ajaxForm({
        dataType: "script",
        beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
      });
	*/
    // If it's a new site enable the url form
    $("#project_type").change(function () {
        //if ($(this).val() === 'an existing website') {
          //$("label[for='pitch_existing_site_url']").css({'color':'#000'});
         // $("input[id='website_address']").attr('disabled', false);
       // } else {
          //$("label[for='pitch_existing_site_url']").css({'color':'#ddd'});
         // $("input[id='website_address']").val('');
         // $("input[id='website_address']").attr('disabled', true);
       // }
      });
	
    // found us
    $("#found_us").change(function () {
        if ($(this).val() === 'Someone liked me so much that they told me about Stone Soup.') {
          $("input[id='who']").attr('disabled', false);
		  $("table[id='tbl_who']").css({'display':'block'});
        } else {
          $("input[id='who']").val('');
		  $("input[id='who']").attr('disabled', true);
		  $("table[id='tbl_who']").css({'display':'none'});
        }
      });


    var sect = $("#rfp .section");
    var si = $(" :input", sect);
	
	
	
    sect.each( function(i) {
        var id = $(this).attr("id");
        var inputs = $("#" + id + " :input");

		sectionComplete(id,inputs,i);
		var c = 0;
		formComplete(si, c);
		scroll();
		
        inputs.change(function() {
            var inputid = $(this).attr("id");
            var c = 0;
            //if(! validate(/^\b[A-Z0-9'\"._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i, '#pitch_contact_email', '#warn_eml')) {
            //  c--;
            //}
            //if(! validate(/(\d.*?){5,}/i, '#pitch_contact_telephone', '#warn_phn')) {
            //  c--;
            //}
				sectionComplete(id,inputs,i);
				formComplete(si, c);
				scroll();
          });
      });

    $("#description textarea").change(function() {
        count(this);
      });
    $("#description textarea").keydown(function() {
        count(this);
      });
      }
    // count - counts the number of words used in a textarea
    function count(val) {
      var a = $(val).val().split(' ').length;
      if (a === 1 ) {
        $("#words").text(a + " word ");
      } else if (a > 300 ) {
        $("#words").html("<b>" + a + " words</b>");
      } else {
        $("#words").text(a + " words ");
      }
    }
    /* 

     validate - check the value against the regex
    */
    function validate(regex, target, msg) {
          var v = $(target).val();
          if (v.length !== 0 && regex.exec(v) === null) {
            $(msg).fadeIn("slow");
            return false;
          } else {
            $(msg).fadeOut("slow");
            return true;
          }
    }
    /* 

     sectionComplete - checks the to see if each form input within a
     section has been complete, if the section is complete it calls
     write() to template out the copy[]
     */
    function sectionComplete(id, inputs, i) {
      var data = {};
      data.values = formData(id, inputs); 
      cache[id] = data.values; 

	  if (Object.size(cache[id])!==0) {
        write(data, copy[i], $("#message div:eq("+i+")"));
      } else {
        $("#message div:eq("+i+")").fadeOut("slow");
      }
      if (i === 0 && cache.contact) {
        write(data, copy[copy.length - 1], $("#message div:last"));
      }
    }
    /* 

     formData - get the values of each input and return them, but only
     when the section is complete or is a checkbox section
     */
    function formData(id, inputs) {
      var values = {};
      var chkd = [];
      inputs.each( function(){
          var type = this.type;
          var tag = this.tagName.toLowerCase();
          if (type === 'text' || type === 'password' || tag === 'textarea' || tag === 'select') {
            if ($(this).val().length!==0) {
              values[$(this).attr("id")] = sanitise($(this).val());
            }
          } else if (type === 'radio') {
            if (this.checked === true) {
              values[$(this).attr("id")] = $(this).val();
            }
          } else if (type === 'checkbox') {
            if (this.checked === true) {
              chkd.push($(this).val());
              values[id+type] = chkd;
            }
          }
        });

		if(id=="project" && document.getElementById("project_type")!="") {
			 return(values);
		  }

		if(id=="found" && document.getElementById("found_us")!="") {
			 return(values);
		  }

      if (Object.size(values)===(inputs.length - $("#" + id + " :disabled").length)) {
        return(values);
      } else if ($("#" + id + " :checkbox").length!==0) {
        return(values);
      } else {
        return(0);
      }
    }
    /*

     formComplete - checks to see if each available form input is
     complete, the show's submit button
     */
    function formComplete(si, c) {
      var a = si.length - $("#rfp .section :disabled").length;
      si.each( function() {
          var type = this.type;
          var tag = this.tagName.toLowerCase(); // normalize case
          if (type === 'text' || type === 'password' || tag === 'textarea' || tag === 'select') {
            if (this.value.length > 0) {
              c++;
            }
          } else if (type === 'checkbox' || type === 'radio') {
            a--;
            if (this.checked === true) {
              c++;
              a++;
            }
          }
        });
      if (c === a && ($(".submit").css("display") !== "block")) {
        $("p.submit").fadeIn("800");
      } else if (c < a) {
        $("p.submit").fadeOut("800");
      }
    }
    function scroll() {
      var st = $(window).scrollTop();
      var dh = $(document).height();
      var wh = $(window).height();
      var bh = $("#message").innerHeight();
      var fh = $("#rfp form").innerHeight();
      var fo = $("#top_bar").offset().top;
      var p = (st / (dh - wh));
      var y =  Math.round(((fh - bh) * (p)) - (fo * (1 - p)));
      y = Math.max(y,0);
      $("#message").animate({'top' : y},{duration:500,queue:false});
    }
    /*
     
     sanitise - Protect us from XSS http://ha.ckers.org/xss.html and
     give us our daily strings
     */
    function sanitise(str) {
      str = str
      .replace(/\;/g, "&#59;")
      .replace(/\(/g, "&#40;")
      .replace(/\)/g, "&#41;")
      .replace(/a/g, "&#97;")
      .replace(/</g, "&#60;")
      .replace(/\./g, "&#46;");
      return str;
    }
    /* 

     write - Write the copy to the page
     */
    function write(data, src, div) {
      $(div).fadeOut("fast", function callback() {
          var line = tmpl(src, data);
          $(this).html(line);
        });
      $(div).fadeIn("800");
    }
  });
/*

 What size(length) is an Object
 */
Object.size = function(obj) {
  var size = 0, key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      size++;
    }
  }
  return size;
};

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
    var cache = {};

    this.tmpl = function tmpl(str, data){
      // Figure out if we're getting a template, or if we need to
      // load the template - and be sure to cache the result.
      var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
      tmpl(document.getElementById(str).innerHTML) :

      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

          // Introduce the data as local variables using with(){}
          "with(obj){p.push('" +

          // Convert the template into pure JavaScript
          str
        .replace(/[\r\t\n]/g, " ")
        .split("<%").join("\t")
        .replace(/((^|%>)[^\t]*)'/g, "$1\r")
        .replace(/\t=(.*?)%>/g, "',$1,'")
        .split("\t").join("');")
        .split("%>").join("p.push('")
          .split("\r").join("\\'")
          + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn( data ) : fn;
      };
    })();

