var LocationNotFoundError = function(){};

window.addEvent('domready', function() {
    var printers = $$('a.print');

    printers.each(function(el) {
	el.addEvent('click', function(clicker) {
	    var event = new Event(clicker);
	    event.preventDefault();
	    window.print();
	});
    });
});

function setupGoogleMap (address) {
    function setup(point) {
        if (!point) {
            throw new LocationNotFoundError();
        }
        var map = new GMap2(document.getElementById("map_canvas"));

        map.setCenter(point, 15);
        map.addOverlay(new GMarker(point));
        map.setUIToDefault();
    }

    function sorry() {
        var div = new Element('p', {
            'class': 'sorry',
            'text': 'sorry, this address could not be found'
        });
        div.replaces($('map_canvas'));
    }

    if (GBrowserIsCompatible() && $('map_canvas')) {
        if (address !== "Address Withheld") {
            try {
                // address.SuburbName may be 'Whangarei Area'
                // this is not actually the name of any suburb
                // so google will probably choke on it
                if (address.SuburbName.test(/Whangarei Area/i)) {
                    // We'll just omit it and hope for the best
                    address.SuburbName = "";
                }
                var addressString = "{StreetNumber} {StreetName}, {SuburbName} {Region} New Zealand".substitute(address);
                var geo = new GClientGeocoder();
                var point = geo.getLatLng(addressString, setup);
            } catch(e) {
                if (e instanceof LocationNotFoundError) { 
                    sorry();
                } else {
                    throw e;
                }
            }
        } else {
            $('map_canvas').set('text', 'Address Withheld');
        }
    }
}

var myShowcase;

var callWithPropertyDetails = function (id, fn, failure) {
    // if id is false, we assume that you're on a property page

    var data = id ? {
        "altTemplate": "PropertyDetailsJSON",
        "id": id
    }
    :  {
        "altTemplate": "PropertyDetailsJSON"
    };

    var url = id ? "/property-details.aspx" : "" ;

    var req = new Request.JSON({
        "url": url,
        "data": data,
        "onSuccess": function(obj, text) { return fn(obj); },
        "onFailure": failure || function () {}
    }).get();
};

window.addEvent(
    'domready', function() {
        var largeLinks, show;

        show = function show(index) {
            largeLinks.fade('hide');
            largeLinks[index].fade('show');
        };

        if($$('.showcaseItem').length > 0) {
            myShowcase = new Showcase(
                $$(".showcaseItem"), {
                    playOnStart: true,
                    interval: 6000
                });
        }

        if ($('photos')) {
            largeLinks = $$('a.mainPropertyImageLink');

            show(0);

            $$('#photos .thumbnail a').each(
                function(item, index){
                    var link = largeLinks[index];
                    item.addEvent(
                        'click', function (event) {
                            new Event(event).preventDefault();
                            show(index);
                        });
                });

            /* Setup the maximise/minimise animation */

            var tween = new Fx.Tween (
                $('thumbnailsWrapper'), {
                    'property': 'height'
                });

            var smallSize = function () {
                return $$('.mainPropertyImage')[0].get('height').toInt() + 2;
            };

            var bigSize = function () {
                return Math.max($$('ul.thumbnails')[0].getSize().y, smallSize());
            };

            tween.set(smallSize());

            var showLink = new Element('a', {'text': "maximise" , 'class': "hideShow maximise"});
            var hideLink = new Element('a', {'text': "minimise", 'class': "hideShow minimise"});

            showLink.addEvent('click', function  () {
                tween.start(bigSize());
                hideLink.replaces(showLink);
            });

            hideLink.addEvent('click', function () {
                tween.start(smallSize());
                showLink.replaces(hideLink);
            });

            showLink.inject('photos', 'bottom');
        }

        function setupMapTab (propertyDetails) {

            if ($$('.tabContainer')) {
                var myTabs = new Tabset($$('.tabContainer')[0]);
                var mapready = false;
                myTabs.getPair('map').addEvent('active', function () {
                    if (!mapready) {
                        if ('Address' in propertyDetails) {
                            setupGoogleMap(propertyDetails.Address);
                        }
                        mapready = true;
                    }
                });
            }
        }

        if ($('map')) {
            callWithPropertyDetails(false, setupMapTab);
        }

    });

