﻿function BarcodeController(port, statusLabelId, callBackFunc) {
	this.inloop = false;
	this.LastBarcode = "";
	this.IsReadingBarcode = false;
	this.Port = port;
	this.CallBackFunc = callBackFunc;
	this.StatusLabelID = statusLabelId;
	this.StopLooping = false;
	this.TimeOutIds = new Array();

	window.hasinControlManager.Register("BarcodeController", this);
}
BarcodeController.prototype.ShowStatus = function (str) {
	var element = document.getElementById(this.StatusLabelID);

	if (element != null)
		element.innerText = str;
}
BarcodeController.prototype.ShowWaitingForBarcode = function () {
	this.ShowStatus("منتظر دریافت اطلاعات از بارکدخوان...");
}
BarcodeController.prototype.ShowReadyToUse = function () {
	//	this.ShowStatus("جهت استفاده کلیک کنید...");
	this.ShowStatus("");
}
BarcodeController.prototype.Stop = function () {
	this.StopLooping = true;

	for (var i = 0; i < this.TimeOutIds.length; i++)
		clearTimeout(this.TimeOutIds[i]);
}
BarcodeController.prototype.GetModule = function () {
	if (this.CheckBrowser())
		return document.getElementById('IEHasinSCardActiveCtrl');
	else
		return document.getElementById('HasinSCardActiveCtrl');
}
BarcodeController.prototype.CheckBrowser = function () {
	var ua = window.navigator.userAgent
	var msie = ua.indexOf("MSIE ")

	if (msie > 0)	      // If Internet Explorer, return version number
		return 1;          //parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
	else                  // If another browser, return 0
		return 0;
}
BarcodeController.prototype.ReadBarcode = function (callBackFunc) {
	var module = this.GetModule();

	if ((module == null) || module.IsBlock())
		return;

	if (!this.IsReadingBarcode) {
		this.IsReadingBarcode = true;
		this.StopLooping = false;

		this.ShowWaitingForBarcode();
		module.ReadBarcode(this.Port);

		this.TimeOutIds.push(setTimeout('hasin("BarcodeController").GoFor();', 100));
	}
}
BarcodeController.prototype.GoFor = function () {
	var module = this.GetModule();

	if ((module == null) || module.IsBlock()) {
		if (!this.StopLooping) {
			this.TimeOutIds.push(setTimeout('hasin("BarcodeController").GoFor();', 100));
		}
		else {
			this.IsReadingBarcode = false;
			this.ShowReadyToUse();
		} return;
	}

	var tmp = module.GetResult();

	if ((tmp != undefined) && (tmp != null) && (tmp != "")) {
		this.LastBarcode = tmp;

		if (typeof (this.CallBackFunc) == 'function')
			try {
				this.CallBackFunc(this.LastBarcode);
			} catch (e) {
			}

		this.ShowReadyToUse();
		this.IsReadingBarcode = false;
	}
}
