
//This function serves as a barcode class.
//var BarcodeDescriptor = function (descriptorName, descriptorFieldId, descriptorType, descriptorIso, descriptorWms, descriptorAI, descriptorMin, descriptorMax, descriptorDate)
var BarcodeDescriptor = function (barcode)
{
    if (!(this instanceof BarcodeDescriptor))
        return new BarcodeDescriptor(name)

    this.name = barcode.Name;
    this.barcodeFieldId = barcode.BarcodeFieldId;
    this.barcodeType = barcode.BarcodeType;
    this.isoPrefix = barcode.IsoPrefix;
    this.wmsPrefix = barcode.WmsPrefix;
    this.applicationIdentifier = barcode.ApplicationIdentifier;
    this.minLength = barcode.MinLength;
    this.maxLength = barcode.MaxLength;
    this.isDate = barcode.IsDate;

    this.dataValue = '';
    this.hasData = false;    

    this.getname = function () {
        return this.name;
    }
    this.getbarcodeFieldId = function () {
        return this.barcodeFieldId;
    }
    this.getbarcodeType = function () {
        return this.barcodeType;
    }
    this.getisoPrefix = function () {
        return this.isoPrefix;
    }
    this.getwmsPrefix = function () {
        return this.wmsPrefix;
    }
    this.getapplicationIdentifier = function () {
        return this.applicationIdentifier;
    }
    this.getminLength = function () {
        return this.minLength;
    }
    this.getmaxLength = function () {
        return this.maxLength;
    }
    this.getisDate = function () {
        return this.isDate;
    }
    this.getDataValue = function () {
        return this.dataValue;
    }
    this.getHasData = function () {
        return this.hasData;
    }
    this.setDataValue = function(data){
        this.hasData = true;
        this.dataValue=data;
    }
    //In order to move this object around in other lists we must declare a function that returns the instance of the object... ishish.... it is unknown how js
    //handles manipulation of the returned object if added to another array for example..
    this.getBarcodeDescriptor = function () {
        return this;
    }
};

