var results = [];

var stockist = {};

var icon_home = new GIcon();
icon_home.image = "/images/stockist/me.png";
icon_home.iconSize = new GSize(75, 59);
icon_home.iconAnchor = new GPoint(24, 54);

function getIconForBrand(brandId) {
    
    var icon = new GIcon();
    
    /*
    icon.image = "/images/stockist/home-" + brandId + ".png";
    icon.iconSize = new GSize(63, 59);
    icon.iconAnchor = new GPoint(24, 54);
    icon.infoWindowAnchor = new GPoint(35, 1);
    */
    
    // use same pin for all brands now  
    icon.image = "/images/stockist/purple-pushpin.png";
    icon.iconSize = new GSize(32, 32);
    icon.iconAnchor = new GPoint(1, 1);
    icon.infoWindowAnchor = new GPoint(25, 1);
    
    return icon;
}

stockist.init = function() {
    
    $("form.stockistsearch input").keydown(function(e) {
        
        // return key
        if(e.keyCode == 13) {
            e.preventDefault();
            stockist.findClick(e);
        }
    });
        
    $('#find').click(stockist.findClick);
    
    stockist.checkBookmark();
    
    stockist.updateBrand();
    stockist.updateProducts();
    
    $('#brand').change(stockist.updateProducts);
}

stockist.updateBrand = function() {
    var query = {
        dataType: "json",
        method: "brands"
    };

    $.getJSON("/rpc_stockist.php", query, function(results) {
        
        if (results.length == 0) {
            $('#brandRow').css("visibility","hidden");
        }
        else {  

            $('#brand').empty();

            for (var i = 0; i < results.length; i++)
            {
                $('#brand').append('<option value="' + results[i].brandCode + '">' + results[i].brandName + '</option>');
            }
            $('#brand option').eq(0).attr('selected', 'selected');
/*
            $("#product").html("<option value=''>All Models</option>" + get_options(results, 'modelReference', 'productString'));
            
            $('#product').val(stockist.modelReference);
*/
                
            $('#brandRow').css("visibility","visible");
        }
    });
}

stockist.updateProducts = function() {
    
    var brandId = $('#brand option:selected').attr('id').slice(5)
    stockist.brandName = $('#brand option:selected').text();

    var query = {
        dataType: "json",
        brandId: brandId
    };
    
    $.getJSON("/products.php", query, function(results) {
        
        if (results.length == 0) {
            $('#productRow').css("visibility","hidden");
        }
        else {  
            $("#product").html("<option value=''>All Models</option>" + get_options(results, 'modelReference', 'productString'));
            
            $('#product').val(stockist.modelReference);
                
            $('#productRow').css("visibility","visible");
        }
    });
}

stockist.checkBookmark = function() {
    var currentUrl = document.location.toString();
    if (currentUrl.indexOf('#') != -1) {
        var search = { count: 0 };
        var queryString = currentUrl.substr(currentUrl.indexOf('#') + 1);
        var query = queryString.split("&");
        for (var i = 0; i < query.length; i ++) {
            var arg = query[i].split("=");
            switch(arg[0]) {
                case "postcode":
                    search.postcode = arg[1].replace(/%20/," ");
                    search.count++;
                    break;
                case "brand":
                    search.brand = arg[1];
                    search.count++;
                    break;
                case "distance":
                    search.distance = arg[1];
                    search.count++;
                    break;
                case "modelReference":
                    search.modelReference = arg[1];
                    search.count++;
                    break;
                default:
                    break;
            }
        }
        if (search.count == 3) {
            stockist.search(search)     
        }
        
        stockist.updateForm(search);
        
    }
    else {
        return false;
    }
}

stockist.updateForm = function(query) {
    if (query.postcode) {
        $('#postcode').val(query.postcode);
    }
    if (query.distance) {
        $('#distance').val(query.distance);
    }
    if (query.brand) {
        $('#brand').val(query.brand);
        stockist.brand = query.brand;
    }
    if (query.modelReference) {
        stockist.modelReference = query.modelReference;
        $('#productRow').css("visibility","visible");
    }
}

stockist.findClick = function(event){
    event.preventDefault();
    
    var postcode = $('#postcode').val();
    var distance = $('#distance').val();
    var brand = $('#brand').val();
    
    if (postcode.length < 5) {
        $('#searchstatus').html("<span class='error'>Please supply a valid UK postcode.</span>");
        $('#searchstatus').fadeIn("slow");
        return;
    }
    
    stockist.brand = brand;
    stockist.brandName = $('#brand option:selected').text();
    
    
    var query = {
        postcode: postcode,
        distance: distance,
        brand: brand
    };
    
    // if product row is visible then
    // pass through the model reference
    // of selected product
    if($('#productRow').css('visibility') == 'visible') {
        if ($('#product').val() != "") {
            query.modelReference = $('#product').val();
            stockist.modelReference = query.modelReference;
        }
        else
        {
            stockist.modelReference = 0;            
        }
    }
    else
    {
        stockist.modelReference = 0;        
    }
    
    stockist.search(query);
}

