

// current step
var curStepIndex = 0;

/**
 * Go to next or prev step in quoteRequest sequence
 * 
 * @param int (0 based step)
 * @param bool animated
 */
function goToStep(step,animate) {

  if ( animate == undefined ) animate = true;
  
  // go slide...
  if ( animate ) {

    $('#quoteRequest-inner').animate( {
      //marginLeft : ((-45 + (-983 - 50) * step)) + 'px'
      marginLeft : ((1 + (-1000 - 25) * step)) + 'px'
    }, 300);

  } else {
    
    $('#quoteRequest-inner').css( {
      //marginLeft : ((-45 + (-983 - 50) * step)) + 'px'
      marginLeft : ((1 + (-1000 - 25) * step)) + 'px'
    }, 300);

  }
  
  // steps, first reset all steps...
  var steps = new Array('one', 'two', 'three', 'threefive', 'four', 'five');
  $('.stepBox li').each(function(ind, obj) {
    $(obj).attr('class', steps[ind]);
    $(obj).children('span.arrow').remove();
  });

  // then set all "done steps"
  $('.stepBox li:lt(' + step + ')').each(function(ind, obj) {
    $('.stepBox li').eq(ind).attr('class', steps[ind] + '3');
  });

  // and set "current" step
  $('.stepBox li').eq(step).attr('class', steps[step] + '2');
  $('.stepBox li').eq(step).prepend('<span class = "arrow"></span>');

  document.location = URI_PATH + '/offerte-aanvragen.html#stap' + (step+1);
}

$(document).ready(function() {

  // next/prev
  $('.next-step').click(function() {
      validateCurrentStepAndGoToStep(curStepIndex + 1 );    
  });
  $('.prev-step').click(function() {
      goToStep(--curStepIndex);
  });

  /**
   * Validate a step, we need to have all fields filled in before we continue
   * 
   * @param int (0 based step)
   * @return bool
   */
  function validateCurrentStepAndGoToStep(step) {
   
    switch ( curStepIndex ) {
    
      case 0:
        validateStep1AndGoTo(step);
        break;
      case 1:
        validateStep2AndGoTo(step);
        break;
      case 2:
        validateStep3AndGoTo(step);
        break;
      case 3:
        validateStep4AndGoTo(step);
        break;
      case 35:
        validateStep5AndGoTo(step);
        break;        
      case 4:
        validateStep6AndGoTo(step);
        break;
    
    }
    
  }
  
  // hash tag current step?
  var string = document.location.toString();
  if ( string.indexOf('#stap') !== -1 ) {

    var step = string.substring(string.indexOf('#stap') + 5, string.indexOf('#stap') + 6 );


    if ( step <= maxStep ) {
    
      curStepIndex = step-1;
      goToStep(curStepIndex,false);
      
      
    }
  }
  
  
  // not applicable
  $('#step2-place_na').click(function() {
    
    if ( $(this).is(':checked') ) {

      $('#step2-zip, #step2-number').attr('disabled','true');
      
    } 
    else
      $('#step2-zip, #step2-number').attr('disabled','');
      
  });

});

/**
 * Validate method for step 1. Check if all categories are selected..
 * 
 * @param int
 */
function validateStep1AndGoTo(step) {

  if ( $('.step1-cat').last().val() == '' ) {
   
    jAlert(LANG_STEP1_SELECT_CATEGORY_MESSAGE,LANG_STEP1_SELECT_CATEGORY_TITLE);
    return false;
    
  } else {
    
    $.getJSON(URI_PATH + '/ajax/quoteRequest/step1/save.php', { category_id: $('.step1-cat').last().val() }, function(response) {
      
      if ( response.success ) {
        
        // go to next step
        loadStep2ForCategoryId($('.step1-cat').last().val());
        curStepIndex = step;
        goToStep(step);
        return true;
        
      } else {
      
        jAlert(LANG_UNEXPECTED_ERROR_MESSAGE, LANG_UNEXPECTED_ERROR_TITLE );
        return false;
        
      }
      
    });
    
  }
  
  return false;

}

