﻿/// <reference path="~/resources/js/jquery.min.js" />

/**
* Class to load and read xml with a server proxy to get over the same domain rule
* @require jQuery
*/
var AsynXmlReader = (function() {
    function Class(url, proxy, cache) {
        this.url = url;
        this.proxy = proxy;
        this.cacheDuration = cache;
        this.cacheBust = false;
        this.$parser;
    }

    jQuery.extend(Class.prototype, {
        "getUrl": function() {
            return this.url;
        },
        "getValue": function(selector, $node) {
            var $source = $node || this.$parser;
            // get value from attribute
            var attr;
            if (selector.indexOf("@") > -1) {
                attr = selector.split('@')[1];
                selector = selector.split('@')[0];
            }
            var $foundNode = (!selector) ? $source : $source.find(selector);
            if ($foundNode.length) {
                if (!!attr) return $foundNode.attr(attr);
                if ($foundNode.get(0).text) return $foundNode.get(0).text;
                if ($foundNode.get(0).firstChild) return $foundNode.get(0).firstChild.nodeValue;
            }
        },
        "getNodes": function(selector) {
            return this.$parser.find(selector);
        },
        "load": function(callback) {
            var _this = this;
            var params = { url: this.url, cache: this.cacheDuration };
            if (this.cacheBust == true)
                params.timestamp = (new Date()).getTime();
            jQuery.get(this.proxy, params, function(xml) {
                _this.$parser = jQuery(xml);
                callback();
            });
            return this;
        }
    });

    return Class;
})();