stockist.search = function(query) {
    
    $.getJSON("/rpc_stockist.php", query, function(results) {
                var pcode = query.postcode;
                
                stockist.response(results, pcode, query);
            }
    )
    
    stockist.map.removePoints();
    stockist.map.hide();
    stockist.results.clear();
    stockist.results.hide();
    stockist.throbber.show();
    stockist.updateLocation(query);
}

stockist.updateLocation = function(query) {
    hash = "postcode=" + query.postcode;
    hash += "&distance=" + query.distance;
    hash += "&brand=" + query.brand;
    if(query.modelReference)
        hash += "&modelReference=" + query.modelReference;
    
    var currentUrl = document.location.toString();
    if (currentUrl.indexOf('#') != -1) {
        var baseUrl = currentUrl.substr(0, currentUrl.indexOf('#'));
    }
    else {
        baseUrl = currentUrl;
    }
    
    var newUrl = baseUrl + '#' + hash;
    
    document.location = newUrl;
}

stockist.response = function(stockists, postcode, query) {
    if (stockists.error) {
        stockist.throbber.hide();
        
        if (stockists.error.indexOf("not found")) {
            $('#searchstatus').text("Sorry, we could not verify your postcode.");
            $('#searchstatus').fadeIn("slow");
        }
        else {
            $('#searchstatus').text("Sorry, there was a problem searching our database. Please try again.");
            $('#searchstatus').fadeIn("slow");
        }
    }
    else {
        stockist.buildResults(stockists);
        stockist.throbber.hide();
        
        var searchTerm = "";
        var resultsWithinRange = true;
        
        if (stockists.length != 0) {
        
            stockist.map.show();
            if (!stockist.map.ready) {
                stockist.map.init();
            }
            else {
                stockist.map.removePoints();
            }
            
            stockist.map.center($('#postcode').val());
            results = stockists;
            stockist.map.setPoints();
            
            for (var i = 0; i < results.length; i++) {
                if (results[i].databasePostcode.distanceMiles > query.distance) {
                    resultsWithinRange = false;
                    break;
                }
            }       
        }
        
        if(query.modelReference != null)
        {
            searchTerm = "model " + query.modelReference;
            isModelSearch = true;
        }
        else
        {
            searchTerm = stockist.brandName + " stockists";
            isModelSearch = false;
        }

        stockist.results.setText(stockists.length, searchTerm, resultsWithinRange, isModelSearch);
        stockist.results.show();
    }
}

stockist.buildResults = function(results) {
    
    for (var i = 0; i < results.length; i++) {
        
        /*
        var link = $("<a href='#map'>" + results[i].partyName + '</a>').bind("click", {id: i}, function(event) {
                var key = i;
                stockist.select(event, key);
        });
        */
        var details = $("<div style='display: none'>" + stockist.makeInfo(results[i]) + "</div>");

        var stockistresult = "<div class='stockistresult'>";
        stockistresult += "<div class='stockisttop'>";
        stockistresult += "<span class='stockistnum'>" + (i + 1) + ".</span><span class='stockistname'>" + results[i].partyName + "</span>";
        stockistresult += "</div>";
        stockistresult += "<div class='stockistdetail'>";
        //stockistresult += "<img src='/images/stockist/home-" + stockist.brand + ".png' width='63' height='59' alt='' />";
        stockistresult += "<table cellspacing='0' cellpadding='0'>";
        stockistresult += "<tr><td width='400'><strong>Address</strong></td>";
        
        if (results[i].phoneNumber && results[i].phoneNumber.length > 0) {
            stockistresult += "<td>Tel. " + results[i].phoneNumber + "</td></tr>";
        }
        
        if (results[i].address1 && results[i].address1.length > 0) {
            stockistresult += "<tr><td>" + results[i].address1 + "</td><td>&nbsp;</td></tr>";
        }
        
        if (results[i].address2 && results[i].address2.length > 0) {
            stockistresult += "<tr><td>" + results[i].address2 + "</td><td>&nbsp;</td></tr>";
        }
        
        if (results[i].city && results[i].city.length > 0) {
            stockistresult += "<tr><td>" + results[i].city + "</td><td>&nbsp;</td></tr>";   
        }
        
        if (results[i].stockistPostcode && results[i].stockistPostcode.length > 0) {
            stockistresult += "<tr><td>" + results[i].stockistPostcode + "</td><td>&nbsp;</td></tr>";
        }
        
        stockistresult += "</table>";
        stockistresult += "</div>";
        stockistresult += "</div>";
        
        var resultelement = $(stockistresult).bind("click", {id: i}, function(event) {
                var key = i;
                stockist.select(event, key);
        });
        
        var container = $("<div/>").append(details).append(resultelement);
        $('#stockists').append(container);  
        
    }
}

