/**********************************************************************************
 * FUNCTIONS
 **********************************************************************************/
function fill_dealers()
{
	// get elements
	var el_region = document.getElementById('region');
	var el_dealers = document.getElementById('dealers');

	// load up selection
	var load_dealers = dealers[el_region.selectedIndex];

	// load up dealers
	el_dealers.options.length = 0;
	var len = load_dealers.length;

	for( i=0, j=0; i < len; i++, j++ )
	{
		el_dealers.options[j] = new Option(load_dealers[i]['name'],load_dealers[i]['name']);
	}

	// now look up dealer 1
	look_up_dealer();
}

/**
 * Debug functions
 * 
 * @param {Object} str
 */
function debug(str)
{
	var el = document.getElementById('debug');
	el.innerHTML += str+';<br/>';
}

function debug_array(array)
{
	var el = document.getElementById('debug');
	el.innerHTML += "<pre>"+print_r(array, true)+'</pre><br/>';
}

function print_r( array, return_val ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Michael White (http://getsprink.com)
    // +   improved by: Ben Bryan
    // *     example 1: print_r(1, true);
    // *     returns 1: 1
    
    var output = "", pad_char = " ", pad_val = 4;
 
    var formatArray = function (obj, cur_depth, pad_val, pad_char) {
        if (cur_depth > 0) {
            cur_depth++;
        }
 
        var base_pad = repeat_char(pad_val*cur_depth, pad_char);
        var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
        var str = "";
 
        if (obj instanceof Array || obj instanceof Object) {
            str += "Array\n" + base_pad + "(\n";
            for (var key in obj) {
                if (obj[key] instanceof Array) {
                    str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);
                } else {
                    str += thick_pad + "["+key+"] => " + obj[key] + "\n";
                }
            }
            str += base_pad + ")\n";
        } else if(obj == null || obj == undefined) {
            str = '';
        } else {
            str = obj.toString();
        }
 
        return str;
    };
 
    var repeat_char = function (len, pad_char) {
        var str = "";
        for(var i=0; i < len; i++) { 
            str += pad_char;
        };
        return str;
    };
    output = formatArray(array, 0, pad_val, pad_char);
 
    if (return_val !== true) {
        document.write("<pre>" + output + "</pre>");
        return true;
    } else {
        return output;
    }
}

/**********************************************************************************
 ** GOOGLE MAPS SET UP 
 **********************************************************************************/
// == Some global variables ==
	var map = '';			// map var - will hold map obj
	var ZOOMLEVEL = 11; 	// default zoom level
	// Zoom slider
 	var YSLIDERLENGTH = 97; // maximum length that the knob can move (slide height minus knob height)
    var MAXZOOM = 17; 		// maximum amount you can zoom in
	
	
// build custom controls
// A stihlCustomControls is a GControl that displays textual "Zoom In"
// and "Zoom Out" buttons (as opposed to the iconic buttons used in
// Google Maps).
function stihlCustomControls() {
}
stihlCustomControls.prototype = new GControl();

// SLIDER SET UP

// == This function positions the slider to match the specified zoom level ==
stihlCustomControls.prototype.setSlider = function(zoom) {
	var top = Math.round(YSLIDERLENGTH - (YSLIDERLENGTH / MAXZOOM * zoom));
  	this.slide.top = top;
  	this.knob.style.top = top+"px";
  	
  	// GLog.write("Map was zoomed to:"+zoom+" new Knob position:"+top);
}