$(document).ready(function() {
 
  var evt = $.browser.msie ? "click" : "change";
  $('.step1-cat').live(evt, function() {
    
    var index = $(this).parent().index();
    var obj = $(this);
    
    // remove all latter select fields
    $('.step1-cat:gt(' + index + ')').parent().remove();
    
    // empty?
    if ( $(this).val() == '' ) return;
    
    // get from backend...
    $.getJSON(URI_PATH + '/ajax/quoteRequest/step1/loadCategoryChildren.php', { parent_id: $(this).val() }, function(json ) {
      
      if ( json.success ) {

        if ( json.categories.length > 0 ) {
    
          var html = '<p><label>&nbsp;</label><select name = "step1-category" class = "step1-cat"><option value = "">Selecteer een subcategorie</option>';
          for ( i = 0; i < json.categories.length; i++ )
            html += '<option value = "' + json.categories[i].id + '">' + json.categories[i].name + '</option>';
  
          html += '</select></p>';
          
          // add to page
          $(html).insertAfter($(obj).parent());
          
          }
        
      } else
        jAlert(LANG_UNEXPECTED_ERROR_MESSAGE, LANG_UNEXPECTED_ERROR_TITLE );
    
    });
    
  });

});

var step2_currentCategoryId = step2_currentCategoryId  || null;

/**
 * Validate method for step 2. Check if all categories are selected..
 * 
 * @param int
 */
function validateStep2AndGoTo(step) {

  // title ?
  if ($('#step2-desc').val() == '' || $('#step2-desc').val() == LANG_QUOTE_REQUEST_TITLE_FIELD) {
    jAlert(LANG_STEP2_NO_DESC_MESSAGE, LANG_ERROR_ALERT_TITLE);
    return false;
  }
  
  // valid until?

  if ( $('#step2-valid-until').val() == '' || $('#step2-valid-until').val() == LANG_QUOTE_REQUEST_VALID_UNTIL_FIELD ) {
    jAlert(LANG_STEP2_NO_VALID_UNTIL_MESSAGE, LANG_ERROR_ALERT_TITLE);
    return false;
  }  
  // first day?

  if ( $('#step2-first-day').val() == '' || $('#step2-first-day').val() == LANG_QUOTE_REQUEST_FIRST_DAY_FIELD ) {
    jAlert(LANG_STEP2_NO_FIRST_DAY_MESSAGE, LANG_ERROR_ALERT_TITLE);
    return false;
  } 
    
  // desc + detailed desc?
  if ( $('#step2-long-desc').val() == '' || $('#step2-long-desc').val() == LANG_QUOTE_REQUEST_DESCRIPTION_FIELD ) {
    jAlert(LANG_STEP2_NO_LONG_DESC_MESSAGE, LANG_ERROR_ALERT_TITLE);
    return false;
  }

  // zip + number
  if ( ! $('#step2-place_na').is(':checked') ) {
   
    // zip
    var zip = $('#step2-zip').val().replace(/\s+/, '');
    if ( ! zip.match(/^[0-9]{4}[a-zA-Z]{2}$/) ) {

      jAlert(LANG_STEP2_INVALID_ZIP_MESSAGE, LANG_ERROR_ALERT_TITLE);
      return false;
      
    }
    
    // check house number
    var number = $('#step2-number').val();
    if ( number == '' ) {
      
      jAlert(LANG_STEP2_NO_NUMBER_MESSAGE, LANG_ERROR_ALERT_TITLE);
      return false;

    }
    
  }

  // check date..
  var now = new Date();
  now.setMinutes(0);
  now.setSeconds(0);
  now.setHours(0);
  now.setMilliseconds(0);

  if ( $('#step2-first-day').datepicker('getDate') == null || $('#step2-first-day').datepicker('getDate') < now) {
    
    jAlert(LANG_STEP2_NO_FIRST_DAY_MESSAGE, LANG_STEP2_NO_FIRST_DAY_TITLE);
    return false;
    
  }
 
  if ( $('#step2-valid-until').datepicker('getDate') == null || $('#step2-valid-until').datepicker('getDate') < now) {
    
    jAlert(LANG_STEP2_NO_VALID_UNTIL_MESSAGE, LANG_STEP2_NO_VALID_UNTIL_TITLE);
    return false;
    
  }  
  
  if ( $('#step2-valid-until').datepicker('getDate') > $('#step2-first-day').datepicker('getDate') ) {
    
   // jAlert(LANG_STEP2_VALID_UNTIL_AFTER_FIRST_DAY_MESSAGE, LANG_STEP2_VALID_UNTIL_AFTER_FIRST_DAY_TITLE);
   // return false;
    
  }

    // direct request number replace
    var direct_request_number = $("#step2-direct-request-number").val();
  
    if( direct_request_number == LANG_QUOTE_REQUEST_DIRECT_REQUEST_FIELD) {
        $("#step2-direct-request-number").val("");
    }  
  
  
  // validate all option fields..
  var ok = true;
  $('.option input, .option select, .option textarea').each(function(index, obj) {

    if ($(obj).val() == '' && ok && $(obj).attr('rel') == 'mandatory' ) {
      jAlert(LANG_STEP2_NOT_ALL_OPTIONS_MESSAGE, LANG_STEP2_NOT_ALL_OPTIONS_TITLE);
      ok = false;
    }

  });

  // ok?
  if (!ok)
    return false;

  $.post(URI_PATH + '/ajax/quoteRequest/step2/save.php',
      $('fieldset.second input, fieldset.second select, fieldset.second textarea').serialize()
  , function(response) {

    if (response.success) {

      // go to next step
      curStepIndex = step;
      goToStep(step);
      return true;

    } else {

      jAlert(LANG_UNEXPECTED_ERROR_MESSAGE, LANG_UNEXPECTED_ERROR_TITLE);
      return false;

    }

  }, "json");

}

