

// 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', '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 4:
        validateStep5AndGoTo(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) {

  // desc + detailed desc?
  if ($('#step2-desc').val() == '' || $('#step2-desc').val() == LANG_QUOTE_REQUEST_TITLE_FIELD) {
    jAlert(LANG_STEP2_NO_DESC_MESSAGE, LANG_STEP2_NO_DESC_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_STEP2_NO_LONG_DESC_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_STEP2_INVALID_ZIP_TITLE);
      return false;
      
    }
    
    // check house number
    var number = $('#step2-number').val();
    if ( number == '' ) {
      
      jAlert(LANG_STEP2_NO_NUMBER_MESSAGE, LANG_STEP2_NO_NUMBER_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 3. Check if all categories are selected..
 * 
 * @param int
 */
function validateStep3AndGoTo(step) {

  // setup next step
  loadStep4();

  // go to next step
  curStepIndex = step;
  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');

});

function loadStep4() {
  
  // we get this entire step from the backend, because it's highly dynamic and js would cause problems
  //$('#step4-inner').load(URI_PATH + '/ajax/quoteRequest/step4/load.php' );
  
  $.ajax({
    url: URI_PATH + '/ajax/quoteRequest/step4/load.php',
    cache: false,
    success: function(html){
        $('#step4-inner').html(html);
    }
  }); 
    
}

$(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 = 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' );
  
  
  // ajax instead of load, caching must be disabled
  $.ajax({
    url: URI_PATH + '/ajax/quoteRequest/step5/load.php',
    cache: false,
    success: function(html){
        $('#step5-inner').html(html);
    }
  });  
  
}
