/*
 * supporting javascript for si_integrators.jsp
 */
var customerMarker = null;
var map = null;

// initialize SI location map
document.observe ( "dom:loaded", function() {
    if ( GBrowserIsCompatible() ) {
        map = new GMap2(document.getElementById("siMap"));                 
                        
        var centerPoint = new GLatLng(38, -98);
        map.setCenter(centerPoint, 4);

        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());           
  
        // add adc marker
        //var adcLocation = new GLatLng(34.190, -84.14860);
        //GIcon adcIcon = new GIcon ( "/images/SystemIntegrator/smileyMarker.png" );
        //var markerOptions = { icon:adcIcon }; // zIndexProcess:new function(){return 900;} };
        //var adcMarker = new GMarker ( adcLocation, markerOptions );
        //map.addOverlay ( adcMarker );
        //adcMarker.setImage ( "/images/SystemIntegrator/marker_green.png" );
        
        // add all si markers
        integrators.values().each ( function(si)  {
            si.gMarker = new GMarker ( new GLatLng(si.latitude, si.longitude) );
            map.addOverlay ( si.gMarker );
            si.gMarker.setImage ( "/images/SystemIntegrator/marker_green.png" );
            // GEvent.addListener ( si.gMarker, "mouseover", function() { 
            GEvent.addListener ( si.gMarker, "click", function() {
                si.gMarker.openInfoWindowHtml (
                    "<div style='float:left'>" + 
                    si.address.co_name + "<br>" +
                    si.address.addr1.replace(/&amp;quote;/g,'"') + "<br>" +  
                    si.address.city + ", " + si.address.st + " " + si.address.zip + "<br><br>" +
                    "<a href='http://" + si.website + "'>" + si.website + "</a><br>" +
                    si.address.def_attn_name + "<br>" +
                    si.address.phone + "<br>" +
                    "<a href='mailto:" + si.address.email_addr + "' " +
                    "   class='si_contact_email'  " +
                    "   id='em" + si.branchId + "' " + 
                    "   onclick='showInquiryForm(this);return false;'>" + si.address.email_addr + "</a>" + "<br>" +
                    "</div>" );
            } );
        } );

        addLegend();
        updateSIListing();

        if ( customerLocation != null ) {
        	point = new GLatLng ( customerLat, customerLon );
			var newZoomLvl = customerZoom; // map.getZoom() > 5 ? map.getZoom() : 5; 
			map.setCenter ( point, newZoomLvl );
			customerMarker = new GMarker(point,{ zIndexProcess:new function(){return 1000;} });
			map.addOverlay ( customerMarker );
			customerMarker.setImage ( "/images/SystemIntegrator/marker.png" );
        }
        
    }
    // else, fall back to static image map (placed on page load)...
} );
  
// mark customer location
function updateCustomerLocation ( customerZip, map ) {          
    var geocoder = new GClientGeocoder();
    geocoder.getLocations ( customerZip,
        function ( response ) {
            if ( !response || response.Status.code != 200 ) {
                alert ( 'Could not retrieve location information!' );
                $('custZip').focus();
            }
            else {
            	var place = response.Placemark[0];
	        	point = new GLatLng ( place.Point.coordinates[1],
	                                  place.Point.coordinates[0] );
	            saveZip ( customerZip, point.lat(), point.lng() );
            }
        } );
}

// handler to set up for move of customer location.
function setCustomerLocation() {
    if ( map != null ) {
        var newZip = $('custZip').value;
        if ( /^[0-9]{5}(?:-[0-9]{4})?$/.test(newZip) ) {
            updateCustomerLocation ( newZip, map );
        } 
        else {
            alert ( 'Please use a valid 5 digit US zip code' );
            $('custZip').focus();
        }
    }
}

// save zip code change (send to server).
function saveZip ( customerZip, customerLat, customerLon ) {
    new Ajax.Request ( "/ajax?", {
	    method: 'post',
	    parameters: { 
	        fctype:'adc.falcon.SystemIntegrator.SiFormCtrl',
	        txnNumber:-1,
	        cmd:'setCurrentCustomerLocation', 
	        custZip:customerZip,
	        custLat:customerLat,
	        custLon:customerLon
        },
        onSuccess: function(transport) {
            document.location.reload();
        }
    } );  
}

