window.gmaps = [ 0, 1, 2, 3, 4, 5, 6, 7, 8 ];

$.gmap = {};
$.gmap.o = [];
$.gmap.op = {};
$.gmap.defaults = {
    lat: 0,
    lon: 0,
    zoom: 9,
    tab: 0,
    hoverClassName: 'ui-state-hover'
};

$.fn.gmap = function( op ) {

    var s = this.serial = $.gmap.o.length;
    var o = $.extend( {}, $.gmap.defaults, op );
    $.gmap.o[ s ] = $.gmap.op = o;

    return this.each(function(){

        var map = new GMap2( $(this).get( 0 ) );
        var prefecture = new GLatLng( o.lat, o.lon ),
            $items =  $(this).parent().find('ul.templeList > li');
        // Google Maps Default Map Controls
        map.addControl( new GSmallMapControl() );
        map.addControl( new GMapTypeControl() );
        map.setCenter( prefecture, o.zoom );

        var host = "http://www.kaikyou.net/mt/mt-static/images/honganji/",
            loc = document.location.href;
        if ( loc.indexOf('localhost') != -1 ) {
            host = "http://localhost:8888/www/test/google-map/images/";
        }

        var tabTitle = o.tabTitle;
        var templeIcon = new GIcon( G_DEFAULT_ICON );
        templeIcon.shadow = false;
        templeIcon.image = host + "icon_red.png";
        templeIcon.printImage = host + "icon_red.gif";
        templeIcon.iconSize = new GSize( 20, 48 );
        templeIcon.imageMap = [ 2, 2, 18, 2, 18, 46, 2, 46 ];

        // Info Panel
        var $infoPanel = $( '<div id="gmap-temple-' + o.tab  + '" class="gmap-temple ui-temple-fukyoujo" style="display:none;"><div class="gmap-temple-header"></div><div class="gmap-temple-wrapper"></div><div class="gmap-temple-footer"></div></div>' );
        $( '<span class="gmap-temple-close"><strong><em><a id="close-info-panel' + o.tab + '"></a></em></strong></span>' )
             .click(function(){
                  $infoPanel[ $.browser.msie ? 'hide' : 'fadeOut' ]().removeClass('active');
             })
             .appendTo( $infoPanel );

        var markers = [],
            activeMarker = false,
            centerMarker = false;

        $items.each(
            function( i, item ) {
                var $item = $( item );
                var prop = {
                    lat: parseFloat( $item.attr('lat') ),
                    lon: parseFloat( $item.attr('lon') ),
                    tit: $( 'h2 span', $item ).text(),
                    adr: $item.attr('adr'),
                    tel: $item.attr('tel'),
                    fax: $item.attr('fax')
                };
                if ( !isNaN( prop.lat ) && !isNaN( prop.lon ) ) {
                    $item.addClass('has-geocode');
                    var point = new GLatLng(  prop.lat,  prop.lon );
                    var markerOptions = { icon: templeIcon };
                    var marker = new GMarker( point, markerOptions );
                    var targetBlog = $( 'a:eq(1)' , $( this )).attr('href');
                    marker.gmapInfo = $( '<h3><a href="' + targetBlog + '">' + prop.tit
                          + '</a></h3><p><a href="' + targetBlog + '">'
                          + prop.adr
                          + ( prop.tel ? ( '<br />TEL:' + prop.tel ) : '' )
                          + ( prop.fax ? ( '<br />FAX:' + prop.fax ) : '' )
                          + '</a></p>'
                        );
                    marker.gmapInfoLink = targetBlog;
                    marker.gTempleName = prop.tit;
                    map.addOverlay( marker );
                    markers.push( marker );
                    var $visibleItem = $( '#top-' + $item.attr('id') );
                    if ( $visibleItem.size() > 0 ) {
                        $visibleItem.hover(
                            function() {
                                $( this ).addClass( o.hoverClassName );
                            },
                            function() {
                                $( this ).removeClass( o.hoverClassName );
                            }
                        )
                        .click(
                            function() {
                                var $link = $( 'a:eq(1)', this ).attr('href');
                                document.location.href = $link;
                                return false;
                            }
                        ).find('a.map-me').click(
                            function(){
                                var $tabs = window.$tabs || {
                                    select: function(){}
                                }
                                $tabs.tabs('select', o.tab );
                                if ( map.getZoom() != 10 ) {
                                    map.setZoom( 10 );
                                }
                                var pos = { };
                                pos.curr = marker.getLatLng();
                                pos.center = map.getCenter();
                                pos.bounds = map.getBounds();
                                pos.northEast = pos.bounds.getNorthEast();
                                pos.final = new GLatLng( pos.curr.y, pos.curr.x + ( ( pos.northEast.x - pos.center.x  ) / 1.5 ), true );
                                if ( ( pos.final.lat() != pos.center.lat() ) && ( pos.final.lng() != pos.center.lng() ) ) {
                                    var moveEnd = GEvent.addListener( map, "moveend", function() {
                                        var markerOffset = map.fromLatLngToDivPixel( marker.getPoint() );
                                        $( 'div.gmap-temple-wrapper', $infoPanel ).html(
                                            marker.gmapInfo.clone().clone().click(function(){
                                                document.location.href = marker.gmapInfoLink;
                                            })
                                        );
                                        $infoPanel.css({
                                            top: ( markerOffset.y - 28 ) + 'px',
                                            left: ( markerOffset.x  + 12 ) + 'px'
                                        })
                                        .show();
                                        GEvent.removeListener(moveEnd);
                                    });
                                    map.panTo( pos.final );
                                }
                                else {
                                    var markerOffset = map.fromLatLngToDivPixel( marker.getPoint() );
                                    $infoPanel.css({
                                        top: ( markerOffset.y - 28 ) + 'px',
                                        left: ( markerOffset.x  + 12 ) + 'px'
                                    })
                                    .show();
                                }
                                if ( pageTracker ) {
                                    pageTracker._trackPageview( '/index/map/' + tabTitle + '/' + marker.gTempleName );
                                }
                                activeMarker = marker;
                                centerMarker = true;
                                return false;
                            }
                        );
                    }
                }
            }
        );

        $( markers ).each(
            function( i, marker ) {
                GEvent.addListener( marker, "click", function() {
                    if ( map.getZoom() != 10 ) {
                        map.setZoom( 10 );
                    }
                    var pos = { };
                    pos.curr = marker.getLatLng();
                    pos.center = map.getCenter();
                    pos.bounds = map.getBounds();
                    pos.northEast = pos.bounds.getNorthEast();
                    pos.final = new GLatLng( pos.curr.y, pos.curr.x + ( ( pos.northEast.x - pos.center.x  ) / 1.5 ), true );
                    var refreshInfoPanel = function() {
                        var markerOffset = map.fromLatLngToDivPixel( marker.getPoint() );
                        $( 'div.gmap-temple-wrapper', $infoPanel ).html(
                            marker.gmapInfo.clone().click(function() {
                                document.location.href = marker.gmapInfoLink;
                            })
                        );
                        $infoPanel.css({
                            top: ( markerOffset.y - 28 ) + 'px',
                            left: ( markerOffset.x  + 12 ) + 'px'
                        })[ $.browser.msie ? 'show' : 'fadeIn' ]();
                        if ( pageTracker ) {
                           pageTracker._trackPageview( '/index/map/' + tabTitle + '/' + marker.gTempleName );
                        }
                    };
                    if ( ( pos.final.lat() != pos.center.lat() ) || ( pos.final.lng() != pos.center.lng() ) ) {
                        var moveEnd = GEvent.addListener( map, "moveend", function() {
                            refreshInfoPanel();
                            GEvent.removeListener(moveEnd);
                        });
                        if ( $infoPanel.hasClass('active') ) {
                                if ( $.browser.msie ) {
                                    $infoPanel.hide();
                                    map.panTo( pos.final );
                                }
                                else {
                                    $infoPanel.fadeOut(function(){
                                        map.panTo( pos.final );
                                    });
                                }
                        }
                        else {
                            $infoPanel.addClass('active');
                            map.panTo( pos.final );
                        }   
                    }
                    else {
                        var markerOffset = map.fromLatLngToDivPixel( marker.getPoint() );
                        $infoPanel.css({
                            top: ( markerOffset.y - 28 ) + 'px',
                            left: ( markerOffset.x  + 12 )+ 'px'
                        })[ $.browser.msie ? 'show' : 'fadeIn' ]();
                    }
                    activeMarker = marker;
                    centerMarker = true;
                });
            }
        );

        GEvent.addListener( map, "dragend", function() {
            centerMarker = false;
        });

        $infoPanel.appendTo( map.getPane( G_MAP_FLOAT_SHADOW_PANE ) );

        var zoomCallBack = function() {
            if ( activeMarker ) {
                var moveEnd = GEvent.addListener( map, "moveend", function() {
                     var markerOffset = map.fromLatLngToDivPixel( activeMarker.getPoint() )
                     $infoPanel.css({
                        top: ( markerOffset.y - 28 ) + 'px',
                        left: ( markerOffset.x  + 12 ) + 'px'
                     });
                     GEvent.removeListener(moveEnd);
                 });
                 var pos = { };
                 pos.curr = activeMarker.getLatLng();
                 pos.center = map.getCenter();
                 pos.bounds = map.getBounds();
                 pos.northEast = pos.bounds.getNorthEast();
                 pos.final = new GLatLng( pos.curr.y, pos.curr.x + ( ( pos.northEast.x - pos.center.x  ) / 1.5 ), true );
                 map.setCenter( pos.final );
            }
        }
        GEvent.addListener( map, "zoomend", zoomCallBack );

        window.gmaps[ o.tab ] = map;

    });

}

