window.onload = function() {
   init();
};

var HOST_URL = location.protocol + '//' + location.hostname;
if (location.port && (location.port.length > 0) && (location.port != 80) && (location.port != 443)) {
    HOST_URL += ':' + location.port;
}

var GEOCODE_POST = '/geocoding/v1/address?key=YOUR_KEY_HERE&callback=handleGeocodeResponse';
var TRAFFIC_POST = '/traffic/v1/incidents?key=YOUR_KEY_HERE&callback=handleIncidentsResponse';
var TRAFFIC_CAMERA_POST = '/traffic/v1/cameras?key=YOUR_KEY_HERE&callback=handleCamerasResponse';
var TRAFFIC_CAMERA_IMAGE_POST = '/traffic/v1/cameraImage?key=YOUR_KEY_HERE';
var MARKETS_POST = '/traffic/v1/markets?key=YOUR_KEY_HERE&callback=handleMarketsResponse';
var TRAFFIC_FLOW_POST = '/traffic/v1/flow?key=YOUR_KEY_HERE';
var REAL_PW = 'Dmjtd%7Cluu72162nu%2Cbg%3Do5-54a5q';
if (HOST_URL.indexOf('devhost') != -1 || HOST_URL.indexOf('localhost') != -1 || HOST_URL.indexOf('staging.mapquestapi.com') != -1) {
	REAL_PW = 'Dmjtd%7Clu61n9u2nd%2C8x%3Do5-lytn5';
}

var pois = new Array();
var flowCollection = new MQA.ShapeCollection();
var shapeCollection = new MQA.ShapeCollection();
var marketShapeCollection = new MQA.ShapeCollection();
var collectionName = "incidentsPOICollection";
var marketCollectionName = "marketsPOICollection";
var controller = null;
var mapSize = 400;
var newZoomLevel = null;
var myMap = null;
var nextTrafficURL = null;
var nextCamerasURL = null;
var iFlowInfo = null;

function init() {
    MQA.withModule('shapes', 'viewoptions', 'largezoom', function() {
        myMap = new MQA.TileMap(document.getElementById('mapWindow'), 10, {lat:39.740085, lng:-104.984793});
        myMap.addControl(new MQA.LargeZoom(), 
        new MQA.MapCornerPlacement(MQA.MapCorner.TOP_LEFT, new MQA.Size(5, 5)));		

        myMap.addShapeCollection(flowCollection);
        shapeCollection.setDeclutter(false);
        myMap.addShapeCollection(shapeCollection);

        updateTrafficURL();
        updateTrafficData();
        
        var newURL = MARKETS_POST.replace('YOUR_KEY_HERE', REAL_PW);
        var script = document.createElement('script');
    	script.type = 'text/javascript';
    	script.src = newURL;
    	document.body.appendChild(script);
        
    });

    MQA.mixin(MQA.TileMap.prototype, {
        onZoomEnd$After: function(evt) {
            updateTrafficURL();
            updateTrafficData();
        },                
        onMoveEnd$After: function(evt) {
        	updateTrafficURL();
            updateTrafficData();
        }                
    });
}

function doClick() {        
    var newURL = GEOCODE_POST.replace('YOUR_KEY_HERE', REAL_PW);
    var location = document.getElementById('location').value;
    newURL += "&location=" + location;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = newURL;
    document.body.appendChild(script);          
}

