// *************************************************************************
//
// Licensed Materials - Property of IBM
// 5725-C95
// Copyright IBM Corporation 2012. All Rights Reserved.
// US Government Users Restricted Rights- Use, duplication or disclosure
// restricted by GSA ADP Schedule Contract with IBM Corp.
//
// *************************************************************************
// END COPYRIGHT 

require({ packages: [ {name: 'com.ibm.bpm.coach.controls',
                       location: com_ibm_bpm_coach.getManagedAssetUrl('coach_ng_utilities.zip', com_ibm_bpm_coach.assetType_WEB, 'SYSC') + "/com/ibm/bpm/coach/controls"
                      }]
        });

/**
 * Define a scope for the Coaches toolkit utility functions and globals.
 */
com_ibm_bpm_coach.coaches_toolkit = {};

/**
 * context - required, the context for the view handling the visibility for
 * readOnlyElements - optional, array of elements to set the readonly attribute on
 * readOnlyDijits - optional, array of dijits to set the readonly attribute on
 * disablesElements - optional, array of elements to set the disabled attribute on
 *
 * Returns the visibility for the context and takes view inheritance into account. 
 */
var handleVisibility = function(context, readOnlyElements, readOnlyDijits, disabledElements) {
	if (console && console.warn) {
		console.warn("DEPRECATED: handleVisibility - Use AMD module com.ibm.bpm.coach.controls/utilities instead.");
	}

    var visibility = "DEFAULT";
    if (context.options._metadata.visibility) {
        visibility = context.options._metadata.visibility.get("value");
    }

    if (visibility == "DEFAULT") {
        visibility = context.getInheritedVisibility();
    }
    if (readOnlyElements) {
    	var element;
        for(var i = readOnlyElements.length; element = readOnlyElements[--i];) {
        	var _element = element;
			require(["dojo/dom-attr"], function(domAttr){
	            if (visibility == "READONLY") {
	                domAttr.set(_element, "readonly", "readonly");
	            } else {
	                domAttr.remove(_element, "readonly");
	            }
			});
        }
    }
    if (readOnlyDijits) {
        for(var i = readOnlyDijits.length; widget = readOnlyDijits[--i];) {
            if (visibility == "READONLY") {
                widget.set("readOnly", true);
            } else {
                widget.set("readOnly", false);
            }
        }
    }
    if (disabledElements) {
    	var element;
        for(var i = disabledElements.length; element = disabledElements[--i];) {
        	var _element = element;
			require(["dojo/dom-attr"], function(domAttr){
	            if (visibility == "READONLY") {
	                domAttr.set(_element, "disabled", "disabled");
	            } else {
	                domAttr.remove(_element, "disabled");
	            }
			});
        }
    }
    if (visibility == "NONE") {
    	context.setDisplay(false);
    } else {
    	context.setDisplay(true);
    }

	return visibility;
}


/**
 * cssFile - required, string path to css file 
 *           example "/form/resources/CheckedMultiSelect.css"
 * amdModule - optional, name of the dojo amd module to load the cssFile from.
 *             If this is not specified, the cssFile is used directly
 * amdModulePath - optional, the amdModule maybe be aliased (i.e. dojo) which
 *                 is not the path on the server so we need the module's server
 *                 path as well
 * 
 */