// set up observer to open/close criteria listings.
document.observe ( "dom:loaded", function() {
    $$('.sc_head').each ( function(el) {
        el.setStyle ( { cursor:"pointer" } );
        el.update ( "<nobr>&nbsp;<img id='" + el.id + 
                    "-img' src='/images/SystemIntegrator/opennode.gif'.>&nbsp;" + 
                    el.innerHTML + "</nobr>" );
        el.observe ( "click", function() {
            new Effect.toggle ( this.id+'_opts', 'blind', {duration:.3} );
            if ( $(this.id+'_opts').visible() ) {
                $(this.id+'-img').src = '/images/SystemIntegrator/closenode.gif';
            }
            else {
                $(this.id+'-img').src = '/images/SystemIntegrator/opennode.gif';
            }
        } ); 
    } );
} );

// close all of the criteria selection groupings.
function collapseAllCriteriaList() {
    $$(".sc_head").each ( function(el) { 
        new Effect.BlindUp ( el.id+'_opts', {duration:.3} );
    } );
}

// expand all of the criteria selection groupings.
function expandAllCriteriaList() {
    $$(".sc_head").each ( function(el) { 
        new Effect.BlindDown ( el.id+'_opts', {duration:.3} );
    } );
}

// select All/Any/None for every criteria.
function resetAllCriteriaList() {
    $$('.criteriaOp').each ( function(el) { el.checked = false; } );
    $$('.unspecifiedOpt').each ( function(el) { el.checked = true; } );
    updateSIListing();
}

// fill in services grid.
var clickSet = [ "C-1003-7" ];
var dlSet = [ "C-1003-2", "C-1003-3", "C-1003-4", "C-1003-5", "C-1003-6" ];
var proSet = [ "C-1003-1" ];
var cmoreSet = [ "C-1005-1" ];
var cmoreMicroSet = [ "C-1005-2" ];
var optimateSet = [ "C-1005-3" ];
var sureServoSet = [ "C-1006-1" ];
var drivesSet = [ "C-1006-3", "C-1006-5" ];
var motorsSet = [ "C-1006-7" ];
document.observe ( "dom:loaded", function() {
    $$(".criteriaGrid").each ( function(el) {
        var branchId = el.id.substring(5); 
        var siContainer = $('B-'+branchId);       
        var matchCss = "text-align:center;color:#000000;font-weight:bolder";
        var noMatchCss = "text-align:center;color:#cccccc;font-weight:bold";
        var click = clickSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var dl = dlSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var pro = proSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var cmore = cmoreSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var micro = cmoreMicroSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var optimate = optimateSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var sure = sureServoSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var gs = drivesSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
        var iron = motorsSet.any ( function(c) { return siContainer.hasClassName(c); } ) ? matchCss : noMatchCss;
    	el.update ( "<table frame='void' rules='all' cellpadding='2' cellspacing='1' >" +
    			    "<tr><th style='background-color:#33ff33' align='center'>PLC</td><th style='background-color:#ffff00' align='center'>HMI</td><th style='background-color:#ff3333' align='center'>Motion</td></tr>" +
    			    "<tr><td style='" + pro + ";background-color:#66ff66'>Productivity<br>Pro</td><td style='" + cmore + ";background-color:#ffff66'>C-More</td><td style='" + sure + ";background-color:#ff6666'>SureServo</td></tr>" +
    			    "<tr><td style='" + dl + ";background-color:#99ff99'>DL</td><td style='" + micro + ";background-color:#ffff99'>C-More<br>Micro</td><td style='" + gs + ";background-color:#ff9999'>GS/Durapulse<br>Drives</td></tr>" +
    			    "<tr ><td style='" + click + ";background-color:#ccffcc'>Click</td><td style='" + optimate + ";background-color:#ffffcc'>Optimate</td><td style='" + iron + ";background-color:#ffcccc'>AC<br>Motors</td></tr>" +
    			    "</table>" );
    } );
} );

// set up observer to monitor for criteria selection.
document.observe ( "dom:loaded", function() {
    $$('.criteriaOp').each ( function(el) {
        el.observe ( "click", function() {
            updateCriteriaSelections ( this );
            sendUpdateInfo ( this );
            updateSIListing();
        } );
    } );
} );

// update criteria selections (check/uncheck appropriate entries to match user selection).
function updateCriteriaSelections ( selectedCriteria ) {
    var groupId = selectedCriteria.id.substring(2,6);
    var allOption = $('C-'+groupId+'-U'); 
    //var checkedOpts = $$("#grp"+groupId+">input:checked");
    var checkedOpts = $("grp"+groupId).select ( "input:checked" );
    // TODO: can remove the following if all option is kept hidden...
    if ( selectedCriteria.id.endsWith('-U') ) {
        if ( selectedCriteria.checked ) {
            checkedOpts.each ( function(el) {
                el.checked = false;
            } );
        }
        else {
            if ( allOption != null ) { 
                allOption.checked = true;
            }
        }
    }
    else {
        if ( allOption != null ) {
            allOption.checked = (checkedOpts.length == 0);
        }
    }
}

