/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/*
if (Ext.isGecko) {
	loadFirebugConsole();
}
*/
//console.log("Firebug console loaded.");

Ext.data.Node.prototype.allChildren = function( fn ) {
	
	this.eachChild( function(n) {
//		console.log("allChildren: ", n.attributes.name, ": ", n );
    	if( fn( this, n ) ) {  // if true for node
			if ( !n.isLeaf() ) {				// recurse for children
				n.allChildren( fn );
			}
		}
		return true;
	});
};

//
// This is the main layout definition.
//
Ext.onReady(function(){
	
	Ext.QuickTips.init();
	
	var mapDiv;
	var detailPanel;

	var getDetailPanel = function() {
		if ( !detailPanel ) {
			var dp = Ext.getCmp('details-panel').body;
			dp.update('').setStyle('background','#fff');
			detailPanel = dp.createChild( { id: "details-div" } );
			detailPanel.addClass( "details-div" );
		}
		return detailPanel;	
	};
	var clearDetailPanel = function() {
		if ( detailPanel ) {
			detailPanel.remove();
			detailPanel = null;
		}
	}
	var appendDetailCategory = function( node ) {
		var item = getDetailPanel().createChild( { id: "detail-header:" + node.attributes.name } );
		item.addClass( "detail-" + node.attributes["class"] );
		return item;
	};

	var appendDetailItem = function( node ) {
		var item = getDetailPanel().createChild( { id: "detail-item:" + node.attributes.name } );
		item.addClass( "detail-item" );
		return item;
	};

	// Go ahead and create the TreePanel now so that we can use it below
    var treePanel = new Ext.tree.TreePanel({
    	id: 'tree-panel',
    	title: 'Locations by Category',
        region:'west',
        split: true,
       	width: 250,
        minSize: 150,
        autoScroll: true,
		margins: '2 0 5 2',
		collapsible: true,

        // tree-specific configs:
        rootVisible: false,
        lines: false,
        singleExpand: false,
        useArrows: true,
        
 /*
        loader: new Ext.app.LocationLoader({
            dataid:'data-div'
        }),
 */
        root: new Ext.tree.TreeNode( { expanded: true } ),

        // build a three level tree of categories, subcateogries and items
        // from a flat list of items, sorted by cat/subcat
        buildTree: function( treeNode, data, isFirst ) {
        
        	var cat = {};
    		for ( var i in data.childNodes ) { // for each location category node
    			var n = data.childNodes[i];
    			if ( n.nodeType != 1 ) continue;
//				console.log( "buildTree: ", isFirst, "        ".substr(0,treeNode.getDepth()), n, ": ", n.attributes );
    			if ( n.className == 'category' || n.className == 'subcategory' ) {
	    			cat = treeNode.findChild( 'name', n.id );
    				if ( !cat ) {
//(original)  			cat = this.createNode( n, { checked: isFirst, expanded: isFirst } );
						cat = this.createNode( n, { checked: isFirst } );
						cat = treeNode.appendChild( cat );
    				}
	    			this.buildTree( cat, n, isFirst );
	    		}
	    		else if ( n.className == 'location' ) {
    				var locNode = this.createNode( n, { allowChildren: false, leaf: true, expandable: false } );
    				locNode.attributes.details = n.innerHTML.trim();
    				treeNode.appendChild( locNode );
    			}
    			isFirst = false;
    		}
        },
        
	    createNode : function(node, attrs){
	        var attr = {
	            tagName: node.tagName,
	            text: node.id
	        };
	        
	        Ext.each(node.attributes, function(a){
	            attr[a.nodeName] = a.nodeValue;
	        });
	        Ext.apply(attr,attrs);
	        this.processAttributes(attr);
	        attr.name = attr.id;
	        attr.id = undefined;
	        return new Ext.tree.TreeNode(attr);
	    },
	
	    processAttributes : function(attr){
	    }        
   });
        
    // extract the dataset from the in-line DOM and build the tree
    var data = Ext.getDom( 'data-div' ).getElementsByTagName('div');
	var dest = data[0];								// should be class=destination
	Ext.getDom( 'header' ).innerHTML = dest.id;		// id is the destination name for the header
    treePanel.buildTree( treePanel.root, dest, false);	// extract the inline data and build the category tree (original was true)

	// Assign the changeLayout function to be called on tree node click.
    treePanel.on('click', function(n){
    	var sn = this.selModel.selNode || {}; // selNode is null on initial selection
//		console.log( "onClick:", n.attributes.name );
    	if( n.isLeaf() ){  // ignore clicks on folders and currently selected node 

    		showDetails( n );
//my addon:
var point = new GLatLng( parseFloat( n.attributes.lat ), parseFloat( n.attributes.lng ) );
var marker = createMarker( point, n );
gMap.addOverlay( marker );
gMap.setCenter(point);
//end my addon:
    	}
    });
    treePanel.on('checkchange', function(n,b){
// 		Ext.getCmp('content-panel').layout.setActiveItem(n.id + '-panel');
		
		n.suspendEvents();			// don't generate events for the children
		n.allChildren( function( p, n ) {	// check/uncheck all the children too
			if ( !n.isLeaf() ) {
//				console.log("tree.checkchange: ", n.attributes.name, ": ", b);
				n.attributes.checked = b;
				n.getUI().toggleCheck(b);
			}
			return true;
		});
		n.resumeEvents();
		setDetails( treePanel.root );
    });
    
    var setDetails = function( node ) {

// 		console.log("setDetails");
  		clearDetailPanel();
  		clearMapMarkers();
    	node.allChildren( function( p, n ) {
//     		console.log("setDetails: ", n.attributes.name, " ", p.attributes.checked );
    		if ( n.isLeaf() && p.attributes.checked ) {
				
				// add item to listings
   				var item = appendDetailItem( n );
    			item.dom.innerHTML = n.attributes.details;

				// add marker to map
				if ( gMap ) {
					var point = new GLatLng( parseFloat( n.attributes.lat ), parseFloat( n.attributes.lng ) );
					var marker = createMarker( point, n );
					gMap.addOverlay( marker );
				}
    			return true;
    		}
    		else if ( n.attributes.checked ) {  // subcategory
    			
    			var hdr = appendDetailCategory( n );	// add the subcat header to the listing
    			hdr.dom.innerHTML = n.attributes.name;
    		}
    		return true; // always scan full tree n.getUI().isChecked();
    							// recurse if this branch is checked
    	});
    };
    
    var showDetails = function( node ) {

		Ext.Msg.show({
			title:  node.attributes.name + ' Details',
			msg: node.attributes.details,
			buttons: Ext.Msg.OK,
			//icon: Ext.MessageBox.INFO,
			minWidth: 810,
			animEl: node
		});
	};

	// This is the Details panel that contains the description for each example layout.
	var detailsPanel = {
		id: 'details-panel',
        title: '',
        region: 'south',
		split:false,
		collapsible: false,
        bodyStyle: 'padding-bottom:0px;background:#eee;',
		autoScroll: false,
		height: 0,
		html: '<p class="details-info">When you select a category from the tree, individual listing details will display here.</p>'
    };

	var mapPanel = {
		id: 'map-panel',
		title: 'Map of Locations',
		collapsible: false,
		split:true,
	    region:'center',
		html: '<h1>Map insert</h1>'
	};
	
	// This is the main content center region that will contain each example layout panel.
	// It will be implemented as a CardLayout since it will contain multiple panels with
	// only one being visible at any given time.
	var contentPanel = {
		id: 'content-panel',
		region: 'center', // this is what makes this panel into a region within the containing layout
		layout: 'border',
		split: true,
		border: false,
		margins: '2 2 5 0',
		items: [ mapPanel, detailsPanel ]  // Original was items: [ mapPanel, detailsPanel ]
	};
        
	// Finally, build the main layout once all the pieces are ready.  This is also a good
	// example of putting together a full-screen BorderLayout within a Viewport.

    new Ext.Viewport({
		layout: 'border',
		title: 'Ext Layout Browser',
		items: [{
			xtype: 'box',
			region: 'north',
			applyTo: 'header'		
		}, treePanel,
		   contentPanel ],
        renderTo: Ext.getBody()
    });
    
   	// Now, set up the map display panel
   	
   	mapDiv = Ext.getCmp('map-panel').body.dom;

	var clearMapMarkers = function() {
		if (gMap) {
			gMap.clearOverlays();
		}
	}
	
	var createMarker = function(point,node) {
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function() {
//		  marker.openInfoWindowHtml(html);
//my addon:
gMap.setCenter(point);
//end my addon:
		showDetails( node );
		});
		return marker;
	};

	var mapClick = function(i) {
//		GEvent.trigger(gmarkers[i], "click");
	};

	var customGetTileUrl = function(a,b) {
		if (b==17 && a.x>=14764 && a.x<=14803 && a.y>=34896 && a.y<= 34931) {
		  return "googlemaps/tiles/"+b+"_"+a.x+"_"+a.y+".gif"
		}
		if (b==16 && a.x>=7382 && a.x<=7388 && a.y>=17448 && a.y<= 17456) {
		  return "googlemaps/tiles/"+b+"_"+a.x+"_"+a.y+".gif"
		} 
		if (b==15 && a.x>=3691 && a.x<=3700 && a.y>=8724 && a.y<= 8732) {
		  return "googlemaps/tiles/"+b+"_"+a.x+"_"+a.y+".gif"
		}
		else {
		  return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
		}
	};
	
	var customGetTileUrl2 = function(a,b) {
		if (b==17 && a.x>=14764 && a.x<=14803 && a.y>=34896 && a.y<= 34931) {
		  return "googlemaps/transparent_tiles/"+b+"_"+a.x+"_"+a.y+".gif"
		}
		if (b==16 && a.x>=7382 && a.x<=7388 && a.y>=17448 && a.y<= 17456) {
		  return "googlemaps/transparent_tiles/"+b+"_"+a.x+"_"+a.y+".gif"
		} 
		if (b==15 && a.x>=3691 && a.x<=3700 && a.y>=8724 && a.y<= 8732) {
		  return "googlemaps/transparent_tiles/"+b+"_"+a.x+"_"+a.y+".gif"
		}
		else {
		  return customGetTileUrl(a,b);
		}
	};
	
	var gMap;
    if (GBrowserIsCompatible() && !gMap) {	// instantiate map

		try {
//			console.log("Creating GMap2");
			gMap = new GMap2( mapDiv );
			// ============================================================
			// ===== Write our own getTileUrl function ========
			// This particular one checks to see if the tiles are in range
			// if so, returns the URL of the actual tile
			// Otherwise returns the URL of the Google Map tileserver tile
			
			var copyright = new GCopyright(1, new GLatLngBounds( new GLatLng(64.028938,-139.449463),
																new GLatLng(64.072200,-139.339610) ),
			  										15, "PR Services");
			
			var copyrightCollection = new GCopyrightCollection('Map Data:');
			var copyrightCollection2 = new GCopyrightCollection('Map Data:');
			copyrightCollection.addCopyright(copyright);
			copyrightCollection2.addCopyright(copyright);
			
			
			var tilelayers = [new GTileLayer(copyrightCollection,10,17)];
			var hybridlayers = [new GTileLayer(copyrightCollection2,15,17,
									{ isPng: true, tileUrlTemplate: "googlemaps/transparent_tiles/{Z}_{X}_{Y}.png" } )];
			tilelayers[0].getTileUrl = customGetTileUrl;
//			hybridlayers[0].getTileUrl = customGetTileUrl2;
			
			// ============================================================
			// === If we know the copyright, return it, otherwise look for the G_NORMAL_MAP copyright =====      
			tilelayers[0].getCopyright = hybridlayers[0].getCopyright = function(a,b) {
				var c = copyrightCollection.getCopyrightNotice(a,b);
					if (!c) {
						c = G_NORMAL_MAP.getTileLayers()[0].getCopyright(a,b);
					}
				return c;
			};
			
			
			var custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "Map");
			var hybridlayers = G_SATELLITE_MAP.getTileLayers().concat( hybridlayers );
			var customhybrid = new GMapType( hybridlayers, G_SATELLITE_MAP.getProjection(), "Satellite",
												{ minresolution: 10, maxresolution: 17 } );
			gMap.addMapType(custommap);
			gMap.addMapType(customhybrid);
			gMap.removeMapType(G_HYBRID_MAP);
			gMap.removeMapType(G_NORMAL_MAP);
			gMap.removeMapType(G_SATELLITE_MAP);
			gMap.enableScrollWheelZoom();
			
			gMap.setCenter(new GLatLng(64.063848,-139.432382), 15, custommap);
			gMap.addControl(new GMapTypeControl());
			gMap.addControl(new GLargeMapControl());
			gMap.addControl(new GScaleControl());
		}
		catch( e ) {
			console.log( e );
			mapDiv.update("Couldn't create map: " + e);
		}
    }

    setDetails( treePanel.root );
});

