/*======== UI SCRIPT FOR JS INCLUDE ========*/
var sp_form = {

    variables: [],

    getElement: function(varName) {
        if (sp_form.variables && sp_form.variables[varName]) {
            return document.getElementsByName(sp_form.variables[varName].name)[0];
        } else {
            return document.getElementsByName(varName)[0];
        }
    },

    getControl: function(varName) {
        if (sp_form.variables && sp_form.variables[varName]) {
            return document.getElementById(
                'sp_formfield_' +
                sp_form.variables[varName].name
            );
        } else {
            return document.getElementById(varName);
        }
    },

    /**
     * Get an array of all the attachments associated with the displayed catalog item.
     * FOR USE IN SERVICE PORTAL ONLY.
     * MUST BE ATTACHED TO SERVICE PORTAL THEME, AS A JS INCLUDE.
     * @returns {_CatalogAttachment}
     */
    getAttachments: function() {
        var i, attachmentElement; //init vars for the loop
        var catalogAttachments = []; //This will store the CatalogAttachment records, constructed from the loop over each attachment
        // identified from the angular call
        //var item_guid = angular.element("#sc_cat_item").scope().data._attachmentGUID;
        var attachmentElements = angular.element("#sc_cat_item").scope().attachments; //Use some JS Include scope magic with a nod to
        // angular, to get the list of attachments.
        for (i = 0; i < attachmentElements.length; i++) { //For each attachment document element returned from the angular call
            attachmentElement = attachmentElements[i]; //Grab a single element for each loop
            //Push a constructed CatalogAttachment object into the array, with properties corresponding to the relevant attachment
            // properties.
            //alert('hello '+attachmentElement.file_name+ 'VALU '+attachmentElement.sys_id);
            catalogAttachments.push(
                //Construct a new CatalogAttachment object, for inclusion in the returned array of attachment data.
                new this._CatalogAttachment(
                    attachmentElement.file_name,
                    attachmentElement.ext,
                    attachmentElement.sys_id,
                    attachmentElement.size
                )
            );

        }

        return catalogAttachments;
    },

    /**
     * Call this from the onLoad script of a catalog item to insure that it retrieves
     * the variables for the current item.
     */
    onLoadGetVariables: function() {
        getVariables();
    },

	/**
	* A more flexible replacement for g_form.getReference(field, callback) that 
	* lets you grab any fields you need from the record without needing to 
	* transfer the entire record over the wire. Also supports "dot-walking".
	*/
    fruJAX: function fruJAX(table, sys_id, array_of_fields, callback) {
        if (Object.prototype.toString.call(table) !== '[object String]')
            throw Error('Arg "table" must be a String');
        if (Object.prototype.toString.call(sys_id) !== '[object String]')
            throw Error('Arg "sys_id" must be a String');
        if (Object.prototype.toString.call(array_of_fields) !== '[object Array]')
            throw Error('Arg "array_of_fields" must be an Array');
        if (Object.prototype.toString.call(callback) !== '[object Function]')
            throw Error('Arg "callback" must be a Function');

        var ga = new GlideAjax('FruJAX');
        ga.addParam('sysparm_name', 'getFieldsForIdOnTable');
        ga.addParam('sysparm_table', table);
        ga.addParam('sysparm_sys_id', sys_id);
        ga.addParam('sysparm_fields', JSON.stringify(array_of_fields)); // Fields as an array in JSON format
        ga.getXMLAnswer(function parseAnswer(result) {
            callback(JSON.parse(result));
        });
    },

    /**
     * Constructs a custom CatalogAttachment object
     * @param file_name {string} The name of the file, INCLUDING the extension. e.g.: 'test_file.csv'.
     * @param file_extension {string} The file extension, WITHOUT the dot. e.g.: 'xls'.
     * @param sysID {string} the sys_id of the attachment record (not to be confused with the table_sys_id)
     * @param file_size {string} the size of the attachment, in KB. e.g.: "13.3 KB".
     * @constructor
     */
    _CatalogAttachment: function(file_name, file_extension, sysID, file_size) {

        this.file_name = file_name;
        this.file_extension = file_extension;
        this.sysID = sysID;
        this.file_size = file_size;
    }
};

//getVariables();

/**
 * This function extends the sp_form object, and adds the 'variables' object, as well as the getElement() and getControl() methods.
 */
function getVariables() {
    var i, varz, vSid, vName, vLabel, catalogItemSid;

    var itemVariables = {};

    var hostLocation = window.location.host + '';

    var sidBegin = window.location.search.indexOf('sys_id=');
    if (sidBegin != -1) {
        sidBegin += 7;
    } else {
        console.log("sidBegin was -1");
        return;
    }

    var sidEnd = window.location.search.indexOf('&', sidBegin);

    if (sidEnd >= 0) {
        catalogItemSid = window.location.search.slice(sidBegin, sidEnd);
    } else {
        catalogItemSid = window.location.search.slice(sidBegin);
    }

    var requestBody = "";
    var client = new XMLHttpRequest();
    //Updated to also get variables from variable sets on the
    client.open("get", "https://" + hostLocation +
        "/api/now/table/item_option_new?sysparm_query=sys_idINjavascript%3Anew%20CatItemVariables().getSysIdsForQuery('" +
        catalogItemSid + "', 'sys_id')" +
        "%5Eactive%3Dtrue&sysparm_fields=sys_id%2Cname%2Cquestion_text&sysparm_limit=100");
    client.setRequestHeader('Accept', 'application/json');
    client.setRequestHeader('Content-Type', 'application/json');
    client.setRequestHeader('X-UserToken', g_ck);

    client.onreadystatechange = function() {
        if (this.readyState == this.DONE) {
            if (this.status == 200 || this.status == 201) {
                varz = JSON.parse(this.response).result;

                for (i = 0; i < varz.length; i++) {
                    vSid = varz[i].sys_id;
                    vName = varz[i].name;
                    vLabel = varz[i].question_text;

                    itemVariables[vName] = new CatalogItemVariable(
                        vName,
                        vSid,
                        vLabel
                    );
                }

                sp_form.variables = itemVariables;

            } else {
                console.error('Error: Some kind of REST error happened.' +
                    "\nStatus: " + this.status +
                    "\nResponse Text: " + this.responseText);
            }
        }
        sp_form.getVariables = function() {
            return sp_form.variables;
        }
    };

    client.send(requestBody);
}

/**
 * @description Constructor function for building CatalogItemVariables
 * @param variableName {string} The name (not to be confused with the label/question) of the variable.
 * @param variableSysID {string} The catalog variable record's sys_id.
 * @param variableQuestion {string} The question/label of the variable itself. May contain spaces.
 * @constructor
 */
function CatalogItemVariable(variableName, variableSysID, variableQuestion) {
    this.name = variableName;
    this.sys_id = variableSysID;
    this.question = variableQuestion;
}