$(function() {
	// Add n-th child on gallery thumbs for IE < 9
	/*if (! Modernizr.borderradius) {
		$('ul.gallery').find('li:nth-child(4n+1)').addClass('gallery_thumb_first_col');
	}*/
    
    // Auto adjust the gallery item margin depending on the gallery width
    $('ul.gallery').each(function() {
        var $this = $(this),
            width = $this.width(),
            cols = $this.data('cols');
        
        // If no columns specificed, we will determine columns by the parent
        // container type
        if (cols == null || cols == "") {
            cols = ($this.parents('.column').data('col_type') == 'single_row') ? 4 : 2;
        }
        
        // Columns should be greater than zero
        if (cols <= 0) {
            cols = 1;
        }
        
        if (cols < 4) {
            $this.find('li:nth-child(' + cols + 'n+1)').addClass('gallery_thumb_first_col');
        }
        else {
            $this.find('li:nth-child(4n+1)').addClass('gallery_thumb_first_col');
        }
    });
    
    $('.copyright').parent().addClass('copyright');
    
    // Auto tab layout
    var tabs = '',
        $tabContents = $('.auto_tabs').each(function(i) {
            var $this = $(this),
                tabName = $this.data('name'),
                href = '#' + tabName.replace(/\s/ig, '-').toLowerCase(),
                selected = ((i == 0 && location.hash == '') || location.hash == href) ? ' class="selected"' : '';
               
            // If pass through url given
            if ($this.data('url')) {
                href = $this.data('url');
            }

            tabs += '<td' + selected + '>\
                    <a data-tab-id="' + $this.attr('id') + '" href="' + href + '">' + tabName + '</a>\
                </td>';
            
            autoColumns($this.find('.auto_cols'));
            
            // Show the selected tab's content
            if (selected != '') {
                $this.addClass('display_block');
            }
        });

    $('<table />', {
        'id' : 'the_tabs',
        'class' : 'fluid_tabs',
        'cellpadding' : '0',
        'cellspacing' : '0'
    }).html('<tr>' + tabs + '</tr>').insertBefore($tabContents.first());
    
    // Setup the auto columns for our multi column layouts
    autoColumns('.auto_cols');
	
	$('.full_photograhpy_paginate').each(function() {
		var $this = $(this),
			$photos = $('.full_photos'),
			$pag = $('ul', $this),
			photoCount = $photos.length,
			tmp = 0,
			c = 0,
			n = 0;
		
		$photos.eq(0).addClass('active');
		
		// If more than one photo, we perform pagination
		if (photoCount > 1) {
			var dots = '',
				leftOffset = 92;
				
			for (var i = 0; i < photoCount; i++) {
				var selected = (i == 0) ? ' class="selected"' : '';
				dots += '<li' + selected + '><span class="readers">' + (i + 1) + '</span></li>';
				leftOffset -= 10;
			}
			
			$pag.css('left', leftOffset).html(dots);
			$this.show();
			
			$('.next', $this).click(function(e) {
				e.preventDefault();
				doTransition('next');
			});
			
			$('.prev', $this).click(function(e) {
				e.preventDefault();
				doTransition('prev');
			});
		}
		
		function doTransition(dir) {
			// Assume 'next'
			tmp = c = n;
			n++;
			n = (n >= photoCount) ? 0 : n;
			
			if (dir == 'prev') {
				tmp--
				n = (tmp < 0) ? photoCount - 1 : tmp;
			}
			
			$('li', $pag).removeClass('selected').eq(n).addClass('selected');
			
			$photos.eq(c).fadeOut(function() {
				$(this).css('visibility', 'visible').removeClass('active');
			});
			$photos.eq(n).hide().css('visibility', 'visible').fadeIn();
		}
	});
	
	$('.tab_list').each(function() {
		var $h4 = $(this).find('h4');
		
		$h4.each(function() {
			var $this = $(this),
				offset = Math.round($this.width() / 2) - 8;
				
			$this.css('backgroundPosition', '-' + (387 - offset) + 'px 22px');
		})
		.click(function() {
			$(this).parent().addClass('selected').siblings().removeClass('selected');
		});
	});
	
	$('.fluid_tabs').each(function() {
		$(this).find('td:not(.click_through)').click(function(e) {
			e.preventDefault();
            
            // Explicity set the location has since the anchor tag may
            // not have gotten clicked
            window.location = $(this).find('a').attr('href');
		});
	});
    
    $('.fancybox').fancybox({
        overlayOpacity : 0.2,
        titlePosition : 'inside'
    });
    
    $('.fancybox_video').fancybox({
        overlayOpacity : 0.2,
        type : 'swf'
    });
    
    // Auto correct plain H3 tags within the content area
    $('.content').find("h3:not([class])").each(function() {
        var $this = $(this);
        if ($this.find('span').length == 0) {
            $this.wrapInner('<span />')
        }
    });
    
    // Form validation
    $('#form_validate').validationEngine();
    
    // For dropdowns with "other" option
    $('[class*=other_option]').change(function(e) {
        var $this = $(this),
            val = $this.val(),
            match = $this.attr('class').match(/\[(.*)\]/);
        
        if ((val.toLowerCase() == 'other' || e.target.checked) && match != null) {
            $('#' + match[1]).css('display', 'block').find("input[type='text']").focus();
        }
        else {
            $('#' + match[1]).css('display', 'none').find("input[type='text']").val('');
        }
    });
    
    // Calendar
    $('a.event_name').each(function() {
		var timeout = null,
			$link = $(this),
			$desc = $link.parent().find('div.event_desc');
			
        $link.click(function(e) {
            e.preventDefault();
            clearTimeout(timeout);
            
            var pos = $link.position(),
                left = pos.left - Math.round($desc.outerWidth() / 1.2);
                
            if (left <= 240) {
                left = pos.left + 22;
            }
            
            $desc.css({
                'top' : pos.top - $desc.outerHeight(),
                'left' : left,
                'visibility' : 'visible'
            })
            .data('hidden', false);
        })
        .bind('mouseout', function() {
            clearTimeout(timeout);
            if ($desc.data('hidden') == false) {
                timeout = setTimeout(function() {
                    $desc.css('visibility', 'hidden').data('hidden', true);
                }, 500);
            }
        });
        
        /*
		$link.hover(
			function() {
				var pos = $link.position();
				
				clearTimeout(timeout);
				timeout = setTimeout(function() {
					var left = pos.left - Math.round($desc.outerWidth() / 1.2);
					if (left <= 240) {
						left = pos.left + 22;
					}
					$desc.css({
						'top' : pos.top - $desc.outerHeight(),
						'left' : left,
						'visibility' : 'visible'
					})
					.data('hidden', false);
				}, 500);
			},
			function () {
				clearTimeout(timeout);
				if ($desc.data('hidden') == false) {
					timeout = setTimeout(function() {
						$desc.css('visibility', 'hidden').data('hidden', true);
					}, 500);
				}
			}
		);*/
		
		$desc.hover(
			function() {
				clearTimeout(timeout);
			},
			function() {
				$desc.css('visibility', 'hidden').data('hidden', true);
			}
		);
	});
    
    // GA event tracking on book now buttons
    $('.ga_event').click(function() {
        var data = $(this).data(),
            title = $('#page_title').html() || document.title;
        
        _gaq.push(['_trackEvent', data.category, data.action, title]);
    });
});

