﻿function Validator(ctrlId, sectionSummaryId, errorlineId, validateFunction, parameters, enabled)
{
  this.ctrlId = '#'+ctrlId;
  this.sectionSummaryId = sectionSummaryId;
  this.errorlineId = errorlineId;
  this.validateFunction = validateFunction;
  this.parameters = parameters;
  this.enabled = (arguments.length > 5 ? enabled : true);
  this.isValid = true;
  this.regex = null;
  this.optional = false;
  if (parameters)
  {
    if (parameters.checkNum && parameters.checkNum == true) {
      $(ctrlId).bind('keydown', this.checkNumEntry);
    }
    if (parameters.optional && parameters.optional == true) {
      this.optional = true;
    }
    if (parameters.regex) {
      this.regex = parameters.regex;
    }
  }
  this.handlersAdded = false;
  
  this.checkNumEntry = function(event) {
    var keyCode = event.keyCode;
    var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode >= 105) || (keyCode == 8) || (keyCode == 9) || (keyCode == 46) || (keyCode == 37) || (keyCode == 39));
    if (!ret) event.stopPropagation();
    return ret;
  };
  
  this.evaluate = function() {
    var retValue = true;
    if (this.regex)
    {
      if (this.optional) {
        retValue = !validateNotEmpty(this);
        if (!retValue) retValue = validateString(this, this.regex);
      } else {
        retValue = validateString(this, this.regex);
      }
      if (retValue == false && typeof(this.validateFunction) == 'function') {
        retValue = eval(this.validateFunction(this));
      }
    } else {
      if (typeof(this.validateFunction) == 'function') retValue = eval(this.validateFunction(this));
    }
    this.displayError(!retValue);
    
    if (this.handlersAdded == false) {
      var ctrl = $(this.ctrlId);
      if (ctrl.length>0)
      {
        var ctrlNodeName = ctrl[0].nodeName.toLowerCase();
        if ((ctrlNodeName == 'input' && ctrl.attr('type') == 'text') || ctrlNodeName == 'textarea' || ctrlNodeName == 'checkbox') ctrl.bind('blur', recheckPage);
        if (ctrlNodeName == 'select') ctrl.bind('change', recheckPage);
      }
      this.handlersAdded = true;
    }
    
    return retValue;
  };
  
  this.displayError = function(display) {
    if (isNaN(this.sectionSummaryId) && isNaN(this.errorlineId)) {
      if (display) {
        this.showError();
      } else {
        this.hideError();
      }
    }
  };
  
  this.showError = function() {
    $('#'+this.sectionSummaryId).show();
    $('#'+this.errorlineId).show();
  };
  
  this.hideError = function() {
    $('#'+this.errorlineId).hide();
    var show = false;
    $('#'+this.sectionSummaryId+'>div').each(function() { $(this).css('display')!='none' ? show = true : void(0)});
    if (show) {
      $('#'+this.sectionSummaryId).show();
    } else {
      $('#'+this.sectionSummaryId).hide();
    }
  };
};

function Validation()
{
  this.validators = new Array();
  $('form').bind('submit', function(event) {
    var retval=recheckPage(true);
    if (!retval) event.stopPropagation();
    return retval;
  });
  
  this.register = function(ctrlId, sectionSummaryId, errorlineId, validateFunction, parameters, enabled) {
    var val = new Validator(ctrlId, sectionSummaryId, errorlineId, validateFunction, parameters, enabled);
    this.validators.push(val);
    $('#'+errorlineId).bind('click', function(event) {
      if ($('#'+ctrlId)[0].disabled==false) {
       $('#'+ctrlId)[0].focus(); 
      }
    });
  };
  
  this.unregister = function(ctrlId) {
    $.each(this.validators, function() {
      if (this.ctrlId == '#'+ctrlId) {
        this.validators.pop(this);
        return true;
      }
    });
    return false;
  };
  
  this.enableValidator = function(ctrlId, state) {
    $.each(this.validators, function(state) {
      if (this.ctrlId == '#'+ctrlId) {
        this.enabled = state;
      }
    });
  };
  
  this.checkPage = function(jumpToError) {
    var valid = this.isValid(jumpToError);
    if (typeof(showOrHideClientValidationErrorMessage)=='function') {
      showOrHideClientValidationErrorMessage(valid);
    }
    return valid;
  };
  
  this.isValid = function(jumpToError) {
    var valid = true;
    $.each(this.validators, function() {
      if (this.enabled) {
        var retVal = this.evaluate();
        if (!retVal) {
          this.isValid = false;
          valid = false;
        } else {
          this.isValid = true;
        }
      };
    });
    
    var firstError = true;
    var currentControlId = '';
    var currentControlIsValid;
    $.each(this.validators, function() {
      if (currentControlId != this.ctrlId)
      {
        if (currentControlId != '')
        {
          if (currentControlIsValid == true) {
            removeErrorHighlighting(currentControlId);
          } else {
            addErrorHighlighting(currentControlId);
          }
        }
        currentControlId = this.ctrlId;
        currentControlIsValid = true;
      }
      if (this.isValid == false) {
        currentControlIsValid = false;
        if (firstError) {
          firstError = false;
          if (jumpToError) {
            window.scrollTo(0, $('#'+this.errorlineId)[0].offsetTop);
            $(this.ctrlId).focus();
          }
        }
        try {
          var parcon = $(this.ctrlId)[0];
          while (parcon.className.indexOf('insertion-block')==-1 && parcon.parentNode != null) {
            parcon = parcon.parentNode;
          }
          if (parcon.parentNode != null) { 
            var parconElems = $(parcon).find('div');
            if ($(parconElems[4]).css('display')=='none') {
              $(parcon).find('img:eq(1)').trigger('click');
            }
          }
        } catch (e) {}
      }
    });
    
    if (currentControlId != '')
    {
      if (currentControlIsValid == true) {
        removeErrorHighlighting(currentControlId);
      } else {
        addErrorHighlighting(currentControlId);
      }
    }
    return valid;
  };
  
  this.showAllMessages = function() {
    $.each(this.validators, function() {
      this.showError();
    });
  };
};

