$(document).ready(function() {
	var img_path = '/wp/wp-content/themes/xploredive/img/';

    $('header label').label_as_input();
    $('ul li:last-child').addClass('last');
    $('.cols .col:last-child').addClass('last');
    
	$('body.home .signup').click(function() {
		var href = $('a', this).eq(0).attr('href');
		document.location.href = href;
	});
	
	$('.box.feedback label').label_as_input();

	var $membership_type = $('.userform input[name=membership_type]');
	var handlePaymentOptions = function() {
		if ($('.userform input[name=membership_type]:checked').val() == 'free') {
			$('.userform .field-payment_option').hide();
		}
		else {
			$('.userform .field-payment_option').show();
		}
	};
	
	$membership_type.click(handlePaymentOptions);
	handlePaymentOptions();
	
	$('footer .menu-item').not(':last').append('<span class="sep">|</span>');

	$('#what_human').attr('checked', 'checked');
	$('form .field-what').hide();

    $('.ajax-form').submit(function() {
        var form = $(this);
        var post_data = form.serialize();
        $.post(form.attr('action') + '?ajax=1', post_data, function(data) {
            form.html(data);
            $('.error-msg, .error', form).hide().fadeIn();
			$('.field-what', form).hide();
			$('.box.feedback label').label_as_input();
        });
        return false;
    });
	
	$('#commentform input[type=submit]').addClass('submit-button');

	// Open external links in new window
    $('a[href^=http]').each(function() {
        var href = $(this).attr('href');
        if (href && !href.match(/xploredive|bluecandle/)) {
            $(this).attr('target','_blank')
        }
    });    

	XPL.Slideshow.init();
    XPL.Comments.init();
	XPL.DiveMaps.init();
});

var XPL = {

	Slideshow : {
		current : 0,
		delay : 8000,
		timer : null,
		
		init : function() {
			if (!$('body.home').get(0)) return;
			
			if ($('#featured .slide').size() <= 1) return;
			
			XPL.Slideshow.setTimer();
			
			$('#featured').append('<div id="fnav"><ul></ul></div>');
			
			$('#featured .slide').each(function(i) {
				var bg = $(this).css('background-image');
				bg = bg.replace('url("', '');
				bg = bg.replace('")', '');
				
				var img = new Image();
				img.src = bg;
				
				$('#fnav ul').append('<li><a href=""></a></li>');
				$('#fnav li:last-child a').click(function() {
					XPL.Slideshow.clearTimer();
					XPL.Slideshow.show(i);
					return false;
				});
			});
			
			var ul_width = 17 * $('#fnav li').size();
			$('#fnav ul').width(ul_width);
			
			XPL.Slideshow.upnav();
		},
		
		show : function(i) {
			$('#featured .slide').eq(XPL.Slideshow.current).fadeOut(1500);
			XPL.Slideshow.current = i;
			
			$('#featured .slide').eq(XPL.Slideshow.current).fadeIn(1500);
			
			XPL.Slideshow.upnav();
			
			XPL.Slideshow.setTimer();
		},
		
		next : function() {
			var x = XPL.Slideshow.current + 1;
			
			if (x >= $('#featured .slide').size())
				x = 0;
			
			XPL.Slideshow.show(x);
		},
		
		upnav : function() {
			$('#fnav a').removeClass('current');
			$('#fnav a').eq(XPL.Slideshow.current).addClass('current');
		},
		
		setTimer : function() {
			XPL.Slideshow.timer = window.setTimeout(XPL.Slideshow.next, XPL.Slideshow.delay);
		},
		
		clearTimer : function() {
			window.clearTimeout(XPL.Slideshow.timer);
		}
	},

    Comments : {
        
        init : function() {
			$('#commentform input[type=submit]').addClass('submit-button');
			
            $('#commentform').ajaxError(function() {
                if (!$('.error-msg', this).get(0)) {
                    $('.comment-notes', this).after('<p class="error-msg copy">Please fill in all the required fields below.</p>');
                }
                $('.error-msg', this).hide().fadeIn();
            });
            
            $('#commentform').submit(function() {
                $.post($(this).attr('action'), $(this).serialize(), function(data) {
                    $('#comment').val('');
                    window.location.reload();
                });
                return false;
            });
        }
        
    },

    DiveMaps : {
        current : 0,

        init : function() {
            $('#maps .map').click(function() {
                XPL.DiveMaps.popup(this);
                return false;
            });
        },
        
        popup : function(obj) {
            XPL.DiveMaps.current = 0;
            
            $.blockUI.defaults.css = {};
            $.blockUI({ message : '\
                <div class="nav prev">&lt;</div>\
                <div class="nav next">&gt;</div>\
                <div class="viewer"><div class="title"><h4></h4><a href="#" class="close">close</a></div><ul></ul></div>\
            ' });
			
			$('.blockMsg .viewer h4').append($('h4', obj).text());
			
			$('.images li a', obj).each(function() {
	            $('.blockMsg .viewer ul').append('<li><img src="' + $(this).attr('href') + '" /></li>');
			});

            XPL.DiveMaps.show_item(0);
            
            $('.blockMsg .prev').click(function() {
                XPL.DiveMaps.show_item(-1);
            });

            $('.blockMsg .next').click(function() {
                XPL.DiveMaps.show_item(1);
            });
            
            $('.blockMsg .viewer .close').click(function() {
                $.unblockUI();
                return false;
            });
            
            $('.blockOverlay').click(function() {
                $.unblockUI();
            });
        },
        
        show_item : function(x) {
            var item_num = XPL.DiveMaps.current + x;
            var num_lis = $('.blockMsg .viewer li').size();
            if (item_num >= num_lis)
                item_num = 0;
            if (item_num < 0)
                item_num = num_lis - 1;
            
            var li = $('.blockMsg .viewer li').hide().eq(item_num);
            
            var img = new Image();
            $(img).load(function() {
                li.width(img.width).fadeIn();
				$('.blockMsg .viewer .title').width(img.width);
                $('.blockMsg').center();
            });
            img.src = $('img', li).attr('src');
            
            XPL.DiveMaps.current = item_num;
        }

    }

};


