﻿// JScript File
var identifyTask = new esri.tasks.IdentifyTask(dynamicAlertsURL);
var identifyParams = new esri.tasks.IdentifyParameters();
var cipURL = "http://your.kingcounty.gov/kcdot/roads/cip/ProjectDetail.aspx?CIPID=";
var camURLBase = "http://your.kingcounty.gov/kcdot/mycommute/default.aspx?camid=";
var textcamsURL = "http://your.kingcounty.gov/kcdot/mycommute/allcamstxt.aspx";
var allcamsURL = "http://your.kingcounty.gov/kcdot/mycommute/allcamstb.aspx";
var refreshrate=10;           //SECONDS BETWEEN REFRESH
var camIMGURL;
var selectedFeatureQuery = ""; // used for capturing selected Feature for building URL arguments in createURLForCurrentExtent()
var closureResults, cameraResults;

var dateMask = "mmm d, yyyy 'at' h:MM tt";
var mlkImg = new Image();
var wsdotImg = new Image();
mlkImg.src='images/mlktrafficcam.gif';
wsdotImg.src='images/dottrafficcam.gif';


function initIdentify(){
    console.log("initIdentify begins");
 //map.infoWindow.resize(325,340);
    identifyParams.tolerance = 3;
    identifyParams.returnGeometry = true;
    identifyParams.layerOption = esri.tasks.IdentifyParameters.LAYER_OPTION_ALL;

    map.infoWindow.setTitle(""); // set at the appropriate time, not now.
    map.infoWindow.resize(350,350);
    console.log("initIdentify" +identifyTask);     
}
 
function doIdentify(evt) {
    //map.graphics.clear();
    console.log("doIdentify");
    //map.infoWindow.hide();
    selectedFeatureQuery = "";
    identifyParams.layerIds = [2,0,1]; // query traffic cams first
    identifyParams.geometry = evt.mapPoint;
    identifyParams.mapExtent = map.extent;
    identifyTask.execute(identifyParams, function(idResults) { addToMap(idResults, evt.screenPoint); });
    dojo.stopEvent(evt);

}