var BarcodeDescriptorList = function()
{
	var self = {};
	self.list = [];
	self.count = 0;
	self.currentDescriptors = [];
	self.valueDescriptors = [];
	self.hasIsoPrefix = false;
	self.hasWmsPrefix = false;

	self.addDescriptor = function(addDescriptor)
	{	
		self.list.push(new BarcodeDescriptor(addDescriptor));
		self.updatecount();
	}
//	self.addDescriptor = function(descriptorName, descriptorFieldId, descriptorType, descriptorIso, descriptorWms, descriptorAI, descriptorMin, descriptorMax, descriptorDate)
//	{	
//	    var desc = new BarcodeDescriptor(descriptorName, descriptorFieldId, descriptorType, descriptorIso, descriptorWms, descriptorAI, descriptorMin, descriptorMax, descriptorDate);
//		self.list.push(desc);
//		self.updatecount();
//	}

	self.clear = function () {
	    //self.count = 0;
	    //self.list = [];
	    self.currentDescriptors = [];
	    self.valueDescriptors = [];
	    self.hasIsoPrefix = false;
	    self.hasWmsPrefix = false;
	    self.isGs128 = false;
	}

	self.listalldescriptornames = function () {
	    var data = '';
	    for(var i = 0; i<self.count;i++)
	    {
	        data += self.list[i].getname()+'\r\n';
	    }
	    //alert(data);
	}



	self.setDescriptor = function (barcodeText) {
	    self.clear();
	    //alert('in set descriptor');
	    var isoDescriptorTestVar = barcodeText.substring(0, 3);

        //First we check for an ISO prefix
	    for (var i = 0; i < self.list.length; i++) {
	       //alert('Comparing ' + self.list[i].getisoPrefix() + ' with ' + isoDescriptorTestVar);
	        if (isoDescriptorTestVar == self.list[i].getisoPrefix()) {
	            //alert('has iso');
	            self.hasIsoPrefix = true;
	            if (isoDescriptorTestVar == ']C1') {
                    //alert('is gs128')
	                self.isGs128 = true;
	            }
	            else {
	               // alert('is not gs128');
	                self.isGs128 = false;
	            }
	            //alert('iso prefix found');
	            self.currentDescriptors.push(self.list[i].getBarcodeDescriptor());
	            //alert('push to current successfull if no undefined statement above!');
	            //alert('current list.length = ' + self.currentDescriptors.length);
	            if (!defined(self.list[i].getapplicationIdentifier())) {
	                //alert('we have no AID');
	            }
	            else {
	                //alert(''+self.list[i].getapplicationIdentifier().length);
	            }
	            //if(self.list[i].getapplicationIdentifier().length==0)
	            //{
	            //    var valueDescr = new BarcodeDescriptor({ "BarcodeFieldId": self.list[i].barcodeFieldId });
	            //    //alert('valDesc created: barcodetext = ' + barcodeText);
	                
	            //    var bctlength = barcodeText.length;
	            //    //alert(bctlength);
	            //    valueDescr.setDataValue(barcodeText.substring(3));
	            //    //alert('data has been set');
	            //    self.valueDescriptors.push(valueDescr);
	            //    //alert('data has been pushed');
	            //    return;
	            //}
	        }
	    }
	    
        //If we dont have an ISO prefix we test for wms prefixes
	    if (self.hasIsoPrefix == false) {
	        var wmsDescriptorTestVar = barcodeText.substring(0, 1);
	        for (var i = 0; i < self.list.length; i++) {
	            if (wmsDescriptorTestVar == self.list[i].getwmsPrefix()) {
	                self.hasWmsPrefix = true;
	                self.currentDescriptors.push(self.list[i].getBarcodeDescriptor());
	            }
	        }//Gotcha... there may be an unknown iso identifier..!
	        if(self.hasWmsPrefix==false)
	        {
	            wmsDescriptorTestVar = barcodeText.substring(3, 4);
	            for (var i = 0; i < self.list.length; i++) {
	                if (wmsDescriptorTestVar == self.list[i].getwmsPrefix()) {
	                    self.hasWmsPrefix = true;
	                    self.currentDescriptors.push(self.list[i].getBarcodeDescriptor());
	                }
	            }
	        }
	    }
	    else if (self.hasIsoPrefix == true) {
	        var wmsDescriptorTestVar = barcodeText.substring(3, 4);
	        for (var i = 0; i < self.list.length; i++) {
	            if (wmsDescriptorTestVar == self.list[i].getwmsPrefix()) {
	                self.hasWmsPrefix = true;
	                self.currentDescriptors.push(self.list[i].getBarcodeDescriptor());
	            }
	        }
	    }

            //In case we cant identify the scanned code, add an unkown descriptor to the current descriptors array
	    else if (self.hasIsoPrefix == false && self.hasWmsPrefix == false) {
	        self.currentDescriptors.push(new BarcodeDescriptor({}).getBarcodeDescriptor());	        
	    }

	    //alert('Current descriptors length = ' + self.currentDescriptors.length);
	    if (self.isGs128) {
	        //alert('Dissecting as gs128');
	        self.dissectUsingDescriptors(barcodeText);
	    }
	    else {
	        //alert('Dissecting as Standard');
	        self.dissectStandardCodes(barcodeText.substring(3, barcodeText.length));
	    }
	}

	self.dissectStandardCodes = function (barcodeText) {
	    for(var i = 0; i<self.currentDescriptors.length;i++)
	    {
	        //alert(' checking if ' + barcodeText.length + ' is less than or equal to ' + self.currentDescriptors[i].getmaxLength() + ' and that it is greater than or equal to ' + self.currentDescriptors[i].getminLength());
	        if (barcodeText.length <= self.currentDescriptors[i].getmaxLength()
                && barcodeText.length >= self.currentDescriptors[i].getminLength()) {
                //alert('Testing')
	            var valueDescr = new BarcodeDescriptor({ "BarcodeFieldId": self.currentDescriptors[i].barcodeFieldId });
	            valueDescr.setDataValue(barcodeText);
	            self.valueDescriptors.push(valueDescr);
	        }
	    }
	}

	self.dissectUsingDescriptors = function (barcodeText) {

	    var localBarCode = barcodeText.concat("");
        var wmsPrefixLetter = '';
	    //alert(localBarCode);
	    if (self.hasIsoPrefix == true) {
	        localBarCode = localBarCode.substring(3, localBarCode.length);
	       //alert(localBarCode);
	        if (self.hasWmsPrefix == true) {
	            wmsPrefixLetter = localBarCode.substring(0, 1);
	            localBarCode = localBarCode.substring(1, localBarCode.length);

	        }
	    }
	    else if (self.hasWmsPrefix == true) {
	        wmsPrefixLetter = localBarCode.substring(0, 1);
	        localBarCode = localBarCode.substring(1, localBarCode.length);
	    }

	    ////alert('wmsprefix: ' + wmsPrefixLetter);
       
	    var groupSeparator = String.fromCharCode(29);
	    var testSeparator = '@';
	    //0159123123321321101234562120130605001

        
	    //Iterate for applicationIdentifiers
	    if (self.hasWmsPrefix == false && self.hasIsoPrefix == true) {
	        //alert('ai count :' + self.currentDescriptors.length);
	        var num = 0;
	        while (localBarCode.length > 0) 
	        {
                
	            //alert(localBarCode);
	            var aiFromBarcode = localBarCode.substring(0, 2);
	            //alert('Barcode ai: ' + aiFromBarcode);
	            var tmpValue = null;
	            var applicationIdentifierFound = false;
	            for (var i = 0; i < self.currentDescriptors.length; i++) {
	                var appId = self.currentDescriptors[i].getapplicationIdentifier();
	                var valueDescr = new BarcodeDescriptor({"BarcodeFieldId": self.currentDescriptors[i].barcodeFieldId});
	                if (appId.length > 0) {
	                    //alert('comparing ai: ' + aiFromBarcode+' with '+appId);
	                    if (aiFromBarcode == appId) {
	                        applicationIdentifierFound = true;

	                        //alert('found appid: ' + appId);

	                        //If the length is fixed we need not worry about anything else, but only return the value;
	                        if (self.currentDescriptors[i].getminLength() == self.currentDescriptors[i].getmaxLength()) {
	                            var endIndex = parseInt(self.currentDescriptors[i].getmaxLength());
	                            endIndex++;
	                            endIndex++;
	                            //alert('len: ' + endIndex);
	                            tmpValue = localBarCode.substring(2, endIndex);
	                            localBarCode = localBarCode.substring(endIndex, localBarCode.length);

	                            valueDescr.setDataValue(tmpValue);
	                            self.valueDescriptors.push(valueDescr);

	                            //alert('found temporary value: ' + tmpValue);
	                            break;
	                        }

	                        if (localBarCode.length >= self.currentDescriptors[i].getmaxLength() && parseInt(self.currentDescriptors[i].getminLength) <
                                parseInt(self.currentDescriptors[i].getmaxLength)) {
	                            //alert('found Variable length ai and the barcode length is larger than the max length of the ai field type ');

	                            var delimiterIndex = localBarCode.indexOf(testSeparator);
	                            //alert('delim index: ' + delimiterIndex);
	                            if (delimiterIndex == -1) {
	                                delimiterIndex = localBarCode.indexOf(groupSeparator);
	                            }
	                            //alert('delim index: ' + delimiterIndex);
	                            if (delimiterIndex > -1) {
	                                tmpValue = localBarCode.substring(2, delimiterIndex);
	                                localBarCode = localBarCode.substring(delimiterIndex + 1, localBarCode.length);

	                                valueDescr.setDataValue(tmpValue);
	                                self.valueDescriptors.push(valueDescr);
	                                //alert('Added a new thing');
	                            }
	                            else if (delimiterIndex == -1) {
	                                tmpValue = localBarCode.substring(2, localBarCode.length);
	                                //alert('found temporary value: ' + tmpValue);
	                                localBarCode = '';

	                                valueDescr.setDataValue(tmpValue);
	                                self.valueDescriptors.push(valueDescr);
	                                //alert('Added a new thing');
	                            }
	                            else {
	                                localBarCode = localBarCode.substring(delimiterIndex + 1, localBarCode.length);
	                            }



	                        }
	                        else if (localBarCode.length > self.currentDescriptors[i].getminLength()) {
	                            //alert('barcode length is larger than the ai field type min length');
	                            var delimiterIndex = localBarCode.indexOf(testSeparator);
	                            //alert('delim index: ' + delimiterIndex);
	                            if (delimiterIndex == -1) {
	                                delimiterIndex = localBarCode.indexOf(groupSeparator);
	                            }
	                            //alert('delim index: ' + delimiterIndex);
	                            if (delimiterIndex > -1) {
	                                tmpValue = localBarCode.substring(2, delimiterIndex);
	                                //alert('found temporary value: ' + tmpValue);
	                                localBarCode = localBarCode.substring(delimiterIndex + 1, localBarCode.length);

	                                valueDescr.setDataValue(tmpValue);
	                                self.valueDescriptors.push(valueDescr);
	                               //alert('Added a new thing');
	                            }
	                            else if (delimiterIndex == -1) {
	                                tmpValue = localBarCode.substring(2, localBarCode.length);
	                                //alert('found temporary value: ' + tmpValue);
	                                localBarCode = '';

	                                valueDescr.setDataValue(tmpValue);
	                                self.valueDescriptors.push(valueDescr);
	                                //alert('Added a new thing');
	                            }
	                            else {
	                                localBarCode = localBarCode.substring(delimiterIndex + 1, localBarCode.length);
	                            }
	                        }
	                        else if (localBarCode.length == self.currentDescriptors[i].getminLength) {
	                            tmpValue = localBarCode.substring(2, localBarCode.length);
	                            localBarCode = '';

	                            valueDescr.setDataValue(tmpValue);
	                            self.valueDescriptors.push(valueDescr);
	                            //alert('Added a new thing');
	                        }
	                    }
	                    
	                }
	                //]C1015912312332132110123456@2120130605001
	                //]A0L12345
	                //]C0L123456
	                //]C0K1234567
	                //]C0K1234567
	                //]C0L12345678
	                //]C0L12345678
	                //]C110123456@400123456@37123456

	                //]A0L12345
	                //    ]E05700004003001



	                //num++;
	                //if (num == 3) {
	                //    localBarCode = '';
	                //    break;
	                //}
	            }

	            if (applicationIdentifierFound == false) {
	             //We did not identify the AI so we need to rid the barcode of this nuisance

	                var delimiterIndex = localBarCode.indexOf(testSeparator);
	                ////alert('delim index: ' + delimiterIndex);
	                if (delimiterIndex == -1) {
	                    delimiterIndex = localBarCode.indexOf(groupSeparator);
	                }
	                ////alert('delim index: ' + delimiterIndex);
	                if (delimiterIndex > -1) {
	                    ////alert('found temporary value: ' + tmpValue);
	                    localBarCode = localBarCode.substring(delimiterIndex + 1, localBarCode.length);
	                }
	                else if (delimiterIndex == -1) {
	                    localBarCode = '';
	                }
	            
	            }
	        }
	    }
	    else if (self.hasWmsPrefix) {
	        ////alert('Wms prefix should be easy');
	        for (var i = 0; i < self.currentDescriptors.length; i++) {
	            if (wmsPrefixLetter == self.currentDescriptors[i].getwmsPrefix()) {
	                tmpValue = localBarCode.substring(0, localBarCode.length);
	                localBarCode = '';
	                var valueDescr = new BarcodeDescriptor({ "BarcodeFieldId": self.currentDescriptors[i].barcodeFieldId });
	                if (!self.hasIsoPrefix) {
	                    tmpValue = wmsPrefixLetter + tmpValue;
	                }
	                valueDescr.setDataValue(tmpValue);
	                self.valueDescriptors.push(valueDescr);
	                ////alert('Added a new thing');
	                break;
	            }
	        }

	    }
	    ////alert('found: ' + self.valueDescriptors.length);
	    
	}

	self.updatecount = function () {
		self.count = self.list.length
	}

	self.InitializeGenericScanning = function () {
	//    console.log('Creating element');
	//    var txt = document.createElement('scanner_input');
	//    console.log('setting attributes type');
	//    txt.setAttribute("type", 'text');
	//    console.log('setting attributes name');
	//    txt.setAttribute("name", 'name');
	//    //select element in which you want to append textbox
	//    //var foo = document.getElementById("#Receive_Product2")
	//    console.log('appending to specified part');

	//    //$("#Receive_Product2").append(txt);
	//    console.log(txt.innerHTML);

	//    var $newdiv1 = $('<div id="object1"/>'),
    //newdiv2 = document.createElement('div'),
    //existingdiv1 = document.getElementById('Receive_Product2');
	//    console.log('Attempting jquery append');
	//    $('Receive_Product2').append($newdiv1, [newdiv2, existingdiv1]);

	    //foo.appendChild(txt);
	}

	return self;
}

var barcodedescriptorlist = BarcodeDescriptorList();