function handleMarketsResponse(response) {
    var markets = response.markets;
    if (!markets) {
        alert('No known traffic markets were found on this map');
        return;
    }
    var i;
    var defaultIcon = null;
    for (i = 0; i < markets.length; i++) {
        var market = markets[i];
        var latLng = {lat:  market.lat, lng:  market.lng};
        var myPoint = new MQA.Poi(latLng);
        var iconURL = MQA.Util.ie6Image(market.iconURL);
        if (!defaultIcon) {
           defaultIcon = new MQA.Icon(iconURL, 16, 30);
           defaultIconURL = iconURL;
        }
        myPoint.setIcon((iconURL == defaultIconURL) ? defaultIcon : new MQA.Icon(iconURL, 29, 29));
        var marketName = market.city + ", " + market.state;
        myPoint.setInfoTitleHTML(marketName);
        var divZTS = document.createElement("p");
        divZTS.innerHTML = marketName + "<br>";
        var lnkZTS = document.createElement("a");
        lnkZTS.href = "javascript:void(0)";
        lnkZTS.innerHTML = "Zoom to City";
        var _map = myMap;
        var marketClickHandler = function(map, market) {
            return function() {
                map.setCenter(new MQA.LatLng(market.lat, market.lng), 10);
                return false;
            };
        };
        MQA.EventUtil.observe(lnkZTS,'click', marketClickHandler(_map, market));
        divZTS.appendChild(lnkZTS);
        myPoint.setInfoContentHTML(divZTS);
        myPoint.setValue('maxInfoWindowWidth', 285); // Value from dotcom
        myPoint.setValue('key', 'marketPOI' + i);
        marketShapeCollection.add(myPoint);        
    }
    marketShapeCollection.setMaxZoomLevel(9);
    marketShapeCollection.setMinZoomLevel(1);    
    myMap.addShapeCollection(marketShapeCollection);
}

function handleGeocodeResponse(response) {
    if (response.collections) {
        var text = 'Whoops!  Ambiguous addresses detected.  Please use non-ambiguous locations.';
        text += '\n\nAmbiguous locations:\n\n';
        for (i = 0; i < response.collections.length; i++) {
            var collection = response.collections[i];
            if (collection.length == 1) {
                continue;
            }
            for (j = 0; j < collection.length; j++) {
                text += '    ' + (collection[j].adminArea5 || ' ');  
                text += ' ' + (collection[j].adminArea4 || ' ');  
                text += ' ' + (collection[j].adminArea3 || ' ');  
                text += ' ' + (collection[j].adminArea2 || ' ');  
                text += ' ' + (collection[j].adminArea1 || ' ');  
                text += '\n';
            }
        }
        alert(text);
        return;
    }

    var location = response.results[0].locations[0].latLng;
    myMap.setCenter(new MQA.LatLng(location.lat, location.lng));
    if (newZoomLevel) {
        myMap.setZoomLevel(newZoomLevel);
        newZoomLevel = null;
    }
    else {
	    updateTrafficURL();
	    updateTrafficData(); 
    }
}