$.updateMap = {
    perform: function( o ) {
        var $curMap = o.map || false;
        if ( $curMap ) {
            $curMap.updateMap({
                tab: o.tab,
                mapSettings: {
                    zoom: o.zoom,
                    lat: o.lat,
                    lon: o.lon,
                    idx: o.tit
                },
                action: o.action
            });
        }
    },
    init: function( $nav ) {
        $nav.each(function( i ) {
            var $el = $(this);
            $el.bind( 'click', function() {
                if ( $el.parent().hasClass('ui-tabs-selected') ) {
                     $.updateMap.perform({
                         tab: i,
                         action: 'reset',
                         map: $( '#' + $el[ 0 ].href.split( '#' )[ 1 ] + ' div.map' ),
                         zoom: parseInt( $el.attr('zoom'), 10 ),
                         lat: parseFloat( $el.attr('lat') ),
                         lon: parseFloat( $el.attr('lon') ),
                         tit: $el.attr('title')
                    });
                } 
            });
        });
    }
};

$.updateMap.o = [];
$.updateMap.op = {};
$.updateMap.defaults = {
    tab: 0,
    mapSettings: {},
    action: 'load'
};

$.fn.updateMap = function( op ) {

    var s = this.serial = $.updateMap.o.length;
    var o = $.extend( {}, $.updateMap.defaults, op );
    $.updateMap.o[ s ] = $.updateMap.op = o;

    var $curMap = $( this ),
        mapSettings = o.mapSettings;

    if ( o.action == "load" ) {
        return $curMap.gmap({
            lat: mapSettings.lat,
            lon: mapSettings.lon,
            zoom: mapSettings.zoom,
            tab: o.tab,
            tabTitle: mapSettings.idx
        }).attr("isloaded","on");
    }
    else {
        var googleMap = window.gmaps[ o.tab ];
        if ( googleMap ) {
            var infoWindows = $('div.gmap-temple');
            infoWindows.hide();
            if ( googleMap.getZoom() != mapSettings.zoom ) {
                googleMap.setZoom( mapSettings.zoom );
            }
            googleMap.panTo( new GLatLng( mapSettings.lat, mapSettings.lon ) );
            return $curMap;
        }
    }

};

