
function wireupAjaxVoting() {

    $("a.vote-for-object").live('click', function(e) {
        e.preventDefault();

        var url = $(this).attr("href");
        // For ease, the a has a class of a<entityid> eg a123, and the parent div has a class of that name, used for scoping
        var entityId = $(this).attr("id");
        var parentDivSelector = "div." + entityId;

        $.ajax(
                {
                    url: url,
                    success: function(data) {
                        $(parentDivSelector).html(data);
                        rewireFacebox();
                        highlightFade();
                    }
                }
            );
    });
}

function wireupEmailFriend() {
    $(".emailFriend").live('submit', function() {

        $(this).ajaxSubmit({
            target: '#facebox .ajaxValidationSummary',
            success: function(responseText, statusText, xhr) {
                if (xhr.status == 299) {
                    // 299 = validation error
                    // Make the facebox higher to allow for the error messages
                    $('#facebox .content').css('height', '430px');
                } else {
                    // success
                    $("#facebox .content").html("<p class='sent'>Your email has been sent</p>");
                    setTimeout(function() { $(document).wait(2000).trigger('close.facebox') }, 3000);
                }
            }
        });
        return false; // important!
    });
}

function rewireFacebox() {
    $('a[rel*=facebox]').facebox({ overlay: true, opacity: 0.5 });
}

function wireupFacebox() {
    rewireFacebox();
    $("a.close-facebox").live('click', function(e) {
        e.preventDefault();
        $(document).trigger('close.facebox');
    });
}

function wireupGalleryThumbnails() {
    // user clicks a thumbnail - display the larger image in the gallery
    $("ul#gallery-index li a").click(function(e) {

        e.preventDefault();

        var url = $(this).attr("href");
        $.ajax({
            url: url,
            dataType: 'html',
            success: function(data) {
                $("div#pit-view").html(data);
                // Wire up email a friend links again. 
                // Would like to use .live behaviour but not clear how this would work
                rewireFacebox();

            },
            complete: function() { $("img#progress").hide() },
            beforeSend: function() { $("img#progress").show() }
        });
    });

    $("div#order-buttons a").click(function(e) {
        e.preventDefault();
        $("#sortby").val($(this).attr("id"));
        $("#progress").show();
        $("#search-form").submit();
    });
}

// Extend Number object with methods for converting degrees/radians
Number.prototype.toRad = function() {  // convert degrees to radians
    return this * Math.PI / 180;
}

String.prototype.startsWith = function(str) {
    return (this.match("^" + str) == str);
}

// Calculate property's distance in miles from user's location
function milesFromPoint(propertyLat, propertyLng, pointLat, pointLng) {
    var R = 3959; // radius of earth in miles [6371km]
    var dLat = (pointLat - propertyLat).toRad();
    var dLon = (pointLng - propertyLng).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                    Math.cos(propertyLat.toRad()) * Math.cos(pointLat.toRad()) *
                    Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
}


function highlightFade() {
    $(".highlightFade").animate({ backgroundColor: "white" }, 5000);
}


// Used to limit description in new entry form
function wordCount(s) {
    return s ? s.split(" ").length : 0;
}

// Helper wait fn
$.fn.wait = function(time, type) {
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            $(self).dequeue();
        }, time);
    });
};



function fadeVoteMessage() {
    // IE6 - no fade down
    if ($.browser.msie && $.browser.version.startsWith("6.")) {
        setTimeout(function() { $("#vote-message").hide() }, 3000);
    } else {
        $("#vote-message").wait(3000).animate({ opacity: 0 }, 1000);
    }
}



function ClientExceptionLogger() {

    function Log(message, url, line) {
        try {
            var data = "jsmessage=" + encodeURIComponent(message);
            data += "&jsurl=" + encodeURIComponent(url);
            data += "&jsline=" + encodeURIComponent(line);
            data += "&pageurl=" + encodeURIComponent(location.href);
            data += "&useragent=" + encodeURIComponent(navigator.userAgent);

            $.post(
		          "/site/jserror",
		          {
		              jsmessage: encodeURIComponent(message),
		              jsurl: encodeURIComponent(url),
		              jsline: encodeURIComponent(line),
		              pageurl: encodeURIComponent(location.href),
		              useragent: encodeURIComponent(navigator.userAgent)
		          },
                  function(data) { }
            );

        }
        catch (e) {
            // ignore logging errors
        }
    };

    this.Log = Log;

    return this;
};

// Log client browser javascript exceptions to the server
logger = new ClientExceptionLogger();
window.onerror = function(message, url, line) { logger.Log(message, url, line); }

// page load ...
$(function() {

    $('#about-menu div').hide();
    $('#about-menu li > a').click(function(e) {
        $(this).next().slideToggle('normal');
        $(this).toggleClass('selected');
        e.preventDefault();
    }
	);

    $('.transcript ol').hide();
    $('.transcript a').click(function(e) {
        $(this).next().slideToggle(400);
        $(this).toggleClass('selected');
        e.preventDefault();
    }
	);

//    $('.tabs').accessibleTabs({
//        tabhead: 'h2',
//        fx: 'fadeIn',
//        tabbody: '.body'
//    });

    $("a[rel=external]").attr("target", "_blank");

    highlightFade();

});