function updateTrafficURL() {
	var newURL;
	var bounds = myMap.getBounds();
    var lr = bounds.lr;
    var lrLat = lr.lat.toFixed(6);
    var lrLng = lr.lng.toFixed(6);
    var ul = bounds.ul;
    var ulLat = ul.lat.toFixed(6);
    var ulLng = ul.lng.toFixed(6);
    var informat = document.getElementById('inFormat').value;
    var outformat = document.getElementById('outFormat').value;

    var bboxKVP = "boundingBox=" + ulLat + "," + ulLng + "," + lrLat + "," + lrLng;
    var bboxJSON = 'boundingBox: { ul: { lat: ' + ulLat + ' , lng: ' + ulLng + '}, '
                                + 'lr: { lat: ' + lrLat + ', lng: ' + lrLng + '}}';
    var bboxXML = '<boundingBox><ul><latLng><lat>' + ulLat + '</lat><lng>' + ulLng + 
                     '</lng></latLng></ul><lr><latLng><lat>' + lrLat + '</lat><lng>' +
                     lrLng + '</lng></latLng></lr></boundingBox>';                                   

    //  First handle the traffic camera call...         
    newURL = HOST_URL + TRAFFIC_CAMERA_POST;
    if (informat == 'kvp') {
       newURL += "&" + bboxKVP;
       newURL += '&inFormat=kvp';
    } else if (informat == 'json') {
       newURL += '&inFormat=json';
       newURL += '&json={' + bboxJSON + '}';
    } else if (informat == 'xml') {
       newURL += '&inFormat=xml';
       newURL += '&xml=<traffic>' + bboxXML + '</traffic>';
    }
    newURL += '&outFormat=' + outformat;
    nextCamerasURL = newURL.replace('YOUR_KEY_HERE', REAL_PW);
    document.getElementById('trafficCamerasUrl').innerHTML = newURL.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace();    
    document.getElementById('trafficCamerasUrl').style.display = 'block';

    //  Then handle the traffic incidents call...         
    var filterNum = 1;
    var filterText = null;
    for (;;) { // We will break when needed... 
       var filter = document.getElementById('filter' + filterNum);
       if (!filter) {
           break;
       }
       if (filter.checked) {
          if (filterText) {
             filterText += ',';
          } else {
             filterText = '';
          }
          filterText += filter.value;
       }
       filterNum++;
    }    
    newURL = HOST_URL + TRAFFIC_POST;
    if(informat == 'json') {
        var jsonText = '{';
        jsonText += bboxJSON;
        if(filterText != null) {
        	jsonText += ',filters:[' + filterText + ']';
        }
        jsonText += '}';
        var jsonOptions = '&inFormat=json';
        jsonOptions += '&outFormat='+ outformat;
        jsonOptions += '&json=';
        jsonOptions += jsonText;
        newURL += jsonOptions;                  
    } else if(informat == 'xml') {
        var xmlText = '<traffic>';
        xmlText += bboxXML;
        
        filterText = null;
        filterNum = 1;
        for (;;) { // We will break when needed... 
            var filter = document.getElementById('filter' + filterNum);
            if (!filter) {
                break;
            }
            if (filter.checked) {
	        	if (!filterText) {
	                filterText = '';
	             }
                filterText += '<filter>' + filter.value +'</filter>';      
            }
            filterNum++;
         }
        if(filterText != null) {
        	xmlText += '<filters>' + filterText + '</filters>';
        }
        xmlText += '</traffic>';
        var xmlOptions = '&inFormat=xml';
        xmlOptions += '&outFormat='+ outformat;
        xmlOptions += '&xml=';
        xmlOptions += xmlText;
        newURL += xmlOptions;     
    } else if(informat == 'kvp') {            
        newURL += "&" + bboxKVP;
        if (filterText) {
           newURL += "&filters=" + filterText; 
        }
        newURL += '&inFormat=kvp';
        newURL += '&outFormat=' + outformat;
    }
    nextTrafficURL = newURL.replace('YOUR_KEY_HERE', REAL_PW);    
    document.getElementById('trafficIncidentsUrl').innerHTML = newURL.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace();    
    document.getElementById('trafficIncidentsUrl').style.display = 'block';

    newURL = HOST_URL + TRAFFIC_FLOW_POST;
    iFlowInfo = {};
    iFlowInfo.centerPoint = myMap.getCenter();
    iFlowInfo.width = myMap.width;
    iFlowInfo.height = myMap.height;
    iFlowInfo.scale = myMap.getScale();
    iFlowInfo.left = 0; 
    iFlowInfo.top = 0;
    iFlowInfo.bottom = iFlowInfo.top + iFlowInfo.height;
    iFlowInfo.right = iFlowInfo.left + iFlowInfo.width;
    
    if(informat == 'json') {
    	 var jsonText = '{';
         jsonText += 'mapState: { center: { lat:' + iFlowInfo.centerPoint.getLatitude() + ' , lng:' + 
                     iFlowInfo.centerPoint.getLongitude() + '}, ';
         jsonText += 'height:' + iFlowInfo.height + ', width:' + iFlowInfo.width + ', scale:' + iFlowInfo.scale +'}';         
         jsonText += '}';
         var jsonOptions = '&projection=merc&inFormat=json';         
         jsonOptions += '&json=';
         jsonOptions += jsonText;
         newURL += jsonOptions;      	
    } else if(informat == 'xml') {
    	var xmlText = '<traffic>';
        xmlText += '<mapState><center><lat>' + iFlowInfo.centerPoint.getLatitude() + '</lat><lng>' +
                   iFlowInfo.centerPoint.getLongitude() + '</lng></center>' +
                   '<height>' + iFlowInfo.height +'</height><width>' + iFlowInfo.width + 
                   '</width><scale>' + iFlowInfo.scale + '</scale></mapState>';
        xmlText += '</traffic>';
        var xmlOptions = '&inFormat=xml';        
        xmlOptions += '&projection=merc'; 
        xmlOptions += '&xml=';
        xmlOptions += xmlText;
        newURL += xmlOptions;  
    } else if(informat == 'kvp') {
    	newURL += "&projection=merc&mapLat=" + iFlowInfo.centerPoint.getLatitude()  +
    	         "&mapLng=" + iFlowInfo.centerPoint.getLongitude() + "&mapHeight=" + 
    	         iFlowInfo.height  + "&mapWidth=" + iFlowInfo.width + "&mapScale=" + iFlowInfo.scale ;
    }
    iFlowInfo.src = newURL;
    document.getElementById('trafficFlowUrl').innerHTML = newURL.replace(/</g, '&lt;').replace(/>/g, '&gt;').replace();    
    document.getElementById('trafficFlowUrl').style.display = 'block';    
}