// background message to update selected options on server side.
function sendUpdateInfo ( selectedCriteria ) {
    var groupId = selectedCriteria.id.substring(2,6);
    var params = new Hash ( { 
        fctype:'adc.falcon.SystemIntegrator.SiFormCtrl',
        txnNumber:-1,
        cmd:'updateSingleCriteria', 
        cid:groupId 
    } );
    var allOptions = $("grp"+groupId).select ( "input" );
    var optParams = allOptions.map ( function(opt) { params.set(opt.id,opt.checked); } );
    new Ajax.Request ( "/ajax?", { 
    	method: 'post', 
    	parameters: params 
    } );  
}                            

// update SI listing (show/hide entries)
function updateSIListing() { //  selectedCriteria ) {
    // show all
    $$('.siEntry').each ( function(el) {
        // TODO: show all (not just the ones who have the selected criteria???)                
        //if ( el.hasClassName(selectedCriteria.id) ) {
            el.show(); // setStyle ( { color:'#000000' } );
            var branchId = el.id.substring(2);
            ////$('matchImg'+branchId).show();
            ////$('noMatchImg'+branchId).hide();
            //integrators.get(branchId).gMarker.show();
            integrators.get(branchId).gMarker.setImage ( "/images/SystemIntegrator/marker_green.png" );
        //}
    } );
    
    // TODO: modify to work off of integrators list (add isMatch field that is set here)
    //       to update status of page in a single loop after the isMatch field is updated
    //       for all integrators.....
    
    // for each checked criteria, hide those that do not have the corresponding class id.
    $$('.criteriaOp').each ( function(el) {
        $$('.siEntry').each ( function(el2) {
            if ( el.checked && !el2.hasClassName(el.id) ) {
                el2.hide(); // setStyle ( { color:'#cccccc' } );
                var branchId = el2.id.substring(2);
                // TODO: don't show if already hidden because of a previously processed criteriaOp selection....                                
                ////$('noMatchImg'+branchId).show();
                ////$('matchImg'+branchId).hide();
                //integrators.get(branchId).gMarker.hide();
                integrators.get(branchId).gMarker.setImage ( "/images/SystemIntegrator/marker_grey.png" );
            }
        } );
    } );
}

// update distance calculations.
//function updateDistances() {
//    integrators.values().each ( function(integrator) {
//        var dist = 0.00062137119 * integrator.gMarker.getLatLng().distanceFrom ( customerMarker.getLatLng() );
//        $('dist-'+integrator.branchId).update ( dist.toFixed(1) + " mi." );
//    } );
//}       

// add a legend and input field for zip code (i.e. customer location) to the map display.
function addLegend() {
    $('siLegend').update ( 
        "<table width='100%' cellpadding='0' cellspacing='0'><tr>" +
        "<td align='left' style='margin-top:3px;font-weight:bold' nowrap>" +
        "<img align='absmiddle' src='/images/SystemIntegrator/marker_green_small.png'/> = Matching Integrators&nbsp;&nbsp;" +
        "<img align='absmiddle' src='/images/SystemIntegrator/marker_grey_small.png'/> = Non-matching Integrators&nbsp;&nbsp;" +
        "</td>" +
        "<td align='right' style='font-size:10pt;font-weight:bold' nowrap>" +
        "<span style='padding:2px;background-color:yellow'>" + 
        "<img align='absmiddle' src='/images/SystemIntegrator/marker_small.png'/> = Your zip code:&nbsp;" +
        "<input style='font-size:8pt' type='text' name='custZip' id='custZip' size='8' " +
            "onClick='this.select()' " +
            "value='" + (null==customerLocation?'&lt;unknown&gt;':customerLocation) + "'/> " +
        "<a href='javascript:setCustomerLocation()' style='font-weight:bold'>Update</a>" +
        "</span>" + 
        "</td></tr></table>" 
    );
	// monitor for enter key on zip code field and submit if pressed.
	$('custZip').observe('keypress', function(event){
	    if(event.keyCode == Event.KEY_RETURN) {
	    	setCustomerLocation();
	        Event.stop(event);
	    }
	});
}


