﻿// Declare global variables.
var map = null;
var geocoder = new GClientGeocoder();
var global_markers = new Array;
var global_locations = new Array;
var selected_location = false;
var page_length = 5;
var current_page = null;
document.domain='pella.com';

// Map MAPICON field to color.
var pellaColor = new Object();
pellaColor["PellaStore"] = "yellow";
pellaColor["PelLowesDS"] = "blue";
pellaColor["PellaRet"] = "orange";
pellaColor["PellaTherm"] = "yellow";
pellaColor["PellaLum"] = "green";

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.

var baseIcon = new GIcon();
baseIcon.shadow = "images/map/mapIconShadow.png";
baseIcon.iconSize = new GSize(25, 35);
baseIcon.shadowSize = new GSize(38, 35);
baseIcon.iconAnchor = new GPoint(11, 34);

// Initialize page.
function init(storeLocation) 
{      
    var mapCanvas = $("mapCanvas");

    if (!GBrowserIsCompatible()) 
    {
        mapCanvas.innerHTML = "Sorry... this browser isn't compatible with Google Maps!";
        return;
    }

    // Initialize map objects.
    map = new GMap2(mapCanvas);        
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.enableContinuousZoom();
    map.enableScrollWheelZoom();
    var initialLatLng = new GLatLng(39.83, -98.58);
    var initialZoom = 3;
    if (storeLocation.lat.length != 0 && storeLocation.lat != '0')
    {
        initialLatLng = new GLatLng(parseFloat(storeLocation.lat), parseFloat(storeLocation.lng));
        initialZoom = 12;
    }
    map.setCenter(initialLatLng, initialZoom);
    map.addOverlay(addMarker(initialLatLng, storeLocation));  
    // Add event listeners.
    /*
    GEvent.addListener(map, "zoomend", 
        function() 
        {
	        var my_window = $('overlay');
	        if (!my_window) return;
	        
	        map.getPane(G_MAP_MARKER_PANE).removeChild(my_window);
	        show_custom_info_window(global_markers[selected_location.pk]);
        }
    );
    */
}    

function addMarker(point, markerData) 
{
    // Create new marker.
    var pellaIcon = new GIcon(baseIcon);
    pellaIcon.image = "images/map/mapIcon.png";
    markerOptions = { icon:pellaIcon };
    var marker = new GMarker(point, G_DEFAULT_ICON, true);
    
/*
    // Populate marker content.
    marker.pk = unescape(markerData.distrib);
    marker.content = new Object();
    marker.content.Name = unescape(markerData.name);
    marker.content.Range = '';
    marker.content.AddressLine = markerData.addressLine;
    
	marker.content.AddressShort = '';
	marker.content.AddressBlock = '';
	marker.content.ViewSite = '';
    marker.content.logo = null;
	global_markers[marker.pk] = marker;
    // Add event listeners.
    GEvent.addListener(marker, "click_action", 
        function() 
        {
    		close_window();
    		show_custom_info_window(marker);
        }
    );

    GEvent.addListener(marker, "click", 
        function() 
        {
    		activate_marker(global_locations[marker.pk]);
        }
    );
    */
    return marker;
}

