text:
var site_url = "/";
var decimalPlaces = 3;

$(function () {

        $("input.display").on("click", function(e){
            e.preventDefault();

            var $curclick = $(this).val();
            var $serval   = $(".search_box input.search").val();
            var $tableid  = $("table#ship-details");

            SearchCode($serval,$tableid,$curclick)

        });

function SearchCode(searchTerm, tableid, buttons) {

    if(buttons == 'CLEAR'){
        $(".search_box input.search").val("").focus();
        $('.bb').removeClass('curloc');
    } else {

        if(searchTerm) {
            var tableid = tableid || "body";

            if(!$('.bb').hasClass('curloc')){

             tableid.find('input.barcode').each(function(index) {
                    $(this).removeClass('matched');
                    $(this).siblings('.upc_1, .upc_2').removeClass('matched');

                    var bc = $(this).val();
                    var upc1 = $(this).siblings('.upc_1').val();
                    var upc2 = $(this).siblings('.upc_2').val();

                    var bf = '';
                    var upf1 = '';
                    var upf2 = '';

                    console.log(searchTerm);
                    console.log(upc2);

                    if(bc == searchTerm) {
                        bf = $(this).addClass('matched');
                        console.log('barcode');
                    }
                    else if(upc1 == searchTerm ){
                        upf1 = $(this).siblings('.upc_1').addClass('matched');
                        console.log('upc1');
                    }

                    else if(upc2 == searchTerm ){
                        upf2 = $(this).siblings('.upc_2').addClass('matched');
                        console.log('upc2');
                    }

                    if(bc == searchTerm) {
                        $('.bb').removeClass('curloc');

                        $('.matched').eq(0).siblings('.bb').addClass('curloc').focus();

                        temp = $(this).val();
                        cc=1;
                        getindex = index+1;
                    }

                    else if(upc1 == searchTerm) {
                        $('.bb').removeClass('curloc');

                        $('.matched').eq(0).siblings('.bb').addClass('curloc').focus();

                        temp = $(this).siblings('.upc_1').val();
                        cc=1;
                        getindex = index+1;
                    }

                     else if(upc2 == searchTerm) {
                        $('.bb').removeClass('curloc');

                        $('.matched').eq(0).siblings('.bb').addClass('curloc').focus();

                        temp = $(this).siblings('.upc_2').val();
                        cc=1;
                        getindex = index+1;
                    }

                });

            } else {

                if(temp == searchTerm){
                    $('.bb').removeClass('curloc');

                    tableid.find('input.matched').each(function(index) {
                        getindex = index+1;
                    });

                    if(getindex == 1){
                        cc=0;
                    }

                    $('.matched').eq(cc).siblings('.bb').addClass('curloc').focus();

                    cc+=1;

                    if(cc == getindex){
                        cc=0;
                    }

                } else {

                tableid.find('input.barcode').each(function(index) {
                    $(this).removeClass('matched');
                    $(this).siblings('.upc_1, .upc_2').removeClass('matched');

                    var bc = $(this).val();
                    var upc1 = $(this).siblings('.upc_1').val();
                    var upc2 = $(this).siblings('.upc_2').val();

                    var bf = '';
                    var upf1 = '';
                    var upf2 = '';

                    if(bc == searchTerm) {
                        bf = $(this).addClass('matched');
                    }
                    else if(upc1 == searchTerm ){
                        upf1 = $(this).siblings('.upc_1').addClass('matched');
                    }

                    else if(upc2 == searchTerm ){
                        upf2 = $(this).siblings('.upc_2').addClass('matched');
                    }

                    if(bc == searchTerm) {
                        $('.bb').removeClass('curloc');

                        $('.matched').eq(0).siblings('.bb').addClass('curloc').focus();

                        temp = $(this).val();
                        cc=1;
                        getindex = index+1;
                    }

                    else if(upc1 == searchTerm) {
                        $('.bb').removeClass('curloc');

                        $('.matched').eq(0).siblings('.bb').addClass('curloc').focus();

                        temp = $(this).siblings('.upc_1').val();
                        cc=1;
                        getindex = index+1;
                    }

                     else if(upc2 == searchTerm) {
                        $('.bb').removeClass('curloc');

                        $('.matched').eq(0).siblings('.bb').addClass('curloc').focus();

                        temp = $(this).siblings('.upc_2').val();
                        cc=1;
                        getindex = index+1;
                    }

                });

                }
            }
        } else {
            alert('Field is empty');
        }
    }

}

    $('.print-tag-form form, .dispatch-form form').bind("keypress", function(e) {
      if (e.keyCode == 13) {
        e.preventDefault();
        return false;
      }
    });

	 $("form#w0").on("beforeSubmit", function (event, messages, deferreds, attribute) {
       // $("button[type=\"submit\"]").attr("disabled","disabled");
    });
	/*date picker*/
	/*
	if (jQuery().datePicker) {
		$( "#datepicker-1, #datepicker-2" ).datepicker({
			showOn: "button",
			buttonImage: "../images/calendar.gif",
			buttonImageOnly: true,
			buttonText: "Select date"
		});
	}*/

	/*modal view*/
	$("#forgotpassword, #openpallet, #closepallet, #rejectpallet, #createto").modal('hide');

	/*dropdown menu*/
	$('.dropdown-toggle').dropdown();

	/*temporary direct page*/
	$( ".cancel-button" ).click(function(e){
		e.preventDefault();
		goBack();
	});

	$( ".backto" ).click(function(e){
		e.preventDefault();
		goBack();
	});

	$( ".back-to-main" ).click(function(e){
		e.preventDefault();
		gotoMain();
	});

	$( ".disabled-button" ).click(function(e){
		e.preventDefault();
	});

	$( ".goto-recieving" ).click(function(e){
		e.preventDefault();
		gotoReceiving();
	});

});

/*function temporary direct page*/
function goBack() {
    window.history.back();
}

function backto() {
    window.history.back();
}

function gotoMain() {
    window.location = base_url;
}

function gotoReceiving() {
    window.location = "/";
}

/* function to set value to any HTML field by id */
function setFieldValueById(id, value, onchange) {
	if (document.getElementById(id)) {
		document.getElementById(id).value = value;

		// trigger onchange event on change value of field
		if (onchange) {
		    var ctrl = document.getElementById(id);
            if (document.createEvent && ctrl.dispatchEvent) {
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("change", true, true);
                ctrl.dispatchEvent(evt); // for DOM-compliant browsers
            } else if (ctrl.fireEvent) {
                ctrl.fireEvent("onchange"); // for IE
            }
		}
	}
}

/* function to get value of any HTML field by name */
function setFieldValueByName(name, value, onchange) {
	if (document.getElementsByName(name)[0]) {
		document.getElementsByName(name)[0].value = value;

		// trigger onchange event on change value of field
		if (onchange) {
		    var ctrl = document.getElementsByName(name)[0];
            if (document.createEvent && ctrl.dispatchEvent) {
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("change", true, true);
                ctrl.dispatchEvent(evt); // for DOM-compliant browsers
            } else if (ctrl.fireEvent) {
                ctrl.fireEvent("onchange"); // for IE
            }
		}
	}
}

/* function to get the inner html of any HTML element */
function getInnerHTMLById(id) {
	if (document.getElementById(id)) {
		return document.getElementById(id).innerHTML;
	}
}

/* function to set the inner html of any HTML element */
function setInnerHTMLById(id, value) {
	if (document.getElementById(id)) {
		document.getElementById(id).innerHTML = value;
	}
}

/* function to get value of any HTML field by id */
function getFieldValueById(id) {
	return document.getElementById(id).value;
}

function getFieldValueRadioByName(name) {
	var radioFields = document.getElementsByName(name);
	var radioValue = '';

	for(var i = 0; i < radioFields.length; i++){
		if(radioFields[i].checked){
			radioValue = radioFields[i].value;
			break;
		}
	}

	return radioValue;
}

/* function to get value of any HTML field by name */
function getFieldValueByName(name) {
	return document.getElementsByName(name)[0].value;
}

/* function to set field value to uppercase */
function setFieldValueToUpperCaseById(id) {
    setFieldValueById(id, getFieldValueById(id).toUpperCase());
}

/* function to filter non-numeric field value */
function filterNonNumericFieldValue(id) {
    setFieldValueById(id, getFieldValueById(id).replace(/[^\d.-]/g,''));
}

/* function to convert to decimal format */
function convertToDecimalFormat(value, numberOfDecimals) {
    var decimal = '.';

    for (var i = 0; i < numberOfDecimals; i++) {
        decimal = decimal + '0';
    }
    /* if the user didn't add a dot, we add one with 3 zeros */
    if (value.indexOf('.') == -1) value += decimal;
    /* Otherwise, we check how many numbers there are after the dot
       and make sure there's at least 3*/
    if (value.substring(value.indexOf('.') + 1).length < numberOfDecimals)
        while (value.substring(value.indexOf('.') + 1).length < numberOfDecimals)
            value += '0';
    return value;
}

/* function to hide HTML element by id */
function hideHTMLById(id) {
	document.getElementById(id).style.display = "none";
}

/* function to show HTML element by id */
function showHTMLById(id) {
	document.getElementById(id).style.display = "block";
}