function updateTrafficData() {
    if (flowCollection) {
        flowCollection.removeAll();
    }
    if (shapeCollection) {
        shapeCollection.removeAll();
    }

    if (myMap.getZoomLevel() < 10) {             
        var html = "<p><b>NOTE:</b>  Your map is currently at zoom level " + myMap.zoom + ".";
        html += "  This is too far out to display traffic results.  ";
        html += "Please zoom in to at least zoom level 10 to see the results.";
        var resultsDiv = document.getElementById('trafficResults');
        resultsDiv.innerHTML = html;
        resultsDiv.style.display = "block";
        return;
    }
    
    if (nextTrafficURL) {
        //  show the incidents... 
        nextTrafficURL = nextTrafficURL.replace('&outFormat=xml', '&outFormat=json');
		var script = document.createElement('script');
    	script.type = 'text/javascript';
    	script.src = nextTrafficURL;
    	document.body.appendChild(script); 

        //  Create an image overlay with the URL needed to get the flow overlay...
        var flowImage = new MQA.ImageOverlay();
        flowImage.setZIndex('traffic_flow');
        newURL = iFlowInfo.src.replace('YOUR_KEY_HERE', REAL_PW);
        flowImage.setValue('imageURL', newURL);
        flowImage.setValue('imageOpacity', 0.6);
        var iShapePoints = new MQA.LatLngCollection();
        iShapePoints.add(myMap.pixToLL(new MQA.Point(iFlowInfo.left, iFlowInfo.top)));
        iShapePoints.add(myMap.pixToLL(new MQA.Point(iFlowInfo.right, iFlowInfo.bottom)));
        flowImage.setValue('shapePoints', iShapePoints);
        flowCollection.bestFit=false;
        flowCollection.setName("demo_traffic_flow");
        flowCollection.add(flowImage);
        // Make this overlay appear under all the other overlays.
        if (flowImage.shape) {
            flowImage.shape.style.zIndex = -1;
        }
    }
    
    if (nextCamerasURL) {
        nextCamerasURL = nextCamerasURL.replace('&outFormat=xml', '&outFormat=json');
		var script = document.createElement('script');
    	script.type = 'text/javascript';
    	script.src = nextCamerasURL;
    	document.body.appendChild(script); 
    }
}

