var geocoder;
var map;
var markersArray = [];
var userLocation = {};
userLocation.new_address = '';
userLocation.address = '';
userLocation.lat = 0.0;
userLocation.lng = 0.0;

function setFeaturedContentHeight() {
    $('div.featured-content').height($('div.featured-content').siblings('img').height());
}

function initialize() {
    geocoder = new google.maps.Geocoder();
    var myLatlng = new google.maps.LatLng(-24.994167, 134.86694);
    var myOptions = {
        zoom: 4,
        center: myLatlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
  
function loadScript() {
    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
    document.body.appendChild(script);
}

function clearMarkers () {
    if (markersArray) {
        for (i in markersArray) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

function updateMap(data) {
    clearMarkers();
    var bounds = new google.maps.LatLngBounds();
    var addressLatlng = new google.maps.LatLng(userLocation.lat, userLocation.lng);
    bounds.extend(addressLatlng);
    var marker = new google.maps.Marker({
        position: addressLatlng,
        title: 'You are here'
    });
    markersArray.push(marker);
    marker.setMap(map);
    $('#supplier-listing').html('');
    $.each(data, function(index, supplier) {
        var supplierLatlng = new google.maps.LatLng(supplier.lat, supplier.lng);
        bounds.extend(supplierLatlng);
        var marker = new google.maps.Marker({
            position: supplierLatlng,
            title: supplier.title
        });
        markersArray.push(marker);
        marker.setMap(map);
        supdiv = $('<div>')
                     .append($('<b>').append(supplier.title))
                     .append('<br/>')
                     .append(supplier.address + '<br/>')
                     .append('tel:' + supplier.telephone + '<br/>')
                     .append('web:')
                     .append($('<a>').attr('href', 'http://'+supplier.website).html(supplier.website))
                     .append('<br/>')
                     .appendTo('#supplier-listing');
    });
    map.fitBounds(bounds);
    $.throbberHide();
}

function updateSuppliers(data) {
    $('#supplier-listing').html('');
    $.each(data, function(index, supplier) {
        supline = $('<p>').append(supplier.title).appendTo('#supplier-listing');
    });
    $('<a>')
        .attr('href', $('#link-wheretobuy').attr('href'))
        .html('More...')
        .appendTo('#supplier-listing');
    $.throbberHide();
}

function codeAddress(address_id, callback) {
    var address = document.getElementById(address_id).value;
    if ( address != userLocation.address ) {
        userLocation.new_address = address;
        geocoder.geocode( { 'address': address+", Australia"}, function(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
            userLocation.address = userLocation.new_address;
            userLocation.lat = results[0].geometry.location.lat()
            userLocation.lng = results[0].geometry.location.lng()
            callback(userLocation.lat, userLocation.lng);
          } else {
            alert("Geocode was not successful for the following reason: " + status);
            $.throbberHide();
          }
        });
    } else {
        callback(userLocation.lat, userLocation.lng);
    };
  }


$(document).ready(function()
{
    setFeaturedContentHeight();
    $('#tabbed-container').tabs();

    /* Rollovers for the categories */
    $('div.category')
        .mouseover(function() {
            var prev_panel_id = $('div.current-category').attr('rel');
            var panel_id = $(this).attr('rel');
            if (panel_id != prev_panel_id) {
                $(prev_panel_id).hide();
                $(panel_id).show();
                $('div.current-category').removeClass('current-category');
                $(this).addClass('current-category');
            };
        });

    /* Dynamically load the google maps js only if we have a map. */
    if ($('#map_canvas').length != 0) {
        loadScript();
    };
    //
    // Where to buy text input defaults.
    $("#address").focus(function() {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    // Add the default text if the textbox loses focus.
    $("#address").blur(function() {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        };
    });
    
    $('#shopfinder').submit(function() {
        if ($('#address').val() == $('#address')[0].title) {
            return false;
        };
        codeAddress("address", function(lat, lng) {
            $.getJSON(window.location+'/@@shopfinder?'+$('#shopfinder').serialize()+'&lat='+lat+'&lng='+lng, updateMap);
        });
        $.throbberShow({parent: '#shopfinder-wrapper', image: navroot+'++resource++simmonds.portal/throbber.gif'});
        return false;
    });
    if ($('a.popup-image').length > 0) {
        $('a.popup-image').fancybox();
    };
    // Remove the default text if clicking on the textbox.
    $("#where-address").focus(function() {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    
    // Add the default text if the textbox loses focus.
    $("#where-address").blur(function() {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        };
    });
    
    // Get adresses.
    $("#where-form").submit(function(e) {
        e.preventDefault();
        e.stopPropagation();
        if ($('#where-address').val() == $('#where-address')[0].title) {
            return false;
        };
        if ($('#where-address').val().length < 4) {
            return false;
        };
        codeAddress("where-address", function(lat, lng) {
            product_url = window.location.href.split('?')[0];
            $.getJSON(product_url+'/@@shopfinder?'+$('#where-form').serialize()+'&lat='+lat+'&lng='+lng, updateSuppliers);
        });
    });

    // Initial blur
    $("#where-address").blur();
    $("#address").blur();

    $('#shopfinder-leftbar').height($('#shopfinder-map').height());

    // The Any Product checkbox is mutually exclusive with the rest.
    $('#shopfinder-wrapper input').click(function () {
        var this_obj = $(this);
        if (this_obj.attr('id') == 'any-product') {
            if (this_obj.is(':checked')) {
                this_obj.siblings().prop('checked', false);
            };
        } else {
            if (this_obj.is(':checked')) {
                $('#any-product').prop('checked', false);
            };
        };
    });
    // Where to buy text input defaults.
    $("#mce-EMAIL").focus(function() {
        if ($(this).val() == $(this)[0].title)
        {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });
    // Add the default text if the textbox loses focus.
    $("#mce-EMAIL").blur(function() {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        };
    });
    

});