/**
 * Initialize step 2. We load all dynamic fields here...
 * 
 * @param int
 * @void
 */
function loadStep2ForCategoryId(category_id) {

  // only load if empty html..
  var html = $('.option').eq(0).html();
  html = html.replace(/^\s+/, '');
  html = html.replace(/\s+$/, '');

  if (html != '' && step2_currentCategoryId == category_id)
    return;

  // get fields
  $.getJSON(URI_PATH + '/ajax/quoteRequest/step2/loadOptionsForCategory.php', {
    category_id : category_id
  }, function(json) {

    if (json.success) {

      $('.option').eq(0).html(json.html);
      step2_currentCategoryId = category_id;

    } else
      jAlert(LANG_UNEXPECTED_ERROR_MESSAGE, LANG_UNEXPECTED_ERROR_TITLE);

  });

}

/**
 * Validate method for step 35. Check if all categories are selected..
 * 35 is an extra step between 3 and 4
 * @param int
 */
function validateStep3AndGoTo(step) {
  
  // go to next step
  curStepIndex = step;
  
  // logged in, skip next step and load data from step after that
  if ( isLoggedIn ) {
    loadStep4(); 
    goToStep(step,false); // disable animate for the step we skip, so user wont notice
    goToStep(step+1);
  }
  else {
    goToStep(step);
  }
  
  return true;

}

$(document).ready(function() {

  // images
  createImageUploadify(1, '#img-upload1', URI_PATH + '/ajax/quoteRequest/step3/uploadImage.php');
  createImageUploadify(2, '#img-upload2', URI_PATH + '/ajax/quoteRequest/step3/uploadImage.php');
  createImageUploadify(3, '#img-upload3', URI_PATH + '/ajax/quoteRequest/step3/uploadImage.php');
   
  createFileUploadify(1, '#file-upload1', URI_PATH + '/ajax/quoteRequest/step3/uploadFile.php');

});

/**
 * Validate method for step 35. Check contactdata
 * 
 * @param int
 */

var quoteRequestRegistrationType;

