function sendForm(form_id) {
  if( validate()){
    $.ajax({
      type: "POST",
      data: $("#"+form_id).serialize(),
      url: "/report_save_form.php",
      success: function(msg){
        window.location.href = msg;
      }
    });
  }
  return false;
}

function confirmEmail(form_id) {
  var email = $("#email").val();
  if(email == "") {
    alert("Please enter your email address");
    return false;
  }
  
  quiteSaveForm(form_id);
  $.getJSON('/report_check_email.php?email='+email,function(data){
    if(data.msg == "notconfirmed") {
      buildPopup("<h3>Email Confirmation</h3><p>You have been sent an email. Once you have confirmed this email address you will be able to print the proposal</p>");
    } else {
      saveForm(form_id);
    }
  });
  return false;
}

function share(form_id) {
  var email = $("#email").val();
  if(email == "") {
    alert("Please enter your email address");
    return false;
  }
  
  quiteSaveForm(form_id);
  $.getJSON('/report_check_email.php?email='+email,function(data){
    if(data.msg == "notconfirmed") {
      buildPopup("<h3>Email Confirmation</h3><p>You have been sent an email. Once you have confirmed this email address you will be able to share the proposal</p>");
    } else {
      //build popup form to share
      buildPopup("<h2>Share Your Profit Proposal Report</h2><form id='share_form' onSubmit='return share_email();' action='#'><label>Subject</label><input size='50' type='text' name='subject' id='subject' /><label>CC <span class='small_info'>( example@example.com,example2@example.com )</span></label><input size='50' type='text' name='cc' id='cc' /><label>Message</label><textarea name='message' id='message' rows='5' cols='45'></textarea><div class='clear'></div><input type='submit' name='send' value='Share' /></form>");
    }
  });
  return false;
}

function quiteSaveForm(form_id) {
  $.ajax({
    type: "POST",
    data: $("#"+form_id).serialize(),
    url: "/report_generate.php",
    success: function(msg){}
  });
}

function saveForm(form_id) {
  if( validate()){ 
    if(loggedin) {
      realSaveForm(form_id);
    } else {
      askForAccount(); 
    }
  }
  return false;
}

var isOpen = false;
var build = true;

function showOverlayBox() {
	//if box is not set to open then don't do anything
	if( isOpen == false ) return;
	// set the properties of the overlay box, the left and top positions
	$('#popPassword').show();
	// set the window background for the overlay. i.e the body becomes darker
	$('#overlay').css({
	  display:'block',
	  width: $(window).width(),
	  height:$(document).height()
	});
}

function buildPopup(content) {
  if(build){
    $("body").append("<div id='overlay'></div><div id='popPassword'><a href='#' onClick='return hideMe();' class='closePop'><img src='/wp-content/themes/moreorless/images/close_03.png' alt='close' /></a><div class='pop_top'></div><div class='popInner'></div><div class='pop_bottom'></div></div>");
    $(".popInner").html(content);
    build = false;

  } else {
  	$(".popInner").html(content);
  }
  
  //set status to open
  isOpen = true;
  showOverlayBox();
  $('#overlay').css({opacity:0}).animate( {opacity:0.5} );
  
 
  return false;
}

function share_email() {
  //popup loading message
  $.ajax({
    type: "POST",
    data: $("#share_form").serialize(),
    url: "/report_share.php",
    success: function(msg){
      if(msg == "SENT")
        buildPopup("<h3>Success</h3><p>We have sent this report to the supplied emails</p>");
      else
        buildPopup("<h3>Error</h3><p>We could not send the emails at this time</p>");
    }
  });
  return false;
}

function realSaveForm(form_id) {
  //popup loading message
  buildPopup("<div class='loader'><img src='/wp-content/themes/moreorless/images/ajax-loader_trans.gif' />Loading Profit Proposal... Please wait.</div>");
  $.ajax({
    type: "POST",
    data: $("#"+form_id).serialize(),
    url: "/report_generate.php",
    success: function(msg){
      $('.report').html(msg);
      cleanInput("company","company_arrow","report_company");
      cleanInput("name","name_arrow","report_name");
      hideMe();
      //hide gen button and show print
      //$("#save_link").hide();
      //$("#print_link").show();
      var found = false;
      jQuery.each(jQuery.browser, function(i, val) {
        if(i=="msie" && val) {
          found = true;
        }
      });
      //$("#print_link").click();
      //if(found) {
        window.open("/report_pdf.php");
      //} else {
      //  var html = "<iframe style='border:none;' src='/report_pdf.php'></iframe>";
      //  $("body").append(html);
      //}
      
    }
  });
}