function addToMap(idResults, screenPoint) {
    //layerresults = {displayFieldName:null,features:[]};
    closureResults = {displayFieldName:null,features:[]};
    cameraResults = {displayFieldName:null,features:[]};    
     var content = "";
     map.infoWindow.setContent(content);
     map.infoWindow.setTitle("");
     var infoWindowOK = false;
     console.log("Result length: " + idResults.length);
    
    
    if (idResults.length > 0) {
        for (var i=0, il=idResults.length; i<il; i++) {
            var idResult = idResults[i];
            console.log("LayerID: " + idResult.layerId);
            //layerId == 0 is road closures

            if ((idResult.layerId == 0 && (isCurrentAlertLayerOn===true) || (idResult.layerId == 1 && (isFutureAlertLayerOn===true)))&& (content==="")) {
                closureResults.features.push(idResult.feature);                
                if (!closureResults.displayFieldName) {closureResults.displayFieldName = idResult.displayFieldName};
					var titleContent= '<div class="titleWrapper"><span class="titleLeftText"><img src="images/mlktrafficcam.gif" alt="King County DOT logo" border="0" align="top">&nbsp;&nbsp;King County DOT Travel Alert</span></div>';               
			    	map.infoWindow.setTitle(titleContent);
				//map.infoWindow.setTitle("<div id='alertTitle' class='trafficcamTitle'><img src='images/mlktrafficcam.gif' /></div>" + "King County Travel Alert");

                // loop through and show the results
                //content = "";
                selectedFeatureQuery = "clid=" + closureResults.features[0].attributes['GlobalID'];
                console.log("selectedFeatureQuery: " + selectedFeatureQuery);
                for (var j=0, jl=closureResults.features.length; j<jl; j++) {
                    //get all the values we need
                    var roadStatus = closureResults.features[j].attributes['Road Status'];
                    var closureName = closureResults.features[j].attributes['Closure Name'];
                    var location = closureResults.features[j].attributes['Location and Limits'];
                    var timeClosed = closureResults.features[j].attributes['Actual Closure Date'];
                    var changeDate = closureResults.features[j].attributes['Change Date'];
                    var dateAdded = closureResults.features[j].attributes['Date Added'];
                    var plannedClosed = closureResults.features[j].attributes['Planned Closure Date'];
                    var closureReason = closureResults.features[j].attributes['Closure Reason'];
                    var statusOther = closureResults.features[j].attributes['Status Description'];
                    var projectNo = closureResults.features[j].attributes['Project No.'];
                    var actualOpeningDate = closureResults.features[j].attributes['Actual Opening Date'];
                    var plannedOpen = closureResults.features[j].attributes['Anticipated Opening Date'];
                    var spotlight = closureResults.features[j].attributes['Spotlight'];
                    var now = new Date();
                    var tb=new Date(timeClosed);                      
  console.log(closureResults.features[j]);
                    
                    // now some logic

                    content += "<div>"
                    content += "<strong>"+ location + "</strong>";
                    if ((spotlight == "Yes") || (spotlight == "Y")){
                        content += "&nbsp;<img src='images/smallstar.jpg' title='Spotlight' alt='spotlight graphhic'/>";
                    }
console.log("spotlight: " + spotlight);
                    if ((changeDate == undefined) || (changeDate == "Null")) {
                        content +="<br/><span class='bubbleUpdated'>Last updated: " + dateFormat(dateAdded, dateMask) + "</span>"; 
                    }else{
                        content +="<br/><span class='bubbleUpdated'>Last updated: " + dateFormat(changeDate, dateMask) + "</span>";
                    }
                    
                    if ((timeClosed == undefined) || (timeClosed == "Null") || (tb > now)) {
                        var statText;
                         switch (roadStatus){
                            case "Closed":
                                statText = "closure";
                                break;
                            case "Open":
                                statText = "opening";
                                break;                            
                            case "Restricted":
                                statText = "restriction";
                                break;
                        } 
                        content +="<br/><br/><span class='bubbleStatusUpcoming'>Upcoming " + statText + "</span>";
                    }else{
                        var statusCSS;
                        switch (roadStatus){
                            case "Closed":
                                statusCSS = "bubbleStatusClosed";
                                break;
                            case "Open":
                                statusCSS = "bubbleStatusOpen";
                                break;                            
                            case "Restricted":
                                statusCSS = "bubbleStatusRestricted";
                                break;
                        }        
                        content += "<br/><br/><span class='" +statusCSS+"'>" +roadStatus + "</span>";
                    }
                    if (roadStatus != "Open"){
                        if (closureReason == "Other")  {
                            content +="<br/>Due to: " + statusOther;
                        }else{
                            content +="<br/>Due to: " + closureReason;  
                        }
                    }
                    
                    if (roadStatus == "Restricted"){ 
                        content +="<br/><br/>Effective: " + dateFormat(timeClosed, dateMask);
                    }else{           
                        if ((timeClosed !== undefined) && (timeClosed !== "Null")&& (tb <= now)) {
                            if (roadStatus == "Open"){
                                var theReason;
                                    if (closureReason == "Other")  {
                                        theReason = statusOther;
                                    }else{
                                        theReason = closureReason;  
                                    }
                                content +="<br/><br/>Closed: " + dateFormat(timeClosed, dateMask) + ", " + theReason;    
                            }else{
                                content +="<br/><br/>Closed: " + dateFormat(timeClosed, dateMask); 
                            }
                        }else{
                            if ((plannedClosed !== undefined) && (plannedClosed !== "Null")) {
                                content +="<br/><br/>Planned closure date: " + dateFormat(plannedClosed, dateMask);
                            }    
                        }    
                    }
                    if ((actualOpeningDate !== undefined) && (actualOpeningDate !== "Null")) {
                        content +="<br/>Opened: " + dateFormat(actualOpeningDate, dateMask); 
                    }else{
                        if ((plannedOpen !== undefined) && (plannedOpen !== "Null")) {
                            content +="<br/>Anticipated opening date: " + dateFormat(plannedOpen, dateMask);
                        }    
                    }  
console.log("projectNo: " + projectNo);                   
                    if ((projectNo !== undefined) && (projectNo !== "Null")&& (projectNo !== "")) {
                        content +="<br/><br/><A href='" + cipURL + projectNo + "' target='_blank'>More project info &gt;&gt;</a>";
                    }    

                    if ((jl > 1) && (j < jl-1)) {
                         content += "<hr style='margin-top: 7px; margin-bottom: 4px;color: #cccccc; background-color: #cccccc;'>"
                    }
                    content +="</div>";
                }
            
                infoWindowOK = true;
                map.infoWindow.resize(350,200);
                //layerId == 2 is traffic cams
 //           }else if ((idResult.layerId == 2) && (isTrafficCamLayerOn===true)&& (content==="")) { 
                // the content is empty check will make sure traffic cams are not listed if closures have already been identified with this click
            }else if ((idResult.layerId == 2) && (isTrafficCamLayerOn===true)) {    
                cameraResults.features.push(idResult.feature);
                console.log("cameraResults"+cameraResults);
               console.log("identify cams:" + i);
                var camID = cameraResults.features[0].attributes['TRAFCAM_ID'];
                var camURL = camURLBase + camID + "#maptop";
                var location = cameraResults.features[0].attributes['LOCATION'];                
                var camowner;
                var titleContent="";
                var camDescription;
                
                camowner = cameraResults.features[0].attributes['OWNER'];
                camIMGURL = cameraResults.features[0].attributes['IMAGE'];
                content = "";
                if ((camID !== undefined) && (camID !== "Null")) {
                    selectedFeatureQuery = "cameraid=" + camID; 
                }
                if (camowner ==="KC") {
                    titleContent= "<div id='camTitle' class='trafficcamTitle'><img src='images/mlktrafficcam.gif' /></div>" + location;
                }else if (camowner ==="WSDOT"){
                    titleContent= "<div id='camTitle' class='trafficcamTitle'><img src='images/dottrafficcam.gif' /></div>" + location;
                }else{
                    titleContent= location;
                }  

                for (var j=0, jl=cameraResults.features.length; j<jl; j++) {

                    camDescription = cameraResults.features[j].attributes['DESCRIPTION'];
                    content += "<img src='" + cameraResults.features[j].attributes['IMAGE'] + "' width='314' height='240' name='imgTrafficCam' id='imgTrafficCam'/>";
                    content+= "<div class='trafficcamAllLink'><a href='" + allcamsURL + "' target='_blank'>" + "All cameras </a></div>";
                    content+= "<div class='trafficcamTextLink'><a href='" + textcamsURL + "' target='_blank'>" + "Small screens </a></div>";                    
                    content += "<div class='trafficcamDescription'>" + camDescription + "<p /></div>";
                }    
                map.infoWindow.setTitle(titleContent);          
                infoWindowOK = true;
                map.infoWindow.resize(325,340);
                setTimeout('refreshTrafficCam(camIMGURL)', refreshrate*1000);
            }
        }
        console.log("Content: " + content);
        map.infoWindow.setContent(content);
        if (infoWindowOK === true){
            map.infoWindow.show(screenPoint, map.getInfoWindowAnchor(screenPoint));
        }
    }
}