function handleCamerasResponse(response) {
    var cameras = response.cameras;
    if (!cameras) {
        return;
    }
    var i;
    for (i = 0; i < cameras.length; i++) {
        var camera = cameras[i];
        var name = camera.name;
        name = name.replace(' ', '&nbsp;');
        
        var latLng = {lat:  camera.lat, lng:  camera.lng};
        var myPoint = new MQA.Poi(latLng);
        var iconURL = MQA.Util.ie6Image('/media/images/camera_photo.png');
        myPoint.setIcon(new MQA.Icon(iconURL, 29, 29));

        var content = document.createElement('div');
        content.className = 'trafficInfoWindow';
        content.style.width = '340px';
        content.style.height = '260px';
        myPoint.setRolloverContent('<span class="trafficInfoWindowRollover">' + name + '</span>');
        myPoint.setValue('key', 'camera' + camera.id);
        myPoint.setShadow(null);

        title = document.createElement('div');
        title.className = 'trafficInfoWindowTitle';
        title.innerHTML = name;
        content.appendChild(title);
        myPoint.setInfoContentHTML(content);
        
        width = 320;
        height = 240;
        (function (point, c, cam) {
           MQA.EventManager.addListener(point, "infowindowopen", function (ev) {
              view = document.createElement('div');
              view.innerHTML = (cam.view.length > 0) ? '<p>View direction:  ' + cam.view + '</p>' : ''; // TODO:  i18n
              image = document.createElement('img');
              imageURL =  HOST_URL + TRAFFIC_CAMERA_IMAGE_POST;
              imageURL = imageURL.replace('YOUR_KEY_HERE', REAL_PW);
              imageURL += "&id=" + cam.id;
              image.src= imageURL;
              image.width = width;
              image.height = height;
              copyright = document.createElement('div');
              copyright.innerHTML = (cam.copyrightNotice.length > 0) ? '<p>' + cam.copyrightNotice + '</p>' : '';
              innerContent = document.createElement('div');
              innerContent.className = 'trafficInfoWindowContent';
              innerContent.appendChild(view);
              innerContent.appendChild(image);
              innerContent.appendChild(copyright); 
              c.appendChild(innerContent);
           });            
        }(myPoint, content, camera));
        
        myPoint.setValue('infoTitleHTML', '<span></span>');
        myPoint.setTitleVisible(false);
        
        shapeCollection.add(myPoint);        
    }
}

function handleIncidentsResponse(response) {
    var incidents = response.incidents;
    if (!incidents) {
        alert('no incidents found on this map');
        return;
    }
    var i;
    for (i = 0; i < incidents.length; i++) {
        var incident = incidents[i];
        var latLng = {lat:  incident.lat, lng:  incident.lng};
        var myPoint = new MQA.Poi(latLng);
        var type = parseInt(incident.type);
        var severity = parseInt(incident.severity);
        var iconURL = MQA.Util.ie6Image(incident.iconURL);
        myPoint.setValue('icon', new MQA.Icon(iconURL, 29, 29));
        var s = incident.fullDesc + '<br/><br/>';
        s += '<b>Start&nbsp;Time:</b>&nbsp;' + incident.startTime + '<br/>';
        s += '<b>End&nbsp;Time:</b>&nbsp;' + incident.endTime + '<br/>';
        s += '(All times estimated)<br/>';
        var innerText = "<p>" + s + "<br><br>";
        var linkText = "<a ";
        linkText += "href='javascript:myMap.setCenter(new MQA.LatLng(" + incident.lat + ","  + incident.lng + "), 14);'";
        linkText += ">Zoom to Street</a>";
        myPoint.setInfoContentHTML(innerText + linkText);
        myPoint.setValue('maxInfoWindowWidth', 285); // Value from dotcom
        myPoint.setValue('key', 'incidentPOI' + i);
        shapeCollection.add(myPoint);        
    }

    var html = "<h3>Results:</h3>";
    html += "<p>Your request found " + 
            incidents.length + 
            " incidents which were on the map " +
            " and of the incident types requested.";
            "<p>Hover over an incident icon to get more information.";
    if (myMap.zoom < 4) {             
        html += "<p><b>NOTE:</b>  Your map is currently at zoom level " + myMap.zoom + ".";
        html += "  This is too far out to display traffic results.  ";
        html += "Please zoom in to at least zoom level 4 to see the results.";
    }                
    var resultsDiv = document.getElementById('trafficResults');
    resultsDiv.innerHTML = html;
    resultsDiv.style.display = "block";
}
