var map, req;

// search variables
var proxyUrl = 'index.php?Action=GeoSmart.poiproxy';
var maxResults = 20;
var radius = 100000;
var sort = 'distance';

var iconstore = {};
iconstore['4400'] = new GSIcon();
iconstore['4400'].imageSrc = '/Site/Designs/Images/smartfind/bed.png';
iconstore['4400'].imageSize = new GSDimension(24, 24);
iconstore['4400'].iconOffset = new GSPoint(-24, -24);
iconstore['4400'].iconInfoWindowOffset = new GSPoint(10, 0);
iconstore['6224'] = new GSIcon();
iconstore['6224'].imageSrc = '/Site/Designs/Images/smartfind/dollar.png';
iconstore['6224'].imageSize = new GSDimension(24, 24);
iconstore['6224'].iconOffset = new GSPoint(-24, -24);
iconstore['6224'].iconInfoWindowOffset = new GSPoint(10, 0);
iconstore['4511'] = new GSIcon();
iconstore['4511'].imageSrc = '/Site/Designs/Images/smartfind/food.png';
iconstore['4511'].imageSize = new GSDimension(24, 24);
iconstore['4511'].iconOffset = new GSPoint(-24, -24);
iconstore['4511'].iconInfoWindowOffset = new GSPoint(10, 0);
iconstore['463102'] = new GSIcon();
iconstore['463102'].imageSrc = '/Site/Designs/Images/smartfind/parking.png';
iconstore['463102'].imageSize = new GSDimension(24, 24);
iconstore['463102'].iconOffset = new GSPoint(-24, -24);
iconstore['463102'].iconInfoWindowOffset = new GSPoint(10, 0);
iconstore['80'] = new GSIcon();
iconstore['80'].imageSrc = '/Site/Designs/Images/smartfind/school.png';
iconstore['80'].imageSize = new GSDimension(24, 24);
iconstore['80'].iconOffset = new GSPoint(-24, -24);
iconstore['80'].iconInfoWindowOffset = new GSPoint(10, 0);
iconstore['451147'] = new GSIcon();
iconstore['451147'].imageSrc = '/Site/Designs/Images/smartfind/food.png';
iconstore['451147'].imageSize = new GSDimension(24, 24);
iconstore['451147'].iconOffset = new GSPoint(-24, -24);
iconstore['451147'].iconInfoWindowOffset = new GSPoint(10, 0);

function init() {
    $('searchForm').onsubmit = function() {return false;}
    
    initControls();
    
    createMap();
    
    $('searchQuery').focus();
}

function initControls() {
    // search button
    $('searchButton').onclick = doSearch;
    
    
    // links panel
    Event.observe('demoSitesShutButton', 'click', function(e) {
            Element.hide('demoSitesShut');
            Element.show('demoSitesOpen');
            Event.stop(e);
        });

    Event.observe('demoSitesOpenButton', 'click', function(e) {
            Element.show('demoSitesShut');
            Element.hide('demoSitesOpen');
            Event.stop(e);
        });

    // categories
    var checkboxes = $$('#category input');
    checkboxes.each(function(checkbox) {
            Event.observe(checkbox, 'click', toggleLayer.bindAsEventListener(checkbox), false);
        });

    // search autocomplete
    var url = proxyUrl;
    var options = {indicator: 'searchIndicator', afterUpdateElement: doSearch, paramName: 'address', minChars: 3, method: 'get'};
    var autocompleter = new Ajax.Autocompleter('searchQuery', 'searchAutocomplete', url, options);

    $('layers').reset();
}

function doSearch() {
    Element.show('searchIndicator');

    var query = $F('searchQuery');
    var tokens = query.split(',');
    for(var i = 0; i < tokens.length; i++) {
        tokens[i] = trim(tokens[i]);
    }

    var parameters = '';
    switch(tokens.length) {
    case 3:  
        if(tokens[2].length > 0) {
            parameters += '&region=' + encodeURIComponent(tokens[2]);
        }
    case 2:
        if(tokens[1].length > 0) {
            parameters += '&suburb=' + encodeURIComponent(tokens[1]);
        }
    case 1:
        if(tokens[0].length > 0) {
            parameters += '&name=' + encodeURIComponent(tokens[0]);
        }
        break;
    }
	parameters = 'params=' + encodeURIComponent(parameters);
    var url = proxyUrl;
    new Ajax.Request(url, {method: 'get', parameters: parameters, onComplete: showPOI});
}

function toggleLayer(e) {
    if(this.checked === true) {
        Element.show('searchIndicator');
        var url = proxyUrl;
        var parameters = buildQuery(this.value);
	parameters = 'params=' + encodeURIComponent(parameters);
        var req = new Ajax.Request(url, {method: 'get', parameters: parameters, onComplete: showLayer});
    } else {
        var layer = map.getLayer(this.value);
        if(layer) {
            layer.clear();
        }
    }
    //Event.stop(e);
}

function buildQuery(category) {
    var mapCenter = map.getMapCenter();
    return 'category=' + category + '&x=' + mapCenter.x + '&y=' + mapCenter.y + '&radius=' + radius + '&sort=' + sort + 
        '&maxResults=' + maxResults;
}

function showPOI(request) {
    var data = eval('(' + request.responseText + ')');
    if(data.pois.poi.length == 0) {return;}
    var layer = map.getLayer('base');
    layer.clear();
    layer.addFeaturesJson(data.pois.poi, initFeature);
    map.centerOnLayer('base', function() {
            // if a single match open the popup for the feature
            if(data.pois.poi.length == 1) {
                var poi = data.pois.poi[0];
                var feature = GSUtil.getFeatureById(layer.data, poi.id);
                feature.showInfoWindow();
            } 
        });
    Element.hide('searchIndicator');
}

function showLayer(request) {
    var data = eval('(' + request.responseText + ')');
    var category = getCategoryFromQuery(data.pois.query);
    var layer = map.getLayer(category);
    if(layer == null) {
        layer = map.createLayer(category);
    }
    layer.addFeaturesJson(data.pois.poi, initFeature, category);
    Element.hide('searchIndicator');
}

function getCategoryFromQuery(querystring) {
    var re = new RegExp(/category=([^&]+)/);
    return re.exec(querystring)[1];
}

function initFeature(feature, data, args) {
    if(args) {
        var icontype = args[0].toLowerCase();
        var protoicon = iconstore[icontype];
        var icon = new GSIcon(protoicon);
        icon.alt = data.name;
        feature.setIcon(icon);
    }
    var html = '<strong>' + data.name + '</strong><br/>';
    if(data.street) {
        html += data.street + '<br/>';
    }
    html += data.suburb + ', ' + data.region + '<br/>';
    feature.infoHtml = html;
    feature.addEventHandler('click', function(e) {this.showInfoWindow();Event.stop(e);});
}

function createMap() {
    map = new GSMap('theMap');
    var labels = [{level: 9, value: 'Region'}, {level: 3, value: 'Suburb'}, {level: 0, value: 'Street'}];
    var mapControl = new GSMapControl(labels);
    map.addControl(mapControl);
    map.centerOnNewZealand();
}

function trim(str) {
    return str.replace(/^\s*|\s*$/g,'');
}

window.onload = init;
