var cache = {};
$(document).ready(function() {
    var copy = [];
    copy[0] = "<p>Dear Banjax,</p><p>My name is <%=cache.about.pitch_name%> and I represent <%=cache.about.pitch_company%>.</p>";
    copy[1] = "<p>We are in need of some help with <% if (cache.project.pitch_existing_site_url) { %> an existing website, located at <a href=\"<%=cache.project.pitch_existing_site_url%>\"><%=cache.project.pitch_existing_site_url%></a>.<% } else { %> a new website.<% } %></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.description) { %><p><%=cache.description.pitch_description%></p><% } %>";
    copy[4] = "<% if (cache.cost) { %><p>We would like this project finished in <%=cache.cost.pitch_days%> and our budget range is <%=cache.cost.pitch_budget%> depending on experience and strength of proposal.</p><% } %>";
    copy[5] = "<p>Thank you for your time and interest in our project. I can be reached by phone at <%=cache.contact.pitch_contact_telephone%> or via email at <%=cache.contact.pitch_contact_email%></p><% if (cache.about) { %><p>Yours,<br><%= cache.about.pitch_name%></p><% } %>";

    // add map to footer
    if ($("#map_canvas").length !== 0) {
      if (GBrowserIsCompatible()) {
        var icon = new GIcon();
        icon.image = "/assets/i/marker.png";
        icon.shadow = "/assets/i/marker_shadow.png";
        icon.iconSize = new GSize(70, 23);
        icon.shadowSize = new GSize(70, 23);
        icon.iconAnchor = new GPoint(22, 23);

        var map = new GMap2(document.getElementById("map_canvas"));
        var point = new GLatLng(54.587837,-5.933036);
        map.setCenter(new GLatLng(54.588536,-5.933186), 14);
        map.setMapType(G_PHYSICAL_MAP);
        map.addOverlay(new GMarker(point, icon));
        map.addControl(new GSmallMapControl());
      }
    }

    // Banner animations
    jQuery.easing.def = "easeOutSine";
    $('#greet').css({backgroundPosition: '40% 0',
        opacity: 0
      });
    $('#greet .inner').css({backgroundPosition: '0 0'});
    $('#greet').animate({
        opacity: 1,
        backgroundPosition: '(50% 0)'
      }, 1000); 
    $('#greet .inner').animate({
        opacity: 1,
        backgroundPosition: '(50% 0)'
      }, 1000); 

    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
    $("#pitch_type_of_site").change(function () {
        if ($(this).val() === 'renew') {
          $("label[for='pitch_existing_site_url']").css({'color':'#000'});
          $("input[id='pitch_existing_site_url']").attr('disabled', false);
        } else {
          $("label[for='pitch_existing_site_url']").css({'color':'#ddd'});
          $("input[id='pitch_existing_site_url']").val('');
          $("input[id='pitch_existing_site_url']").attr('disabled', true);
        }
      });

    var sect = $("#rfp .section");
    var si = $(" :input", sect);
    sect.each( function(i) {
        var id = $(this).attr("id");
        var inputs = $("#" + id + " :input");
        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 (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 = $("#pitch").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;
      };
    })();