$(window).load(function() {

        // Google Map Update Plugin
        var $tabsLink = $( '#localNavigation a' );
        
        // Reset Google Map Functions
        $.updateMap.init( $tabsLink );

        // jQuery UI Tabs
        var tabSelection = function( event, ui ) {
           var $link = $( ui.tab ),
               linkHref = $link.attr('href'),
               op = {
                   map: $( '#' + $link[0].href.split( '#' )[ 1 ] + ' div.map' ),
                   tab: ui.index,
                   zoom: parseInt( $link.attr('zoom'), 10 ),
                   lat: parseFloat( $link.attr('lat') ),
                   lon: parseFloat( $link.attr('lon') ),
                   tit: $link.attr('title')
                };
            if ( !op.map.attr('isloaded') ) {
                op.action = 'load';
            }
            else {
                op.action = 'reset';
            }
            $.updateMap.perform( op );
        };

        // Home page only: preload all tabs
        $tabsLink.each(
            function( i ){
                tabSelection( null, {
                    index: i,
                    tab: $(this)
                });
            }
        );

        var $tabs = $( 'div#tabs' ).tabs({
            selected: 0,
            show: tabSelection
        });
        
        window.$tabs = $tabs;

        $('#chunk div.rightColumn li').hover(
            function() {
                $( this ).addClass( 'ui-state-hover' );
            },
            function() {
                $( this ).removeClass( 'ui-state-hover' );
            }
        ).click(
            function() {
                var $link = $( 'a:eq(0)', this ).attr('href');
                document.location.href = $link;
                return false;
            }
        );

});
