jQuery(function($) {

	var hero = $('#show-hero'),
		accordion = $('#accordion'),
		media_thumbs = $('ul.media-thumbs'),
		upcoming_eps = $('div.upcoming-episodes'),
		show_menu = $('#content ul.menu'),
		slides = accordion.children('div'),
		accordion_params = ($.browser.msie && $.browser.version < 7) ? { animated : false } : {};

	$('a.rating').clickModals(380);

	function embedBioVideo() {
		// If an argument is passed in, use that, otherwise find the active slide.
		var video_box = (arguments.length > 0) ? $('div.video-col > div.viewer', arguments[0]) : $('div.ui-accordion-content-active div.video-col > div.viewer', accordion);
		if (video_box.length > 0) {
			var id = parseInt(video_box.parent().attr('id').replace('video-col-',''), 10);
			video_box.prepend('<div id="flash-player"><p>It appears you do not have the latest version of the <a href="http://get.adobe.com/flashplayer/">Adobe Flash Player</a> or you may have JavaScript disabled.</p></div>');
			swfobject.embedSWF(
				HISTORY.static_server_path + "/flash/VideoPlayer.swf",
				"flash-player",
				"262",
				"188",
				"10",
				"",
				{ mrss: HISTORY.mrss_feeds[id], acudeoConfig: HISTORY.acudeo_config, backgroundColor: "0xffffff", buttonUpColor: "0x000000", buttonOverColor: "0x30B2E8" },
				{ allowScriptAccess: "always", wmode: "transparent", allowFullScreen: "false" , bgcolor: "#f1f1ea" }
			);
		}
	}

	if (hero.length > 0 && $.browser.msie && $.browser.version < 7) {
		$('.header img',hero).ifixpng();
	}

	if (accordion.length > 0) {

		//HISTORY.log('Accordion - started, slide length = ' + slides.length);

		// Attach previous and next tabs to accordion slides.
		slides.each(function () {
			var obj = $(this),
				prev_rel = obj.prev().prev().prev().attr('rel'),
				next_rel = obj.next().attr('rel');

			//HISTORY.log('Accordion - slide iteration, prev_href = ' + prev_rel + ', next_href = ' + next_rel);

			if (typeof(next_rel) !== 'undefined') {
				obj.children('div.content').after('<a href="#slide-' + next_rel + '" rel="' + next_rel + '" class="tab tab-next">Next</a>');
				//HISTORY.log('Accordion - slide iteration, not last, so add "Next" tab.');
			}

			if (typeof(prev_rel) !== 'undefined') {
				obj.children('div.content').before('<a href="#slide-' + prev_rel + '" rel="' + prev_rel + '" class="tab tab-prev-ud">Previous</a>');
				//HISTORY.log('Accordion - slide iteration, not first, so add "Previous" tab.');
			}
		});

		// Bind click events to prev/next tabs.
		$('a.tab', accordion).live('click', function (e) {
			if (e.button === 0) {

				e.preventDefault();

				var rel = $(this).attr('rel'),
					index = $('a.header', accordion).index($('a.header[rel=' + rel + ']'));

				//HISTORY.log('Accordion - tab click identified. rel = ' + rel + ', index = ' + index);

				if (index !== -1) {
					accordion.accordion('activate', index);
				}
			}
		});

		$('a.temp-hide, div.temp-hide', accordion).removeClass('temp-hide');
		//HISTORY.log('Accordion - removed "temp-hide" class.');

		$.extend(accordion_params, {
			autoHeight	: false,
			change		: function(e, u) {
				//HISTORY.log('Accordion - change callback.');
				$.scrollTo(u.newContent.parent(), 400);
				embedBioVideo(u.newContent);
			},
			changestart : function(e, u) {
				//HISTORY.log('Accordion - changestart callback.');
				window.location.hash = u.newHeader.attr('href');
				$('#flash-player').remove();
			},
			header		: 'a.header',
			navigation  : true
		});

		accordion.accordion(accordion_params);

		// If we're being deep-linked to a specific slide, we'll need to scroll to it.
		if (location.href.match('#')) {
			setTimeout(function() {
				$.scrollTo($('div.ui-accordion-content-active', accordion), 400);
			}, 1000);
		}

		embedBioVideo();

	} else { // if (accordion.length > 0)
		embedBioVideo($('#content div.accordion-slide'));
	}

	if (upcoming_eps.length > 0) {
		$('a.modal', upcoming_eps).clickModals(300);
	}

	if (media_thumbs.length > 0) {
	    try {
		    $('ul.media-thumbs a.thumb').hoverModals(290);
        } catch (e) {}
	}

	// Add selected states to show menu.
	if (show_menu.length > 0) {

		var show_asset_types = ['articles', 'interactives', 'videos', 'photos', 'bios', 'episodes'],
			nestable_types = ['articles', 'interactives', 'videos', 'bios'],
            deep_nestable_types = ['articles', 'bios'],
			url = window.location.toString(),
			current_section = false,
			i, parent;

        var url_splits = url.split('/');
        var rel_value = url_splits[url_splits.length - 1];

		for (i = 0; i < show_asset_types.length; i++) {
			// Determine that we are in a asset type section.
			if (url.indexOf('/' + show_asset_types[i]) != -1) {

				current_section = show_asset_types[i];
				//HISTORY.log('Show Menu - Current section: ' + current_section);

                if ($.inArray(current_section, nestable_types) != -1) {

					//HISTORY.log('Show Menu - Nestable type.');
					parent = show_menu.find('li.parent.' + current_section);

					// If a parent exists, set it selected and show any child ULs.
					if (parent.length > 0) {
                        var category;
                        var deep_nestable = false;
                        //deal with deep nestable
                        if ($.inArray(current_section, deep_nestable_types) != -1) {
                            category = parent.find('li.category');
                            if (category.length > 0){
                                deep_nestable = true;
                                parent.addClass('selected').find('ul.heading').show();
                                category.find('ul').find('a').each(function(){
                                    if ($(this).attr('rel') == rel_value){
                                        $(this).parent().addClass('selected');
                                        $(this).parent().parent().show().parent().addClass('selected');
                                    }
                                });          

                            }
                        }
                        //if there is no deep nest, deal with one level nest
                        if (!deep_nestable) {
                            parent.addClass('selected').find('ul').show().find('a').each(function(){
                                if ($(this).attr('rel') == rel_value){
                                    //HISTORY.log('Show Menu - Link to asset found.');
                                    $(this).parent().addClass('selected');
                                }
                            });
                        }

					// No parent exists, so we have to find which link it is.
					} else {
						show_menu.find('li.' + current_section + ' a').each(function(){

							if (url.indexOf($(this).attr('rel')) != -1) {
								//HISTORY.log('Show Menu - Link to asset found.');
								$(this).parent().addClass('selected');
							}
						});
					}


				// This is not a nestable type.
				} else {
					//HISTORY.log('Show Menu - Not a nestable type.');
					show_menu.find('li.single > a[href*=' + current_section + ']').parent().addClass('selected');
				}
			}
		}

		// No section found, then we're on the homepage.
		if (current_section === false) {
			show_menu.find('li.home').addClass('selected');
		}

		show_menu.find('li.parent > a').click(function(e) {
		    if (!$(this).parent().hasClass('bios')){
			    e.preventDefault();
                if (!$(this).parent().hasClass('selected')) {
                    var list = $(this).next();
                    if (list.is(':visible')) {
                        list.slideUp(500);
                    } else {
                        list.slideDown(500);
                    }
                }
            } else {
                $(this).parent().css('cursor', 'pointer');
            }
		});

        show_menu.find('li.category > a').click(function(e) {
			e.preventDefault();
			if (!$(this).parent().hasClass('selected')) {
				var list = $(this).next();
				if (list.is(':visible')) {
					list.slideUp(500);
				} else {
					list.slideDown(500);
				}
			}
		});
	} // if (show_menu.length > 0)

    //update addthis url to full url for episode guide
   /* if (fullUrl !== undefined){
        $('ul.content-controls a.addthis_button')
				        .attr('addthis:url', 'http://www.history.com' + fullUrl);
				    window.addthis.ost = 0;
                    window.addthis.ready();
    }*/
}); // ready