(function($){
    
 	$.fn.extend({ 
 		label_as_input: function() {
            
    		return this.each(function() {
                var input = $(this).siblings('input[type=text],textarea').eq(0);
                var txt = $(this).text();
                
                $(this).hide();
                
                var _focus = function() {
                    if (input.val() == txt) {
                        input.removeClass('dim');
                        input.val('');
                    }
                };
                
                var _blur = function() {
                    if (input.val() == '') {
                        input.addClass('dim');
                        input.val(txt);
                    }
                };
            
                input.focus(_focus);
                input.blur(_blur);
                
                _focus();
                _blur();
                
                input.parents('form').submit(_focus);
                
                return this;
    		});
    	}
	});

    $.fn.center = function() {
        // Always return each...
        return this.each(function() {
            var t = $(this);

            var leftMargin = t.width() / 2;
            var topMargin = t.height() / 2;

            if( typeof( window.pageYOffset ) == 'number' ) {
                // Netscape
                var scrollOffset = window.pageYOffset;
            } else if( document.body && document.body.scrollTop ) {
                // DOM
                var scrollOffset = document.body.scrollTop;
            } else if( document.documentElement && document.documentElement.scrollTop ) {
                // IE6 standards compliant mode
                var scrollOffset = document.documentElement.scrollTop;
            }
            else {
                var scrollOffset = 0;
            }

            var topOffset = ($(window).height() / 2) + scrollOffset - topMargin;
            var leftOffset = ($('body').width() / 2) - leftMargin;
            
            if (topOffset < 0)
                topOffset = 0;

            t.css({
                position: 'absolute',
                left: leftOffset + 'px',
                top: topOffset + 'px'
            });
        });
    };

    $.fn.gridify = function(per_row) {
        if (!per_row && this.size()) {
            var container = this.parent();
            var item = this.eq(0);
            per_row = Math.floor(container.width() / item.width());
        }
        
		var row_num = 1;
        return this.each(function(i) {
            if ((i+1) % per_row == 0) {
                $(this).addClass('last');
                
                var max_height = 0;
                var el = $(this);
                for (var x = 1; x <= per_row; x++) {
                    var h = el.height();
                    if (h > max_height)
                        max_height = h;
                    el = el.prev();
                }
                
                var el = $(this);
                for (var x = 1; x <= per_row; x++) {
                    el.height(max_height);
					el.addClass('row-' + row_num);
					el.addClass('col-' + (per_row - x + 1));
                    el = el.prev();
                }
				
				row_num++;
            }
        });
    };
    
})(jQuery);

