var RFM = RFM || {};
jQuery(function () {
    RFM.btgmi.initialize();
});

RFM.btgmi = (function ($) {
    var that = {};

    var if_height;
    var lastUsernameCheck = null;

    that.initialize = function() {
        listenForIframeResize();
        setupPrintLink();
        setupSpeakerRequest();
        homepageDonateOtherToggle();
        autoFillScreenNameOnRegister();
        setupUsernameCheck();
        lightbox();
        $('input.search-site-form').hint('Search');
        $('.imagezoom').imageZoom();

		    $("#slider").scrollable({
					size: 1,
					clickable: false
				}).circular().navigator(".navi").autoscroll(9000);
				
		$(".photo-gallery a").fancybox();
    };

    function lightbox() {
        if ($('.lightbox').length > 0) {
            $('#lightbox-overlay').show();
            $('.lightbox').show();
        }
        $('body').click(function() {
            if ($('#lightbox-overlay:visible').length > 0) {
                $('.lightbox').hide();
                $('#lightbox-overlay').hide();
            }
        });
    }

    function homepageDonateOtherToggle() {
        var otherValue = $('#other-value');
        var donateButton = $('#donate-button');
        $('input[name=set.Value][type=radio]').change(function() {
            if ($(this).attr('id') === 'radioother') {
                otherValue.show();
                donateButton.hide();
            }
            else {
                otherValue.hide();
                donateButton.show();
            }
        });
        if ($('#radioother:checked').length > 0) {
            $('#radioother:checked').trigger('change');
        }
        else {
            otherValue.hide();
            donateButton.show();
        }
    }

    function setupPrintLink() {
        $('a.print-page').click(function() {
            window.print();
            return false;
        });
    };

    // create links to the speaker request form, and add click handlers to
    // them that scrolls to the form, selects the correct speaker, highlights
    // the form, and focuses the first field.
    function setupSpeakerRequest() {
        var $speakers = $('div.speaker-holder .row');
        if ($speakers.length) {
            $speakers
                // create a link to request the speaker, giving it an
                // appropriate hash
                .each(function () {
                    var $div = $(this),
                        hash = '#' + $div.attr('id').replace(
                            '_speaker_', '_request_'
                        );
                    $('<p></p>').attr('className', 'speaker-request')
                        .append(
                            '<a href="' + hash + '">Request this speaker</a>'
                        ).appendTo($div.find('.text'));
                })

                // delegate clicks on the newly-created links
                .delegate('p.speaker-request a', 'click', function() {
                    var $link = $(this),
                        $item = $($link.attr('hash')),
                        $box  = $item.closest('.speaker');

                    // select the given option and focus its form's first
                    // input element
                    $item.attr('selected', true).closest('form')
                        .find('input[type="text"]').first().focus();

                    // scroll to the form
                    $.scrollTo($box, {duration: 500});
                    $box.stop(true, true).effect("highlight", {}, 5000);

                    return false;
                });
        }
    }

    function listenForIframeResize() {
        $.receiveMessage(function(e){
            // Get the height from the passsed data.
            var h = Number( e.data.replace( /.*if_height=(\d+)(?:&|$)/, '$1' ) );
            var iframe = $('#convio_iframe');

            if ( !isNaN( h ) && h > 0 && h !== if_height ) {
                // Height has changed, update the iframe.
                iframe.height( if_height = h );
            }
        // An optional origin URL (Ignored where window.postMessage is unsupported).
        }, 'https://secure3.convio.net' );
    };

    // give mapData, display the global ministries map
    that.displayGlobalMinistriesMap = function(mapData) {
        google.load('visualization', '1', {'packages': ['geomap']});
        google.setOnLoadCallback(function() {
            var data = new google.visualization.DataTable();
            data.addRows(mapData.length);

            data.addColumn('string', 'Country');
            data.addColumn('number', 'Ministries');
            data.addColumn('string', 'Title');

            for (var i = 0; i < mapData.length; i++) {
                data.setValue(i, 0, mapData[i].name);
                data.setValue(i, 1, parseInt(mapData[i].ministries, 10));
                data.setValue(i, 2, mapData[i].name +
                                    " - " + mapData[i].languages);
            }

            var options = {
                'dataMode' : 'regions',
                'width'    : '960px',
                'height'   : '425px'
            };
            var container = document.getElementById('map_canvas');
            var geomap = new google.visualization.GeoMap(container);
            geomap.draw(data, options);
        });
    };

    function autoFillScreenNameOnRegister() {
        if ($('#txt-screenname').length == 0) { return; }
        // on first or last name update auto-generate screen name
        $('#txt-lname, #txt-fname').bind('change.autofill', function() {
            var sn = $('#txt-fname').val() + ' ' + $('#txt-lname').val();
            sn = sn.replace(/^\s+|\s+$/g,"");
            $('#txt-screenname').val(sn);
            that.isScreenNameAvailable();
        });

        // on manual screen name change, remove auto-fill and check avail
        $('#txt-screenname').change(function() {
            $('#txt-lname, #txt-fname').unbind('change.autofill');
            that.isScreenNameAvailable();
        });
    }

    that.isScreenNameAvailable = function() {
        var screenname = $('#txt-screenname').val();
        if (screenname == '') { return; }
        $.ajax({
            type: 'GET',
            url:  '/members/search-screen-name/' + escape(screenname),
            dataType: 'text',

            beforeSend : function () {
                $('.screen_name_available, .screen_name_unavailable').hide();
                $('.sn-loading').show();
            },

            success : function (msg) {
                $('.screen_name_text').html(screenname);
                if (msg.match(/^true/)) {
                    $('.screen_name_available').hide();
                    $('.screen_name_unavailable').show();
                }
                else {
                    $('.screen_name_unavailable').hide();
                    $('.screen_name_available').show();
                }
            },

            complete: function () {
                $('.sn-loading').hide();
            }
        });
    };

    function setupUsernameCheck() {
        if ($('#search_username_form').length == 0) { return; }
        $('#txt-email').change(function() {
            that.isUsernameAvailable();
        });
    }

    that.isUsernameAvailable = function() {
        if ($('#txt-email').val() == '') { return; }
        $('.un-loading').show();
        $('.username_available, .username_unavailable').hide();
        var now = new Date().getTime();
        // only allow searches every 6 seconds
        if (lastUsernameCheck && lastUsernameCheck + 6000 > now) {
            setTimeout("RFM.btgmi.isUsernameAvailable()", 6000 - (now - lastUsernameCheck));
            return;
        }
        lastUsernameCheck = now;
        $('#search_username').val($('#txt-email').val());
        $('#search_username_form').ajaxSubmit({
            success: function(responseText) {
                var usernames = responseText.split('|delimiter|');
                var found = false;
                for (var i = 0; i < usernames.length; i++) {
                    if (usernames[i].toLowerCase() == $('#search_username').val().toLowerCase()) {
                        found = true;
                    }
                }
                $('.un-loading').hide();
                $('.username_text').html($('#search_username').val());
                if (found) {
                    $('.username_unavailable').show();
                }
                else {
                    $('.username_available').show();
                }
            }
        });
    };

    return that;
}(jQuery));