// For todays date;
Date.prototype.today = function () {
    return (((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) + ((this.getDate() < 10)?"0":"") + this.getDate()
        + this.getFullYear().toString().substring(2,4);
}

// For the time now
Date.prototype.timeNow = function () {
     return ((this.getMinutes() < 10)?"0":"") + this.getMinutes() + ((this.getSeconds() < 10)?"0":"") + this.getSeconds();
}

/* function to generate timestamp */
function getTimestamp() {
    var currentDate = new Date();
    var dateTime = currentDate.today() + currentDate.timeNow();
	return dateTime;
}

/* function to check material sled */
function checkMaterialSled(dateType) {
    var materialSled = getMaterialSled();

	if (null != materialSled && materialSled != 0 && dateType == "manufacturing_date") {
		var calculatedDate = calculateDate(getFieldValueById("trxtransactiondetails-manufacturing_date"),materialSled,"add");
		if(calculatedDate)
		{
			setFieldValueById("trxtransactiondetails-expiry_date",calculatedDate);
		}
	}

    if (null != materialSled && materialSled != 0 && dateType == "expiry_date") {
		var calculatedDate = calculateDate(getFieldValueById("trxtransactiondetails-expiry_date"),materialSled,"subtract");
		if(calculatedDate)
		{
			setFieldValueById("trxtransactiondetails-manufacturing_date",calculatedDate);
		}
    }
}

/* function to add/subtract days in a date string */
function calculateDate(strDate, days, type) {
	if(!strDate)
	{
		return;
	}

    var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var date = strDate.split('-');

	if(isNaN(date[1])) //js formatted date
	{
		var year = date[2];
		var month = monthNames.indexOf(date[1]);
		 var day = date[0];
	}
	else //mysql formatted date
	{
		var year = date[0];
		var day = date[2];
		var month = date[1] - 1;
	}

	var newDate = new Date(year, month, day);

	if (type == 'add') {
		newDate.setDate(newDate.getDate() + parseInt(days));
	} else if (type == 'subtract') {
		newDate.setDate(newDate.getDate() - parseInt(days));
	} else {
		// do nothing
	}

	var dd = ('0' + newDate.getDate()).slice(-2);
	var mm = newDate.getMonth();
	var y = newDate.getFullYear();

	var formattedDate = dd + '-' + monthNames[mm] + '-' + y;

	return formattedDate;
}

/* function to search material by barcode/description */
/*
function searchMaterial() {
	var material_val = material_list_barcode[getFieldValueById("material_barcode")];
	if (null == material_val) {
		material_val = material_list_desc[getFieldValueById("material_barcode")];
	}

	return material_val;
}
*/

/* function to retrieve sled of material */
function getMaterialSled() {
	var material_sled_val = material_sled[getFieldValueById("trxtransactiondetails-material_code")];

	return material_sled_val;
}

/* function to retrieve pallet_ind of material */
function getMaterialPalletInd() {
    var material_pallet_ind_val = material_pallet_ind[getFieldValueById("trxtransactiondetails-material_code")];

    return material_pallet_ind_val;
}

/* function to retrieve unit of material conversion */
function getMaterialConversionUnit() {
	if (!material_conversion['conversion_flag']) {
	    return 'KG';
	} else {
        return material_conversion[getFieldValueById('trxtransactiondetails-net_unit')]['unit'];
	}
}

/* function to get total weight of material */
function getMaterialTotalWeight() {
	var material_total_weight = getFieldValueById("trxtransactiondetails-net_weight");
	if (null != material_total_weight && material_total_weight.length > 0) {
		switch(getMaterialConversionUnit()) {
			case 'KG':
			    material_total_weight = convertToDecimalFormat(material_total_weight, decimalPlaces);
                setFieldValueById("trxtransactiondetails-net_weight", material_total_weight);
				break;
			default:
				material_total_weight = parseFloat(getFieldValueById("trxtransactiondetails-net_weight")) * (material_conversion[getFieldValueById('trxtransactiondetails-net_unit')]['den'] /
					   material_conversion[getFieldValueById('trxtransactiondetails-net_unit')]['num']);
			    material_total_weight = material_total_weight.toFixed(decimalPlaces);
				break;
		}
	} else {
		material_total_weight = "0.000";
	}

	return material_total_weight;
}

/* function to check if the pallet can be processed */
function checkTransactionStatus() {
	if (typeof transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")] != 'undefined'
	   && transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['status'] == 'closed') {
      return false;
    } else {
      return true;
    }
}

/* function to check existing pallet kitted unit of transaction detail */
function checkTransactionKittedUnit() {
    if (checkTransactionStatus()) {
        if (null != transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]) {
            var trx_kitted_unit = transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['kitted_unit'];
            var trx_kitting_code = transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['kitting_code'];

            // set fixed value
            setFieldValueById("trxtransactiondetails-kitting_code", trx_kitting_code);
            setFieldValueById("trxtransactiondetails-kitted_unit", trx_kitted_unit);
        }
    } else {
      alert('Pallet ' + getFieldValueById("trxtransactiondetails-pallet_no") + ' is already closed.');
      document.getElementById("trxtransactiondetails-kitted_unit").value = "";
      document.getElementById("trxtransactiondetails-pallet_weight").value = "0.000";
    }
}

/* function to check pallet weight of transaction_detail */
function checkTransactionPalletWeight() {
    if (checkTransactionStatus()) {
        var trx_pallet_weight = "0.000";
        // add current net weight
        if (null != getMaterialTotalWeight()) {
            trx_pallet_weight = parseFloat(trx_pallet_weight) + parseFloat(getMaterialTotalWeight());
        }

        if (null != transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]) {
            trx_pallet_weight = parseFloat(trx_pallet_weight) + parseFloat(transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['pallet_weight']);
        }
        setFieldValueById("trxtransactiondetails-pallet_weight", trx_pallet_weight.toFixed(decimalPlaces));
	}
}

/* new function to validate pallet type of material and transaction_detail */
function validatePalletType(palletNo, materialCode, transactionId) {
    if (palletNo && transactionId) {
        load('validate-pallet?id=' + palletNo + '&material_code=' + materialCode + '&transaction_id=' + transactionId, function(xhr) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                if (jsonData.error) {
                    alert(jsonData.error);
                    setFieldValueById("trxtransactiondetails-pallet_no", "");
                } else {
                    checkTransactionKittedUnit();
                    checkTransactionPalletWeight();
                    checkTransactionPalletType();
                }
            }
        });
    }
}

function validateMaterialLocation(materialCode)
{
	if(materialCode)
	{
        load('validate-material-location?&material_code=' + materialCode, function(xhr) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                if (jsonData.error) {
                    alert(jsonData.error);
					setFieldValueById('trxtransactiondetails-material_code', '', false);
                }
            }
        });
	}
}

function validateKittingTypeLocation(materialCode)
{
	if(materialCode)
	{
        load('validate-kitting-type-location?&material_code=' + materialCode, function(xhr) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                if (jsonData.error) {
                    alert(jsonData.error);
					setFieldValueById('trxtransactiondetails-kitting_code', '', false);
                }
            }
        });
	}
}

/* new function to validate kitting type of material and transaction_detail */
function validateKittingType(palletNo, materialCode, transactionId) {
    if (palletNo && transactionId) {
        load('validate-pallet?id=' + palletNo + '&material_code=' + materialCode + '&transaction_id=' + transactionId, function(xhr) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                if (jsonData.error) {
                    alert(jsonData.error);
                    setFieldValueById("trxtransactiondetails-kitted_unit", "");
                }
            }
        });
    }
}

/* function to check pallet type of transaction_detail */
function checkTransactionPalletType() {
	if (checkTransactionStatus() && null != transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]) {
		setFieldValueById("material-pallet_type", transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['pallet_type']);
	}
}

/* function to validate pallet type of material and transaction_detail */
function validateTransactionPalletType() {
	if (null != transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")] && getFieldValueById("trxtransactiondetails-pallet_type").length > 0) {
		var pallet_type = transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['pallet_type'];
		if (pallet_type !== getFieldValueById("trxtransactiondetails-pallet_type")) {
			document.getElementsByClassName("field-trxtransactiondetails-pallet_no")[0].className = "form-group field-trxtransactiondetails-pallet_no required has-error";
			alert('Pallet type is different with the customer product pallet type.');
		} else {
			document.getElementsByClassName("field-trxtransactiondetails-pallet_no")[0].className = "form-group field-trxtransactiondetails-pallet_no required has-success";
		}
	}
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  alert('Query Variable ' + variable + ' not found');
}

/* function to retrieve material conversion */
function getMaterialConversion() {
    load('get-material-conversion?id=' + getFieldValueById("trxtransactiondetails-material_code"), function(xhr) {
        var jsonData = JSON.parse(xhr.responseText);
        material_conversion = jsonData;

        if (!jsonData.conversion_flag) {
            // remove select element
            if (document.getElementById('trxtransactiondetails-net_unit')) {
                document.getElementById('net-wt').removeChild(document.getElementById('trxtransactiondetails-net_unit'));
            }

            // add span element
            if (!document.getElementById('net-unit')) {
                var spanElem = document.createElement('span');
                spanElem.id = "net-unit";
                spanElem.innerHTML = "KG";

                document.getElementById('net-wt').appendChild(spanElem);
            }
            document.getElementById('net-weight').innerHTML = "NET WT";

            // remove unit span element
            if (document.getElementById('unit-label')) {
            	document.getElementById('unit-label').remove();
            }
        } else {
            // remove span element
            if (document.getElementById('net-unit')) {
                document.getElementById('net-unit').remove();
            }

            // add select element
            var selectElem = document.getElementById('trxtransactiondetails-net_unit');
            if (!selectElem) {
                selectElem = document.createElement('select');
                selectElem.id = "trxtransactiondetails-net_unit";
                selectElem.setAttribute('name', 'TrxTransactionDetails[net_unit]');
                selectElem.setAttribute('class', 'uborder help-25percent');
                selectElem.setAttribute('onchange', 'calculateTotalWeight()');

                document.getElementById('net-wt').appendChild(selectElem);
            }

            // clear options
            var i = 0;
            selectElem.options.length = 0;
            if (typeof jsonData.unit_1 != 'undefined' && jsonData.unit_1.unit != 'KG') {
                var option  = document.createElement('option');
                option.value = "unit_1";
                option.text = jsonData.unit_1.unit + ' (' +  jsonData.unit_1.den / jsonData.unit_1.num + ' KG)';
                selectElem.add(option, selectElem[i+1]);
                i++;
            }

            if (typeof jsonData.unit_2 != 'undefined' && jsonData.unit_2.unit != 'KG') {
                var option  = document.createElement('option');
                option.value = "unit_2";
                option.text = jsonData.unit_2.unit + ' (' +  jsonData.unit_2.den / jsonData.unit_2.num + ' KG)';
                selectElem.add(option, selectElem[i+1]);
                i++;
            }

            if (typeof jsonData.unit_3 != 'undefined' && jsonData.unit_3.unit != 'KG') {
                var option  = document.createElement('option');
                option.value = "unit_3";
                option.text = jsonData.unit_3.unit + ' (' +  jsonData.unit_3.den / jsonData.unit_3.num + ' KG)';
                selectElem.add(option, selectElem[i+1]);
                i++;
            }

            document.getElementById('net-weight').innerHTML = "QUANTITY";
        }
    });
}

function searchMaterial(value, customer_code, id) {
    load('get-material?id=' + customer_code + '&desc=' + value, function(xhr) {
        var jsonData = JSON.parse(xhr.responseText);

        var x  = document.getElementById(id);

        // clear options
        x.options.length = 0;

        // set prompt value
        var promptOption = document.createElement('option');
        promptOption.value = '';
        promptOption.text = "-- Select a material --";
        x.add(promptOption);

		if(jsonData) {
			var i  = 1;
			for(var key in jsonData)
			{
				var option  = document.createElement('option');
				option.value = key;
				option.text = jsonData[key];

				x.add(option, x[i]);
				i++;
			}
        }
		x.onchange();
    });
}