function askForAccount() {
  buildPopup("<h2>Save Your Profit Proposal</h2><p>Would you like to save your report to edit it later or just print it?<br /></p><a style='float:left; margin-right:10px;' onclick='hideMe(); return createAccount();' href='#'><span class='button_left'>&nbsp;</span><span class='button_middle'>Save and Print</span><span class='button_right'>&nbsp;</span></a><a style='float:left;' onclick='return realSaveForm(\"tool_form\");' href='#'><span class='button_left'>&nbsp;</span><span class='button_middle'>Just Print</span><span class='button_right'>&nbsp;</span></a>");  
}

function hideMe(){
  //set status to closed
	isOpen = false;
	$('#popPassword').css( 'display', 'none' );
	// now animate the background to fade out to opacity 0
	// and then hide it after the animation is complete.
	$("#overlay").hide();
	//$('#overlay').animate( {opacity:0}, "fast", true, function() {  } );
	//$('#overlay').animate( {opacity:0}, );
	return false;
}

function saveForLaterCreateAccount() {
//alert("ERER");
  $.ajax({
    type: "POST",
    data: $("#tool_form").serialize(),
    url: "/report_save_form.php",
    success: function(msg){
      $.ajax({
        type: "POST",
        data: $("#save_account").serialize(),
        url: "/account_create.php",
        dataType:"json",
        success: function(resp){
          //resp = JSON.parse(resp);
          //not sure what to do here
          //remove form
          if(resp.msg) {
            $("#pop_error").html(resp.msg);
          } else {
            $("#popPassword").remove();
            window.location.href = resp.url;
          }
        }
        
      });
      
    }
  });
  
  return false;
}
function saveForLater() {
  $.ajax({
    type: "POST",
    data: $("#tool_form").serialize(),
    url: "/report_save_form.php",
    success: function(msg){
      if(window.location.href.indexOf("private") !== -1)
        window.location.href = "/private/account/";
      else
        window.location.href = "/my-account/";  
    }
  });
  
  return false;
}

function account_login() {
  $.ajax({
    type: "POST",
    data: $("#login_account").serialize(),
    url: "/account_login.php",
    success: function(resp){
      //resp = JSON.parse(msg);
      if(resp.msg) {
        $("#pop_error").html(resp.msg); 
      } else {
        saveForLater();
      }
    },
    dataType:"json"
  });
  
  return false;
}


function createAccount() {
  if(!loggedin) {
    //if( validate()){
    buildPopup("<div id='pop_error'></div><div class='pop-left'><h2>Create Account</h2><form id='save_account' action='#' onSubmit='return saveForLater();'><input type='hidden' name='ajax' value='1' /><input type='hidden' name='account' value='1' /><label for='name'>Name</label><input type='text' id='name' name='name' /><label for='email'>Email</label><input type='text' id='email' name='email' /><label for='password'>Password</label><input type='password' id='password' name='password' /><label for='password2'>Confirm Password</label><input type='password' id='password2' name='password2' /><a style='float:left;' onclick='return saveForLaterCreateAccount();' href='#'><span class='button_left'>&nbsp;</span><span class='button_middle'>Create Account</span><span class='button_right'>&nbsp;</span></a></form></div><div class='pop-right'><h2>Login</h2><form id='login_account' action='#' onSubmit='return account_login();'><input type='hidden' name='ajax' value='1' /><input type='hidden' name='login' value='1' /><label for='email'>Email</label><input type='text' id='email' name='email' /><label for='password'>Password</label><input type='password' id='password' name='password' /><a style='float:left;' onclick='return account_login();' href='#'><span class='button_left'>&nbsp;</span><span class='button_middle'>Login</span><span class='button_right'>&nbsp;</span></a></form></div><div class='clear'></div>");
    //}

  } else {
    saveForLater();
  }
  return false;
}

