/* Copyright (c) 2006-2008 MetaCarta, Inc., published under the Clear BSD
 * license.  See http://svn.openlayers.org/trunk/openlayers/license.txt for the
 * full text of the license. */

/**
 * @requires OpenLayers/Format/XML.js
 * @requires OpenLayers/Feature/Vector.js
 * @requires OpenLayers/Geometry/Point.js
 * @requires OpenLayers/Geometry/LineString.js
 * @requires OpenLayers/Geometry/Polygon.js
 */

/**
 * Class: OpenLayers.Format.MBMetaData
 * Read/write MBMetaData parser. Create a new instance with the 
 *     <OpenLayers.Format.MBMetaData> constructor.
 *
 * Inherits from:
 *  - <OpenLayers.Format.XML>
 */
OpenLayers.Format.MBMetaData = OpenLayers.Class(OpenLayers.Format.XML, {
    
    directories: {},

    /**
     * Constructor: OpenLayers.Format.MBMetaData
     * Create a new parser for MBMetaData.
     *
     * Parameters:
     * options - {Object} An optional object whose properties will be set on
     *     this instance.
     */
    initialize: function(options) {
        OpenLayers.Format.XML.prototype.initialize.apply(this, [options]);
    },
    
    /**
     * Requests the metadata.
     */
    setMetaData: function() {
        var request = OpenLayers.Request.GET({
                url: 
"http://terrapages.net/abdera-config/atom/configuration.xml?edition=61",
                success: this.geoRSSMDSuccess,
                failure: function(){alert("Service not available"); $("#tabs").show().tabs('select', 0);},
                scope: this
        });
    },

    geoRSSMDSuccess: function(request) {
        var doc = request.responseXML;
        if (!doc || !doc.documentElement) {
            doc = request.responseText; 
        }
        
        if (typeof doc == "string") { 
            doc = OpenLayers.Format.XML.prototype.read.apply(this, [doc]);
        }

        /* Try RSS items first, then Atom entries */
        var itemlist = null;
        itemlist = this.getElementsByTagNameNS(doc, '*', 'item');
        if (itemlist.length == 0) {
            itemlist = this.getElementsByTagNameNS(doc, '*', 'entry');
        }
        
        var numItems = itemlist.length;
        var features = new Array(numItems);
        var item;
        var id;
        
        var layers = new Array(0);
        var dirs = new Array(0);
        var pois = new Array(0);
        
        for(var i=0; i<numItems; i++) {
            item = itemlist[i];
                          
            id = this.getCertainChildValue(item, "*", "id", "");
            var title = this.getCertainChildValue(item, "*", "title");
            var content = this.getCertainChildValue(item, "*", "content");
            var subId = null;
            var checked;
            
            if (id.match("tag:MOKBEE:LAYER")) {
                subId = id.split("tag:MOKBEE:LAYER:")[1];
                layers.push({subId: subId, title: title, img: content});
            } else if (id.match("tag:MOKBEE:DIRECTORIES")) {
                subId = id.split("tag:MOKBEE:DIRECTORIES:")[1];
                dirs.push({subId: subId, title: title, img: content});
            } else if (id.match("tag:MOKBEE:POIS")) {
                subId = id.split("tag:MOKBEE:POIS:")[1];
                pois.push({subId: subId, title: title, img: content});
            }
        }
        
        $("#directoryTableBody").append('<tr><th colspan="3"><h1>Business Directories</h1></th></tr>');
        
        for (j in dirs) {
            this.createDirectoryEntry(dirs[j]);
        }
        
        $("#directoryTableBody").append('<tr><th colspan="3"><h1>Business Layers</h1></th></tr>');
        
        for (j in layers) {
            this.createDirectoryEntry(layers[j]);
 
        }
        
        $("#directoryTableBody").append('<tr><th colspan="3"><h1>Points of Interest</h1></th></tr>');
        
        for (j in pois) {
            this.createDirectoryEntry(pois[j]);   
        }
        
        $("#directoryTableBody").append('<tr><td colspan="3"><button type="button" onclick'+
                '="directorySubmit();">Back to the map!</button></td>'+
                '</tr>');
    },
    
    createDirectoryEntry: function(entry) {
        if(entry.title && entry.subId) {
            checked = "";
            
            if(!entry.img) {
                entry.img = "images/terrapages.png";
            } 
            var img = '<img src="'+entry.img+'" />';
            
            if(entry.subId.match(directoryParams.dir)) {
                checked = ' checked="true"';
            }
            $("#directoryTableBody").append('<tr><td> <input type="checkbox" name="'+entry.title+
                    '" value="'+entry.subId+'" src="'+entry.img+'" id="dirCheckBox'+entry.subId+'"'+checked+' /> </td><td>'+
                    img+'</td><td>'+entry.title+'</td></tr>');
            
            //directories.push(entry.subId);
            this.directories[entry.subId] = {
                                                id: entry.subId,
                                                img: entry.img,
                                                title: entry.title,
                                                checked: ((checked == "") ? false : true)
                                            }
        }
    },
    
    getCertainChildValue: function(node, nsuri, name, def) {
        var value;
        var eles = this.getElementsByTagNameNS(node, nsuri, name);
        if(eles && eles[0] && eles[0].firstChild
            && eles[0].firstChild.nodeValue) {
            value = eles[0].firstChild.nodeValue;
        } else {
            value = (def == undefined) ? "" : def;
        }
        return value;
    },

    CLASS_NAME: "OpenLayers.Format.MBMetaData" 
});     