/* function to repopulate packaging type based on material pallet_ind */
function populatePackagingType() {
    load('get-packaging-type?id=' + getMaterialPalletInd() + '&plant_location=' + plant_location, function(xhr) {
        var jsonData = JSON.parse(xhr.responseText);
        var x  = document.getElementById('trxtransactiondetails-packaging_code');

        // clear options
        x.options.length = 0;

        if(null != jsonData){
            for(var i = 0; i < jsonData.material_code.length; i++){
                var option  = document.createElement('option');
                option.value = jsonData.material_code[i];
                option.text = jsonData.description[i];
                x.add(option, x[i+1]);
            }
        }
    });
}

/* function to repopulate kitting type based on material pallet_ind */
function populateKittingType() {
    load('get-kitting-type?id=' + getMaterialPalletInd() + '&plant_location=' + plant_location, function(xhr) {
        var jsonData = JSON.parse(xhr.responseText);
        var x  = document.getElementById('trxtransactiondetails-kitting_code');

        // clear options
        x.options.length = 0;

        // set prompt value
        var promptOption = document.createElement('option');
         promptOption.text = "-- Select a kitting type --";
		 promptOption.value = '';
        x.add(promptOption);

        if(null != jsonData){
            for(var i = 0; i < jsonData.material_code.length; i++){
                var option  = document.createElement('option');
                option.value = jsonData.material_code[i];
                option.text = jsonData.description[i];
                x.add(option, x[i+1]);
            }
        }
    });
}

/* function to retrieve pallet weight of transaction_detail */
function getTransactionPalletWeight() {
	var trx_pallet_weight = '0.000';
	if (null != transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]) {
		var trx_pallet_weight = parseFloat(transaction_details[getFieldValueById("trxtransactiondetails-pallet_no")]['pallet_weight']);
	}
	return trx_pallet_weight;
}

/* function to retrieve transaction list */
function getTransactionList(code){
	load('get-transaction-list?id=' + code,function(xhr) {
		document.getElementById('trxtransactiondetails-transaction_id').innerHTML='';

		var jsonData = JSON.parse(xhr.responseText);
		var x  = document.getElementById('trxtransactiondetails-transaction_id');
		//setFieldValueByName('transaction-list', ['']);

		// set prompt value
		var promptOption = document.createElement('option');
		promptOption.text = "-- Select a transaction --";
		x.add(promptOption);

		if(null != jsonData){
			for(var i = 0; i < jsonData.length; i++){
				var option  = document.createElement('option');
				option.text = jsonData[i];
				x.add(option, x[i+1]);
			}
		}

	});
}

/* function to retrieve transaction list by transaction type */
function getTransactionListByType(code, brds_type, sap_type){
    var transaction_type = 'brds';
    if (sap_type) {
        transaction_type = 'sap';
    }
    load('get-transaction-list?id=' + code + '&type=' + transaction_type,function(xhr) {
        var jsonData = JSON.parse(xhr.responseText);
        var x  = document.getElementById('trxtransactiondetails-transaction_id');

        // clear options
		x.options.length = 1;

        if(null != jsonData){
            for(var i = 0; i < jsonData.length; i++){
                var option  = document.createElement('option');
                option.text = jsonData[i];
                x[i+1] = option;
            }
        }

    });
}

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return true;
    }
    return false;
}

function removeOptions(selectbox)
{
    var i;
    for(i=selectbox.options.length-1;i>=0;i--)
    {
        selectbox.remove(i);
    }
}

/* function to retrieve transaction list */
function getMateriaList(code){
    load('get-material-list?id=' + code,function(xhr) {
      if (null != xhr.responseText && xhr.responseText.length > 0) {
        var jsonData = JSON.parse(xhr.responseText);
        var x  = document.getElementById('material-list_id');
        var promptOption = document.createElement('option');
        removeOptions(x);

		x.style.display = "block";
		promptOption.text = "-- Select a materials --";
		promptOption.value = "";
		promptOption.selected = true;
		x.add(promptOption, x[0]);

		if(jsonData) {
			var i  = 1;
			for(var key in jsonData)
			{
				var option  = document.createElement('option');
				option.value = key;
				option.text = jsonData[key];

				x.add(option, x[i]);
				i++;
			}
        } else {
            x.style.display = "none";
        }
    } else {
        document.getElementById.style.display = "none";
    }

    });
}

/*determine if obj is empty*/

/* function to retrieve transaction */
function getTransaction(id) {
	load("get-transaction?id=" + id, function(xhr) {
		if (null != xhr.responseText && xhr.responseText.length > 0) {
			var jsonData = JSON.parse(xhr.responseText);

		    if (null != jsonData) {
		    	// show transaction details panel
		    	showHTMLById("trx-details");

		    	// set corresponding field values
		    	setFieldValueByName("customer_name", jsonData.customer_name);
		    	setFieldValueByName("customer_code", jsonData.customer_code);
		    	setFieldValueByName("created_date", jsonData.created_date_formatted); // @TODO: incorrect date format
		    	setFieldValueByName("transaction_id", jsonData.id);
		    	setFieldValueByName("sap_no", jsonData.sap_no);
		    	setFieldValueByName("plant_location", jsonData.plant_location);
		    	setFieldValueByName("storage_location", jsonData.storage_location);
		    	setFieldValueByName("truck_van", jsonData.truck_van);
		    	setFieldValueByName("pallet_count", jsonData.pallet_count);
		    	setFieldValueByName("total_weight", jsonData.total_weight);

		    	remarks = jsonData.remarks;
		    } else {
		    	// hide transaction details panel
		    	hideHTMLById("trx-details");
		    }
		} else {
			// hide transaction details panel
	    	hideHTMLById("trx-details");
		}

	});
}

/* function to retrieve transaction by transaction type */
function getTransactionByType(id, brds_type, sap_type) {
    var transaction_type = 'brds';
    if (sap_type) {
        transaction_type = 'sap';
    }
    load("get-transaction?id=" + id + '&type=' + transaction_type, function(xhr) {
        if (null != xhr.responseText && xhr.responseText.length > 0) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                // show transaction details panel
                showHTMLById("trx-details");

                // set corresponding field values
                setFieldValueByName("customer_name", jsonData.customer_name);
                setFieldValueByName("customer_code", jsonData.customer_code);
                setFieldValueByName("created_date", jsonData.created_date_formatted); // @TODO: incorrect date format
                setFieldValueByName("transaction_id", jsonData.id);
                setFieldValueByName("sap_no", jsonData.sap_no);
                setFieldValueByName("plant_location", jsonData.plant_location);
                setFieldValueByName("storage_location", jsonData.storage_location);
                setFieldValueByName("truck_van", jsonData.truck_van);
                setFieldValueByName("pallet_count", jsonData.pallet_count);
                setFieldValueByName("total_weight", jsonData.total_weight);

                remarks = jsonData.remarks;
            } else {
                // hide transaction details panel
                hideHTMLById("trx-details");
            }
        } else {
            // hide transaction details panel
            hideHTMLById("trx-details");
        }

    });
}

/* function to retrieve pallet details for View & Close Pallet page */
function getPalletDetails(id) {
    load("get-pallet-details?id=" + id, function(xhr) {
        if (null != xhr.responseText && xhr.responseText.length > 0) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                // show pallet details panel
                showHTMLById("pallet-details");

                // set corresponding field values
                setFieldValueByName("transaction_id", jsonData.transaction_id);
                setFieldValueByName("inbound_no", jsonData.inbound_no);
                setFieldValueByName("customer", jsonData.customer_name);
                setFieldValueByName("material_code", jsonData.material_code);
                setFieldValueByName("batch", jsonData.batch);
                setFieldValueByName("pallet_count", jsonData.pallet_count);
                setFieldValueByName("net_weight", jsonData.net_weight);
                setFieldValueByName("total_weight", jsonData.total_weight);
                setFieldValueByName("pallet_weight", jsonData.pallet_weight);
                setFieldValueByName("kitted_unit", jsonData.kitted_unit);
                setFieldValueByName("manufacturing_date", jsonData.manufacturing_date);
                setFieldValueByName("expiry_date", jsonData.expiry_date);
                setFieldValueByName("pallet_type", jsonData.pallet_type);
                setFieldValueByName("transfer_order", jsonData.transfer_order);
                setFieldValueByName("status", jsonData.status);
                setFieldValueByName("creator", jsonData.creator);
                setFieldValueByName("created_date", jsonData.created_date);
                setFieldValueByName("updater", jsonData.updater);
                setFieldValueByName("updated_date", jsonData.updated_date);

            } else {
                // hide pallet details panel
                hideHTMLById("pallet-details");
            }
        } else {
            // hide pallet details panel
            hideHTMLById("pallet-details");
        }
    });
}

/* function to retrieve pallet details for Edit Receiving page */
function getPalletDetailsForEdit(id) {
    load("get-pallet-details?id=" + id, function(xhr) {
        if (null != xhr.responseText && xhr.responseText.length > 0) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                setFieldValueById('mstcustomer-name', jsonData.customer_code, true);
                setTimeout (function() {
                  setFieldValueById('trxtransactiondetails-transaction_id', jsonData.transaction_id);
                }, 1000);
            } else {
                // hide pallet details panel
                hideHTMLById("pallet-details");
            }
        } else {
            // hide pallet details panel
            hideHTMLById("pallet-details");
        }
    });
}

/* function used for ajax requests */
function load(url, callback) {
    var xhr;

    if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
    else {
        var versions = ["MSXML2.XmlHttp.5.0",
                        "MSXML2.XmlHttp.4.0",
                        "MSXML2.XmlHttp.3.0",
                        "MSXML2.XmlHttp.2.0",
                        "Microsoft.XmlHttp"]

             for(var i = 0, len = versions.length; i < len; i++) {
                try {
                    xhr = new ActiveXObject(versions[i]);
                    break;
                }
                catch(e){}
             } // end for
        }

        xhr.onreadystatechange = ensureReadiness;

        function ensureReadiness() {
            if(xhr.readyState < 4) {
                return;
            }

            if(xhr.status !== 200) {
                return;
            }

            // all is well
        if(xhr.readyState === 4) {
            callback(xhr);
        }
    }

    xhr.open('GET', url, true);
    xhr.send('');
}