function addErrorHighlighting(ctrlId) {
    debugger;
  var ctrl = $(ctrlId)[0];
  if (ctrl.type == 'checkbox') {
    $(ctrl.parentNode).addClass('field input-error');
  } else {
    $(ctrl).addClass('field input-error');
  }
}

function removeErrorHighlighting(ctrlId) {
  var ctrl = $(ctrlId)[0];
  if (ctrl.type == 'checkbox') {
    $(ctrl.parentNode).removeClass('field input-error');
  } else {
    $(ctrl).removeClass('field input-error');
  }
}

function recheckPage(onSubmit) {
  if (validation) {
    var jumpToError = false;
    if (typeof(onSubmit)=='boolean') jumpToError = onSubmit;
    var retVal = validation.checkPage(jumpToError);
    return retVal;
  }
  return false;
}

var validation;
function registerValidation(ctrlId, sectionSummaryId, errorlineId, validateFunction, parameters, enabled) {
  if (typeof(validation) == 'undefined') validation = new Validation();
  validation.register(ctrlId, sectionSummaryId, errorlineId, validateFunction, parameters, enabled);
}

function validateSelectbox(item) {
  return ($(item.ctrlId)[0].selectedIndex > 0);
}

function validateNotEmpty(item) {
  return ($.trim($(item.ctrlId).val()).length > 0);
}

function validateString(item, regex) {
  var ret;
  var value = $.trim($(item.ctrlId).val());
  var v = new RegExp(regex);
  var m = v.exec(value);
  ret = (m != null && value == m[0]);
  return ret;
}

function isSelected(selectId, value) {
  return (getSelectedValue(selectId) == value);
}

function getSelectedValue(selectId) {
	var ret;
  $.each($('#'+selectId)[0].options, function() {
    if (this.selected==true) { ret = this.value; return; }
  });
	return ret;
}

function disableElement(ctrlId) {
  var elem = $('#'+ctrlId)[0];
  elem.disabled = true;
  var elemNodeName = elem.nodeName.toLowerCase();
  if (elemNodeName == 'input')
  {
    if (elem.type == 'text') $(elem).val('').removeClass('input-error');
    if (elem.type == 'checkbox') $(elem).attr('checked', 'false').removeClass('input-error');
  }
}

function enableElement(ctrlId) {
  $('#'+ctrlId)[0].disabled = false;
}

function displayMandatoryMarker(ctrlId, twoCols, state) {
  var targetStar, targetLabel, elem = $('#'+ctrlId)[0];
  if (arguments.length < 3) state = true;
  try {
    targetStar = $(getFirstChild(elem.parentNode.parentNode)).find('img');
    if (twoCols) {
      targetLabel = $(elem.parentNode.parentNode.parentNode);
    } else {
      targetLabel = $(elem.parentNode.parentNode);
    }
    if (state)
    {
      targetStar.css('display', 'inline');
      $(targetStar.parent()).css('width', '23px');
      targetLabel.removeClass('insertion-line-simple').addClass('insertion-line-bold');
    } else {
      targetStar.css('display', 'none');
      $(targetStar.parent()).css('width', '0px');
      targetLabel.removeClass('insertion-line-bold').addClass('insertion-line-simple');
    }
  } catch (e) {}
}

function getFirstChild(elem) {
  if (elem.childNodes.length==0) return;
  var children = elem.childNodes.length;
  for (var i=0; i<=children; ++i)
  {
    if (elem.childNodes[i].nodeType==1) return elem.childNodes[i];
  }
  return;
}

function clearField(ctrlId) {
    var elem = $('#' + ctrlId)[0];
    if (elem.type == 'select-one') {
        elem.selectedIndex = 0;
    }
    if (elem.type == 'text' || elem.type == 'textarea') {
        elem.value = "";
    }
    if (elem.type == 'checkbox') {
        elem.checked = false;
    }
   }

 function displayMandatoryMarkerForFinancing(ctrlId, twoCols, state) {
   	var targetStar, targetLabel, elem = $('#' + ctrlId)[0];
   	if (arguments.length < 3) state = true;
   	try {
   		targetStar = $(getFirstChild(elem.parentNode.parentNode)).find('img');
   		if (twoCols) {
   			targetLabel = $(elem.parentNode.parentNode.parentNode);
   		} else {
   			targetLabel = $(elem.parentNode.parentNode);
   		}
   		if (state) {
   			targetStar.css('display', 'inline');
   			$(targetStar.parent()).css('width', '23px');
   			targetLabel.removeClass('insertion-line-simple-financing').addClass('insertion-line-bold-financing');
   		} else {
   			targetStar.css('display', 'none');
   			$(targetStar.parent()).css('width', '0px');
   			targetLabel.removeClass('insertion-line-bold-financing').addClass('insertion-line-simple-financing');
   		}
   	} catch (e) { }
   }