// == This function reads the slider and sets the zoom level ==
stihlCustomControls.prototype.setZoom = function() {
    var z = Math.round(MAXZOOM-(this.slide.top*MAXZOOM/YSLIDERLENGTH));
    this.map.setZoom(z);
    // GLog.write("New knob position:"+this.slide.top+" new zoom: "+z);
}

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
stihlCustomControls.prototype.initialize = function(map) {
	var container = document.createElement("div");
	container.style.width = "52px";
	
	// UP BUTTON	
	var upDiv = document.createElement("div");
    this.setButtonStyle_(upDiv);
    container.appendChild(upDiv);
	upDiv.style.marginLeft = "19px";
	upDiv.style.background = "url(images/control_up.gif) #fff no-repeat";
    GEvent.addDomListener(upDiv, "click", function() {
    	map.panDirection(0, 1);
    });

	// MIDDLE ROW
	var middle_row = document.createElement("div");
	container.appendChild(middle_row);
	middle_row.style.position = "relative";
	middle_row.style.height = "19px";
	
		// LEFT BUTTON
		var leftDiv = document.createElement("div");
	    this.setButtonStyle_(leftDiv);
	    middle_row.appendChild(leftDiv);
		leftDiv.style.position = "absolute";
		leftDiv.style.top = 0;
		leftDiv.style.left = 0;
		leftDiv.style.background = "url(images/control_left.gif) #fff no-repeat";
	    GEvent.addDomListener(leftDiv, "click", function() {
	    	map.panDirection(1, 0);
	    });
		
		// CENTER BUTTON		
		var centerDiv = document.createElement("div");
	    this.setButtonStyle_(centerDiv);
		middle_row.appendChild(centerDiv);
		centerDiv.style.position = "absolute";
		centerDiv.style.top = 0;
		centerDiv.style.left = "19px";
		centerDiv.style.background = "url(images/control_center.gif) #fff no-repeat";
	    GEvent.addDomListener(centerDiv, "click", function() {
	    	map.returnToSavedPosition();
			// GLog.write("move to saved position: "+map.getCenter());
		 });
		
		// RIGHT BUTTON
		var rightDiv = document.createElement("div");
	    this.setButtonStyle_(rightDiv);
		middle_row.appendChild(rightDiv);
		rightDiv.style.position = "absolute";
		rightDiv.style.top = 0;
		rightDiv.style.left = "38px";
		rightDiv.style.background = "url(images/control_right.gif) #fff no-repeat";

	    GEvent.addDomListener(rightDiv, "click", function() {
	    	map.panDirection(-1, 0);
	    });
	
	// DOWN BUTTON
	var downDiv = document.createElement("div");
    this.setButtonStyle_(downDiv);
    container.appendChild(downDiv);
	downDiv.style.marginLeft = "19px";
	downDiv.style.background = "url(images/control_down.gif) #fff no-repeat";
    GEvent.addDomListener(downDiv, "click", function() {
    	map.panDirection(0, -1);
    });
	
	// ZOOM IN BUTTON	
	var zoomInDiv = document.createElement("div");
    this.setButtonStyle_(zoomInDiv);
    container.appendChild(zoomInDiv);
	zoomInDiv.style.marginLeft = "19px";
	zoomInDiv.style.background = "url(images/control_zoomin.gif) #fff no-repeat";
    GEvent.addDomListener(zoomInDiv, "click", function() {
    	if( map.getZoom() < MAXZOOM )
		{
			map.zoomIn();
		}
    });

	// SLIDER BAR
	var sliderBarDiv = document.createElement("div");
	container.appendChild(sliderBarDiv);
	sliderBarDiv.style.background = "url(images/control_slider_bar.gif) no-repeat";
	sliderBarDiv.style.height = "104px";
	sliderBarDiv.style.width = "17px";
	sliderBarDiv.style.marginTop = "-3px";
	sliderBarDiv.style.marginLeft = "19px";
	sliderBarDiv.style.position = "relative";

	// CUSTOM SLIDER KNOB (tee hee)
    // == This gets called but the API when addControl(new stihlCustomControls()) is used ==
   
	// Obtain Function Closure on a reference to "this"
	var that = this;
	// Store a reference to the map so that we can call setZoom() on it
	this.map = map;

	// create the knob as a GDraggableObject
	this.knob = document.createElement("img");
	this.knob.src = "images/control_slider_knob.gif";
	this.knob.height = "7";
	this.knob.width = "17";
	this.knob.style.top = "0px";
	// GLog.write("knob pos marginTop: " + this.knob.style.marginTop);
	// GLog.write("knob pos Top: " + this.knob.style.top);

	sliderBarDiv.appendChild(this.knob);
	this.slide = new GDraggableObject(this.knob, {container:sliderBarDiv});
	
	// Listen for other things changing the zoom level and move the slider
	GEvent.addListener(map, "zoomend", function(a,b) {
		that.setSlider(b);
		
		// check zoom level
		if( map.getZoom() == 8 )
		{
			load_markers(1, 1, 8, true);
		}
		else if( map.getZoom() == 7 )
		{
			load_markers(1, 1, 7, true);
		}
	});
	
	// Listen for the slider being moved and set the zoom level
	GEvent.addListener(this.slide, "dragend", function() {
		that.setZoom();
	});

	// ZOOM OUT	BUTTON
    var zoomOutDiv = document.createElement("div");
    this.setButtonStyle_(zoomOutDiv);
    container.appendChild(zoomOutDiv);
	zoomOutDiv.style.marginLeft = "19px";
	zoomOutDiv.style.background = "url(images/control_zoomout.gif) #fff no-repeat";
    GEvent.addDomListener(zoomOutDiv, "click", function() {
    	map.zoomOut();
    });

	// RETURN MAP CONTROLS ===================	
    map.getContainer().appendChild(container);
    return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
stihlCustomControls.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

// Sets the proper CSS for the given button elements.
stihlCustomControls.prototype.setButtonStyle_ = function(button) {
    button.style.color = "#f37a1f";
    button.style.font = "small Arial";
    button.style.marginBottom = "3px";
    button.style.textAlign = "center";
    button.style.width = "16px";
    button.style.height = "16px";
    button.style.cursor = "pointer";
}

	// SET UP MAP
	function initialize() {
		if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("map_canvas"));
			map.addControl(new stihlCustomControls());
			map.setCenter(new GLatLng(-36.873853,174.792137), ZOOMLEVEL);
			map.savePosition();
			// do nothing here - do it all in the look up_dealers function
		}

		fill_dealers();
	}
	
	function look_up_dealers()
	{
		// get selection
		var el = document.getElementById('dealers');
		var el_region = document.getElementById('region');
		reg_choice = el_region.selectedIndex;
		dealer_choice = el.selectedIndex;
	}

	function look_up_dealer()
	{
		// get selection
		var el = document.getElementById('dealers');
		var el_region = document.getElementById('region');
		reg_choice = el_region.selectedIndex;
		dealer_choice = el.selectedIndex;
//		alert("dealers["+reg_choice+"]["+dealer_choice+"]");

		// set messages
		var c = 0;
		message = new Array();
		for(i=0; i < dealers.length; i++)
		{
			for(j=0; j < dealers[i].length;j++)
			{
				if( dealers[i][j]['message'].length > 0 ) 
				{
					message[c] = dealers[i][j]['message'];					
				}
				else
				{
					message[c] = 'no content found...';
				}

				c++;
			}
		}

		if (GBrowserIsCompatible())
		{
			// move map to new location and save that point
			map.setCenter(new GLatLng(dealers[reg_choice][dealer_choice]['lon'],dealers[reg_choice][dealer_choice]['lat']));
			map.setZoom(dealers[reg_choice][dealer_choice]['zoom']);
			map.savePosition();
			
			// load markers
			load_markers(reg_choice, dealer_choice, map.getZoom(), false);
		}
	}
	
	/**
	 * loads th markers layer
	 */
	function load_markers(reg_choice, dealer_choice, size, auto_open_over_ride)
	{
		// Load ICONs
		var blueIcon = new GIcon(G_DEFAULT_ICON);

		if( size >= 8 )
		{
	        blueIcon.image = "http://www.iwihost.com/dev/email_tool/star.gif";
		}
		else
		{
	        blueIcon.image = "http://www.iwihost.com/dev/email_tool/star_sm.gif";
		}
		// alert(size+ ' = '+blueIcon.image);
		
		// Set up our GMarkerOptions object
		markerOptions = { icon:blueIcon };
		
		// Creates a marker at the given point
	    // Clicking the marker will hide it
	    function createMarker(latlng, number, autoshow) {
	    	var marker = new GMarker(latlng, markerOptions);
	    	marker.value = number;
		    if( autoshow == true && auto_open_over_ride == false )
		    {
   				var myHtml = message[number -1]; // loads messages
				map.openInfoWindowHtml(latlng, myHtml);
	    	}
	    	GEvent.addListener(marker,"click", function() {
			var myHtml = message[number -1]; // loads messages
			map.openInfoWindowHtml(latlng, myHtml);
	      });
	      return marker;
		}
		// closes currently open window and clears old layers
		map.closeInfoWindow();
		map.clearOverlays();
		
		var c = 1;
		for(i=0; i < dealers.length; i++)
		{
			for(j=0; j < dealers[i].length;j++)
			{
				if( j != 0) // hide first markers as they are region level views
				{
					var latlng = new GLatLng(dealers[i][j]['lon'], dealers[i][j]['lat']);
					
					if( dealers[i][j]['lon'] == dealers[reg_choice][dealer_choice]['lon'] && dealers[i][j]['lat'] == dealers[reg_choice][dealer_choice]['lat'])
					{
						map.addOverlay(createMarker(latlng, c, dealers[reg_choice][dealer_choice]['autoopen'] ));
					}
					else
					{
						map.addOverlay(createMarker(latlng, c, false ));
					}
				}
				c++;
			}
		}
	}