/* function to retrieve account info */
function getAccountInfo(id) {
	load('get-account-info?id=' + id,function(xhr) {
		document.getElementById('modal-content').innerHTML=xhr.responseText;
	});
}

/* number extension for values with leading zeroes */
Number.prototype.padLeft = function(base,chr) {
    var  len = (String(base || 10).length - String(this).length)+1;
    return len > 0? new Array(len).join(chr || '0')+this : this;
}

/* function to retrieve material list by customer */
function getMaterialList(code) {
	load('get-material-list?item_code=' + code, function(xhr) {
		var jsonData = JSON.parse(xhr.responseText);
		var x  = document.getElementById('material');

		// clear options
		x.options.length = 0;

		// set prompt value
		var promptOption = document.createElement('option');
		promptOption.value = "";
		promptOption.innerHTML = "-- Select a material --";
		x.add(promptOption);

		if(jsonData) {
			var i  = 1;
			for(var key in jsonData)
			{
				var option  = document.createElement('option');
				option.value = key;
				option.text = jsonData[key];

				x.add(option, x[i]);
				i++;
			}
        }

	});
}

/* function to calculate net weight */
function calculateNetWeight() {
    var grossWeight = 0;
    var palletTare = 0;
    var productTare = 0;
    var palletPackagingTare = 0;

    if (!isNaN(parseFloat(getFieldValueById('gross_weight')))) {
	    grossWeight = parseFloat(getFieldValueById('gross_weight'));
    }

    if (!isNaN(parseFloat(getFieldValueById('pallet_tare')))) {
    	palletTare = parseFloat(getFieldValueById('pallet_tare'));
    }

    if (!isNaN(parseFloat(getFieldValueById('product_tare_total')))) {
        productTare = parseFloat(getFieldValueById('product_tare_total'));
    }

    if (!isNaN(parseFloat(getFieldValueById('pallet_packaging_tare')))) {
        palletPackagingTare = parseFloat(getFieldValueById('pallet_packaging_tare'));
    }

	var netWeight = grossWeight - (palletTare + productTare + palletPackagingTare);
	if (!isNaN(netWeight) && netWeight > 0) {
		setFieldValueById('net_weight', netWeight);
	} else {
		setFieldValueById('net_weight', '0');
	}
}

/* function to calculate total product tare */
function calculateTotalProductTare() {
	var productTare = getFieldValueById('product_tare');
	var units = getFieldValueById('units');

	if (!isNaN(productTare) && null != productTare && productTare.length > 0
		&& !isNaN(units) && null != units && units.length > 0) {
		setFieldValueById('product_tare_total', parseFloat(productTare) * parseFloat(units));
	} else {
		setFieldValueById('product_tare_total', '0');
	}
}

function calculateNOWorNEVER(){
    var grossWeight = 0;
    var palletTare = 0;
    var productTare = 0;
    var units = 0;
    var productTareTotal = 0;
    var palletPackagingTare = 0;
    var netWeight = 0;

    if (!isNaN(parseFloat(getFieldValueById('gross_weight')))) {
        grossWeight = parseFloat(getFieldValueById('gross_weight'));
    }

    if (!isNaN(parseFloat(getFieldValueById('pallet_tare')))) {
        palletTare = parseFloat(getFieldValueById('pallet_tare'));
    }

    if (!isNaN(parseFloat(getFieldValueById('product_tare')))) {
        productTare = parseFloat(getFieldValueById('product_tare'));
    }

    if (!isNaN(parseFloat(getFieldValueById('units')))) {
        units = parseFloat(getFieldValueById('units'));
    }

    if (!isNaN(parseFloat(getFieldValueById('product_tare_total')))) {
        productTareTotal = parseFloat(getFieldValueById('product_tare_total'));
    }

    if (!isNaN(parseFloat(getFieldValueById('pallet_packaging_tare')))) {
        palletPackagingTare = parseFloat(getFieldValueById('pallet_packaging_tare'));
    }

    if (!isNaN(parseFloat(getFieldValueById('net_weight')))) {
        netWeight = parseFloat(getFieldValueById('net_weight'));
    }

    ptt = (parseFloat(productTare) * parseFloat(units)).toFixed(3);
    ppt = (parseFloat(palletTare) + parseFloat(ptt)).toFixed(3);
    nt  = (parseFloat(grossWeight) - parseFloat(ppt)).toFixed(3);

	if(1 > palletTare)
	{
		setFieldValueById('units', 0);
	}

    setFieldValueById('product_tare_total', ptt);
    setFieldValueById('pallet_packaging_tare', ppt);
	document.getElementsByName('print')[0].disabled = false;

    if(nt >= 0) {
		setFieldValueById('net_weight', numberWithCommas(nt));
    } else {
        setFieldValueById('net_weight', '0');
        alert('NET Weight should not be negative value. NET Weight has changed to ZERO!');
    }
}

function validateNetWeight()
{
	var netWeight = getFieldValueById('net_weight');
	netWeight = parseFloat(netWeight.replace(',',''));

	if(1000 < netWeight)
	{
		alert('NET Weight should not be greater than 1000');
		return false;
	}

	return true;
}

function numberWithCommas(number) {
    var parts = number.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

/* function to view transaction summary */
function viewTransactionSummary(transaction_id, transaction_type) {
	if (null != transaction_id && "" != transaction_id && "-- Select a transaction --" != transaction_id) {
		window.location = "view-entries?id=" + transaction_id + "&transaction_type=" + transaction_type;
	} else {
		alert('Please select a transaction.');
	}
}

/* function to view pallet details */
function viewPalletDetails(pallet_no, transaction_id) {
	if (null != transaction_id && "" != transaction_id && "-- Select a transaction --" != transaction_id) {
		if (null != pallet_no && "" != pallet_no) {
			window.location = "view-entries?TrxTransactionDetailsSearch[pallet_no]=" + pallet_no + "&id=" + transaction_id;
		} else {
			alert('Please enter pallet no.');
		}
	} else {
		alert('Please select a transaction.');
	}
}

function createToSelectPallet(pallet_no)
{
	if(!pallet_no)
	{
		alert('Please enter pallet no.');
	}
	else
	{
		window.location = "create-to?TrxTransactionDetailsSearch[pallet_no]=" + pallet_no;
	}
}

/* synchronize js*/
var brdsdev_site_url = "http://192.168.1.121";
var brdsapi_site_url = "http://192.168.1.122/brdsapi/";

function ajax (url, method, params, container_id, loading_text) {
    try { // For: chrome, firefox, safari, opera, yandex, ...
    	xhr = new XMLHttpRequest();
    } catch(e) {
	    try{ // for: IE6+
	    	xhr = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch(e1) { // if not supported or disabled
		    alert("Not supported!");
		}
	}
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			toggleSync('hide');
			document.getElementById(container_id).innerHTML = xhr.responseText;
		} else {
			toggleSync('show');
			document.getElementById(container_id).innerHTML = loading_text;

		}
	}
	xhr.open(method, url, true);
	xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//xhr.setRequestHeader("Access-Control-Allow-Origin",brdsapi_site_url);
	xhr.send(params);
}

function ajax_view (url, method, params, container_id, loading_text) {
    try { // For: chrome, firefox, safari, opera, yandex, ...
        xhr = new XMLHttpRequest();
    } catch(e) {
        try{ // for: IE6+
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(e1) { // if not supported or disabled
            alert("Not supported!");
        }
    }
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4) {
            document.getElementById(container_id).style.display = 'block';
            document.getElementById(container_id).innerHTML = xhr.responseText;
        } else {

            document.getElementById(container_id).style.display = 'block';
            document.getElementById(container_id).innerHTML = loading_text;

        }
    }
    xhr.open(method, url, true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	//xhr.setRequestHeader("Access-Control-Allow-Origin","");
    xhr.send(params);
}

function toggleSync(display_type) {
    var e = document.getElementById("sync-progress");
    var m = document.getElementById("sync-bg");

	if(display_type)
	{
		var syncDisplay = ('show' == display_type) ? 'block' : 'none';

		if('show' == display_type)
		{
			syncDisplay = 'block';
		}

		e.style.display = syncDisplay;
		m.style.display = syncDisplay;
	}
	else
	{
		e.style.display = (e.style.display == "block") ? "none" : "block";
		m.style.display = (m.style.display == "block") ? "none" : "block";
	}
}

function ajax_dispatch (url, method, params, container_id, loading_text) {
    try { // For: chrome, firefox, safari, opera, yandex, ...
    	xhr = new XMLHttpRequest();
    } catch(e) {
	    try{ // for: IE6+
	    	xhr = new ActiveXObject("Microsoft.XMLHTTP");
	    } catch(e1) { // if not supported or disabled
		    alert("Not supported!");
		}
	}
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			document.getElementById(container_id).innerHTML = xhr.responseText;
		} else {
			document.getElementById(container_id).innerHTML = loading_text;
		}
	}
	xhr.open(method, url, true);
	xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
	xhr.send(params);
}

function onSelectMaterial(shouldNotClear) {
    if (!shouldNotClear) {
        clearAllFields();
    }

	validateMaterialLocation(getFieldValueById("trxtransactiondetails-material_code"));

    if (getFieldValueById("trxtransactiondetails-material_code") != '-- Select a product --') {
        setFieldValueById("material_code",getFieldValueById("trxtransactiondetails-material_code"));
    }
    populatePackagingType();
    populateKittingType();
    getMaterialConversion();
    populateBatchDropdown(getFieldValueById("trxtransactiondetails-material_code"), getQueryVariable('id'));

    enableDisableManufacturingDate();
}

function enableDisableManufacturingDate()
{
    var sledValue =Number(getMaterialSled());
    var disableManuDate = (0 < sledValue) ? true:false;
    $( "#trxtransactiondetails-manufacturing_date" ).datepicker( "option", "disabled", disableManuDate );

    // Set back from disabled to read-only
    $('#trxtransactiondetails-expiry_date').attr('disabled', false);
    $('#trxtransactiondetails-manufacturing_date').attr('disabled', false);
}

function clearManufacturingExpiryDates()
{
    setFieldValueById("trxtransactiondetails-manufacturing_date", "");
    setFieldValueById("trxtransactiondetails-expiry_date", "");
}

function clearAllFields() {
    setFieldValueById("trxtransactiondetails-batch", "");
    setFieldValueById("trxtransactiondetails-manufacturing_date", "");
    setFieldValueById("trxtransactiondetails-expiry_date", "");
    setFieldValueById("trxtransactiondetails-net_weight", "");
    setFieldValueById("trxtransactiondetails-total_weight", "");
    setFieldValueById("trxtransactiondetails-pallet_no", "");
    setFieldValueById("trxtransactiondetails-kitted_unit", "");
    setFieldValueById("trxtransactiondetails-pallet_weight", "");
}

