/*
 * Google Earth API for Ext JS
 * Copyright(c) 2008, Bjorn Sandvik
 * bjorn@thematicmapping.org
 *
 * Danish version
 * Søren Johannessen Copyright(c) 2008
 * http://www.microformats.dk/om/
 * Under en GNU General Public License v3 http://www.gnu.org/copyleft/gpl.html
 *
 * http://extjs.com/license
 */
Ext.namespace('Ext.ux');

/**
 *
 * @class GEarthPanel
 * @extends Ext.Panel
 */
Ext.ux.GEarthPanel = Ext.extend(Ext.Panel, {

    initComponent: function(){
        var defConfig = {
            border: true,
            kmlTreePanel: new Ext.tree.TreePanel({
                border: false,
                bodyStyle: 'padding-bottom: 15px',
                root: new Ext.tree.TreeNode({
                    text: 'KML Documents',
                    iconCls: 'folder',
                    expanded: true
                }),
                rootVisible: false,
                listeners: {
                    checkchange: {
                        fn: function(node, checked){
                            node.attributes.kml.setVisibility(checked);
                            node.bubble(function(n){ // If a child node is checked, check all the ancestors
                                if (node.getUI().isChecked()) {
                                    if (!node.parentNode.getUI().isChecked()) {
                                        node.parentNode.getUI().toggleCheck();
                                    }
                                }
                            })
                        }
                    }
                }
            }),
            kmlUrlField: new Ext.form.TextField({
                fieldLabel: 'URL',
                width: 195,
                name: 'url'
            }),
            earthLayers: {
                LAYER_BORDERS: true,
                LAYER_ROADS: true,
                LAYER_BUILDINGS: false,
                LAYER_TERRAIN: true
                /* rem .k */
                //LAYER_STREETVIEW:	false
                //LAYER_3DBUILDINGS:	false,
                // LAYER_BUILDINGS: false,
            
            },
            earthOptions: {
                setStatusBarVisibility: false,
                setGridVisibility: false,
                setOverviewMapVisibility: false,
                setScaleLegendVisibility: false,
                setAtmosphereVisibility: true,
                setMouseNavigationEnabled: true
                /*,
                 setSunVisibility: false*/
            }
        };
        Ext.applyIf(this, defConfig);
        Ext.ux.GEarthPanel.superclass.initComponent.call(this);
        this.addEvents('earthLoaded');
    },
    
    afterRender: function(){
        Ext.ux.GEarthPanel.superclass.afterRender.call(this);
        //eddited to cehck for gearth plugin .k
        //google.earth.createInstance(this.body.dom, this.onEarthReady.createDelegate(this), {});
        google.earth.createInstance(this.body.dom, this.onEarthReady.createDelegate(this), pluginFail);
        
    },
    
    // Called by above function
    onEarthReady: function(object){
        /*
         * get the point to lookat and scale
         * .k
         */
        var myLaLat = parseFloat(document.getElementById('laLat').value);
        var myLaLng = parseFloat(document.getElementById('laLng').value);
        var myLaZoom = parseFloat(document.getElementById('laZoom').value);
        
		//this all moved to touringireland.js, to be removed if it works ok 
		//TODO .k
        //get the ad to view, [if we are looking for a indivdual ad .k
		/*
        try {
            var myAdID = parseFloat(document.getElementById('viewAdID').value);
        } 
        catch (err) {
            //  alert("error county not load individual ad ");
        }*/
        //alert(myAdID );
        //alert(viewAdURL);
        
        this.earth = object;
        this.earth.getWindow().setVisibility(true);
        
        // show the sun, or maybe not ! .k
        //this.earth.getSun().setVisibility(true);
        
        this.earth.getNavigationControl().setVisibility(this.earth.VISIBILITY_SHOW);
        var la = this.earth.createLookAt(''); //30, 10000
        //la.set(53.3047,-7.91, 8, this.earth.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 600000);
        la.set(myLaLat, myLaLng, 8, this.earth.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, myLaZoom);
        this.earth.getView().setAbstractView(la);
        this.addLayers(this.earthLayers);
        this.addOptions(this.earthOptions);
        
        //ind ad view test .k
        //this.earth.addKml.createDelegate(viewAdURL);
        /*if (myAdID) { // check if it exists, if no ind ad is requested it wont .k
          //  var viewAdURL = 'http://touringireland.com/mapData/kml/getKML.php?adID=' + myAdID;
          //  this.fetchKml(viewAdURL);
        }*/
        
        this.fireEvent('earthLoaded', this);
        
    },
    
    getEarth: function(){
        return this.earth;
    },
    
    addKmlRadio: function(kmlStore){
        var uniqueId = Ext.id();
        
        // 'None' option
        var items = [{
            boxLabel: 'Ingen',
            inputValue: 'none',
            checked: true,
            name: uniqueId
        }];
        
        // Loop through all items in kmlStore
        for (var count = 0; count < kmlStore.getCount(); count++) {
            var item = kmlStore.data.items[count];
            items.push({
                boxLabel: item.data.name,
                inputValue: item.id,
                name: uniqueId,
                kml: null,
                kmlStore: item.data,
                kmlUrl: item.data.kmlUrl,
                earth: this.earth,
                handler: this.clickHandler
            });
        }
        
        var kmlGroup = new Ext.form.RadioGroup({
            hideLabel: true,
            columns: 1,
            items: items
        });
        
        return kmlGroup;
    },
    
    
    addKmlCheckbox: function(kmlStore){
        var items = [];
        
        // Loop through all items in kmlStore
        for (var count = 0; count < kmlStore.getCount(); count++) {
            var item = kmlStore.data.items[count];
            items.push({
                boxLabel: item.data.name,
                inputValue: item.id,
                kml: null,
                kmlStore: item.data,
                kmlUrl: item.data.kmlUrl,
                earth: this.earth,
                handler: this.clickHandler
            });
        }
        
        var kmlGroup = new Ext.form.CheckboxGroup({
            hideLabel: true,
            columns: 1,
            items: items
        });
        
        return kmlGroup;
    },
    
    
    // Handler used by addKmlRadio and addKmlCheckbox
    clickHandler: function(item, visibility){
        if (item.kml) {
            item.kml.setVisibility(visibility); // Toggle KML
        }
        else { // Load KML
            google.earth.fetchKml(item.earth, item.kmlUrl, function(kmlObject){
                if (kmlObject) {
                    item.earth.getFeatures().appendChild(kmlObject);
                    kmlObject.setVisibility(true)
                }
                else {
                    alert('There has been an error loading the requested information (KML error)');
                }
                item.kml = kmlObject;
            })
        }
        
        var desc;
        /*
         bottom panel stuff removed .k
         if (visibility) { // Show KML info in south panel
         var store = item.kmlStore;
         desc = "<h2>" + store.name + "</h2>"
         + (store.description != null ? store.description + "<br />" : "")
         + "Web Site Address: <a href='" + store.sourceUrl + "'>" + store.source + "</a>"
         + (store.credit != null ? " - Contact: " + store.credit : "")
         + "</a>";
         }
         */
        Ext.getCmp('sourcePanel').body.update(desc);
    },
    // added this to display the indivdual ad
    // hope it don't break anyting else .k
    /* showIndvAd: function(kmlURL){
     
     google.earth.fetchKml(this.earth, kmlUrl, function(kmlObject){
     if (kmlObject) {
     this.earth.getFeatures().appendChild(kmlObject);
     kmlObject.setVisibility(true)
     }
     else {
     alert('There has been an error loading the requested information (KML error)');
     }
     kmlURL.kml = kmlObject;
     })
     
     
     },*/
    fetchKml: function(kmlUrl){
        google.earth.fetchKml(this.earth, kmlUrl, this.addKml.createDelegate(this));
    },
    
    addKml: function(kmlObject){
        if (kmlObject) {
            this.earth.getFeatures().appendChild(kmlObject);
            this.kmlTreePanel.getRootNode().appendChild(this.treeNodeFromKml(kmlObject));
        }
        else {
            alert('Fejl i KML');
        }
    },
    
    treeNodeFromKml: function(kmlObject){
        var result = this.createKmlTreeNode(kmlObject);
        
        if (kmlObject.getFeatures().hasChildNodes()) {
            var subNodes = kmlObject.getFeatures().getChildNodes();
            for (var i = 0; i < subNodes.getLength(); i++) {
                var subNode = subNodes.item(i);
                switch (subNode.getType()) {
                    case 'KmlFolder':
                        var node = this.treeNodeFromKml(subNode);
                        break;
                    default:
                        var node = this.createKmlTreeNode(subNode);
                        break;
                }
                result.appendChild(node);
            }
        }
        return result;
    },
    
    createKmlTreeNode: function(kmlEl){
        var node = new Ext.tree.TreeNode({
            text: kmlEl.getName(),
            checked: (kmlEl.getType() != 'KmlPlacemark' ? (kmlEl.getVisibility() ? true : false) : null),
            expanded: (kmlEl.getOpen() ? true : false),
            iconCls: kmlEl.getType(),
            kml: kmlEl
        });
        return node;
    },
    
    getKmlTreePanel: function(){
        return this.kmlTreePanel;
    },
    
    getKmlUrlForm: function(){
        var form = new Ext.FormPanel({
            frame: false,
            labelWidth: 30,
            border: false,
            items: this.kmlUrlField,
            buttons: [{
                text: 'Tilføj KML/KMZ',
                earthPanel: this, // Accessible in handler
                handler: function(button, pressed){
                    // It's all about scope...
                    google.earth.fetchKml(button.earthPanel.earth, button.earthPanel.kmlUrlField.getValue(), button.earthPanel.addKml.createDelegate(button.earthPanel));
                    button.earthPanel.kmlUrlField.reset();
                }
            }]
        });
        return form;
    },
    
    addLayers: function(layers){
        for (layer in layers) {
            this.earth.getLayerRoot().enableLayerById(this.earth[layer], layers[layer]);
        }
    },
    
    
    // Returns FormPanel for finding locations - geocodning
    getLocationPanel: function(){
        var locationPanel = new Ext.FormPanel({
            title: 'Find location',
            labelAlign: 'top',
            items: new Ext.form.TriggerField({
                fieldLabel: 'Søg efter',
                triggerClass: 'x-form-search-trigger',
                anchor: '100%',
                name: 'location',
                scope: this,
                onTriggerClick: function(){
                    this.scope.findLocation(this.getValue());
                },
                listeners: {
                    specialkey: {
                        fn: function(f, e){
                            if (e.getKey() == e.ENTER) {
                                this.onTriggerClick();
                            }
                        }
                    }
                }
            })
        });
        return locationPanel;
    },
    
    // Fly to location (geocoding) - used by above function
    // Based on http://earth-api-samples.googlecode.com/svn/trunk/examples/geocoder.html
    findLocation: function(geocodeLocation){
        var geocoder = new google.maps.ClientGeocoder();
        geocoder.getLatLng(geocodeLocation, function(point){
            if (point) {
                var lookAt = this.earth.createLookAt('');
                lookAt.set(point.y, point.x, 12, this.earth.ALTITUDE_RELATIVE_TO_GROUND, 0, 30, 10000);
                this.earth.getView().setAbstractView(lookAt);
            }
        }
.createDelegate(this));
    },
    /*
     
     // zoom to are on init, ireland or county .k
     
     zoomArea: function(myLat, myLng, myAlt){
     
     alert(typeof(myLat));
     
     var lookAt = this.earth.createLookAt('');
     lookAt.set(myLat, myLng, myAlt, this.earth.ALTITUDE_RELATIVE_TO_GROUND, 0, 30, 10000);
     this.earth.getView().setAbstractView(lookAt);
     
     },*/
    // slut geocodning
    
    // Returns CheckBoxGroup containing Google Earth layers
    getLayers: function(){
        var layers = this.earthLayers;
        
        var layerNames = {
            LAYER_BORDERS: 'Borders',
            LAYER_ROADS: 'Roads',
            LAYER_BUILDINGS: '3D Building',
            LAYER_TERRAIN: 'Terrain'
            //LAYER_STREETVIEW: 'Street View'
            // LAYER_BUILDINGS: '3D Bygninger',
        }
        
        var items = [];
        for (layer in layers) {
            items.push({
                boxLabel: layerNames[layer],
                checked: layers[layer],
                name: layer,
                earth: this.earth,
                handler: function(checkbox, visibility){
                    checkbox.earth.getLayerRoot().enableLayerById(checkbox.earth[checkbox.name], visibility);
                }
            });
        }
        var layerGroup = new Ext.form.CheckboxGroup({
            columns: 1,
            items: items
        });
        
        return layerGroup;
    },
    
    addOptions: function(options){
        for (option in options) {
            this.earth.getOptions()[option](options[option]);
        }
    },
    
    // Returns CheckBoxGroup containing Google Earth options
    getOptions: function(){
        var options = this.earthOptions;
        
        var optionNames = {
            setStatusBarVisibility: 'Show status bar',
            setGridVisibility: 'Show grid',
            setOverviewMapVisibility: 'Show overview map',
            setScaleLegendVisibility: 'Show scale legend',
            setAtmosphereVisibility: 'Show atmosphere',
            setMouseNavigationEnabled: 'Enable mouse navigation',
            setMouseNavigationEnabled: 'Enable mouse navigation'
            /*,
            
             setSunVisibility: 'see the sun'*/
            
        }
        
        var items = [];
        for (option in options) {
            items.push({
                boxLabel: optionNames[option],
                hideLabel: true,
                checked: options[option],
                name: option,
                earth: this.earth,
                handler: function(checkbox, visibility){
                    checkbox.earth.getOptions()[checkbox.name](visibility);
                }
            });
        }
        var optionGroup = new Ext.form.CheckboxGroup({
            columns: 1,
            items: items
        });
        return optionGroup;
    }
});

Ext.reg('gearthpanel', Ext.ux.GEarthPanel);

/*
 * Function to run if plugin is not installed
 *
 * .k
 */
function pluginFail(errorCode){
    window.location = "http://www.touringireland.com/getPlugin.php"
    
}