function addStore(point, data, index) 
{
    // Create new marker.
    var pellaIcon = new GIcon(baseIcon);
    pellaIcon.image = "images/map/" + pellaColor[unescape(data.getAttribute("MapIcon"))] + "-" + index + ".png";
    markerOptions = { icon:pellaIcon };
    var marker = new GMarker(point, pellaIcon);
    
    // Populate marker content.
    marker.pk = unescape(data.getAttribute("Distrib"));
    marker.content = new Object();
    marker.content.Name = unescape(data.getAttribute("Name"));
    marker.content.Range = unescape(data.getAttribute("txtRange"));
    marker.content.AddressLine = unescape(data.getAttribute("Addr1")) + ", " + unescape(data.getAttribute("City")) + ", " + unescape(data.getAttribute("State")) + " " + unescape(data.getAttribute("Zip"));
    
	marker.content.AddressShort = unescape(data.getAttribute("Addr1"));
	marker.content.AddressShort +=  "<br />" + unescape(data.getAttribute("City")) + ", " + unescape(data.getAttribute("State")) + " " + unescape(data.getAttribute("Zip"));
	marker.content.AddressBlock = marker.content.AddressShort;
	if (unescape(data.getAttribute("Phone")) != '') marker.content.AddressBlock += "<br />tel " + unescape(data.getAttribute("Phone"));
	if (unescape(data.getAttribute("Fax")) != '') marker.content.AddressBlock += "<br />fax " + unescape(data.getAttribute("Fax"));
	
	//marker.content.AddressBlock += "<br />VIEW WEBSITE";
	marker.content.ViewSite = "";
	switch (unescape(data.getAttribute("MapIcon")))
	{
	    case "PellaStore" : 
	        marker.content.logo = "images/info/pellaLogo.gif";
    		marker.content.ViewSite = "<a target='_top' href='http://"+unescape(data.getAttribute("URL"))+".pella.com/storedetails.asp?project="+unescape(data.getAttribute("URL"))+"&siteid="+unescape(data.getAttribute("Distrib"))+"'>VIEW WEBSITE</a>";
	        break;
	        
	    case "PelLowesDS" :
	        marker.content.logo = "images/info/lowesLogo.gif";
	        break;
	        
	    case "PellaTherm" :
	        marker.content.logo = "images/info/pellaLogo.gif";
    		marker.content.ViewSite = "<a target='_top' href='http://"+unescape(data.getAttribute("URL"))+".pella.com/storedetails.asp?project="+unescape(data.getAttribute("URL"))+"&siteid="+unescape(data.getAttribute("Distrib"))+"'>VIEW WEBSITE</a>";
	        break;
	        
	    default :
	        marker.content.logo = null;
	}
    
	global_markers[marker.pk] = marker;

    // Add event listeners.
    GEvent.addListener(marker, "click_action", 
        function() 
        {
    		close_window();
    		show_custom_info_window(marker);
        }
    );

    GEvent.addListener(marker, "click", 
        function() 
        {
    		activate_marker(global_locations[marker.pk]);
        }
    );

    // Create list element.
	var location = document.createElement("li");
	location.pk = marker.pk;
	location.id = "location_" + marker.pk;
	
	// Apply special class to last item.
	if ($('ResultDetail').getElementsByTagName('li').length == page_length - 1)
	{
	    location.className = "last";
	}

    // Add icon to list element.
    var location_icon = document.createElement("img");
    location_icon.src = "images/list/" + pellaColor[unescape(data.getAttribute("MapIcon"))] + "-" + index + ".png";
    location_icon.style.width = "20px";
    location_icon.style.height = "17px";
    location.appendChild(location_icon);
    
    // Add range to list element.
    var location_range = document.createElement("h5");
	location_range.appendChild(document.createTextNode(location_range));
	location_range.firstChild.nodeValue = "~ " + marker.content.Range + " mi";
	location.appendChild(location_range);
	
    // Add store name to list element.
    var location_title = document.createElement("h4");
	location_title.appendChild(document.createTextNode(location_title));
	location_title.firstChild.nodeValue = marker.content.Name;
	location.appendChild(location_title);
	
    // Add store address to list element.
	var location_address = document.createElement("p");
	location_address.innerHTML = marker.content.AddressShort;
	location.appendChild(location_address);
	
    // Add store to list.
	$('ResultDetail').appendChild(location);
	
	global_locations[location.pk] = location;
    
    // Attach highlight scripts to list items.
    highlight_locations();
    
    return marker;
}

// Handle Enter key in text box.
function txtHere_onkeypress(e)
{
    var keynum;

    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
    if (keynum == 13) 
    {
        btnGo_onclick()
        return false;
    }
    else return true;
}

function fromAddress_onkeypress(e)
{
    var keynum;

    if (window.event) // IE
    {
        keynum = e.keyCode;
    }
    else if (e.which) // Netscape/Firefox/Opera
    {
        keynum = e.which;
    }
    
    if (keynum == 13) 
    {
        $("btnGetDir").click();
        return false;
    }
    else return true;
}

// Handle text box focus.
function txtHere_onfocus(obj)
{
    obj.style.backgroundColor = "#FFFFFF";
}

// Handle text box blur.
function txtHere_onblur(obj)
{
    if (obj.value != "") return;
    obj.style.backgroundColor = "Transparent";
}

