﻿function AutoJumpData(controller, id, maxLength, additionalData) {
    this.controller = controller;
    this.id = id;
    this.maxLength = maxLength;
    this.addtionalData = additionalData;
    this.GetControl().onkeyup = function(event) { return hasin(controller.id).CheckGoNext(this, event); };
}
AutoJumpData.prototype.GetControl = function () {
    return document.getElementById(this.id);
}

function AutoJumpController(id) {
    if (!id)
        id = "default_autojump";

    this.id = id;

    window.hasinControlManager.Register(id, this);
    this.autojumps = new Array();
    this.currentIndex = 0;
}
AutoJumpController.prototype.Register = function (id, maxLength, additionalData) {
	this.autojumps.push(new AutoJumpData(this, id, maxLength, additionalData));
}
AutoJumpController.prototype.FindIndex = function (control) {
    for (var i = 0; i < this.autojumps.length; i++)
    	if (this.autojumps[i].GetControl() == control)
            return i;

    return -1;
}
AutoJumpController.prototype.GetCurrent = function () {
	if (this.currentIndex >= this.autojumps.length)
		return null;
	else
		return this.autojumps[this.currentIndex];
}
AutoJumpController.prototype.GoToNext = function (control) {
	var firstPos = this.FindIndex(control);

	if (firstPos < 0)
		firstPos = 0;

	this.currentIndex = firstPos;
	if (firstPos >= this.autojumps.length)
		return;

	var control = null;

	for (var i = 1; i <= this.autojumps.length; i++) {
		var nextIndex = (i + firstPos) % this.autojumps.length;
		var autojump = this.autojumps[nextIndex];
		control = autojump.GetControl();
		var value = control.value;

		if (!control.disabled && (value.length < autojump.maxLength))
			break;

	}

	if ((control != null) && !control.disabled)
		control.focus();
}
AutoJumpController.prototype.CheckGoNext = function (e, event) {
	var ch = event.keyCode * 1;
	if (isNaN(ch))
		return;

	var control = e;
	var index = this.FindIndex(control);

	if (index < 0)
		return;

	var value = control.value + "";
	var newValue = value;// +String.fromCharCode(ch);

	if (newValue.length >= this.autojumps[index].maxLength) {
		var returnVal = newValue.length <= this.autojumps[index].maxLength;
		this.GoToNext(control);

		return returnVal;
	}

	return true;
}

window.autoJumpController = new AutoJumpController();
