
var map, markers, gmap;
var test;
var globFlickrIds;
var features;
var vl=false;

function parse_querystring(key){
    var re = new RegExp( "[?&]" + key + "=([^&$]*)", "i" );
    var offset = location.search.search( re );
    if ( offset == -1 ) return null;
    return RegExp.$1;
    }  

function reset_center(c){
    center = parse_querystring('center')
    if (!center){center = c}
    center = center.split(',');lon = parseFloat(center[0]); lat = parseFloat(center[1]);
    zoom = parseFloat(parse_querystring('zoom')) | 11;
    mercPoint = gmap.forwardMercator(lon,lat);
    map.setCenter(new OpenLayers.LonLat(mercPoint.lon,mercPoint.lat), zoom);
    }
    
function init_map(){
    var ghyb, streams, tpoints, drg;
    var options = {
        projection: "EPSG:54004",
        units: "m",
        maxResolution: 2445.984896,
        numZoomLevels: 19,
        maxExtent: new OpenLayers.Bounds(-13810000,5900000,-13440000,6270000)
    };
   
    OpenLayers.ImgPath="./";
    map = new OpenLayers.Map('wfMap', options);
    map.theme = './wf_map.css'
    // define Google layers
    gmap = new OpenLayers.Layer.Google("Streets",{'maxZoomLevel':19,sphericalMercator:true});
    ghyb = new OpenLayers.Layer.Google("Streets & Imagery", {type: G_HYBRID_MAP,'maxZoomLevel':19,sphericalMercator:true});
    // define WMS/Tilecache layers for overlay
    streams = new OpenLayers.Layer.WMS("Streams & Survey Points",
                "http://tc.activetools.org/wildfish/tilecache.py?",
                {'layers': 'wildfish_streams', 'format':'png'},
                {'reproject': false, 'opacity': 0.9, 'isBaseLayer': false, 
                 'attribution': 'Powered by <a href="http://openlayers.org">OpenLayers</a>',
                 'buffer':1});
    drg = new OpenLayers.Layer.WMS("Topo Map",
                "http://tc2.activetools.org/wildfish/tilecache.py?",
                {'reproject': false, 'layers': 'wildfish_drg', 'format':'jpeg'},{'buffer':0});
    tlidar = new OpenLayers.Layer.WMS("LiDAR [elevation]",
                "http://tc3.activetools.org/wildfish/tilecache.py?",
                {'layers': 'wildfish_lidar', 'format':'jpeg'},
                {'reproject': false, 'opacity': 0.5,'isBaseLayer': false, 'visibility':false, 'buffer':0});
    var tr = new OpenLayers.Layer.WMS("Township, Range",
                "http://tc3.activetools.org/wildfish/tilecache.py?",
                {'layers': 'wildfish_tr', 'format':'png'},
                {'reproject': false, 'opacity': 0.9,'isBaseLayer': false, 'visibility':false, 'buffer':0});
    var trs = new OpenLayers.Layer.WMS("Township, Range, Section",
                "http://tc3.activetools.org/wildfish/tilecache.py?",
                {'layers': 'wildfish_trs', 'format':'png'},
                {'reproject': false, 'opacity': 0.9,'isBaseLayer': false, 'visibility':false, 'buffer':0});
    map.addLayers([gmap, ghyb, drg, tlidar, streams, tr, trs]);
    
    map.addControl(new OpenLayers.Control.LayerSwitcher());
    //map.setCenter(new OpenLayers.LonLat(-13682000,5956000), 11);
    reset_center('-122.907,47.085')
    map.addControl(new OpenLayers.Control.Scale());
    
    // define onClick  event
    map.events.register('click', map, function (e) {
        OpenLayers.Util.getElement('clickResults').innerHTML = "Loading... please wait...";
        // get click coords (in mercator)
        var cc = map.getLonLatFromViewPortPx(e.xy);
        var coords = gmap.inverseMercator(cc.lon,cc.lat);
        var lat = coords.lat;
        var lon = coords.lon;
        // set request url
        var url = 'http://wildfish.beardedmaps.com/wf_query.py?callback=setHTML&lat=' + lat + '&lon=' + lon + '&zoom=' + map.getZoom();
        //run json callback
        var id = createScriptRequest(url);
        });
    }
    