function autoColumns(obj) {
    // Auto column layout
    var lCol = rCol = '',
        $columns = (typeof obj === 'string') ? $(obj) : obj,
        $layout = null,
        count = $columns.length - 1;

    $columns.each(function(i) {
        var $this = $(this),
            colType = $this.data('col_type');

        if (colType != 'single_row') {
            if ($layout == null) {
                $layout = $('<div />', { 'class' : 'clearfix' }).insertAfter($this);
            }

            if (colType == 'col_left') {
                lCol += '<section class="column one_half auto_col">' + $this.html() + '</section>';
            }
            else {
                rCol += '<section class="column one_half auto_col">' + $this.html() + '</section>';
            }

            $this.remove();
        }
        if ($layout != null && (colType == 'single_row' || i == count)) {
            $layout.html('<div class="align_left two_column_width">' + lCol + '</div>\
                <div class="align_right two_column_width">' + rCol + '</div>');
            $layout = null;
            lCol = rCol = '';
        }
    });
}

// Just simple support for hash change
$(window).bind('hashchange', function() {
    var $tab = $('a[href$="' + location.hash + '"]', '.fluid_tabs').parent();
    if ($tab.length > 0) {
        $tab.addClass('selected').siblings().removeClass('selected');
        $('.fluid_tab_content').hide().eq($tab.index()).show();
    }
});

if (window.location.pathname == '/about/zepp-cam') {
    setTimeout(function() {
        window.location.reload(true);
    }, 120000);
}