RFM.btgmi.churchmap = (function ($) {
    var that = {};

    var map, geocoder, infowindow, markers = {};

    that.initialize = function(support, liaisons, members) {
        google.load("maps", "3", {other_params: "sensor=false"});
        google.setOnLoadCallback(function() {
            var mapOpts = {
                zoom: 3,
                center: new google.maps.LatLng(38.959409, -95.668945),
                mapTypeId: google.maps.MapTypeId.TERRAIN,
                mapTypeControl: false,
                scrollwheel: false
            };
            map = new google.maps.Map(document.getElementById("church-map-canvas"), mapOpts);

            geocoder = new google.maps.Geocoder();
            infowindow = new google.maps.InfoWindow();
            setupMarkers(support, 'support');
            setupMarkers(liaisons, 'liaisons');
            setupMarkers(members, 'members');

            setupTypeToggle();
        });
    };

    function setupTypeToggle() {
        $('ul.map-types').delegate('a', 'click', function() {
            if ($(this).parent().hasClass('active')) {
                return false;
            }
            $('ul.map-types li').removeClass('active');
            $(this).parent().addClass('active');
            var linkClass = $(this).attr('class');
            infowindow.close();

            $.each(markers, function(key, theseMarkers) {
                $.each(theseMarkers, function (i, marker) {
                    if (key == linkClass) {
                        marker.setMap(map);
                        if (i === 0) {
                            google.maps.event.trigger(marker, 'click');
                        }
                    }
                    else {
                        marker.setMap(null);
                    }
                });
            });
            return false;
        });
    }

    function setupMarkers(data, type) {
        var startWithType = 'support';
        var icon = new google.maps.MarkerImage('http://backtogod.net/images/red_dot.png',
                    new google.maps.Size(22, 22),
                    new google.maps.Point(0, 0),
                    new google.maps.Point(11, 11));
        $.each(data, function(index, church) {
            var loc;
            if (church.latitude && church.longitude) {
                loc = new google.maps.LatLng(church.latitude,
                                                 church.longitude);
            }
            else {
                geocoder.geocode({'address':church.address}, function(res, stat) {
                    if (stat == google.maps.GeocoderStatus.OK) {
                        loc = res[0].geometry.location;
                    }
                });
            }
            var marker = new google.maps.Marker({
                        title: church.title,
                        position: loc,
                        icon: icon
            });
            marker.church = church;
            google.maps.event.addListener(marker,'click',function(){
                infowindow.close();
                infowindow.setContent(marker.church.content);
                infowindow.open(map,marker);
            });
            if (startWithType == type) {
                marker.setMap(map);
            }
            if (index === 0 && startWithType == type) {
                map.panTo(marker.getPosition());
                setTimeout(function(){
                    google.maps.event.trigger(marker, 'click');
                }, 300);
            }
            if (!markers[type]) {
                markers[type] = [];
            }
            markers[type].push(marker);
        });
    }

    return that;
}(jQuery));
// add a 'hint' to an input
jQuery.fn.hint = function (hint) {
    var $ = jQuery;

    // could be added to String.prototype, but this keeps the plugin
    // side-effect free
    function ucfirst(str) {
        return (str.slice(0, 1).toUpperCase() + str.slice(1));
    }

    // add a hint to the item
    function hintify() {
        if (!this.value || this.value == $(this).data('hint')) {
            $(this).addClass('hint').val($(this).data('hint'));
        }
    }

    // remove or select a hint'D input
    function dehintify() {
        var $this = $(this).removeClass('hint');
        if (this.value == $this.data('hint')) {
            $this.val('');
        }
        else {
            $this.select();
        }
    }

    // process the hint for each element
    return $(this).each(function () {
        $(this).data('hint', (hint || ucfirst($(this).attr('name'))));
    }).each(hintify).focus(dehintify).click(dehintify).blur(hintify);
};



