/**
 * jQuery babySteps plugin
 * This jQuery plugin is just a small tool for binding 'steps' together
 * @name jquery.babysteps
 * @author Cory ODaniel http://coryodaniel.com
 * @version 0.2.2
 * @date March 17, 2009
 * @category jQuery plugin
 * @copyright (c) 2008 Vokle, Inc. (http://vokle.com)
 * @license MIT http://www.opensource.org/licenses/mit-license.php
 * @example Visit http://www.vokle.com/open-source/examples/babysteps/index.html
 * And yes, it is a "What About Bob?" reference.
 *
 * CHANGELOG (03/17/2009)
 *  - bindStep method will take a selector instead of just a jQuery object (do what you will)
 *  - added a gotToStep method
 */

(function($) {
  /** Binds to steps together
    * @param nextStep [jQuery Object | jquery Selector] 
    *   The step to bind to
    *
    * @param options  [Hash]
    *   override the default options
    *
    * @see $.fn.bindStep.defaults
    *   
    * @example
    *   $('step1').bindStep('#step2');
    * 
  **/
  $.fn.bindStep = function(nextStep,options) {
   
    // build main options before element iteration
    var opts = $.extend({}, $.fn.bindStep.defaults, options);
    
    //Preload images
    var nextBtnImg = new Image();
    var prevBtnImg = new Image();
    nextBtnImg.src = opts.nextBtn;
    prevBtnImg.src = opts.prevBtn;
   
    /**
     * Bind each step to each nextStep
     *  I usually only bind one step to one step, but i suppose someone may
     *  want to bind multiple steps together...? 
     */
    return this.each(function() {
      $currStep = $(this);
      $currStep.addClass('jQueryBabyStep');

      // build element specific options
      var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
      
      //Preload images if they are different
      if(nextBtnImg.src != o.nextBtn) nextBtnImg.src = o.nextBtn;
      if(prevBtnImg.src != o.prevBtn) prevBtnImg.src = o.prevBtn;
      
      $(nextStep).each(function(){
        $nextStep = $(this);
        $nextStep.addClass('jQueryBabyStep');        
        
        //bind the next button
        displayAndBind($currStep,$nextStep,o,'next');
        //Bind the previous button
        if(o.bindPrev) displayAndBind($nextStep,$currStep,o,'prev');
      });
      
    });
  };
  
  // @param targetStep [jQuery Object or Selector]
  //    The step to skip to
  //
  // @param transition [function]
  //    How to transition between the two steps
  //    Should be a function that accepts to parameters (currStep, targetStep)
  //
  // @see $.fn.bindStep.defaults.transition
  //
  // @return jQuery Object
  jQuery.goToStep = function(targetStep,transition){
    if (transition === undefined) {
      transition = $.fn.bindStep.defaults.transition;
    }
    transition($('.jQueryBabyStep:visible'),$(targetStep));
  };
 
  function displayAndBind(s1,s2,_opts,type){
    //Create ids
    var imgId = s1.attr('id') + '_to_' + s2.attr('id') + '_btn';
    var containerId = imgId + '_container';
    
    //determine image and create markup
    var img = (type == 'next' ? _opts.nextBtn : _opts.prevBtn);
    var imgBtn = _opts.generateMarkup(containerId,imgId,img);
    
    //Layout the new button
    _opts.layoutButton(s1,imgBtn,type);
    
    //Attach the transitions
    var imgRef = $('#'+ containerId);
    attachTransition(imgRef,_opts.transition,s1,s2,_opts.nextValidator);
  }
    
  // attach the transition to the image button and the steps
  function attachTransition(imgBtn,trans,s1,s2,valid){
    imgBtn.click(function(){
      if(valid && valid()) trans(s1,s2);
    });
  }
  
  // private function for debugging
  function debug($obj) {
    if (window.console && window.console.log)
      window.console.log('babySteps: ' + $obj);
  };
  
  // plugin defaults
  $.fn.bindStep.defaults = {
    //Path to your next button image
    nextBtn         :   '',
    //Path to your previous button image
    prevBtn         :   '',
    //When binding next step, should a previous button be bound?         
    bindPrev        :   false,
    /**
     * Validation callback called when 'next' is clicked
     * Validator should return Boolean
     * Make sure you output your error messages!
     */
    nextValidator   :   function(){return true;},
    /**
     * Transition between steps; function(thisStep,nextStep)
     * @params - currStep - jQuery reference to the step that is binding
     * @params - nextStep - jQuery reference to the step that is being bound
     */
    transition      :   function(currStep,nextStep){
      currStep.hide();  
      nextStep.show();
    },
    /**
     * How to lay the button out over/within the step container
     * @params - step - jQuery reference to step container
     * @params - imgBtn - Markup containing button
     * @params - imgType - 'next' or 'prev'
     */
    layoutButton    :   function(step,imgBtn,imgType){
      if(imgType=='next' || imgType=='prev'){
        step.append(imgBtn);
      }
    },
    /**
     * Generate the HTML to wrap the Image
     * @params - id1 - id that transition is bound to, could be used for container like div, or whatever
     * @params - id2 - id for the image, if you used id1 for the image, then just ignore id2
     * @params - img - image path
     */
    generateMarkup  :   function(id1,id2,img){        
       return([
         '<div ',
           'id="', id1, '" ',
         '>',
           '<img ',
             'src="', img, '" ',
             'id="', id2 , '" ',
           '/>',
         '</div>'
       ].join(''));
     }
  };
})(jQuery);




















	//This is the basic example of how to set up some Divs to become babySteps.
	function step1_validator()
	{
		var CreditCardBalance = $('#ddCreditCardBalance').val();

		$('#CreditCardBalance_error').remove();

        if(!CreditCardBalance)
		{
				$('#step1').append("<span id='CreditCardBalance_error' class='mainformmultisteperror'>Please select a value.</span>");
				return false;
		}
		else
		{


			var ddCreditCardBalanceselected = $("#ddCreditCardBalance option:selected");
			if(ddCreditCardBalanceselected.val() != 0)
			{
				   $("#ddCreditCardBalance2").text =  ddCreditCardBalanceselected.text();
			}

			$("#maintopformbottom").animate({"height": "135px"}, "slow");
			return true;
		}
	}

	function step2_validator()
	{
		var CreditCardBalance2 = $('#ddCreditCardBalance2').val();
		var UnsecuredDebtBalance = $('#ddUnsecuredBalance').val();
		var noerrors = true;

		$('#CreditCardBalance2_error').remove();
		$('#UnsecuredDebtBalance_error').remove();

        if(!CreditCardBalance2)
		{
				$('#step2').append("<span id='CreditCardBalance2_error' class='mainformmultisteperrorupper'>Please select a value.</span>");
				noerrors = false;
		}

		if(!UnsecuredDebtBalance)
		{
				$('#step2').append("<span id='UnsecuredDebtBalance_error' class='mainformmultisteperror'>Please select a value.</span>");
				noerrors = false;
		}

		return noerrors;
	}

	function step3_validator()
	{
		var UnsecuredCreditors = $('#ddUnsecuredCreditors').val();
		var HowFarBehindInPayments = $('#ddHowFarBehindInPayments').val();
		var noerrors = true;

		$('#UnsecuredCreditors_error').remove();
		$('#HowFarBehindInPayments_error').remove();

        if(!UnsecuredCreditors)
		{
				$('#step3').append("<span id='UnsecuredCreditors_error' class='mainformmultisteperrorupper'>Please select a value.</span>");
				noerrors = false;
		}

		if(!HowFarBehindInPayments)
		{
				$('#step3').append("<span id='HowFarBehindInPayments_error' class='mainformmultisteperror'>Please select a value.</span>");
				noerrors = false;
		}

		return noerrors;
	}

	function step4_validator()
	{
		var FirstName = $('#txtbFirstName').val();
		var LastName = $('#txtbLastName').val();
		var noerrors = true;

		$('#FirstName_error').remove();
		$('#LastName_error').remove();

        if(FirstName.replace(' ', '').length < 1)
		{
				$('#step4').append("<span id='FirstName_error' class='mainformmultisteperrorupper'>Please enter your first name.</span>");
				noerrors = false;
		}

		if(LastName.replace(' ', '').length < 1)
		{
				$('#step4').append("<span id='LastName_error' class='mainformmultisteperror'>Please enter your last name.</span>");
				noerrors = false;
		}

		return noerrors;
	}

	function step5_validator()
	{
		var Telephone1 = $('#txtbPhoneAreaCode').val();
		var Telephone2 = $('#txtbPhonePrefix').val();
		var Telephone3 = $('#txtbPhoneLast4').val();
		var Email = $('#txtbEmail').val();
		var noerrors = true;

		$('#Telephone_error').remove();
		$('#Email_error').remove();

        /* CHECK PHONE NUMBER */
		if (isNaN(Telephone1) || Math.abs(parseInt(Telephone1)) != parseInt(Telephone1) || Telephone1.length < 3)
		{
			$('#step5').append("<span id='Telephone_error' class='mainformmultisteperrorupper'>Please enter your telephone area code.</span>");
			noerrors = false;
		}
		else if(Math.abs(parseInt(Telephone1)) < 200)
		{
			$('#step5').append("<span id='Telephone_error' class='mainformmultisteperrorupper'>Please enter a valid telephone area code.</span>");
			noerrors = false;
		}

		else if (isNaN(Telephone2) || Math.abs(parseInt(Telephone2)) != parseInt(Telephone2) || Telephone2.length < 3)
		{
			$('#step5').append("<span id='Telephone_error' class='mainformmultisteperrorupper'>Please enter the first 3 digits of your telephone number.</span>");
			noerrors = false;
		}
		else if(Math.abs(parseInt(Telephone2)) < 200)
		{
			$('#step5').append("<span id='Telephone_error' class='mainformmultisteperrorupper'>Please enter a valid number for the first 3 digits of your telephone number.</span>");
			noerrors = false;
		}

		else if (isNaN(Telephone3) || Math.abs(parseInt(Telephone3)) != parseInt(Telephone3) || Telephone3.length < 4)
		{
			$('#step5').append("<span id='Telephone_error' class='mainformmultisteperrorupper'>Please enter the last 4 digits of your telephone number.</span>");
			noerrors = false;
		}

		/* CHECK EMAIL */
		if (Email.replace(' ', '').length < 1)
		{
			$('#step5').append("<span id='Email_error' class='mainformmultisteperror'>Please enter your email address.</span>");
			noerrors = false;
		}
		else
		{
			var emailFilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
			if (!(emailFilter.test(Email)))
			{
				$('#step5').append("<span id='Email_error' class='mainformmultisteperror'>Please enter a valid email address.</span>");
				noerrors = false;
			}
		}

		return noerrors;
	}

	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	$(function()
	{
		//Taking reference to all of my step jQuery Objects (optional)
		var step1 = $('#step1');
		var step2 = $('#step2');
		var step3 = $('#step3');
		var step4 = $('#step4');
		var step5 = $('#step5');
		var step6 = $('#step6');

		//Setting up my buttons and how I want my markup to look
		/*$.fn.bindStep.defaults.prevBtn = "/images/ui/bohemian/icons/unused/arrow_left_48.png";*/
		$.fn.bindStep.defaults.nextBtn = "images/form_next.gif";
		$.fn.bindStep.defaults.generateMarkup = function(id1,id2,img)
		{
			return([
				'<a class="multistepnexttop" href="#" onmousedown="javascript:pageTracker._trackPageview(/funnel_G1/', id1 , ')" ',
				'id="', id1 , '" ',
				'/></a>',
			].join(''));
		}

		//The steps are validated
		step1.bindStep(step2,{nextValidator: step1_validator});
		step2.bindStep(step3,{nextValidator: step2_validator});
		step3.bindStep(step4,{nextValidator: step3_validator});
		step4.bindStep(step5,{nextValidator: step4_validator});
		step5.bindStep(step6,{nextValidator: step5_validator});

	});
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	$(document).ready(function(){

   $(".multistepnexttop").click(function(){
		 var buttonval = this.id;
		 var formdata = {step:'', value1:'', value2:'', value3:'', value4:'', value5:''};
		 var formstep = 0;

		 if(buttonval == "step1_to_step2_btn_container")
		 {
		 	formstep = 1;
		 	var formvalue1 = $('#ddCreditCardBalance').val();
		 	formdata = {step:formstep, value1:formvalue1, value2:'', value3:'', value4:'', value5:''};
			$("#ddCreditCardBalance2").val($('#ddCreditCardBalance').val());
			
			pageTracker._trackPageview("/funnel_HomeForm/step1.html");
		 }
		 else if(buttonval == "step2_to_step3_btn_container")
		 {
		 	formstep = 2;
		 	var formvalue1 = $('#ddCreditCardBalance2').val();
			var formvalue2 = $('#ddUnsecuredBalance').val();
		 	formdata = {step:formstep, value1:formvalue1, value2:formvalue2, value3:'', value4:'', value5:''};
			
			pageTracker._trackPageview("/funnel_HomeForm/step2.html");
		 }
		 else if(buttonval == "step3_to_step4_btn_container")
		 {
		 	formstep = 3;
		 	var formvalue1 = $('#ddUnsecuredCreditors').val();
			var formvalue2 = $('#ddHowFarBehindInPayments').val();
		 	formdata = {step:formstep, value1:formvalue1, value2:formvalue2, value3:'', value4:'', value5:''};
			
			pageTracker._trackPageview("/funnel_HomeForm/step3.html");
		 }
		 else if(buttonval == "step4_to_step5_btn_container")
		 {
		 	formstep = 4;
		 	var formvalue1 = $('#txtbFirstName').val();
			var formvalue2 = $('#txtbLastName').val();
		 	formdata = {step:formstep, value1:formvalue1, value2:formvalue2, value3:'', value4:'', value5:''};
			
			pageTracker._trackPageview("/funnel_HomeForm/step4.html");
		 }
		 else if(buttonval == "step5_to_step6_btn_container")
		 {
		 	formstep = 5;
		 	var formvalue1 = $('#txtbPhoneAreaCode').val();
			var formvalue2 = $('#txtbPhonePrefix').val();
			var formvalue3 = $('#txtbPhoneLast4').val();
			var formvalue4 = $('#txtbPhoneExt').val();
			var formvalue5 = $('#txtbEmail').val();
		 	formdata = {step:formstep, value1:formvalue1, value2:formvalue2, value3:formvalue3, value4:formvalue4, value5:formvalue5};
			
			pageTracker._trackPageview("/funnel_HomeForm/step5.html");
		 }

		 //alert(formstep);

			$.ajax({
			  type: "POST",
			  url: "process.cfm",
			  dataType: "text",
			  data: formdata,
			  success: function(response){
			  		var percent = response.substring(response.lastIndexOf(':') + 1,response.lastIndexOf('}'));
					document.getElementById('progress').style.width = percent + "px";
											}
			  });


		});

		$("#FormSubmit").click(function(){
		 var buttonval = this.id;
		 var formdata = {step:'', value1:'', value2:'', value3:'', value4:'', value5:''};
		 var formstep = 0;

		 //alert(buttonval);

		 if(buttonval == "FormSubmit")
		 {
		 	formstep = 6;
		 	var formvalue1 = $('#txtbCity').val();
			var formvalue2 = $('#ddState').val();
			var formvalue3 = $('#txtbZipCode').val();

		 	formdata = {step:formstep, value1:formvalue1, value2:formvalue2, value3:formvalue3, value4:'', value5:''};
		 }

		$.ajax({
			  type: "POST",
			  url: "process.cfm",
			  dataType: "text",
			  data: formdata,
			  success: function(response){
			  		var percent = response.substring(response.lastIndexOf(':') + 1,response.lastIndexOf('}'));
					document.getElementById('progress').style.width = percent + "px";
											}
			  });


		});
 });