function calculateTotalWeight() {
    filterNonNumericFieldValue("trxtransactiondetails-net_weight");
    setFieldValueById("trxtransactiondetails-total_weight", getMaterialTotalWeight());
    var palletWeight = parseFloat(getMaterialTotalWeight()) + parseFloat(getTransactionPalletWeight());
    setFieldValueById("trxtransactiondetails-pallet_weight", palletWeight.toFixed(decimalPlaces));

	/*
	Commenting this since it is not appended in the DOM
    // add unit span element
	var spanElem = document.getElementById('unit-label');
	if (!spanElem) {
        spanElem = document.createElement('span');
        spanElem.id = 'unit-label';
	}

	spanElem.innerHTML = ' (' + (material_conversion[getFieldValueById('trxtransactiondetails-net_unit')]['den'] /
					   material_conversion[getFieldValueById('trxtransactiondetails-net_unit')]['num']) + ' KG)';
	*/
}

var useFlag = 0;
function toggleUse(id) {
    var btnLabel = document.getElementById('btn-use').innerHTML;
	var materialSled =  getMaterialSled();

    if (!useFlag) {
        useFlag = 1;
        document.getElementById('batch-dropdown').style.display = 'block';
        document.getElementById('batch-dropdown').children[1].children[0].disabled = false;
        document.getElementById('batch-dropdown').children[1].children[0].setAttribute('class', 'uborder help-25percent');
        document.getElementById('batch-text').style.display = 'none';
        document.getElementById('batch-text').children[1].children[0].disabled = true;
        document.getElementById('batch-text').children[1].children[0].setAttribute('class', 'uborder help-25percent disabled');

		if(materialSled)
		{
			checkMaterialSled("expiry_date");
		}
    } else {
        useFlag = 0;
        document.getElementById('batch-dropdown').style.display = 'none';
        document.getElementById('batch-dropdown').children[1].children[0].disabled = true;
        document.getElementById('batch-dropdown').children[1].children[0].setAttribute('class', 'uborder help-25percent disabled');
        document.getElementById('batch-text').style.display = 'block';
        document.getElementById('batch-text').children[1].children[0].disabled = false;
        document.getElementById('batch-text').children[1].children[0].setAttribute('class', 'uborder help-25percent');
    }

    $('#trxtransactiondetails-expiry_date').datepicker('option','disabled',useFlag);
    $('#trxtransactiondetails-manufacturing_date').datepicker('option','disabled',useFlag);

	if( materialSled > 0 )
	{
		enableDisableManufacturingDate();
	}

    populateManufacturingExpiryDateFromBatch($("#trxtransactiondetails-batch:enabled").val(), getFieldValueById("material_code"));
}

function populateBatchDropdown(material, transactionId) {
    if (material && transactionId) {
        load('get-batch?id=' + material + '&desc=' + transactionId, function(xhr) {
            var jsonData = JSON.parse(xhr.responseText);
            var x = document.getElementById('batch-dropdown').children[1].children[0];

            // clear options
            x.options.length = 0;

            if (null != jsonData && jsonData.length > 0) {
                // show use buttons
                document.getElementById('btn-use').style.display = 'inline-block';
                document.getElementById('btn-use-cancel').style.display = 'inline-block';
                for(var i = 0; i < jsonData.length; i++){
                    var option  = document.createElement('option');
                    option.value = jsonData[i];
                    option.text = jsonData[i];

                    if (i == 0) {
                        option.selected = true;
                    }

                    x.add(option, x[i+1]);
                }
            } else {
                // hide use buttons
                document.getElementById('btn-use').style.display = 'none';
                document.getElementById('btn-use-cancel').style.display = 'none';
            }
        });
    } else {
        if (useFlag) {
            toggleUse();
        }
        // hide use buttons
        document.getElementById('btn-use').style.display = 'none';
        document.getElementById('btn-use-cancel').style.display = 'none';
    }
}

function populateManufacturingExpiryDateFromBatch(batch, materialCode) {
    if (batch) {
        var populateUrl = 'get-manufacturing-expiry-date-from-batch?id=' + batch;
        if (materialCode) {
            populateUrl = populateUrl + '&code=' + materialCode;
        }
        load(populateUrl, function(xhr) {
            var jsonData = JSON.parse(xhr.responseText);

            if (null != jsonData) {
                // set material
                if (jsonData.material_code) {
                    setFieldValueById('trxtransactiondetails-material_code', jsonData.material_code, false);
                    setFieldValueById('material_code', jsonData.material_code, false);
                    setFieldValueById('trxtransactiondetails-batch', batch);
                }

                // set manufacturing date
                if (jsonData.manufacturing_date) {
                    setFieldValueById('trxtransactiondetails-manufacturing_date', jsonData.manufacturing_date);
                } else {
                    setFieldValueById('trxtransactiondetails-manufacturing_date', '');
                }

                // set expiry date
                if (jsonData.expiry_date) {
                    setFieldValueById('trxtransactiondetails-expiry_date', jsonData.expiry_date);

					checkMaterialSled("expiry_date");
                } else {
                    setFieldValueById('trxtransactiondetails-expiry_date', '');
                }
            } else {
                setFieldValueById('trxtransactiondetails-expiry_date', '');
                setFieldValueById('trxtransactiondetails-manufacturing_date', '');
            }
        });
    }
}

function scanPalletBarcode(materialCodeId, netWTId) {
    if (materialCodeId) {
        var barcode = getFieldValueById(materialCodeId).substring(0, 12);
        var netWT = getFieldValueById(materialCodeId).substring(12, 20).replace(/^0+/, '');

        setFieldValueById(materialCodeId, "", true);
        setTimeout(function(){
            setFieldValueById("trxtransactiondetails-material_code", barcode, true);
            setFieldValueById(netWTId, netWT, true);
        },5000);
    }
}

function goBack() {
    var referrer = document.referrer;
    if(referrer != '') {
        window.location = referrer;
    } else {
        window.history.back();
    }
}

$(document).ready(function() {
    $("*").dblclick(function(e) {
        e.preventDefault();
    });
});

$('form').on('keyup keypress', function(e) {
  var code = e.keyCode || e.which;
  if (code == 13) {
    e.preventDefault();
    return false;
  }
});


text:
import os
import sys
import uuid

from sphinx.ext.autodoc import between

sys.path.insert(0, os.path.abspath("../"))

# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    # 'sphinx_rtd_theme',
    # "sphinx.ext.autodoc",
    "sphinx.ext.todo",
    "sphinx.ext.coverage",
    # 'sphinx.ext.mathjax'
    "sphinx.ext.napoleon",
    "sphinxcontrib.contentui",
    "sphinx_gitstamp",
    # "sphinx.ext.autosectionlabel",
    "sphinxcontrib.discourse",
    "autoapi.extension",
]

autoapi_type = "python"
autoapi_dirs = ["../great_expectations"]
autoapi_add_toctree_entry = False
# autoapi_keep_files = True

# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]

# discourse url connect
discourse_url = "https://discuss.greatexpectations.io/"

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = ".rst"

# The master toctree document.
index_doc = "index"

# General information about the project.
project = "great_expectations"
copyright = "2020, The Great Expectations Team. "
author = "The Great Expectations Team"
gitstamp_fmt = "%d %b %Y"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = ""
# The full version, including alpha/beta/rc tags.
release = ""

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = "paraiso-dark"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True

# -- Options for HTML output ----------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
# html_theme = 'alabaster'
html_theme = "sphinx_rtd_theme"

# Theme options are theme-specific and customize the look and feel of a theme
# further.  For a list of options available for each theme, see the
# documentation.
#
html_theme_options = {
    "logo_only": True,
    "collapse_navigation": False,
    "navigation_depth": 4,
}

html_static_path = [
    "_static",
    "_static/style.css",
    "_static/hk-grotesk-pro/HKGroteskPro-Bold.woff2",
    "_static/hk-grotesk-pro/HKGroteskPro-Regular.woff2",
    "_static/hk-grotesk-pro/HKGroteskPro-SemiBold.woff2",
    "_static/hk-grotesk-pro/HKGroteskPro-Medium.woff2",
    "_static/header-logo.png",
    "_static/discuss-logo.png",
]
html_css_files = ["style.css"]

# html_logo = '../static/img/pip-logo.png'

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".

# -- Options for Napoleon Extension --------------------------------------------

# Parse Google style docstrings.
# See http://google.github.io/styleguide/pyguide.html
napoleon_google_docstring = True

# Parse NumPy style docstrings.
# See https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
napoleon_numpy_docstring = True

# Should special members (like __membername__) and private members
# (like _membername) members be included in the documentation if they
# have docstrings.
napoleon_include_private_with_doc = False
napoleon_include_special_with_doc = True

# If True, docstring sections will use the ".. admonition::" directive.
# If False, docstring sections will use the ".. rubric::" directive.
# One may look better than the other depending on what HTML theme is used.
napoleon_use_admonition_for_examples = False
napoleon_use_admonition_for_notes = False
napoleon_use_admonition_for_references = False

# If True, use Sphinx :ivar: directive for instance variables:
#     :ivar attr1: Description of attr1.
#     :type attr1: type
# If False, use Sphinx .. attribute:: directive for instance variables:
#     .. attribute:: attr1
#
#        *type*
#
#        Description of attr1.
napoleon_use_ivar = False

# If True, use Sphinx :param: directive for function parameters:
#     :param arg1: Description of arg1.
#     :type arg1: type
# If False, output function parameters using the :parameters: field:
#     :parameters: **arg1** (*type*) -- Description of arg1.
napoleon_use_param = True

# If True, use Sphinx :rtype: directive for the return type:
#     :returns: Description of return value.
#     :rtype: type
# If False, output the return type inline with the return description:
#     :returns: *type* -- Description of return value.
napoleon_use_rtype = True

# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = "great_expectationsdoc"

# -- Options for LaTeX output ---------------------------------------------

latex_elements = {
    # The paper size ('letterpaper' or 'a4paper').
    #
    # 'papersize': 'letterpaper',
    # The font size ('10pt', '11pt' or '12pt').
    #
    # 'pointsize': '10pt',
    # Additional stuff for the LaTeX preamble.
    #
    # 'preamble': '',
    # Latex figure (float) alignment
    #
    # 'figure_align': 'htbp',
}

# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
#  author, documentclass [howto, manual, or own class]).
latex_documents = [
    (
        index_doc,
        "great_expectations.tex",
        "great_expectations Documentation",
        "The Great Expectations Team",
        "manual",
    ),
]

# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
    (index_doc, "great_expectations", "great_expectations Documentation", [author], 1)
]

# -- Options for Texinfo output -------------------------------------------

# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
#  dir menu entry, description, category)
texinfo_documents = [
    (
        index_doc,
        "great_expectations",
        "great_expectations Documentation",
        author,
        "great_expectations",
        "Always know what to expect from your data.",
        "Miscellaneous",
    ),
]

autodoc_member_order = "bysource"

def process_docstring(app, what, name, obj, options, lines):

    from docs_rtd.feature_annotation_parser import parse_feature_annotation

    docstring = "\n".join(lines)
    annotation_list = parse_feature_annotation(docstring)

    process_between = between(marker="--ge-feature-maturity-info--", exclude=True)
    process_between(app, what, name, obj, options, lines)

    if not annotation_list:
        return

    feature_annotation_admonition = """
.. admonition:: `Feature Maturity <https://docs.greatexpectations.io/en/latest/features>`_

    """

    feature_annotation_template = """
    |   |icon-{icon_hash}| **{title}** - `How-to Guide <{how_to_guide_url}>`_
    |       {description}
    |       **Maturity**: {maturity}
    |       **Details**:
    |           **API Stability**: {maturity_details[api_stability]}
    |           **Implementation Completeness**: {maturity_details[implementation_completeness]}
    |           **Unit Test Coverage**: {maturity_details[unit_test_coverage]}
    |           **Integration Infrastructure/Test Coverage**: {maturity_details[integration_infrastructure_test_coverage]}
    |           **Documentation Completeness**: {maturity_details[documentation_completeness]}
    |           **Bug Risk**: {maturity_details[bug_risk]}\
"""
    expectation_completeness_template = """
    |           **Expectation Completeness**: {maturity_details[expectation_completeness]}\
"""
    icon_template = """
    .. |icon-{icon_hash}| image:: {icon}
              :height: 15px
"""

    for annotation in annotation_list:
        icon_hash = uuid.uuid1().hex
        annotation["icon_hash"] = icon_hash
        description = (
            annotation.get("description")
            or annotation.get("short_description")
            or f"*TODO: {annotation.get('title')} Description*"
        )
        how_to_guide_url = (
            annotation.get("how_to_guide_url")
            or "https://docs.greatexpectations.io/en/latest/how_to_guides.html"
        )
        annotation["how_to_guide_url"] = how_to_guide_url
        annotation["description"] = description

        if annotation["maturity_details"].get("expectation_completeness"):
            feature_annotation_admonition += (
                feature_annotation_template
                + expectation_completeness_template
                + icon_template
            ).format(**annotation)
        else:
            feature_annotation_admonition += (
                feature_annotation_template + icon_template
            ).format(**annotation)

    lines += feature_annotation_admonition.splitlines()

def setup(app):
    app.connect("autodoc-process-docstring", process_docstring)

redpajama_set_name: RedPajamaGithub


text:
const Eventful = require('../models/eventful');
const shell = require('electron').shell;
const Config = require('../config.json');

const __bind = function(fn, me) {
  return function() {
    return fn.apply(me, arguments);
  };
};

class HelpPage extends Eventful {
  constructor() {
    console.debug('help page init');
    super();
    this.reportBug = __bind(this.reportBug, this);
    this.findElements();
    this.listenForBugReports();
  }

  findElements() {
    this.bugReportLink = document.getElementById('bug-report-link');
  }

  listenForBugReports() {
    this.bugReportLink.addEventListener('click', this.reportBug);
  }

  reportBug(event) {
    event.preventDefault();
    event.target.blur();
    shell.openExternal(Config.new_bug_report_url);
  }

  removeListeners() {
    console.debug('unbinding help page listeners');
    this.bugReportLink.removeEventListener('click', this.reportBug);
  }
}

module.exports = HelpPage;


text:
import os
import re

from google.oauth2.credentials import Credentials
from googleapiclient.discovery import build
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler

app = App(token=os.environ["SLACK_BOT_TOKEN"])

SCOPES = ["https://www.googleapis.com/auth/admin.directory.user"]

@app.message("user_list")
def user_list(message, say, client):
    # get user info: https://api.slack.com/methods/users.info
    response = client.users_info(user=message["user"])
    user = response.data["user"]
    if not user["is_admin"]:
        say("You are not an admin!")
        return

    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    service = build("admin", "directory_v1", credentials=creds)

    users_list = service.users().list(
        orderBy="email", maxResults=10, customer="my_customer").execute()

    for user in users_list.get("users", []):
        email = user["primaryEmail"]
        fullname = user["name"]["fullName"]
        say(f"* {email} {fullname}")

@app.message(re.compile(r"user_add (\w+) (\w+) (\w+) (\w+)"))
def insert_user(message, say, context):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)
    service = build("admin", "directory_v1", credentials=creds)

    body = {
        "primaryEmail": context["matches"][0] + "@pycon.jp",
        "password": context["matches"][1],
        "name": {
            "givenName": context["matches"][2],
            "familyName": context["matches"][3]
        }}
    service.users().insert(body=body).execute()
    say(f"User {body['primaryEmail']} created")

if __name__ == "__main__":
    app_token = os.environ["SLACK_APP_TOKEN"]
    SocketModeHandler(app, app_token).start()


text:
<?php

/**
 * Manages rendering and aggregation of a story. A story is an event (like a
 * user adding a comment) which may be represented in different forms on
 * different channels (like feed, notifications and realtime alerts).
 *
 * @task load     Loading Stories
 * @task policy   Policy Implementation
 */