function highlightVectors(features){
    // add the vector layer here, since ie dies if you add it in the init function for some reason
    if (!vl) {
    vl = new OpenLayers.Layer.Vector("Selected Highlight");
    map.addLayer(vl);
        }
    vl.destroyFeatures();
    
    var wf_p_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    wf_p_style.strokeColor = "blue"; 
    wf_p_style.fillColor = "blue"; 
    wf_p_style.strokeWidth = 3;
    wf_p_style.hoverStrokeColor = "red";
    
    point = features[1].geometry;
    var feature = new OpenLayers.Feature.Vector(point, null, wf_p_style);
    vl.addFeatures([feature]);

    //add line
    var lfeature = new OpenLayers.Feature.Vector(features[0].geometry, null, wf_p_style);
    vl.addFeatures([lfeature]);
    }


    
// returns the unique id of this script tag, for later removal    
function createScriptRequest(req){
    var st = document.createElement("script");
    st.setAttribute("type", "text/javascript");
    st.setAttribute("charset", "utf-8");
    st.setAttribute("src", req);
    st.setAttribute("id", Math.random().toString());
    head = document.getElementsByTagName("head").item(0);
    head.appendChild(st);
    //head.removeChild(st);
    return st.id
    }
    
    
function addRow(div,name,value,hidden,rowClassName,id) {
    // adds rowClassName (or simpleResultsRow) to input div
    var srr = document.createElement('div');
    srr.className = 'simpleResultsRow';    
    srr.id = 'simpleResultsRow' + name;
    if (rowClassName) {srr.className = rowClassName;}
    if (id) {srr.id = id;}
    var rt = document.createElement('div');
    rt.className = 'resultsType';
    if (name) {rt.innerHTML = name + ':  ';}
    var rv = document.createElement('div');
    rv.className = 'resultsValue';
    rv.innerHTML = value;
    if (hidden) {
        srr.style.display = 'none';
        }
    srr.appendChild(rt);
    srr.appendChild(rv);
    div.appendChild(srr);
    }

function hideDiv(div) {
    document.getElementById(div).style.display = 'none';
    a = document.getElementById('linkPointInfo');
    a.href = 'javascript:displayDiv("pointDetailsResultsDiv")';
    a.innerHTML = 'Display Point Details';
    }

function displayDiv(div) {
    document.getElementById(div).style.display = 'block';
    a = document.getElementById('linkPointInfo');
    a.href = 'javascript:hideDiv("pointDetailsResultsDiv")';
    a.innerHTML = 'Hide Point Details';
    }
    
function watertypePopup(streamId) {
    div = document.createElement('div');
    div.id = 'watertypePopup';
    div.innerHTML = 'This will eventually query the Watertyping data for stream ' + streamId + '<br>(click here to hide)';
    div.onclick = function() {this.parentNode.removeChild(this);}
    container = document.getElementById('container');
    container.appendChild(div);
    }

function setHTML(json) {
    test = json;
    geojson = new OpenLayers.Format.GeoJSON();
    features = geojson.read(json);
    results = OpenLayers.Util.getElement('clickResults');
    results.innerHTML  = '';
    var attributes; 
    test = features;
    highlightVectors(features);
    if (features.length) {
        for (j=0;j<features.length;j++) {
            feature = features[j];
            results.feature = feature;
            resultsDiv = document.createElement('div');
            if (feature.attributes.type == "stream") {
                resultsDiv.id = 'streamResultsDiv';
                var a = document.createElement('a');
                a.href = 'javascript:createPopup("watertype");';
                a.id = 'linkStreamInfo';
                a.innerHTML = 'Watertyping Details';
                results.appendChild(a);
                attributes = [['Stream','stream'],['Crew','crew'],['Date','sdate']];
                for (f=0;f<attributes.length;f++) {
                    var attrib = attributes[f];
                    addRow(resultsDiv, attrib[0], feature.attributes[attrib[1]]);
                    }
            } else if (feature.attributes.type == "point") {
                resultsDiv.id = 'pointResultsDiv';
                addRow(resultsDiv, 'Stream ID', feature.attributes['stream_id']);
                addRow(resultsDiv, 'Point ID', feature.attributes['pid']);
                globFlickrIds = [];
                for (f=0;f<feature.attributes.attributes.length;f++) {
                    curFeature = feature.attributes.attributes[f];
                    if (curFeature.photo.length < 4) {curFeature.photo = '0' + curFeature.photo;}
                    req = 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=2f740aa9f86a811b8f222de9b954e376&user_id=13853571@N08&text=DSC0' + curFeature.photo + '&format=json&jsoncallback=getFlickrPhoto'
                    //call getFlickrPhoto with response from flickr
                    //console.log(req);
                    createScriptRequest(req);
                    }
            }
            results.appendChild(resultsDiv);
        }
    } else {
        results.innerHTML = 'no results found';
    }

}

