$(function() {
	// References to our various "Most Craved" sections
	most_craved_list = $('body.template_home #listwidget_2, body.template_home #listwidget_3, body.template_home #listwidget_4, body.template_home #listwidget_5')
	trend_classes = 'trend_up trend_down unknown_trend_change no_trend_change'
	
	// Append numbers to our top craved articles
	numbered_list()
	
	// Swap out country specific features
	gn_intl.init()

	// Make the homepage's "Most Craved" section *awesome*
	most_craved()
	most_craved_column()
	
	// onChange handler for Articles and Videos
	channel_clicker()
	
	// Default search term on our 404 page
	errorpage()

	// Swap video tabbedchannelwidget's current channnel
	video_channel_swapper();

	// Staple local widgets onto our right-hand sidebar
	faux_column()

	// Aaah... don't we love this browser?
	ie6.fix_mostcraved()
	ie6.fix_hover()
	ie6.add_bg()
	$(document).bind('refresh', ie6.resize_bg)
	
	// Workaround for small screen widths
	fix_resize()
	$(document).bind('refresh', fix_resize)

	// Fix video tags
	$('span.tag').text($('span.tag').text().split(',').join(', '))

	if (typeof(ad963_enabled) != 'undefined' && ad963_enabled) {
		$('#global-ad_0').css({paddingLeft: '3px'})
	}
})

$(window).load(function() { ie6.fix_cover() })


// Object to manage swapping out various international elements on the site
var gn_intl = {
	country: 'us',

	skin: {
		stub:		'bg_crave',			// Base skin name
		stub_home:	'crave_bg_home',	// Base skin... on the homepage
		path:		'/images/'			// Base skin path
	},

	features: {
		widget_selector: 'body.template_home #listwidget_1, body.test #listwidget_1',	// jQuery object with the features widget
		page_stub: '/features_', // Stub for the features filename
		selector: '#list_0 > div'	// Where can we find the features on the remote page?
	},

	swap_skin: function() {
		// Check to see which stub we should use, and fetch the current skin's URL
		var new_skin = ($('body').hasClass('template_home')) ? this.skin.stub_home : this.skin.stub
		var current_bg = $('body').css('background-image')

		// Short circuit if we're running a reskin
		if (current_bg.indexOf(new_skin) < 0) return false

		// Swap out the background image for a new one
		$('body').css({
			backgroundImage: 'url(' + this.skin.path + new_skin + '_' + this.country + '.jpg)'
		})
	},

	// Swap out the homepage's feature block
	swap_features: function() {
		// Grab our widget
		var $widget = $(this.features.widget_selector)

		// Short circuit if we have no widgets
		if ($widget.length < 1) return false;

		// Identity crisis.
		$widget.find('div').remove()
		$widget.load(this.features.page_stub + this.country + '.php ' + this.features.selector)
	},

	init: function() {
		// Set the locale
		this.country = getCookie('gn_country')
		
		// No country code? BAIL!
		if (this.country === false) return 

		// Lower case country
		this.country = this.country.toLowerCase()

		// GB == UK
		if (this.country == 'gb') this.country = 'uk'
		
		// If we're not in the US swap the skin and homepage features
		if (this.country != 'us') {
			this.swap_skin()
			this.swap_features()
			$('body').addClass('country_' + this.country);
		}
	}
}


function getCookie(cookie_name) {
	var cookies = document.cookie.split('; ')

	if (cookies.length > 0) {
		for (var i=0; i < cookies.length; i++) {
			var current_cookie = cookies[i].split('=')
			if (current_cookie[0] == cookie_name) return current_cookie[1]
		}
	}

	return false
}


function numbered_list() {
	$('div.list').each(function() {
		var header = $.trim($(this).find('div.header_text').text().toLowerCase())

		if (header.indexOf('top') > -1 || header == "what you crave" || header == 'most craved videos') {
			$(this).find('div.article').each(function(i) {
				$(this).find('div.title').prepend((i + 1) + '. ')
			})
		}
	})
}

function faux_column() {
	var sidebar = $('#global-wrapper_0')
	var max = parseInt(sidebar.offset()['top']) + sidebar.outerHeight()

	// If our ad here is turned off, subtract the height of the ad and its padding from max
	if ($('#global-ad_3').outerHeight() < 100) max = max - $('#global-ad_3').outerHeight() - 12
	
	$('#network_0').css({ top: max + 'px' })
	$(document).trigger('refresh')
}


function most_craved_column() {
	var max = 0
	var min = 310

	$(most_craved_list).each(function() {
		$(this).css({height: 'auto'})
		var content = $(this).find('div.content')
		content.css({height:'auto', overflowX: 'hidden'})

		var current = content.outerHeight()
		if (current > max) max = current
	})

	if (min < max) {
		max = max +10
		$(most_craved_list).find('div.content').height(max)
		$('body.template_home #imgs_1, body.template_home #imgs_1 img').height(max + 90)
	}
}


function video_channel_swapper() {
	// Our channels
	var channels = {
		entertainment: 0,
		lifestyle: 1,
		gaming: 2,
		sports: 3
	}

	// An array of clasess on the body
	var classes = $('body').attr('className').split(' ')
	
	// For each class on the body
	for (var i = 0; i < classes.length; i++) {
		// Check to see if it's the template class
		if (classes[i].indexOf('channel_') > -1) {
			// Grab the current channel
			var current_channel = classes[i].split('_').pop()
			
			// If we have an id for the current channel, trigger out tab switcher
			if (channels[current_channel] != undefined) {	
				sb_tabclick_global_tabbedchannel_0('global-tabbedchannel_0', channels[current_channel], true)
			}
		}
	}
}
 