function validateStep4AndGoTo(step) {

    // Clear all error if any
       
    $("form#personal_and_company_data_form .inputError").each(function() {
        $(this).removeClass("inputError");
    });   
              
    // gender
    if ( $("form#personal_and_company_data_form select[name='gender']").val() == '' ) {
         $("form#personal_and_company_data_form select[name='gender']").addClass("inputError"); 
         return false;
    } 

    // last name
    if ( $("form#personal_and_company_data_form input[name='lastname']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='lastname']").addClass("inputError"); 
         return false;
    }                                       
    // first name
    if ( $("form#personal_and_company_data_form input[name='firstname']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='firstname']").addClass("inputError"); 
         return false;
    }  

      // street
    if ( $("form#personal_and_company_data_form input[name='street']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='street']").addClass("inputError"); 
         return false;
    }                                                        

    // streetnumber
    if ( $("form#personal_and_company_data_form input[name='streetnumber']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='streetnumber']").addClass("inputError"); 
         return false;
    }                     

    // zip empty?
    if ( $("form#personal_and_company_data_form input[name='zipcode']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='zipcode']").addClass("inputError"); 
         return false;
    }        
    
    // zip format?
    var zip = $("form#personal_and_company_data_form input[name='zipcode']").val().replace(/\s+/, '');
    if ( ! zip.match(/^[0-9]{4}[a-zA-Z]{2}$/) ) {

      jAlert(LANG_STEP2_INVALID_ZIP_MESSAGE, LANG_ERROR_ALERT_TITLE);
      return false;
      
    }                
     // city
    if ( $("form#personal_and_company_data_form input[name='city']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='city']").addClass("inputError"); 
         return false;
    }    
    
     // phone
    if ( $("form#personal_and_company_data_form input[name='phone']").val() == '' ) {
         $("form#personal_and_company_data_form input[name='phone']").addClass("inputError"); 
         return false;
    } 
    
    
    // check company if user selected company
    if ( quoteRequestRegistrationType == 'company' ) {                               
        // company 
        if ( $("form#personal_and_company_data_form input[name='company_name']").val() == '' ) {
             $("form#personal_and_company_data_form input[name='company_name']").addClass("inputError"); 
             return false;
        } 
                         
        // kvk empty?
        if ( $("form#personal_and_company_data_form input[name='kvk']").val() == '' ) {
             $("form#personal_and_company_data_form input[name='kvk']").addClass("inputError"); 
             return false;
        }

        // btw
        if ( $("form#personal_and_company_data_form input[name='btw']").val() == '' ) {
             $("form#personal_and_company_data_form input[name='btw']").addClass("inputError"); 
             return false;
        }         
    }

    // save data
    
    $.post(URI_PATH + '/ajax/quoteRequest/step35/save.php',
      $('form#personal_and_company_data_form input, form#personal_and_company_data_form select').serialize()
    , function(response) {

    if (response.success) {

    
      // setup next step
      loadStep4();      
        
      // go to next step
      curStepIndex = step;
      goToStep(step);
      return true;

    } else {

      jAlert(LANG_UNEXPECTED_ERROR_MESSAGE, LANG_UNEXPECTED_ERROR_TITLE);
      return false;

    }

    }, "json");
    
}

$(document).ready(function() {   
    
    quoteRequestRegistrationType = $("#company_or_user_select").val()
      
        if ( quoteRequestRegistrationType == 'user')  {
                $("#default_fields").show();
                $("#company_or_user_container").hide();            
        }
        if ( quoteRequestRegistrationType == 'company') {
                $("#default_fields").show();
                $("#company_fields").show();
                $("#company_or_user_container").hide();            
        }
          
        $("#company_or_user_select").change(function() {
            var val = $(this).val();
            if( val == 'user') {
                $("#default_fields").show();
                $("#company_or_user_container").hide();
            }
            if( val == 'company') {
                $("#default_fields").show();
                $("#company_fields").show();
                $("#company_or_user_container").hide();
            }
            
            // set global
            quoteRequestRegistrationType = val;
        })
        
        $("form#quote_request_account_check_form input[name='quote_request_account_check']").click(function(){
            var val = $(this).val();
            
            // set global
            quoteRequestRegistrationType = val;
                        
            if ( val == 'company' ){
                $("#default_fields").show();
                $("#company_fields").show();
            }
            if ( val == 'user') {
                $("#default_fields").show();
                $("#company_fields").hide();                   
            }
            if ( val == 'active') {              
                loadStep4(true); 
                goToStep(4);                 
            }
            
        });
});

function loadStep4(hidePersonalData) {
  
  // we get this entire step from the backend, because it's highly dynamic and js would cause problems 
  if ( hidePersonalData ) {
      
      $("#step4-inner").load(URI_PATH + '/ajax/quoteRequest/step4/load.php', {limit: 25}, function(){
        $("#step_4_personal_data").hide();
      });
  } else {
    $('#step4-inner').load(URI_PATH + '/ajax/quoteRequest/step4/load.php' );    
  }  
}

$(document).ready(function() {

  $('#place-request').live('click', function() {

    // terms ok?
    if ( $('#terms:checked').length == 0 ) {

      // terms nok
      jAlert(LANG_STEP4_TERMS_MESSAGE,LANG_STEP4_TERMS_TITLE);
      return;
      
    }
    
    // all is fine!
    loadStep5();
    curStepIndex = 5;    // was 4
    goToStep(curStepIndex);
    return true;
    
  });
  
});


function loadStep5() {
  
  // we get this entire step from the backend, because it's highly dynamic and js would cause problems
  $('#step5-inner').load(URI_PATH + '/ajax/quoteRequest/step5/load.php' );
  
}