function loadForm() {  

  $("#title").bind("blur",function(){
    setActive($(".spot:eq(1)"));
  }).bind("focus",function(){
    setActive($(".spot:eq(0)"));
  });
  
  $("#situation").bind("blur",function(){
    setActive($(".spot:eq(2)"));
  }).bind("focus",function(){
    setActive($(".spot:eq(1)"));
  });
  
  $("#improvement").bind("blur",function(){
    setActive($(".spot:eq(3)"));
  }).bind("focus",function(){
    setActive($(".spot:eq(2)"));
  });
  
  $("#benefits").bind("blur",function(){
    setActive($(".spot:eq(4)"));
  }).bind("focus",function(){
    setActive($(".spot:eq(3)"));
  });
  
  $("#barriers").bind("blur",function(){
    setActive($(".spot:eq(5)"));
  }).bind("focus",function(){
    setActive($(".spot:eq(4)"));
  }); 
  
  $("#name").bind("blur",function(){
    //put in the value
    var v = $("#name").val();
    $("#report_name").html(v);
    cleanInput("name","name_arrow","report_name");
  }).bind("focus",function(){
    cleanInput("name","name_arrow","report_name");
  });
  $("#company").bind("blur",function(){
    var v = $("#company").val();
    $("#report_company").html(v);
    cleanInput("company","company_arrow","report_company");
  }).bind("focus",function(){
    cleanInput("company","company_arrow","report_company");
  });
  
  //bind the redirect on the buttons
  var url = window.location.href;
  
  if(url.search("step-1") == -1) {
    $("#report_type_cost").bind('click',function(){
      //set value
      $.ajax({
        type: "GET",
        url: "/save_radio.php?field=report_type&value=cost",
        success: function(msg){
          window.location.href='/tool-step-2-cost/'
        }
      });
      
    });
    $("#report_type_sale").bind('click',function(){
      //set value
      $.ajax({
        type: "GET",
        url: "/save_radio.php?field=report_type&value=sale",
        success: function(msg){
          window.location.href='/tool-step-2-revenue/'
        }
      });
    });
  }
  
  if(url.search("step-3") != -1) {
    $("#recurring_1").bind('click',function(){
      //set value
      $.ajax({
        type: "GET",
        url: "/save_radio.php?field=recurring&value=1",
        success: function(msg){
          if($("#report_type_cost").attr('checked'))
            window.location.href='/tool-step-3-cost-once/'
          else
            window.location.href='/tool-step-3-revenue-once/'
        }
      });
    });
  
  
    $("#recurring_2").bind('click',function(){
      //set value
      $.ajax({
        type: "GET",
        url: "/save_radio.php?field=recurring&value=2",
        success: function(msg){
          if($("#report_type_cost").attr('checked'))
            window.location.href='/tool-step-3-cost-recurring/'
          else
            window.location.href='/tool-step-3-revenue-recurring/'
        }
      });
    });
  }
  
  var check = "";
  //adding select to select fiew options
  //$("#current_amount, #amount_after, #cost").focus(function(){
  //  this.select();
  //  check = $(this).val();
  //}).keypress(function(e){
  //  if (48 <= e.which && e.which <= 48 + 10) {
  //      var c = String.fromCharCode(e.which);
  //      var t = $(this).val();
  //      if(t == "$0" || t == check) {
  //        t = "";
  //        check = '';
  //      }
  //      t = t+c;
  //      
  //      $(this).val(formatCurrency(t));
  //      return false;
  //    } 
  //});
  $("#current_amount, #amount_after, #cost").blur(function(){
    check = $(this).val();
    $(this).val(formatCurrency(check));
  });
  
  $.ajax({
    type: "GET",
    url: "/load_form.php",
    success: function(msg){
      var res = JSON.parse(msg);
      $("#report_id").val(res.report_id);
      
      //page one
      $("#title").val(res.title);
      $("#situation").val(res.situation);
      $("#improvement").val(res.improvement);
      $("#benefits").val(res.benefits);
      $("#barriers").val(res.barriers);
      $("#report_type_"+res.report_type+"").attr('checked', true);
      
      //page 2
      $("#current_amount").val(formatCurrency(res.current_amount));
      $("#amount_after").val(formatCurrency(res.amount_after));
      $("#amount_increase").val(formatCurrency(res.amount_increase));
      if(res.increase)
        $("#increase_"+res.increase.toLowerCase()+"").attr('checked', true);
      if(res.recurring)
        $("#recurring_"+res.recurring+"").attr('checked', true);
      $("#cost").val(formatCurrency(res.cost));
      
      //page 3
      if(res.profit_margin && res.profit_margin != "0") {
        var t = $("#profit_margin option:contains('6%')").attr("selected",false);
        var p = res.profit_margin;
        if(res.profit_margin.charAt(0) == "0") {
          var m = res.profit_margin.split(".");
          p = res.profit_margin.substring(1);
        }
        $("#profit_margin option[value='"+p+"']").attr("selected",true);
      }
      if(res.discount_rate && res.discount_rate != "0") {
        var t = $("#discount_rate option:contains('7%')").attr("selected",false);
        var p = res.discount_rate;
        if(res.discount_rate.charAt(0) == "0") {
          var m = res.discount_rate.split(".");
          p = res.discount_rate.substring(1);
        }
        $("#discount_rate option[value='"+p+"']").attr("selected",true);
      }
      $("#plan_length option[value='"+res.plan_length+"']").attr("selected",true);
      if(res.recurring_rate)
        $("#recurring_rate_"+res.recurring_rate+"").attr('checked', true);
      
      //page 4
      $("#company").val(res.company);
      $("#name").val(res.name);
      $("#email").val(res.email);
      $("#industry option[value='"+res.industry+"']").attr("selected","selected");
      
      //remove password if they have an account
      if(res.has_account)
        $("#pass_block").hide();
      
      //if it is the report page then load the report
      if(url.search("step-4") != -1 ||url.search("test-2") != -1) {
        $.ajax({
          type: "POST",
          data: $("#tool_form").serialize(),
          url: "/report_generate.php",
          success: function(msg){
            $('.report').html(msg);
            cleanInput("company","company_arrow","report_company");
            cleanInput("name","name_arrow","report_name");
            
            //this will not let them resubmit the form - only happens on reload or edit
            //var t = $("#company").val();
            //if(t != "") {
            //  $("#save_link").hide();
            //  $("#print_link").show();
            //}
          }
        });
      }
    }
  });
  
  //set up auto show fields
  $("#amount_after,#current_amount,#cost").focus(function(){
    if($(this).val() == "$0")
      $(this).val("");
  });
  $("#amount_after,#current_amount,#amount_increase").bind("blur",function(){
    var first = cleanFloat($("#current_amount").val());
    var second = cleanFloat($("#amount_after").val());
    var formtype = "";
    
    if($("#report_type_cost").attr('checked'))
      formtype = "cost";
    else
      formtype = "revenue";
    
    if(formtype == "cost")
      $("#amount_increase").val(formatCurrency(first-second));
    else
      $("#amount_increase").val(formatCurrency(second-first));
    
    var t = $(this).val();
    $(this).val(formatCurrency(t));
  });
  
  $("#current_amount").bind("blur",function(){
    var t = $(this).val();
    $(this).val(formatCurrency(t));
  });
  $("#cost").bind("blur",function(){
    var t = $(this).val();
    $(this).val(formatCurrency(t));
  });
  
  //scroll to the correct spot
  //window.scrollTo(0,280);

}

