function PalletRequest() {

  this.id = 'palletDialog';
  this.startDelay = 1000;
  this.stepDelay = 500;
  this.finishDelay = 3000;
  this.errorMessageID = 'errorMessageOutput';
  this.errorMessage = '<p class="text_label" style="color:red; font-weight:bold;">Please make sure all the highlighted fields below are filled in</p>';
  this.fieldArray = new Array();
  
  this.palletType = '';

  this.start = function() {
    $('#'+this.id).show();
    this.getLoader();
    var t = setTimeout('palletRequest.step1exec()', this.startDelay);
  }

  this.step1CheckPalletType = function() {
    var check = false;
    
  	$('input[name=palletType]').each(function(){
  	  if (this.checked) {
  	  	palletRequest.palletType = this.value;
  	  	// $('#next_step2').show();
  	  	check = true;
  	  }
  	});
  	if ('' != this.palletType){
      check = true;
    }
  	return check;
  }
  
  this.step1exec = function() {
    this.getStep(1);
  }

  this.storeStep1Fields = function() {
    var fields = this.getStep1Fields();
    this.storeFields(fields);
  }
  
  this.storeStep2Fields = function() {
    var fields = this.getStep2Fields();
    this.storeFields(fields);
  }
  
  this.storeStep3Fields = function() {
    var fields = this.getStep3Fields();
    this.storeFields(fields);
  }  

  this.storeStep4Fields = function() {
    var fields = this.getStep4Fields();
    this.storeFields(fields);
  }
  
  this.step1 = function() {
    this.getLoader();
    var t = setTimeout('palletRequest.step1exec()', this.stepDelay);
  }

  this.step2 = function(previous) {
    if (!this.step1CheckPalletType()) {
      $('#next_step2').blur();
      alert('Please select a pallet type');
      return;
    }
    this.storeStep1Fields();
    this.getLoader();
    var t = setTimeout('palletRequest.step2exec('+previous+')', this.stepDelay);
  }

  this.step2exec = function(previous) {
    if(previous){
      this.getStep(2);
    }else{
      if(this.palletType=='3') {
        this.getStep(2);
      }else{
        this.storeStep2Fields();
        this.getStep(3);
      }
    }
  }
  
  this.sendEnquiry = function() {
    this.fieldArray['enquiry'] = 1;
    this.step3();
  }
    
  this.step3 = function() {
    this.storeStep2Fields();
    if (!this.checkFields(3)){
      return;
    }
    this.getLoader();
    var t = setTimeout('palletRequest.step3exec()', this.stepDelay);
  }
  
  this.checkFields = function(number){
    return palletRequest.check(number-1);
  }
  
  this.step3exec = function() {
    this.getStep(3);
  }  
  
  this.step4 = function() {
    this.storeStep3Fields();
    if (!this.checkFields(4)){
      return;
    }
    this.getLoader();
    var t = setTimeout('palletRequest.step4exec()', this.stepDelay);
  }
  
  this.step4exec = function() {
    this.getStep(4);
  }  
  
  this.submit = function() {
    this.storeStep4Fields();
    if (!this.checkFields(5)){
      return;
    }
    this.getLoader();
    this.savePalletRequest();
  }
  
  this.savePalletRequest = function() {
    var fields = this.getStoredFields();
    var getString = '?';
    for (var i=0; i < fields.length; i++) {
      getString += fields[i] + '=' + this.fieldArray[fields[i]];
      if (i < fields.length-1) {
        getString += '&';
      }
    }
    if (undefined != this.fieldArray['enquiry']) {
      getString += '&enquiry=1';
    }
    getString += '&palletType=' + this.palletType;
    $.get('/palletRequest/step5.jsp'+getString, function(data) {
      $('#'+palletRequest.id).html($.trim(data));
      var t = setTimeout('palletRequest.submitExec()', this.stepDelay);
    })
    this.fieldArray = new Array();
    this.palletType = '';
  }

  this.submitExec = function() {
    $('#productLengthIndex').val('');
    $('#productWidthIndex').val('');
    var t = setTimeout('palletRequest.closeDialog()', this.finishDelay);
  }
  
  this.closeDialog = function() {
    $('#'+this.id).dialog('close');
    // $('#'+this.id).hide(); 
  }
  
  this.storeFields = function(fields) {
    var value = '';
    if (undefined != fields && null != fields && fields.length > 0) {
      for (var i=0; i < fields.length; i++) {
        if ($('#'+fields[i]).attr('type') == 'checkbox') {
          value = $('input[name='+fields[i]+']:checked').val();
        } else if ($('#'+fields[i]).attr('type') == 'radio') {
          value = $('input[id='+fields[i]+']:checked').val();
        }else {
          value = $('#'+fields[i]).val();
        }
        this.fieldArray[fields[i]] = value;
      }
    }  
  }
  
  this.getFieldType = function(id) {
  	return $('#'+id).attr('type');
  }
  
  this.getStoredFields = function() {
    var fields = this.getStep1Fields();
    if (this.palletType == '3'){
      fields = fields.concat(this.getStep2Fields());
    }
    fields = fields.concat(this.getStep3Fields());
    fields = fields.concat(this.getStep4Fields());
    return fields;  
  }
  
  this.getStep = function(number) {
    var getString='';
    if (number == 3){
      if (undefined != this.fieldArray['enquiry']) {
        getString += '?enquiry=1';
      }
    }
  
    $.get('/palletRequest/step'+number+'.jsp'+ getString, function(data){
      $('#'+palletRequest.id).html($.trim(data));
      palletRequest.populateStep(number);
      palletRequest.rePopulatePrevious(number);
    });  
  }

  this.filterDepth = function(type) {
    var width = -1;
    var target = "";
  	if (type == "leaderWidth") {
  	  width = $('#leaderWidth').val();
  	  target = 'leaderDepth';
  	} else if (type == "bottomLeadWidth") {
  	  width = $('#bottomLeadWidth').val();
  	  target = 'bottomLeadDepth';
  	} else if (type == "bearerWidth") {
  	  width = $('#bearerWidth').val();
  	  target = 'bearerDepth';
  	}
  	
  	if (width > 0){
  	  $.get('/palletRequest/dispDepthSelect.jsp?width='+width+'&type='+type, function(data){
  	    if ($.trim(data) != 0){
	      $('#'+target).html($.trim(data));
	      if (type == 'leaderWidth') {
	        palletRequest.rePopulateField('leaderDepth');
	      }
	      if (type == 'bottomLeadWidth') {
            palletRequest.rePopulateField('bottomLeadDepth');
	      }
	      if (type == 'bearerWidth') {
            palletRequest.rePopulateField('bearerDepth');
	      }
	    }else{
	      $('#'+target).html("<option value=\"-1\">Select...</option>");
	    }
 	  });
  	}else{
	  $('#'+target).html("<option value=\"-1\">Select...</option>");
	}
  }
  
  
  this.populateStep = function(number) {
  	if (number == 2) {
  		$('#productLength').val($('#productLengthIndex').val());
  		$('#productWidth').val($('#productWidthIndex').val());
  		$('#leaderQuantity').val('2');
  		$('#bottomLeadQuantity').val('2');
  		$('#leaderLength').val($('#productWidth').val());
  		$('#centreLength').val($('#productWidth').val());
  		$('#bearerLength').val($('#productLength').val());
  		$('#bottomLeadLength').val($('#productWidth').val());
  		$('#bottomCentreLength').val($('#productWidth').val());
  	}
  }
  
  this.rePopulateStep = function(number) {
  	if (number == 2) {
  		var ld = new Number($('#leaderDepth').val());
  		var bd = new Number($('#bearerDepth').val());
  		var bld = new Number($('#bottomLeadDepth').val());
  		var depth = ld + bd + bld;
  		
  		if (ld > 0 && bd > 0 && bld > 0){
  		  $('#productDepth').val(depth);
  		} else {
  		  $('#productDepth').val('');
  		}
  		
  		$('#leaderLength').val($('#productWidth').val());
  		$('#centreLength').val($('#productWidth').val());
  		$('#bearerLength').val($('#productLength').val());
  		$('#bottomLeadLength').val($('#productWidth').val());
  		$('#bottomCentreLength').val($('#productWidth').val());
  		if ($('#leaderDepth').val() > 0 ){
  		  $('#centreDepth').val($('#leaderDepth').val());
  		} else {
  		  $('#centreDepth').val('');
  		}
  		if ($('#bottomLeadDepth').val() > 0 ){
  		  $('#bottomCentreDepth').val($('#bottomLeadDepth').val());
  		} else {
  		  $('#bottomCentreDepth').val('');
  		}
  	}
  }

  this.getLoader = function() {
    $.get('/palletRequest/loader.jsp', function(data){
	  $('#'+palletRequest.id).html($.trim(data));
      palletRequest.getDialog();
	});
  }

  this.getDialog = function() {
    if ($G.isIE()) {
      $('#'+palletRequest.id).dialog({
        autoOpen: true,
  	    bgiframe: true,
  	    position: ['center', 80],
 	    height: 510,
	    width: 800,
	    resizable: false,
	    draggable: false,
	    modal: true,
	    closeOnEscape: false,
	    title: 'QUICK PALLET REQUEST',
		zIndex: 9999,
	    close: function(event, ui) {
          palletRequest.fieldArray = new Array();
          palletRequest.palletType = '';
        }
	  });
    } else {
      $('#'+palletRequest.id).dialog({
        autoOpen: true,
  	    bgiframe: true,
 	    height: 510,
	    width: 800,
	    resizable: false,
	    draggable: false,
	    modal: true,
	    closeOnEscape: false,
	    title: 'QUICK PALLET REQUEST',
	    zIndex: 9999,
	    close: function(event, ui) {
          palletRequest.fieldArray = new Array();
          palletRequest.palletType = '';
        }
	  });
    }
	$('#'+palletRequest.id).dialog('open');  
    if ($G.isIE()) {
      $('#'+palletRequest.id).css('height','510px');
    }
  }

  this.getStep1Fields = function() {
    var fields = new Array('palletType');
    return fields;  
  }
  
  this.getStep2Fields = function() {
  var fields = new Array('productLength', 
                           'productWidth', 
                           'productDepth', 
                           'leaderQuantity', 
                           'leaderLength', 
                           'leaderWidth', 
                           'leaderDepth', 
                           'centreQuantity',
                           'centreLength', 
                           'centreWidth', 
                           'centreDepth', 
                           'bearerQuantity',
                           'bearerLength', 
                           'bearerWidth', 
                           'bearerDepth',
                           'bottomLeadQuantity', 
                           'bottomLeadLength', 
                           'bottomLeadWidth', 
                           'bottomLeadDepth', 
                           'bottomCentreQuantity', 
                           'bottomCentreLength', 
                           'bottomCentreWidth', 
                           'bottomCentreDepth', 
                           'variableSpaceDistribution'
                           );
    return fields;  
  }
  
  this.getStep3Fields = function() {
    var fields = new Array('totalWeight',
                           'shipOverseas',
                           'pickupFromAllSides',
                           'isStencilled1',
                           'isStencilled0',
                           'stencilled',
                           'reusePallets',
                           'additionalInformation',
                           'howMany'
                           );
    return fields;  
  }
  
  this.getStep4Fields = function() {
    var fields = new Array('name',
                           'company',
                           'address',
                           'suburb',
                           'state',
                           'contactNumber',
                           'mobile',
                           'emailAddress',
                           'comments'
                           );
    return fields;  
  }
  
  this.stencilledNo = function() {
    $('#stencilled').val('');
  }
  
  this.stencilledYes = function() {
    var text = $('#stencilled').val();
    var value = $('input[name=isStencilled]:checked').val();
    if (text.length > 0) {
      $('#isStencilled1').attr('checked', 'checked');
      $('#isStencilled0').attr('checked', '');
    } 
  }
  
  this.previousStep = function(step){
    if (step==2) {
      this.step1();
    } else if (step==4) {
      this.step3();
    } else if (step==3) {
      if (this.palletType=='3'){
        this.step2(true);
      }else{
        this.step1();
      }
    }
  }
  
  this.rePopulatePrevious = function(step) {
    var fields = null;
    if (step==1) {
      $('input[name=palletType]').each(function(){
      	if (this.value == palletRequest.palletType) {
      		$(this).attr('checked', 'checked');
      	}
      });
      // this.step1CheckPalletType();
      return;
    } else if (step==2) {
      fields = this.getStep2Fields();
    } else if (step==3) {
      fields = this.getStep3Fields();
    } else if (step==4) {
      fields = this.getStep4Fields();
    }
    var value = '';
    var type = '';
    if (fields.length > 0){
      for(var i=0; i<fields.length;i++){
        value = this.fieldArray[fields[i]];
        type = this.getFieldType(fields[i]);

        if (undefined != value && null != value) {
          if (type == 'radio'){
          	$('input[id='+fields[i]+']').each(function(){
          	  if ($(this).val() == value) {
          	  	$(this).attr('checked','checked');
          	  }
          	});
          }else if(type == 'text'){
            $('#'+fields[i]).val(value);
          }else if(type == 'textarea'){
            $('#'+fields[i]).html(value);
          }else if(type == 'select-one'){
            $('#'+fields[i]).val(value);
          }else if(type == 'checkbox'){
            $('#'+fields[i]).attr('checked','checked');
          
          }
          
        }
      }
      if (step == 2) {
        this.filterDepth('leaderWidth');
        this.filterDepth('bottomLeadWidth');
        this.filterDepth('bearerWidth');
      }
    }
  } 
  
  this.rePopulateField = function(fieldName){
    var value = '';
    var type = '';
    value = this.fieldArray[fieldName];
    type = this.getFieldType(fieldName);
    
    if (undefined != value && null != value) {
      if (type == 'radio'){
      	$('input[id='+fieldName+']').each(function(){
      	  if ($(this).val() == value) {
      	  	$(this).attr('checked','checked');
      	  }
      	});
      }else if(type == 'text'){
        $('#'+fieldName).val(value);
      }else if(type == 'select-one'){
        $('#'+fieldName).val(value);
      }else if(type == 'checkbox'){
        $('#'+fieldName).attr('checked','checked');
      }
    }
  }
  
  this.resetErrors = function(fields) {
    $G.resetErrors(fields, this.errorMessageID);
  }
  
  this.check = function(step) {
    var fields = null;
    if (step==2){
      fields = this.getStep2ValidationFields();
    }else if(step==3){
      fields = this.getStep3ValidationFields();
    }else if(step==4){
      fields = this.getStep4ValidationFields();
    }
    this.resetErrors(fields);
    var errorArray = $G.validateFields(fields);
    if (errorArray.length == 0) {
	  return true;
    } else {
      $G.processErrors(errorArray, this.errorMessage, this.errorMessageID);
      return false;
    }
  }
  
  this.getStep2ValidationFields = function(){
    var fields = new Array('productLength', 
                           'productWidth',
                           'leaderQuantity', 
                           'leaderLength', 
                           'leaderWidth', 
                           'leaderDepth', 
                           'centreQuantity',
                           'centreLength', 
                           'centreWidth', 
                           'bearerQuantity',
                           'bearerLength', 
                           'bearerWidth', 
                           'bearerDepth',
                           'bottomLeadQuantity', 
                           'bottomLeadLength', 
                           'bottomLeadWidth', 
                           'bottomLeadDepth', 
                           'bottomCentreQuantity', 
                           'bottomCentreLength', 
                           'bottomCentreWidth'
                           );
    return fields
  }
  
  this.getStep3ValidationFields = function() {
    var fields = new Array('totalWeight',
                           'shipOverseas',
                           'howMany'
                           );
    return fields;  
  }
  
  this.getStep4ValidationFields = function() {
    var fields = new Array('name',
                           //'company',
                           'address',
                           'suburb',
                           'state',
                           'contactNumber',
                           'mobile',
                           'emailAddress'
                           );
    return fields;  
  }
}

function validatePalletRequestData() {
  var length = $('#productLengthIndex').val();
  var width = $('#productWidthIndex').val();
  var regex_digit = /^\d{3,4}$/;
  var ret = true;
  var message = '';
  	      
  // Test length and width has correct value range 500 - 4000
  if (length.search(regex_digit) || length < 500 || length > 4000) {
    ret = false;
  	message = 'Invalid length specified, please enter a number between 500 - 4000 mm.\n';
  }
  if (width.search(regex_digit) || width < 500 || width > 4000) {
  	ret = false;
  	message += 'Invalid width specified, please enter a number between 500 - 4000 mm.\n';
  }
  	      
  if (!ret) {
  	message += '\nPlease ring 1300 531 536 to speak to a CMTP staff member to discuss your customised pallet options.'
  	alert(message);
  }
      
  return ret;
}