function getFlickrPhoto(json){
    if (!json.photos.photo[0]){
        addRow(resultsDiv,'','No Photo Found');
        }
    else{
        photo = json.photos.photo[0];
        baseUrl = 'http://farm'  + photo.farm + '.static.flickr.com/'
                                 + photo.server + '/' 
                                 + photo.id + '_'
                                 + photo.secret + '_';
        globFlickrIds.push([photo.title,baseUrl]);
        photoThumb = baseUrl + 't.jpg';
        photoLink = 'javascript:createPopup("point_detail")'
                    addRow(resultsDiv,'', 
                          '<a href=' + photoLink + ' title="Click for Photo Details">' + 
                          '<img src="'+ photoThumb +' "/></a>');
        }
    }

function setFilteredMarkers(response){
    results = eval(response.responseText);
    alert(results.length + ' results');
    }
    
function setFilter(filter){
    markers.clearMarkers();
    if (!filter == 'all'){
        var url = './get_streams_and_points.py?callback=setFilteredMarkers&filter=' + filter;
        createScriptRequest(url);
        }
    }

function inFlickrArray(needle, haystack){
    l = haystack.length;
    for (h=0;h<5;h++){
        if (needle == haystack[h][0].substring(4)) {return h + 1;}
        } 
    return false;
    }
    
// The following functions are for the detail templates

function createPopup(page) {
    var w = window.open(page,'windowName','width=900,height=700,resizable=1,scrollbars=1'); w.focus();
    }
 

function getWatertypeDetails(){
    // import
    var uri = "http://jugl.tschaub.net/trunk/lib/Jugl.js";
    var Jugl = window[uri];
    var results=window.opener.features[0].attributes;
    var titleDiv = document.getElementById('wfTitle');
    var template = new Jugl.Template('wfWatertypeDetails');
    template.process();
    }
    
    
    
function getPointDetails(){
    displayItems = [['Point ID','pid'], ['Date','date'],['Reach WW (ft)','reach_ww'], 
                   ['Reach BFW (ft)','reach_ohw'],['Reach Gradient (%)','reach_grade'],
                   ['Water Temp (celsius)','temp'],['Notes','notes']];
    flickrIds = window.opener.globFlickrIds;
    results=window.opener.features[1].attributes
    titleDiv = document.getElementById('wfTitle');
    titleDiv.innerHTML = 'Detailed results for Stream ' + results.stream_id
    resultsDiv = document.getElementById('wfPointDetails');
    resultsDiv.innerHTML  = '';
    for (r=0;r<results.attributes.length;r++) {
        //for each result, check to see if we have this photo in our global flickr ids hack
        var result = results.attributes[r]
        flickrArrayId = inFlickrArray(result.photo,flickrIds)
        if (flickrArrayId) {
            flickrArrayId -= 1; 
             //create container row for this result
            rowContainer = 'pointContainerRow' + r;
            addRow(resultsDiv,'','','','pointRowContainer',rowContainer);
            rowContainerDiv = document.getElementById(rowContainer);
            //add photo and regular result div holders to container row
            rowDetail = 'pointDetailRow'
            addRow(rowContainerDiv,'','','',rowDetail);
            addRow(rowContainerDiv,'','<a href=' + flickrIds[flickrArrayId][1] + 'b.jpg><img src=' + flickrIds[flickrArrayId][1] + 'm.jpg></a>',0,'pointDetailRowPhoto');
            for (d=0;d<displayItems.length;d++){
                var val = displayItems[d][1]
                if (result[val]) {addRow(rowContainerDiv,displayItems[d][0],result[val],0,rowDetail);}
                }
            }
        }
    }
    
function displayLegend(){
    createPopup('legend');
    }
    

//geocode address in the address form
function geocode(address) {
    var geocoder = new GClientGeocoder();
    var address=document.getElementById("addressGeocoder").value;
    geocoder.getLatLng(address,function(point) {
        if (!point) {alert(address + " not found");} 
        else {
            mercPoint = gmap.forwardMercator(point.x,point.y);
            console.log(point);
            console.log(mercPoint);
            map.setCenter(mercPoint, 14);
            //var marker = new GMarker(merpoint);
            //map.addOverlay(marker);
            //marker.openInfoWindowHtml(address);
            }
            });
    }