function validate() {
  //if it is not page 1 check all money inputs
  
  var url = window.location.href;
  
  if(url.search("step-4") == -1) {
    //check content
    if($("#title").val() == "" )
      return setError("Please enter in a proposal title.");
    if($("#situation").val() == "" )
      return setError("Please enter in a current situation.");
    if($("#improvement").val() == "" )
      return setError("Please enter in a proposal improvements.");
    if($("#benefits").val() == "" )
      return setError("Please enter in the proposal benefits.");
    if($("#barriers").val() == "" )
      return setError("Please enter in barriers of implementation.");
    
    if(!$("#report_type_cost").attr('checked') && !$("#report_type_sale").attr('checked')) {
      return setError("Please select a proposal type.");
    }
  
  }
  
  var type = "Current ";
  var after = " After Improvement";
  if($("#report_type_cost").attr('checked')) {
    type += "Cost";
    after = "Cost"+after;
  }
  else {
    type += "Revenue";
    after = "Revenue"+after;
  }
  
  if(url.search("step-1") == -1 && url.search("step-4") == -1) {
    //page 2
    //if($("#current_amount").val() == "" || $("#current_amount").val() == "$0")
      //return setError("Please enter a value for "+type);
    //if($("#amount_after").val() == "" || $("#amount_after").val() == "$0")
      //return setError("Please enter a value for "+after);
    
    //if it is cost
    if($("#report_type_cost").attr('checked')) {
      //make sure the cost after is less
      if(cleanFloat($("#current_amount").val()) <= cleanFloat($("#amount_after").val())) {
        return setError("Improvement must be less than Current Cost or there will be no net benefit");
      }
    } else {
      //make sure the revinue after is more
      if(cleanFloat($("#current_amount").val()) >= cleanFloat($("#amount_after").val())) {
        return setError("Improvement must be more than Current Revenue or there will be no net benefit");
      }
    }
    
    if(!$("#recurring_1").attr('checked') && !$("#recurring_2").attr('checked')) {
      return setError("Please select whether this is one time or recurring");
    }
    
    if(url.search("step-2-revenue") != -1 || url.search("step-3-revenue-recurring") != -1 ) {
      if(!$("#increase_sales").attr('checked') && !$("#increase_other").attr('checked')) {
        return setError("Please choose where the revenue increase is coming from");
      }
    }
    //if($("#cost").val() == "" || $("#cost").val() == "$0")
      //return setError("The Cost of Implementation is a mandatory field.  Include all costs relating to this proposal, such as proposal creation time, management review time, implementation time, etc.  What else will the company spend money on to make this proposal work?");
  }
  
  if(url.search("recurring") != -1) {
    //page 3
    if(!$("#recurring_rate_month").attr('checked') && !$("#recurring_rate_quarter").attr('checked') && !$("#recurring_rate_annual").attr('checked')) {
      return setError("Please select how often the benefits will recur");
    }
  }
  
  if(url.search("step-4") != -1) {
    if($("#name").val() == "")
      return setError("Please Enter your name");
    if($("#company").val() == "")
      return setError("Please Enter your company name");
    if($("#industry").val() == "")
      return setError("Please Enter your industry");
    if($("#email").val() == "")
      return setError("Please Enter your email address");
  }
  
  return true;
}

