var cache = {};
jQuery(document).ready(function() {
    var copy = [];
    
 var copy = [];
    copy[0] = "<p>Dear All,</p><p>My name is <%=cache.about.TR_First_Name%> and I represent <%=cache.about.TR_Company_Name%>.</p>";
	 copy[1] = "<p>This project is for : <%=cache.project.type_of_site%>.</p><p>We are in need of some help with <% if (cache.project.existing_site_url) { %> an existing website, located at <a href=\"<%=cache.project.existing_site_url%>\"><%=cache.project.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] = "<p><% if (cache.detail_description) { %><%=cache.detail_description.description%><% } %></p>";
    copy[4] = "<% if (cache.cost) { %><p>We would like this project finished in <%=cache.cost.days%> and our budget range is <%=cache.cost.budget_chk1%> depending on experience and strength of proposal.</p><% } %>";
    copy[5] = "<p>I can be reached by phone at <%=cache.contact.phone%> or via email at <%=cache.contact.TREF_Email%></p><p>You can call me at this time <%=cache.contact.best_time%></p>";
	copy[6] = "<p>City : <%=cache.city.TN_City%></p>";
	
	copy[7] = "<p><% if(cache.address.TN_Country!=='USA'){%> Other State: <%=cache.address.TN_Other_state%> <br>Country: <%=cache.address.TN_Country%><%} else{%> State : <%=cache.address.TN_State%> <br> Country: USA <%}%> <br>Thank you for your time and interest in our project..</p> <% if (cache.about) { %><p>Yours,<br><%= cache.about.TR_First_Name%></p><% } %>";


    if (jQuery("#rfp").length !== 0) {
    // Move the RFP email along side the window position on the form
    jQuery(window).scroll(function () { 
        scroll();
      });
    // Enable ajax submission of the form
    jQuery('#new_pitch').ajaxForm({
        dataType: "script",
        beforeSend: function(xhr) {xhr.setRequestHeader("Accept", "text/javascript");}
      });
  
   jQuery("#type_of_site").change(function () {
        if ((jQuery(this).val() === 'An Existing website') || (jQuery(this).val() === 'Iphone Programming') || (jQuery(this).val() === 'Application Development')) {
          jQuery("label[for='existing_site_url']").css({'color':'#000'});
          jQuery("input[id='existing_site_url']").attr('disabled', false);
        } else {
          jQuery("label[for='existing_site_url']").css({'color':'#ddd'});
          jQuery("input[id='existing_site_url']").val('');
          jQuery("input[id='existing_site_url']").attr('disabled', true);
        }
      });

 jQuery("#TN_Country").change(function () {
if ((jQuery(this).val() === 'USA')){
	jQuery("select[id='TN_State']").attr('disabled', false);
	jQuery("input[id='TN_Other_state']").val('');
	jQuery("input[id='TN_Other_state']").attr('disabled', true);
	
}
else if ((jQuery(this).val() === '')){
	jQuery("input[id='TN_Other_state']").val('');
	jQuery("select[id='TN_State']").val('');
	jQuery("select[id='TN_State']").attr('disabled', true);
	jQuery("input[id='TN_Other_state']").attr('disabled', true);

}
else
{
	
	jQuery("select[id='TN_State']").val('');
	jQuery("select[id='TN_State']").attr('disabled', true);
	jQuery("input[id='TN_Other_state']").attr('disabled', false);
	
}
 });
    var sect = jQuery("#rfp .section");
    var si = jQuery(" :input", sect);
    sect.each( function(i) {
        var id = jQuery(this).attr("id");
        var inputs = jQuery("#" + id + " :input");
        inputs.change(function() {
            var inputid = jQuery(this).attr("id");
            var c = 0;
            if(! validate(/^\b[A-Z0-9'\"._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\bjQuery/i, '#TREF_Email', '#warn_eml')) {
              c--;
            }
            if(! validate(/(\d.*?){5,}/i, '#phone', '#warn_phn')) {
              c--;
            }
			 
            sectionComplete(id,inputs,i);
            formComplete(si, c);
            scroll();
          });
      });

      }
    // count - counts the number of words used in a textarea
    function count(val) {
      var a = jQuery(val).val().split(' ').length;
      if (a === 1 ) {
        jQuery("#words").text(a + " word ");
      } else if (a > 300 ) {
        jQuery("#words").html("<b>" + a + " words</b>");
      } else {
        jQuery("#words").text(a + " words ");
      }
    }
    /* 

     validate - check the value against the regex
    */
    function validate(regex, target, msg) {
          var v = jQuery(target).val();
          if (v.length !== 0 && regex.exec(v) === null) {
            jQuery(msg).fadeIn("slow");
            return false;
          } else {
            jQuery(msg).fadeOut("slow");
            return true;
          }
    }
    
    function sectionComplete(id, inputs, i) {
	  var data = {};
      data.values = formData(id, inputs); 
      cache[id] = data.values;
	  //alert("id=>"+id+""+"i=>"+i);
	 // alert("Data===>"+data.values);
	 // alert("Size===>"+Object.size(cache[id]));
    if (Object.size(cache[id])!==0) {
	        write(data, copy[i], jQuery("#message div:eq("+i+")"));
      } else {
        jQuery("#message div:eq("+i+")").fadeOut("slow");
      }
	  if (i === 0 && cache.address) {
        write(data, copy[copy.length - 1], jQuery("#message div:last"));

	 
      }
   
 


    }
   
    function formData(id, inputs) {//alert("Inputs->"+inputs+" "+"Id->"+id);
      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 (jQuery(this).val().length!==0) {
              values[jQuery(this).attr("id")] = sanitise(jQuery(this).val());//alert("Tag->"+tag);
            }
          } else if (type === 'radio') {
			            if (this.checked === true) {
			
              values[jQuery(this).attr("id")] = jQuery(this).val();
            }
          } else if (type === 'checkbox') {
            if (this.checked === true) {
              chkd.push(jQuery(this).val());
              values[id+type] = chkd;
            }
          }
        });

if(id==="address"){
//jQuery("#" + id + " :disabled").length=1;
var disabled_length_id=1;
}
else
{
var disabled_length_id=jQuery("#" + id + " :disabled").length;
}
//alert("jQuery(\"#\" + id + \" :disabled\").length -> "+disabled_length_id);
//alert(inputs.length - disabled_length_id);
      if (Object.size(values)===(inputs.length - disabled_length_id)) {//alert("Values->"+values);
		        return(values);
      } else if (jQuery("#" + id + " :checkbox").length!==0) {
		    return(values);
      }
	  else if (jQuery("#" + id + " :radio").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 - jQuery("#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 && (jQuery(".submit").css("display") !== "block")) {
        jQuery("p.submit").fadeIn("800");
      } else if (c < a) {
        jQuery("p.submit").fadeOut("800");
      }
    }
    function scroll() {
      var st = jQuery(window).scrollTop();
      var dh = jQuery(document).height();
      var wh = jQuery(window).height();
      var bh = jQuery("#message").innerHeight();
      var fh = jQuery("#rfp form").innerHeight();
      var fo = jQuery("#pitch").offset().top;
      var p = (st / (dh - wh));
      var y =  Math.round(((fh - bh) * (p)) - (fo * (1 - p)));
	  y = y+100;
	  var divOffset = jQuery('#rfp form').offset().top;
	  //alert("divoffset==>"+divOffset);
      y = Math.max(y,0);
	  //alert(y);
      jQuery("#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;
    }
    
    function write(data, src, div) {
	
      jQuery(div).fadeOut("fast", function callback() {
		// alert(src+"   "+data);
          var line = tmpl(src, data);//alert(line);
          jQuery(this).html(line); 
        });
     jQuery(div).fadeIn("800");
	 
    }
  });

Object.size = function(obj) {
  var size = 0, key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      size++;
    }
  }
  return size;
};


(function(){
    var cache = {};
    this.tmpl = function tmpl(str, data){//alert(str);
      
	  var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
      tmpl(document.getElementById(str).innerHTML) :

     
      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;
      };
    })();