// function to simulate the Identify function but can call from code instead of a click

function doIdentifyProg(mapPoint) {
    var screenPoint;
    screenPoint = esri.geometry.toScreenPoint(map.extent, map.width, map.height, mapPoint);
   // map.graphics.clear();
    identifyParams.geometry = mapPoint;
    identifyParams.mapExtent = map.extent;
    identifyTask.execute(identifyParams, function(idResults) { addToMap(idResults, screenPoint); });
}


//Traffic cam auto-refresh

function refreshTrafficCam(url){
        theDate = new Date();
        url += '?dummy=' + theDate.getTime().toString(10);
        // The dummy above enforces a bypass of the browser image cache
        if ((document.imgTrafficCam !== undefined) && (document.imgTrafficCam !== null) &&(map.infoWindow.isShowing)) {
            document.imgTrafficCam.src = url;
			clearTimeout(camTimer);
            camTimer = setTimeout("refreshTrafficCam(camIMGURL)", refreshrate*1000);
            //console.log(url);
            console.log("refreshTrafficCam " + camTimer);
        }    
}    
function stopTrafficCam(){
//console.log("stopTrafficCam " + camTimer);
  if (camTimer !== null) {
    clearTimeout(camTimer);
    camTimer = 0;
  }
//console.log("stopTrafficCam ()" + camTimer);  
} 