var loadCSS = function (cssFile, amdModule, amdModulePath) {
    if (console && console.warn) {
        console.warn("DEPRECATED: loadCSS - Use AMD module com.ibm.bpm.coach.controls/utilities instead.");
    }

    var _loadCSS = function(cssFile) {
        var head  = document.getElementsByTagName('head')[0];

        // check to make the css file is not present in the HTML dom
        var links = head.querySelectorAll("link[type='text/css']");
        for(var i = links.length; i > 0;) {
            var link = links[--i];
            var index = link.href.indexOf(cssFile);
            if (index != -1) {
                var href = link.href.slice(index)
                if (href == cssFile) {
                    // this css file has already been added to the HTML dom
                    return;
                }
            }
        }

        var link  = document.createElement('link');
        link.rel  = 'stylesheet';
        link.type = 'text/css';
        link.href = cssFile;
        link.media = 'all';
        head.appendChild(link);
    }

    if (amdModule) {
        var found = false;
        var packages = dojo.config.packages;
        for(var i = packages.length; i > 0;) {
            var pkg = packages[--i];
            if (pkg.name == amdModule) {
                _loadCSS(pkg.location+cssFile);
                // stop, we have found amd module
                found = true;
                break;
            }
        }

        if (!found) {
            var dojoVersion = [ dojo.version.major, dojo.version.minor, dojo.version.patch ].join(".")
            // We did not find amd module, so use the hard-coded location
            if (amdModulePath) {
                _loadCSS(dojo.config.App._bpmContextRootMap.teamworks + "/script/coachNG/dojo/"+dojoVersion+"/"+amdModulePath+cssFile);
            } else {
                _loadCSS(dojo.config.App._bpmContextRootMap.teamworks + "/script/coachNG/dojo/"+dojoVersion+"/"+amdModule+cssFile);
            }
        }
    } else {
        _loadCSS(cssFile);
    }
}

/**
 * xhr - required, the Dojo AMD module xhr
 * lang - required, the Dojo AMD module lang 
 * context - optional, the context for the view requesting localized messages 
 *
 * Returns the localized messages as an hashable object.
 */
com_ibm_bpm_coach.coaches_toolkit.initLocalizedMessages = function(xhr, lang, context) {
    if (console && console.warn) {
        console.warn("DEPRECATED: initLocalizedMessages - Use AMD module com.ibm.bpm.coach.controls/utilities instead.");
    }

    if(context) context.log("initLocalizedMessages", "is called");

    if (com_ibm_bpm_coach.coaches_toolkit.localizedMessages) {
        if(context) context.log("initLocalizedMessages", com_ibm_bpm_coach.coaches_toolkit.localizedMessages);
        return com_ibm_bpm_coach.coaches_toolkit.localizedMessages;
    }

    // This is the Coaches Localized Messages Loader AJAX Service from the Coaches Toolkit
    var _serviceId = "1.3402b466-ea01-464c-bc00-317677d58a67";
    var _url = dojo.config.App._bpmContextRootMap.rest + "/v1/service/" + _serviceId + "?snapshotId=" + com_ibm_bpm_coach.projectsnapshot.SYSC + "&action=start&createTask=false&parts=all";

    var _handleComplete = function(data) {
        if(context) context.log("initLocalizedMessages._handleComplete", data);

        if (data.output && data.output.items && data.output.items.length) {
            var items = data.output.items;
            com_ibm_bpm_coach.coaches_toolkit.localizedMessages = {};
            for(var i = items.length; i > 0;) {
                var item = items[--i];
                com_ibm_bpm_coach.coaches_toolkit.localizedMessages[item.name] = item.value;
            }
        }
    };

    var _handleError = function(errorData) {
        if(context) context.log("initLocalizedMessages._handleError", errorData);
    };

    var _callAjaxService = function(ajaxUrl, args) {
        var paramsKey = "&params="
        var params = null;
        if (!!args) {
            if (!!(args.params)) {
                if (lang.isString(args.params)) {
                    params = encodeURIComponent(args.params);                   
                } else {
                    params = encodeURIComponent(json1.stringify(args.params));
                }
            }
        }
        var tempStr = (!!params)? (ajaxUrl+paramsKey+params) : ajaxUrl;
        var tempArray = tempStr.split("?");

        var xhrArgs = {
            url: tempArray[0],
            handleAs: "json",
            headers: {"Content-Type": "application/x-www-form-urlencoded",
                "Accept": "application/json"},
            sync: true,
            postData: tempArray[1],
            load: function(data){
                if ((!!(args.load)) && (lang.isFunction(args.load))) {
                    args.load(data.data.data);
                }
            },
            error: function(err) {
                if ((!!(args.error)) && (lang.isFunction(args.error))) {
                    args.error(err);
                } else {
                    console.log(err);
                }
            }
        };
        xhr.post(xhrArgs);
    }

    _callAjaxService(_url, {load:_handleComplete, error:_handleError});

    if(context) context.log("initLocalizedMessages", com_ibm_bpm_coach.coaches_toolkit.localizedMessages);

    return com_ibm_bpm_coach.coaches_toolkit.localizedMessages;
}
