define(['tools/tools', 'tools/urls', 'config', 'tools/validate'], function () {
    'use strict';
    var module = {};

    var tools = require('tools/tools');
    var urls = require('tools/urls');
    var validate = require('tools/validate');
    var getStr = validate.getStr;
    var config = require('config');

    var trimr = tools.trimr;
    var log = tools.log;

    module.isUrl = function (url) {
        var str = getStr(url, '');
        if (str != '') {
            return str.indexOf("://") >= 0 || str.substring(0, 1) == '/' || str.indexOf("$relativepath") >= 0;
        }
        return false;
    };

    module.resourceUrl = function (folder, url) {
        var str = getStr(url, '');
        var relfolder = trimr(folder, '/');

        if(!config.isDesktop) {           
            relfolder = '/app/' + folder;            
        }

        if (str.indexOf("://") < 0) {
            if (str.indexOf("$relativepath") >= 0) {
                str = str.replace(/\\/g, "/");
                if (relfolder && relfolder != '') {
                    str = str.replace("$relativepath", relfolder);
                } else {
                    str = str.replace("$relativepath", '');
                }
            } else {
                if (relfolder && relfolder != '') {
                    str = relfolder + '/' + str;
                }
            }

            str = urls.toAbsoluteURL(str);
        }

        log('resource url:', str);
        return str;
    };

    module.xmlToJson = function (xml) {
        try {
            // Create the return object
            var obj = {};
            if (xml.nodeType === 1) { // element
                // do attributes
                if (xml.attributes.length > 0) {
                    for (var j = 0; j < xml.attributes.length; j++) {
                        var attribute = xml.attributes.item(j);
                        obj['@' + attribute.nodeName] = attribute.nodeValue;
                    }
                }
            } else if (xml.nodeType === 3 || xml.nodeType === 4) { // text
                obj = xml.nodeValue;
            }

            // do children
            if (xml.hasChildNodes()) {
                for (var i = 0; i < xml.childNodes.length; i++) {
                    var item = xml.childNodes.item(i);
                    var nodeName = item.nodeName;
                    if (typeof (obj[nodeName]) === 'undefined') {
                        obj[nodeName] = module.xmlToJson(item);
                    } else {
                        if (typeof (obj[nodeName].push) === 'undefined') {
                            var old = obj[nodeName];
                            obj[nodeName] = [];
                            obj[nodeName].push(old);
                        }
                        obj[nodeName].push(module.xmlToJson(item));
                    }
                }
            }
            return obj;
        } catch (e) {
			return {};
        }
    };

    module.queryObject = function(obj, qry) {
        var curObj = obj;
        var result = [];
        var parts = qry.split('.');
        parts.forEach(function(part, i) {
            if (part in curObj) {
                if (i === parts.length - 1) {
                    var resultObj = curObj[part];
                    var type = resultObj.constructor.name;
                    if (type == "Array") {
                        result = [];
                    } else if (type == "Object") {
                        result = {};
                    }
                    var keys = Object.keys(resultObj);
                    for (var prop in keys) {
                        if (type == "Array") {
                            result[prop] = resultObj[prop];
                        } else if (type == "Object") {
                            var propName = keys[prop];
                            result[propName] = resultObj[propName];
                        }
                    }
                } else {
                    curObj = curObj[part];
                }
            } else {
                return false;
            }
        });
        if (!Array.isArray(result)) {
            return [result];
        }
        return result;
    };

    module.tryGetPath = function (obj, path, def, max) {

        if (typeof path == 'undefined' || path.trim() == "") throw "Het ingestelde objectpad bestaat niet";
        var curObj = obj;
        var result = def;
        var parts = path.split('.');

        parts.forEach(function (part, i) {
            if (part in curObj) {
                if (i === parts.length - 1) {
                    var resultObj = curObj[part];
                    var type = resultObj.constructor.name;


                    if (type == 'Array') {
                        result = [];
                    } else if (type == "Object") {
                        result = {};
                    }

                    var keys = Object.keys(resultObj);
                    if (typeof max == 'undefined' || max == 0) max = keys.length;

                    keys = keys.slice(0, max);

                    for (var prop in keys) {

                        if (type == 'Array') {
                            result[prop] = resultObj[prop];
                        } else if (type == "Object") {
                            var propName = keys[prop];
                            result[propName] = resultObj[propName];
                        }
                    }

                } else {
                    curObj = curObj[part];
                }
            } else {
                return false;
            }
        });

        return result;
    };

    module.parseXml = function (xml) {
        try {
            if ('DOMParser' in window) {
                var parser = new window.DOMParser();
                var xmlDoc = parser.parseFromString(xml.trim(), 'text/xml');
                var data = module.xmlToJson(xmlDoc);
            }
        } catch (ex) {
            // Could not parse XML, ignoring
        }

        return data;
    };

    module.getContentTypeFromHeader = function (xhrObject) {
        return xhrObject.getResponseHeader("Content-Type").toLowerCase();
    };

    module.contentTypeIsXml = function (contentType) {
        var reg = /\bxml\b/gi;
        return reg.test(contentType);
    };

    module.contentTypeIsHtml = function (contentType) {
        var reg = /\bhtml\b/gi;
        return reg.test(contentType);
    };

    module.contentTypeIsJson = function (contentType) {
        var reg1 = /\bjson\b/gi;
        var reg2 = /\bjavascript\b/gi;
        return reg1.test(contentType) || reg2.test(contentType);
    };

    module.contentTypeIsJsonp = function (xhrObject) {
        return this.getContentTypeFromHeader(xhrObject) == "application/javascript";
    };

    return module;
});