abstract class PhabricatorFeedStory
  implements
    PhabricatorPolicyInterface,
    PhabricatorMarkupInterface {

  private $data;
  private $hasViewed;
  private $framed;
  private $hovercard = false;
  private $renderingTarget = PhabricatorApplicationTransaction::TARGET_HTML;

  private $handles = array();
  private $objects = array();
  private $projectPHIDs = array();
  private $markupFieldOutput = array();

/* -(  Loading Stories  )---------------------------------------------------- */

  /**
   * Given @{class:PhabricatorFeedStoryData} rows, load them into objects and
   * construct appropriate @{class:PhabricatorFeedStory} wrappers for each
   * data row.
   *
   * @param list<dict>  List of @{class:PhabricatorFeedStoryData} rows from the
   *                    database.
   * @return list<PhabricatorFeedStory>   List of @{class:PhabricatorFeedStory}
   *                                      objects.
   * @task load
   */
  public static function loadAllFromRows(array $rows, PhabricatorUser $viewer) {
    $stories = array();

    $data = id(new PhabricatorFeedStoryData())->loadAllFromArray($rows);
    foreach ($data as $story_data) {
      $class = $story_data->getStoryType();

      try {
        $ok =
          class_exists($class) &&
          is_subclass_of($class, 'PhabricatorFeedStory');
      } catch (PhutilMissingSymbolException $ex) {
        $ok = false;
      }

      // If the story type isn't a valid class or isn't a subclass of
      // PhabricatorFeedStory, decline to load it.
      if (!$ok) {
        continue;
      }

      $key = $story_data->getChronologicalKey();
      $stories[$key] = newv($class, array($story_data));
    }

    $object_phids = array();
    $key_phids = array();
    foreach ($stories as $key => $story) {
      $phids = array();
      foreach ($story->getRequiredObjectPHIDs() as $phid) {
        $phids[$phid] = true;
      }
      if ($story->getPrimaryObjectPHID()) {
        $phids[$story->getPrimaryObjectPHID()] = true;
      }
      $key_phids[$key] = $phids;
      $object_phids += $phids;
    }

    $objects = id(new PhabricatorObjectQuery())
      ->setViewer($viewer)
      ->withPHIDs(array_keys($object_phids))
      ->execute();

    foreach ($key_phids as $key => $phids) {
      if (!$phids) {
        continue;
      }
      $story_objects = array_select_keys($objects, array_keys($phids));
      if (count($story_objects) != count($phids)) {
        // An object this story requires either does not exist or is not visible
        // to the user. Decline to render the story.
        unset($stories[$key]);
        unset($key_phids[$key]);
        continue;
      }

      $stories[$key]->setObjects($story_objects);
    }

    // If stories are about PhabricatorProjectInterface objects, load the
    // projects the objects are a part of so we can render project tags
    // on the stories.

    $project_phids = array();
    foreach ($objects as $object) {
      if ($object instanceof PhabricatorProjectInterface) {
        $project_phids[$object->getPHID()] = array();
      }
    }

    if ($project_phids) {
      $edge_query = id(new PhabricatorEdgeQuery())
        ->withSourcePHIDs(array_keys($project_phids))
        ->withEdgeTypes(
          array(
            PhabricatorProjectObjectHasProjectEdgeType::EDGECONST,
          ));
      $edge_query->execute();
      foreach ($project_phids as $phid => $ignored) {
        $project_phids[$phid] = $edge_query->getDestinationPHIDs(array($phid));
      }
    }

    $handle_phids = array();
    foreach ($stories as $key => $story) {
      foreach ($story->getRequiredHandlePHIDs() as $phid) {
        $key_phids[$key][$phid] = true;
      }
      if ($story->getAuthorPHID()) {
        $key_phids[$key][$story->getAuthorPHID()] = true;
      }

      $object_phid = $story->getPrimaryObjectPHID();
      $object_project_phids = idx($project_phids, $object_phid, array());
      $story->setProjectPHIDs($object_project_phids);
      foreach ($object_project_phids as $dst) {
        $key_phids[$key][$dst] = true;
      }

      $handle_phids += $key_phids[$key];
    }

    $handles = id(new PhabricatorHandleQuery())
      ->setViewer($viewer)
      ->withPHIDs(array_keys($handle_phids))
      ->execute();

    foreach ($key_phids as $key => $phids) {
      if (!$phids) {
        continue;
      }
      $story_handles = array_select_keys($handles, array_keys($phids));
      $stories[$key]->setHandles($story_handles);
    }

    // Load and process story markup blocks.

    $engine = new PhabricatorMarkupEngine();
    $engine->setViewer($viewer);
    foreach ($stories as $story) {
      foreach ($story->getFieldStoryMarkupFields() as $field) {
        $engine->addObject($story, $field);
      }
    }

    $engine->process();

    foreach ($stories as $story) {
      foreach ($story->getFieldStoryMarkupFields() as $field) {
        $story->setMarkupFieldOutput(
          $field,
          $engine->getOutput($story, $field));
      }
    }

    return $stories;
  }

  public function setMarkupFieldOutput($field, $output) {
    $this->markupFieldOutput[$field] = $output;
    return $this;
  }

  public function getMarkupFieldOutput($field) {
    if (!array_key_exists($field, $this->markupFieldOutput)) {
      throw new Exception(
        pht(
          'Trying to retrieve markup field key "%s", but this feed story '.
          'did not request it be rendered.',
          $field));
    }

    return $this->markupFieldOutput[$field];
  }

  public function setHovercard($hover) {
    $this->hovercard = $hover;
    return $this;
  }

  public function setRenderingTarget($target) {
    $this->validateRenderingTarget($target);
    $this->renderingTarget = $target;
    return $this;
  }

  public function getRenderingTarget() {
    return $this->renderingTarget;
  }

  private function validateRenderingTarget($target) {
    switch ($target) {
      case PhabricatorApplicationTransaction::TARGET_HTML:
      case PhabricatorApplicationTransaction::TARGET_TEXT:
        break;
      default:
        throw new Exception('Unknown rendering target: '.$target);
        break;
    }
  }

  public function setObjects(array $objects) {
    $this->objects = $objects;
    return $this;
  }

  public function getObject($phid) {
    $object = idx($this->objects, $phid);
    if (!$object) {
      throw new Exception(
        "Story is asking for an object it did not request ('{$phid}')!");
    }
    return $object;
  }

  public function getPrimaryObject() {
    $phid = $this->getPrimaryObjectPHID();
    if (!$phid) {
      throw new Exception('Story has no primary object!');
    }
    return $this->getObject($phid);
  }

  public function getPrimaryObjectPHID() {
    return null;
  }

  final public function __construct(PhabricatorFeedStoryData $data) {
    $this->data = $data;
  }

  abstract public function renderView();
  public function renderAsTextForDoorkeeper(
    DoorkeeperFeedStoryPublisher $publisher) {

    // TODO: This (and text rendering) should be properly abstract and
    // universal. However, this is far less bad than it used to be, and we
    // need to clean up more old feed code to really make this reasonable.

    return pht(
      '(Unable to render story of class %s for Doorkeeper.)',
      get_class($this));
  }

  public function getRequiredHandlePHIDs() {
    return array();
  }

  public function getRequiredObjectPHIDs() {
    return array();
  }

  public function setHasViewed($has_viewed) {
    $this->hasViewed = $has_viewed;
    return $this;
  }

  public function getHasViewed() {
    return $this->hasViewed;
  }

  final public function setFramed($framed) {
    $this->framed = $framed;
    return $this;
  }

  final public function setHandles(array $handles) {
    assert_instances_of($handles, 'PhabricatorObjectHandle');
    $this->handles = $handles;
    return $this;
  }

  final protected function getObjects() {
    return $this->objects;
  }

  final protected function getHandles() {
    return $this->handles;
  }

  final protected function getHandle($phid) {
    if (isset($this->handles[$phid])) {
      if ($this->handles[$phid] instanceof PhabricatorObjectHandle) {
        return $this->handles[$phid];
      }
    }

    $handle = new PhabricatorObjectHandle();
    $handle->setPHID($phid);
    $handle->setName("Unloaded Object '{$phid}'");

    return $handle;
  }

  final public function getStoryData() {
    return $this->data;
  }

  final public function getEpoch() {
    return $this->getStoryData()->getEpoch();
  }

  final public function getChronologicalKey() {
    return $this->getStoryData()->getChronologicalKey();
  }

  final public function getValue($key, $default = null) {
    return $this->getStoryData()->getValue($key, $default);
  }

  final public function getAuthorPHID() {
    return $this->getStoryData()->getAuthorPHID();
  }

  final protected function renderHandleList(array $phids) {
    $items = array();
    foreach ($phids as $phid) {
      $items[] = $this->linkTo($phid);
    }
    $list = null;
    switch ($this->getRenderingTarget()) {
      case PhabricatorApplicationTransaction::TARGET_TEXT:
        $list = implode(', ', $items);
        break;
      case PhabricatorApplicationTransaction::TARGET_HTML:
        $list = phutil_implode_html(', ', $items);
        break;
    }
    return $list;
  }

  final protected function linkTo($phid) {
    $handle = $this->getHandle($phid);

    switch ($this->getRenderingTarget()) {
      case PhabricatorApplicationTransaction::TARGET_TEXT:
        return $handle->getLinkName();
    }

    // NOTE: We render our own link here to customize the styling and add
    // the '_top' target for framed feeds.

    $class = null;
    if ($handle->getType() == PhabricatorPeopleUserPHIDType::TYPECONST) {
      $class = 'phui-link-person';
    }

    return javelin_tag(
      'a',
      array(
        'href'    => $handle->getURI(),
        'target'  => $this->framed ? '_top' : null,
        'sigil'   => $this->hovercard ? 'hovercard' : null,
        'meta'    => $this->hovercard ? array('hoverPHID' => $phid) : null,
        'class'   => $class,
      ),
      $handle->getLinkName());
  }

  final protected function renderString($str) {
    switch ($this->getRenderingTarget()) {
      case PhabricatorApplicationTransaction::TARGET_TEXT:
        return $str;
      case PhabricatorApplicationTransaction::TARGET_HTML:
        return phutil_tag('strong', array(), $str);
    }
  }

  final public function renderSummary($text, $len = 128) {
    if ($len) {
      $text = id(new PhutilUTF8StringTruncator())
        ->setMaximumGlyphs($len)
        ->truncateString($text);
    }
    switch ($this->getRenderingTarget()) {
      case PhabricatorApplicationTransaction::TARGET_HTML:
        $text = phutil_escape_html_newlines($text);
        break;
    }
    return $text;
  }

  public function getNotificationAggregations() {
    return array();
  }

  protected function newStoryView() {
    $view = id(new PHUIFeedStoryView())
      ->setChronologicalKey($this->getChronologicalKey())
      ->setEpoch($this->getEpoch())
      ->setViewed($this->getHasViewed());

    $project_phids = $this->getProjectPHIDs();
    if ($project_phids) {
      $view->setTags($this->renderHandleList($project_phids));
    }

    return $view;
  }

  public function setProjectPHIDs(array $phids) {
    $this->projectPHIDs = $phids;
    return $this;
  }

  public function getProjectPHIDs() {
    return $this->projectPHIDs;
  }

  public function getFieldStoryMarkupFields() {
    return array();
  }

/* -(  PhabricatorPolicyInterface Implementation  )-------------------------- */

  public function getPHID() {
    return null;
  }

  /**
   * @task policy
   */
  public function getCapabilities() {
    return array(
      PhabricatorPolicyCapability::CAN_VIEW,
    );
  }

  /**
   * @task policy
   */
  public function getPolicy($capability) {
    // If this story's primary object is a policy-aware object, use its policy
    // to control story visiblity.

    $primary_phid = $this->getPrimaryObjectPHID();
    if (isset($this->objects[$primary_phid])) {
      $object = $this->objects[$primary_phid];
      if ($object instanceof PhabricatorPolicyInterface) {
        return $object->getPolicy($capability);
      }
    }

    // TODO: Remove this once all objects are policy-aware. For now, keep
    // respecting the `feed.public` setting.
    return PhabricatorEnv::getEnvConfig('feed.public')
      ? PhabricatorPolicies::POLICY_PUBLIC
      : PhabricatorPolicies::POLICY_USER;
  }

  /**
   * @task policy
   */
  public function hasAutomaticCapability($capability, PhabricatorUser $viewer) {
    return false;
  }

  public function describeAutomaticCapability($capability) {
    return null;
  }

/* -(  PhabricatorMarkupInterface Implementation )--------------------------- */

  public function getMarkupFieldKey($field) {
    return 'feed:'.$this->getChronologicalKey().':'.$field;
  }

  public function newMarkupEngine($field) {
    return PhabricatorMarkupEngine::newMarkupEngine(array());
  }

  public function getMarkupText($field) {
    throw new PhutilMethodNotImplementedException();
  }

  public function didMarkupText(
    $field,
    $output,
    PhutilMarkupEngine $engine) {
    return $output;
  }

  public function shouldUseMarkupCache($field) {
    return true;
  }

}


text:
'''
Created on 16/04/2013

@author: henar
'''
import httplib
import sys
import os
from xml.dom.minidom import parse, parseString
from xml.dom.minidom import getDOMImplementation
from xml.etree.ElementTree import Element, SubElement, tostring
import httplib, urllib
import utils

token = utils.obtainToken(keystone_ip, keystone_port, user, password, project)
print(token)

headers = {'Content-Type': 'application/xml', 'X-Auth-Token': token, 'Tenant-ID': vdc}
print(headers)

print('Get products in the software catalogue: ')
resource = "/sdc/rest/catalog/product"
data1 = utils.doRequestHttpOperation(domine, port, resource, 'GET', None, headers)
print("  OK")
dom = parseString(data1)
try:
    product = (dom.getElementsByTagName('product'))[0]
    productname = product.firstChild.firstChild.nodeValue
    print('First product in the software catalogue')
    print("  OK " + productname)

except:
    print ("Error in the request to get products")
    sys.exit(1)