function errorpage() {
	var default_text = 'Try searching for your article'

	$('#search_0 input.text')
	.val(default_text)
	.css({ color: '#666', fontWeight: 'normal' })
	.focus(function() {
		if ($(this).val() == default_text) {
			$(this)
			.val('')
			.css({ color: '', fontWeight: '' })
		}
	})
	.blur(function() {
		if ($(this).val() === '') {
			$(this).val(default_text)
		}
	})
	
	$('#search_0 input.button')
	.click(function() {
		if ($('#search_0 input.text').val() === '' || $('#search_0 input.text').val() == default_text) {
			$('#search_0 input.text').val(default_text)
			return false
		}
	})
}


function channel_clicker() {
	$('#channel_selector .channels').change(function() {
		var new_channel = $(this).val()

		// Entertainment doesn't exist, so we default to Entertainment/Film
		if ($(this).val() == 'Entertainment') new_channel = 'Entertainment/Film'

		window.location.search = 'channel=' + new_channel
	})
}


function find_trend_class(element) {
	// Grab the class, and default to className for Safari
	try {
		var classname = element.attr('class').split(' ')	
	} catch(e) {
		var classname = element.attr('className').split(' ')
	}

	// Iterate through each class and chec to see if it's a trend class
	for (var i=0; i < classname.length; i++) {
		if (classname[i].indexOf('trend') >= 0) return classname[i]
	}
	
	// Default to unknown
	return 'no_trend_change'
}

function most_craved() {
	// Do this to every list
	most_craved_list.each(function() {
		// Grab a reference to the image cell
		var header_image = $(this).find('div.article:first div.article_image')

		// Capture the current header image's pertinent values
		var first = {
			image:	header_image.find('img').attr('src'),
			alt:	header_image.find('img').attr('alt'),
			link:	header_image.find('a').attr('href'),
			trend:	find_trend_class(header_image.parent())
		}

		// Add our trend display markup
		header_image.append('<div class="trend_bg"></div><a class="trend_data"><span class="number">#1</span> Most Craved</a>')
		header_image.find('div.trend_bg').css({ opacity: '.77' })
		header_image.parent().addClass(first.trend)

		$(this).find('div.article').each(function(i) {
			$(this).find('div.title').mouseenter(function() {
				// Store a reference to the article_image
				var article_image = $(this).parent().parent().find('div.article_image')

				// Grab the new values from the article you just hovered over
				var updated = {
					image:	article_image.find('img').attr('src'),
					alt:	article_image.find('img').attr('alt'),
					link:	article_image.find('a').attr('href'),
					trend:	find_trend_class(article_image.parent())
				}

				// If we're looking at the first element, it's source will be of the last item hovered over (we're using its image cell), so grab the stored reference to our original image instead
				if (article_image.parent().hasClass('first')) {
					updated.trend	= first.trend
					updated.image	= first.image
					updated.alt		= first.alt
					updated.link	= first.link
				}

				// Swap in our new values
				header_image.parent().removeClass(trend_classes).addClass(updated.trend)
				header_image.find('img').attr({ src: updated.image, alt: updated.alt })
				header_image.find('a').attr({ href: updated.link })
				header_image.find('.number').text("#" + (i + 1))
			})
		})
	})
}


function fix_resize() {
	var inner_page_width = 1012
	var document_width = $(window).width()
	var new_margin = ''; // Default to unset

	// If we have more content than window, trim the left edge
	if (document_width < inner_page_width) new_margin = '0 -9px'

	// Set our margin, if no changes were needed, we default to an empty string
	$('#wrapper').css({ margin: new_margin })
}


var ie6 = {
	add_bg: function() {
		if ($.browser != 'msie' && parseInt($.browser.version) != 6) return false
        $('#wrapper').append('<div class="placeFooter_ignore ie6_background"></div>')
        $('#wrapper').append('<div class="placeFooter_ignore ie6_background_left"></div>')
        $('#wrapper').append('<div class="placeFooter_ignore ie6_background_right"></div>')
        $('#wrapper').append('<div class="placeFooter_ignore ie6_background_wrapper"></div>')
    },

    resize_bg: function() {
		var wrapper_width = $('#wrapper').width()
		var wrapper_height = $('#wrapper').height()
		var footer_height = $('#global-footer_0').height()

        $('div.ie6_background').css({
            width:      wrapper_width + "px",
            height:     parseInt(wrapper_height - (88 + footer_height)) + "px",
            top:        "88px",
            left:       "9px"
        })

        $('div.ie6_background_wrapper').css({
			height:		parseInt(wrapper_height - 234) + "px",
			margin:		"234px 0 0 5px",
			width:		"664px"
		})

        $('div.ie6_background_left, div.ie6_background_right').css({
            height:     parseInt(wrapper_height - 88) + "px",
            top:       "88px"
        })
    },
	
	fix_hover: function() {
		if ($.browser != 'msie' && parseInt($.browser.version) != 6) return false
		$('ul.nav li.top').hover(
			function() {
				$(this).addClass('over')
				if ($(this).hasClass('nav_entertainment')) $(this).addClass('over_nav_entertainment')
			},
			function() { $(this).removeClass('over over_nav_entertainment') }
		)
	},

	fix_cover: function() {
		if ($.browser != 'msie' && parseInt($.browser.version) != 6) return false
		$('div.cover-blurb').after('<div class="pnghack">')
	},

	fix_mostcraved: function() {
		if ($.browser != 'msie' && parseInt($.browser.version) != 6) return false
		$('body.template_home #imgs_1').attr('src', '/images/bg_mostcraved.jpg')
	}
}

function test_clickable() {
	$('#imgs_1').append("<a href='http://google.com' class='clickable_most_craved'>")
}