// Handle check box clicks.
function cbType_onclick(cb)
{
    // Keep at least one box checked.
    if (!($("cbStoreType").checked || $("cbLowesType").checked || $("cbRetType").checked || $("cbLumType").checked))
    {
        cb.checked = true;
        return;
    }
    
    // Return if no location specified.
    if ($("txtHere").value == '') return;
    
    // Disable checkboxes to prevent collisions.
    $("cbStoreType").disable();
    $("cbLowesType").disable();
    $("cbRetType").disable();
    $("cbLumType").disable();
    
    // Refresh query.
    btnGo_onclick();
}

function highlight_locations()
{
	var locations = $('ResultDetail').getElementsByTagName('li');
	for(i=0; i<locations.length; i++)
	{
		var location = locations[i];
		
		// Hover
		location.onmouseover = function() { this.className += ' hover'; };
		location.onmouseout = function() { this.className = this.className.replace('hover', ''); };
		
		// Active
		location.onclick = function() { activate_marker(this); };
	}
}
		
function activate_marker(element)
{
	if (selected_location == element) return false; 
	element.className += " selected";
	GEvent.trigger(global_markers[element.pk], "click_action");
	if (selected_location) deactivate_marker(selected_location); 
	selected_location = element; 
}
		
function deactivate_marker(element)
{
    element.className = element.className.replace("selected", "");
	selected_location = false;
}

function showGetDir()
{
    $('overlay_directions').style.display = 'block'; 
    position_window($('overlay'), $('overlay').marker);
    $('to_addr').focus();
}

// Create a GMarker & populate it with HTML from XML data.
function show_custom_info_window(marker)
{
	map_point = map.fromLatLngToDivPixel(marker.getPoint());
	
	// Create the overlay inside the map pane
	if (!$('overlay'))
	{ 
		var new_obj = document.createElement("div");
		new_obj.style.display = 'none';
		new_obj.innerHTML = $('overlay_temp').innerHTML;
		new_obj.getElementsByTagName('div')[1].id = 'overlay_content';
		new_obj.getElementsByTagName('td')[0].id = 'overlay_logobox';
		new_obj.getElementsByTagName('img')[0].id = 'overlay_logo';
		new_obj.getElementsByTagName('p')[2].id = 'overlay_directions';
		new_obj.getElementsByTagName('input')[0].id = 'to_addr';
		new_obj.getElementsByTagName('button')[0].id = 'btnGetDir';
		new_obj.id = 'overlay';
		document.body.appendChild(new_obj);
	}
	var my_window = $('overlay');
	
	// Attach the marker
	my_window.marker = marker;

	// Populate content
	var my_logobox = $('overlay_logobox');
	if (marker.content.logo == null) my_logobox.style.display = "none";
	else my_logobox.style.display = "block";
	
	var my_logo = $('overlay_logo');
    my_logo.src = marker.content.logo;
	
	var my_content = $('overlay_content');
	my_content.innerHTML = my_content.innerHTML.replace("[NAME]", marker.content.Name);
	my_content.innerHTML = my_content.innerHTML.replace("[RANGE]", marker.content.Range);
	my_content.innerHTML = my_content.innerHTML.replace("[ADDRESSBLOCK]", marker.content.AddressBlock);
	my_content.innerHTML = my_content.innerHTML.replace("[ADDRESSLINE]", marker.content.AddressLine);
	
	my_content.innerHTML = my_content.innerHTML.replace("[VIEWSITE]", marker.content.ViewSite);


	// Stick it to the map
	map.getPane(G_MAP_MARKER_PANE).appendChild(my_window);
	my_window.style.display = 'block';
	position_window(my_window, marker);
}	

// Position info window over selected marker & center marker in map.
function position_window(my_window, marker)
{
    // Set CSS height to support transparent background in IE6-.
    
    if (navigator.userAgent.charAt(navigator.userAgent.indexOf("MSIE") + 5) <= "6")
    {
        var my_content = $('overlay_content');
        my_content.style.height = '';
        my_content.style.height = my_content.offsetHeight + 'px';
        my_content.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='images/info/inside.png', sizingMethod='scale')";
    }

    // Position window.
	var vert_loc = parseInt(map_point.y) - my_window.offsetHeight - 26;
	my_window.style.top = vert_loc + "px";
	var horiz_loc = parseInt(map_point.x) - 155;
	my_window.style.left = horiz_loc + "px";
	
	// Position map.
	var pinpoint = map.fromLatLngToDivPixel(marker.getLatLng());
	pinpoint.y -= 50;
	map.panTo(map.fromDivPixelToLatLng(pinpoint));
}