stockist.makeInfo = function(stockist) {
    var info = [];
    
    info.push("<strong>" + stockist.partyName + "</strong>");
    
    if (stockist.address1 && stockist.address1.length > 0) {
        info.push(stockist.address1);
    }
    if (stockist.address2 && stockist.address2.length > 0) {
        info.push(stockist.address2);
    }
    if (stockist.city && stockist.city.length > 0) {
        info.push(stockist.city);
    }
    if (stockist.county && stockist.county.length > 0) {
        info.push(stockist.county);
    }
    if (stockist.stockistPostcode && stockist.stockistPostcode.length > 0) {
        info.push(stockist.stockistPostcode);
    }
    return info.join("<br>");
}

stockist.select = function(event) {
    var lat = results[event.data.id].databasePostcode.latitude;
    var lng = results[event.data.id].databasePostcode.longitude;
    stockist.map.instance.setCenter(new GLatLng(lat, lng));
    results[event.data.id].marker.openInfoWindowHtml(stockist.makeInfo(results[event.data.id]));
    $(".details").css("display", "");
    $(this).next().css("display", "block");

    // scroll page to map
    var targetOffset = $('#map').offset().top - 100;
    $('html,body').animate({scrollTop: targetOffset}, 1000);
}

stockist.map = {};
stockist.map.ready = false;
stockist.map.instance = null;
stockist.map.show = function() {
    $('#map').css("display", "");
}

stockist.map.hide = function() {
    $('#map').css("display", "none");
}

stockist.map.init = function() {
    if (GBrowserIsCompatible()) {
        stockist.map.instance = new GMap2(document.getElementById("map"));
        stockist.map.instance.setCenter(new GLatLng(54.87537, -4.20688), 4);

        stockist.map.instance.addControl(new GSmallMapControl());
        stockist.map.ready = true;
    }
}

stockist.map.center = function(postcode) {
    postcode = stockist.map.formatPostcode(postcode);
    geocoder = new GClientGeocoder();
    geocoder.getLatLng(
        postcode + ", UK",
        function(point) {
            if (!point) {
                //alert(postcode + " not found");
            } else {
                stockist.map.instance.setCenter(point, 12);
                var marker = new GMarker(point, icon_home);
                stockist.map.instance.addOverlay(marker);
            }
        }
    );
}

stockist.map.addMarker = function(lat, lng, info)
{
    var point = new GLatLng(lat, lng);
    var marker = new GMarker(point, getIconForBrand(stockist.brand));
    if (typeof info != "undefined") {
        GEvent.addListener(marker, "click", function(){
            marker.openInfoWindowHtml(info);
        });
    }
    stockist.map.instance.addOverlay(marker);
    return marker;
}

stockist.map.setPoints = function() {
    for (var i = 0; i < results.length; i++) {
        info = stockist.makeInfo(results[i]);
        results[i].marker = stockist.map.addMarker(results[i].databasePostcode.latitude, results[i].databasePostcode.longitude, info);
    }
}

stockist.map.removePoints = function() {
    for (var i = 0; i < results.length; i++) {
        stockist.map.instance.removeOverlay(results[i].marker);
    }
}

stockist.map.formatPostcode = function(postcode) {
    postcode = postcode.replace(" ", "");
    if (postcode.length > 4 && postcode.length < 8) {
        outward = postcode.substr(0, postcode.length - 3);
        inward = postcode.substr(postcode.length - 3);
        return outward + " " + inward;
    }
    else {
        
    }
}

stockist.brand = 0;
stockist.modelReference = 0;
stockist.brandName = "";

stockist.results = {};
stockist.results.show = function() {
    $('#results').css('display', "");
}

stockist.results.hide = function() {
    $('#results').css('display', "none");
    $('#searchstatus').css('display', "none");
}

stockist.results.setModelResultCount = function(count) {
    $('#searchstatus').text("Search returned " + count + (count != 1 ? " results." : " result."));
    $('#searchstatus').fadeIn("slow");
}

stockist.results.setText = function(count, searchTerm, resultsWithinRange, isModelSearch){

    var status = "";
    
    if (!resultsWithinRange) {
    
        status = "No matches were found within the specified range.<br />The nearest stockists for the specified model and location have been retrieved.";
        
        if(isModelSearch)
            status += "<br /><br />However closer stockists of the brand may be able to order this model for you.  Please run the search again, selecting only the brand this time, and contact them for advice.";
    }
    else {
    
        status = "Search for " + searchTerm + " returned " + count + (count != 1 ? " results. " : " result. ");
        
        if (count == 0 && stockist.modelReference != 0) 
            status += "<br /><br />Please choose another model or select 'All Models' to search for " + stockist.brandName + " stockists.";
        
    }
    
    $('#searchstatus').html(status);
    $('#searchstatus').fadeIn("slow");
}

stockist.results.clear = function() {
    $('#stockists').empty();
}

stockist.throbber = {};
stockist.throbber.show = function() {
    $('#throbber').css('display', '');
}

stockist.throbber.hide = function() {
    $('#throbber').css('display', 'none');
}


$(document).ready(function() {
    
    stockist.init();
    
});
    