function setActive(item) {
  $(".spot").removeClass("curSpot")
  item.addClass("curSpot");
}

function setError($msg) {
  alert($msg);
  return false;
}

function cleanFloat(string) {
  string = string.replace(/\$|,/g,"");
  return parseFloat(string);
}

function formatCurrencyDec(num) {
  if(!num)
    num = 0;
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
  return (((sign)?'':'-') + '$' + num + "." + cents );
}
function formatCurrency(num) {
  if(!num)
    num = 0;
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
    num = "0";
  sign = (num == (num = Math.abs(num)));
  //cents = num%1;
  //get first
  //tens =  Math.floor(cents*10);
  //ones =  Math.floor(cents*100);
  //if(ones !=0)
  //  cents = tens*10+ones;
  //else
  //  cents = tens;
  num = Math.floor(num*100);//+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
 //alert(cents);
  if(cents<10)
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+num.substring(num.length-(4*i+3));
  if(cents == 0)
    return (((sign)?'':'-') + '$' + num  );
  else
    return (((sign)?'':'-') + '$' + num +"."+cents  );
}

function cleanInput(field_id,img_id,report_id) {
  if($("#"+field_id+"").val() != "") {
    //hide image and remove underline and width;
    $("#"+img_id).hide();
    $("#"+report_id).css("border","0px");
    $("#"+report_id).css("width","auto");
  }
}

function autoSave(repeat) {
  $.ajax({
    type: "POST",
    data: $("#tool_form").serialize(),
    url: "/report_save_form.php",
    success: function(msg){
      if(repeat)
        setTimeout( "autoSave(true)", 10000 );
    }
  });
}

var timer = "";

$(document).ready(function(){
  loadForm();
  setTimeout( "autoSave(true)", 10000 );
  $("#company,#name,#email").blur(function(){
    autoSave(false);
  });
});