// Submit driving directions request to Google Maps. 
function submit_gmap_form(from_addr, to_addr)
{
	var query = "from: " + from_addr + " to: " + to_addr;
	$('gmaps_form_query').value = query;
	$('gmaps_form').submit();
	return false;
}

// Close info window.
function close_window()
{
	var my_window = $('overlay');
	if (!my_window) return;
	
	map.getPane(G_MAP_MARKER_PANE).removeChild(my_window);
	deactivate_marker(global_locations[selected_location.pk]);
}



function btnGo_onclick()
{
	Effect.SlideUp('boxResultDetail', {afterFinish: 
	    function()
	    {
            close_window();
            map.clearOverlays();
    
	        $('ResultDetail').innerHTML = "";
            global_markers.length = 0;
            global_locations.length = 0;
            selected_location = null;
	        
	        getStores(0);
	    }
	});
}

function getStores(start)
{
    // Pull location info from txtHere.
    var txtHere = $("txtHere");
    if (txtHere.value == '') 
    {
        $('ResultHeader').style.display = 'none';    
        return;
    }

    // Geocode user location & display store data.
    geocoder.getLatLng(txtHere.value, 
        function(point)
        {
            if (!point)
            {
                var errormsg = "<p class='error'>\"" + txtHere.value + "\" not found!</p>";
                $('ResultHeader').innerHTML = errormsg;    
                $('ResultHeader').style.display = 'block';  
                cbType_reenable();  
                return;
            }
            
            // Display user location.
            map.setCenter(point, 10);
            
            // Retrieve & display store data.
            var urlGetStores = "GetStores.aspx?";
            urlGetStores += "lon=" + point.lng();
            urlGetStores += "&lat=" + point.lat();
            urlGetStores += "&range=100";
            urlGetStores += "&lowestype=" + $("cbLowesType").checked;
            urlGetStores += "&lumtype=" + $("cbLumType").checked;
            urlGetStores += "&storetype=" + $("cbStoreType").checked;
            urlGetStores += "&rettype=" + $("cbRetType").checked;
            
            GDownloadUrl(urlGetStores, 
                function(data, responseCode) 
                {  
                    var xml = GXml.parse(data);  
                    var markers = xml.documentElement.getElementsByTagName("store");  
                    var point = null;
                    
                    if(markers.length == 0)
                    {
                        var errormsg = "<p class='error'>No results found within 100 miles of your location!</p>";
                        $('ResultHeader').innerHTML = errormsg;    
                        $('ResultHeader').style.display = 'block';  
                        cbType_reenable();  
                        return;
                    }
                    
                    current_page = Math.floor(start / page_length);
				    var end = (markers.length <= page_length || (start + page_length) >= markers.length) ? markers.length : start + page_length;
				    var summary = "<p>";
				    summary += "Results " + (start + 1) + "-" + end + " of " + markers.length + " stores near you.";
				    summary += "</p>";
				    $('ResultHeader').innerHTML = summary;
                    $('ResultHeader').className = "";            
				    
                    for (var i = start; i < end; i++) 
                    {    
                        point = new GLatLng(parseFloat(markers[i].getAttribute("Lat")), parseFloat(markers[i].getAttribute("Lon")));    
                        map.addOverlay(addStore(point, markers[i], i + 1));  
                    }
                    while (!map.getBounds().containsLatLng(point)) map.zoomOut();

				    $('btnPrev').style.display = (start > 0) ? "inline" : "none"; 
				    $('divPrevNext').style.display = (start > 0 && end < markers.length) ? "inline" : "none"; 
				    $('btnNext').style.display = (end < markers.length) ? "inline" : "none"; 
                    
                    $('boxResults').style.display = 'block';
			        Effect.SlideDown('boxResultDetail', {afterFinish: 
			            function()
			            {
                            setTimeout("cbType_reenable()", 500);
			            }
			        });
                }
            );
        }
    );
}

function cbType_reenable()
{
    $("cbStoreType").enable();
    $("cbLowesType").enable();
    $("cbRetType").enable();
    $("cbLumType").enable();
}
		
function set_page(p)
{
	Effect.SlideUp('boxResultDetail', {afterFinish: 
	    function()
	    {
            close_window();
            map.clearOverlays();

	        $('ResultDetail').innerHTML = "";
            global_markers.length = 0;
            global_locations.length = 0;
            selected_location = null;
	        
	        getStores(p * page_length);
	    }
	});
}