print('Get Product Details ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name, 'GET', None, headers)
print("  OK")

print('Get Product Releases ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + "/release", 'GET',
    None, headers)
print("  OK")

print('Get Product Release Info ' + product_name + " " + product_version )
data1 = utils.doRequestHttpOperation(domine, port,
    "/sdc/rest/catalog/product/" + product_name + "/release/" + product_version, 'GET', None, headers)
print("  OK")

print('Get Product Attributes ' + product_name )
data1 = utils.doRequestHttpOperation(domine, port, "/sdc/rest/catalog/product/" + product_name + '/attributes', 'GET',
    None, headers)
print("  OK")


text:
<?php declare(strict_types=1);

namespace PHPUnit\TestFixture\ObjectEquals;

final class ValueObject
{
    private $value;

    public function __construct(int $value)
    {
        $this->value = $value;
    }

    public function equals(self $other): bool
    {
        return $this->asInt() === $other->asInt();
    }

    public function asInt(): int
    {
        return $this->value;
    }
}


text:
(function( $ ) {
    var init = function( userOptions ) {
        var options = {
            stepTime: 60,
            format: "dd:hh:mm:ss",
            startTime: "01:12:32:55",
            digitImages: 6,
            digitWidth: 53,
            digitHeight: 77,
            autoStart: true,
            timerEnd: function() {
            },
            image: "digits.png"
        };
        var digits = [], interval;

        // Draw digits in given container
        var createDigits = function(where) {
            var c = 0;
            var hCounter = 0;
            var mCounter = 0;
            var sCounter = 0;

            // Check the incoming startTime
            // console.log("options.startTime = " + options.startTime);

            if ((typeof options.startTime == 'object') && (options.startTime.constructor == Date)) {
                // console.log("Have been passed a date object? hopefully?");
                var now = new Date();
                if (options.startTime.getTime() < now.getTime()) {
                    options.startTime.setFullYear(options.startTime.getFullYear() + 1);
                    // console.log("options.startTime is now = " + options.startTime);
                }
                // console.log("options.startTime.getTime() = " + options.startTime.getTime());
                // console.log("now.getTime() = " + now.getTime());
                var datediff = Math.ceil((options.startTime.getTime() - now.getTime()) / 1000);
                // console.log("datediff = " + datediff);
                var days = Math.floor(datediff / 86400);
                // console.log("days = " + days);
                var hours = Math.floor((datediff % 86400) / 3600);
                var minutes = Math.floor(((datediff % 86400) % 3600) / 60);
                var seconds = ((datediff % 86400) % 3600) % 60;
                options.startTime = days + ":" + hours + ":" + minutes + ":" + seconds;
            }

            _startTime = options.startTime.split("");
            // Count the number of ":" in the startTime.
            cCounter = 0;
            for (var i = 0; i < _startTime.length; i++) {
                if (isNaN(parseInt(_startTime[i]))) {
                    // console.log("cCounter++ (" + _startTime[i] + ")");
                    cCounter = cCounter + 1;
                }
            }

            // Zero pad each section of the startTime if required.
            // console.log("options.startTime = " + options.startTime)
            var chunks = options.startTime.split(":");
            // console.log("chunks.length = " + chunks.length);
            var newstartTime = "";
            for (var i = 0; i < chunks.length; i++) {
                var max = 59;
                if (chunks.length == 3) {
                    if (i == 0) {
                        max = 23;
                    }
                }
                if (chunks.length == 4) {
                    if (i == 0) {
                        max = 9999;
                    }
                    if (i == 1) {
                        max = 23;
                    }
                }

                if (chunks[i] > max) {
                    chunks[i] = max;
                }
                if (chunks[i].length < 2) {
                    chunks[i] = "0" + chunks[i];
                }
            }

            options.startTime = chunks.join(":");
            // console.log("options.startTime = " + options.startTime)

            // Calculate what the format should be:
            switch (cCounter) {
                case 3:
                    // console.log("options.startTime.split(':', 1).length is " + options.startTime.split(":")[0].length);
                    if (options.startTime.split(":")[0].length == 3) {
                        options.format = "ddd:hh:mm:ss";
                    } else {
                        options.format = "dd:hh:mm:ss";
                    }
                    break;
                case 2:
                    options.format = "hh:mm:ss";
                    break;
                case 1:
                    options.format = "mm:ss";
                    break;
                case 0:
                    options.format = "ss";
                    break;
            }

            // console.log("cCounter == " + cCounter);
            // console.log("options.format == " + options.format);

            // Iterate each startTime digit, if it is not a digit
            // we'll assume that it's a separator
            options.startTime = options.startTime.split("");
            options.format = options.format.split("");
            // console.log("options.startTime = " + options.startTime);
            // console.log("options.startTime.length = " + options.startTime.length);
            for (var i = 0; i < options.startTime.length; i++) {
                // console.log("options.startTime[" + i + "] = " + options.startTime[i]);
                if (parseInt(options.startTime[i]) >= 0) {
                    // console.log("parseInt >= 0");
                    var elem = jQuery('
').css({
                        height: options.digitHeight * options.digitImages * 10,
                        "float": 'left', background: 'url(\'' + options.image + '\')',
                        width: options.digitWidth});
                    // console.log("elem = " + elem);
                    digits.push(elem);
                    margin(c, -((parseInt(options.startTime[i]) * options.digitHeight *
                        options.digitImages)));
                    digits[c].__max = 9;
                    // Add max digits, for example, first digit of minutes (mm) has
                    // a max of 5. Conditional max is used when the left digit has reach
                    // the max. For example second "hours" digit has a conditional max of 4
                    // console.log("options.format[" + i + "] = " + options.format[i]);
                    switch (options.format[i]) {
                        case 'h':
                            if (hCounter < 1) {
                                // console.log("digits[c] = " + digits[c]);
                                digits[c].__max = 2;
                                // console.log("settings digits[" + c + "].__max = 2");
                                hCounter = 1;
                            } else {
                                digits[c].__condmax = 3;
                                // console.log("settings digits[" + c + "].__condmax = 3");
                            }
                            break;
                        case 'd':
                            digits[c].__max = 9;
                            break;
                        case 'm':
                            if (mCounter < 1) {
                                digits[c].__max = 5;
                                mCounter = 1;
                            } else {
                                digits[c].__condmax = 9;
                            }
                            break;
                        case 's':
                            if (sCounter < 1) {
                                digits[c].__max = 5;
                                sCounter = 1;
                            } else {
                                digits[c].__condmax = 9;
                            }
                            break;
                    }
                    ++c;
                } else {
                    elem = jQuery('
').css({"float": 'left'}).text(options.startTime[i]);
                }
                where.append('
');
                where.append(elem);
                where.append('
');
            }
        };

        // Set or get element margin
        var margin = function(elem, val) {
            if (val !== undefined)
                return digits[elem].css({'marginTop': val + 'px'});

            return parseInt(digits[elem].css('marginTop').replace('px', ''));
        };

        // Makes the movement. This is done by "digitImages" steps.
        var moveStep = function(elem) {
            // console.log("digits[elem] = " + digits[elem]);
            digits[elem]._digitInitial = -(digits[elem].__max * options.digitHeight * options.digitImages);
            return function _move() {
                mtop = margin(elem) + options.digitHeight;
                if (mtop == options.digitHeight) {
                    margin(elem, digits[elem]._digitInitial);
                    if (elem > 0) moveStep(elem - 1)();
                    else {
                        clearInterval(interval);
                        for (var i = 0; i < digits.length; i++) margin(i, 0);
                        options.timerEnd();
                        return;
                    }
                    if ((elem > 0) && (digits[elem].__condmax !== undefined) &&
                        (digits[elem - 1]._digitInitial == margin(elem - 1)))
                        margin(elem, -(digits[elem].__condmax * options.digitHeight * options.digitImages));
                    return;
                }

                margin(elem, mtop);
                if (margin(elem) / options.digitHeight % options.digitImages != 0)
                    setTimeout(_move, options.stepTime);

                if (mtop == 0) digits[elem].__isma = true;
            }
        };

        var start = function() {
            if (interval == undefined)
                interval = setInterval(moveStep(digits.length - 1), 1000);
        }

        var pause = function() {
            if (interval) {
                window.clearInterval(interval);
                interval = undefined;
            }
        }

        this.data("countdown", {
            "start": start,
            "pause": pause
        });

        $.extend(options, userOptions);
        this.css({height: options.digitHeight, overflow: 'hidden'});
        createDigits(this);
        if (options.autoStart) {
            start();
        }
    };

    $.fn.countdown = function( method ) {
        var methods = this.data("countdown");
        if ( methods && methods[method] ) {
            return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
        } else if ( typeof method === 'object' || ! method ) {
            return init.apply( this, arguments );
        } else {
            $.error( 'Method ' +  method + ' does not exist on jQuery.countdown' );
        }
    };
})( jQuery );


text:
package org.jboss.arquillian.container.weld.embedded.extension;

import org.jboss.weld.lite.extension.translator.LiteExtensionTranslator;

/**
 * Meant to be same as {@link LiteExtensionTranslator}; this class is present only so that we can register a service
 * provider that originates from this JAR
 *
 * @see org.jboss.weld.lite.extension.translator.LiteExtensionTranslator
 */
public class BuildCompatibleExtensionTranslator extends LiteExtensionTranslator {
}


text:
@implementation NSDictionary (BSCategory)

#pragma mark - generating

- (nullable NSString *)bs_JSONString {
    if (![NSJSONSerialization isValidJSONObject:self]) {
        return nil;
    }
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        NSException *exception = [NSException exceptionWithName:[NSString stringWithFormat:@"Error happen in '%@'", NSStringFromSelector(_cmd)] reason:error.localizedDescription userInfo: nil];
        @throw exception;
        return nil;
    }
    NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return json;
}

+ (nullable instancetype)bs_dictionaryWithAuxiliaryExecutablePlist:(NSString *)plist {

    NSData *plistData = [NSData bs_dataNamed:plist];
    NSError *error = nil;
    NSDictionary *dictionary = (NSDictionary *)[NSPropertyListSerialization propertyListWithData:plistData options:NSPropertyListMutableContainersAndLeaves format:NULL error:&error];
    if (error) {
        NSException *exception = [NSException exceptionWithName:[NSString stringWithFormat:@"Error happen in '%@'", NSStringFromSelector(_cmd)] reason:error.localizedDescription userInfo: nil];
        @throw exception;
        return nil;
    }
    return dictionary;
}

@end


text:
<?php

openSql();
// api/server
switch ($q[1]) {
   case NULL:
      $result = $sql->query('Select ipaddress, games.name from servers, games where tourneyid = 0 and games.gameid = servers.gameid', MYSQLI_USE_RESULT);
      while ($row = $result->fetch_assoc()) {
         echo ($row['ipaddress'] . ' ');
         echo ($row['name'] . '<br/>');
      }
      break;
   case raw:
      if (!is_numeric($q[1])) {
         giveRequestError();
      }
      $q[1] = $sql->real_escape_string($q[1]);
      $result = $sql->query('Select ipaddress, games.name from servers, games where tourneyid = 0 and games.gameid = servers.gameid', MYSQLI_USE_RESULT);
      while ($row = $result->fetch_assoc()) {
         echo ($row['ipaddress'] . ',');
         echo ($row['name'] . ',');
      }
      break;
   default:
      // api/server/x
      if (!is_numeric($q[1])) {
         giveRequestError();
      }
      $q[1] = $sql->real_escape_string($q[1]);
      $result = $sql->query('Select ipaddress, games.name from servers, games where tourneyid = 0 and games.gameid = servers.gameid and servers.id=' . $q[1], MYSQLI_USE_RESULT);
      while ($row = $result->fetch_assoc()) {
         echo ($row['ipaddress'] . ',');
         echo ($row['name']);
      }
}