// private functions
function debug(o) {
	if(window.console && window.console.log) {
		window.console.log(o);
	}
}

if(typeof jQuery != 'undefined') {
	jQuery.noConflict();
	(function($) {

		jQuery(document).ready(function($) {
		$('body').addClass('has-jquery').addClass('js');

		   /* reworked news page stuff*/
		   $(".newsArchive ul, .newsArchive ul ul").hide();
		   if(!$(".newsArchive .active").length){
			   //no active member so set the first active
			   $(".newsArchive li:first a:first").addClass("down");
			   $(".newsArchive li:first ul:first").addClass("display");
		   }else{
			   $(".newsArchive .active").parent().parent().addClass("display");
			   $(".newsArchive .active").parent().parent().parent().parent().addClass("display");
			   $(".newsArchive .active").parent().parent().parent().children("a").addClass("down");
			   $(".newsArchive .active").parent().parent().parent().parent().parent().children("a").attr("class","down");
			}	
		   $(".newsArchive a").click(function(e){
				if($(this).attr("href").substring(0,1) !="/"){
					e.preventDefault();	
					/*add the active/down class on the actual hyperlinks*/
					//$(this).parent().parent().children().children().removeClass("down");
					if($(this).attr("class") =="down"){
						$(this).parent().children("ul").removeClass("display");
						$(this).removeClass("down");
						$(this).parent().children("ul").slideUp();
					}else{
						//$(this).parent().parent().addClass("display");
						$(this).addClass("down");
						$(this).parent().children("ul").slideDown();
					}
				}           
		   });


			/*
			 * SEP Catalyst
			 */
			//Show Banner
			$(".main_image .desc").show(); //Show Banner
			$(".main_image .block").animate({ opacity: 0.85 }, 1 ); //Set Opacity

			//Click and Hover events for thumbnail list
			$(".image_thumb ul li:first").addClass('active');
			$(".image_thumb ul li").hover(function(){
				//Set Variables
				var imgAlt = $(this).find('img').attr("alt"); //Get Alt Tag of Image
				var imgTitle = $(this).find('a').attr("href"); //Get Main Image URL
				var imgDesc = $(this).find('.block').html(); 	//Get HTML of block
				var imgDescHeight = $(".main_image").find('.block').height();	//Calculate height of block

				if ($(this).is(".active")) {  //If it's already active, then...
					return false; // Don't click through
				} else {
					//Animate the Teaser
					$(".main_image .block").animate({ opacity: 0, marginBottom: -imgDescHeight }, 250 , function() {
						$(".main_image .block").html(imgDesc).animate({ opacity: 0.85,	marginBottom: "0" }, 250 );
						$(".main_image img").attr({ src: imgTitle , alt: imgAlt});
					});
				}

				$(".image_thumb ul li").removeClass('active'); //Remove class of 'active' on all lists
				$(this).addClass('active');  //add class of 'active' on this list only
				return false;

			}) .hover(function(){
				$(this).addClass('hover');
				}, function() {
				$(this).removeClass('hover');
			});

			//Toggle Teaser
			$("a.collapse").hover(function(){
				$(".main_image .block").slideToggle();
				$("a.collapse").toggleClass("show");
			});
			
		});

		$.fn.countStories = function() {
			return this.each(function(){
				var h = 0,
					$active, $$ = $(this);

				$$.each(function(){
					if($(this).hasClass(App.options.hover)){
						h++;
					}
				});

				$active = (h === 0) ? $$.filter('.first') : $$.filter('.' + App.options.active);
				$active.addClass(App.options.active);
			});
		};


		// Flash External Interface
		$.fn.callFlash = function(callback, variables, prefix) {
			var $$, dom, data = false;
			$$ = $(this);
			if($$.length === 1) {
				dom = $$.get(0);
				if($$.attr('id').length > 0) {
					dom = document.getElementById($$.attr('id')); // safer
				}
				if(typeof prefix === 'string') {
					callback = prefix + callback.charAt(0).toUpperCase() + callback.substr(1);
				}
				if(typeof dom !== 'undefined' && typeof dom[callback] === 'function') {
					data = dom[callback](variables);
				}
			}
			return data;
		};

	// end of jQuery closure
	})(jQuery);

    jQuery(document).ready(function($) {
       
        $("#faq").find("dt:gt(0),dd:gt(0)").removeClass('active');
        $("#faq dt a").click(function(){
            $("#faq .active").removeClass("active");
            $(this).parent().add($(this).parent().next("dd")).addClass("active");
            return false;
        });
        $('#faqQuestionList li a').click(function() {
            var href = $(this).attr('href');
            var id = href.substring(1,href.length);
            $("#faq .active").removeClass("active");
            $('#'+id).addClass('active').next('dd').addClass('active');
        });
        
        /**
         * Captcha Reload
         */
        $('.verify span').append(
            $('<a></a>')
                .attr('href','javascript:;')
                .html('Try another')
                .click(function(){
                    var $img = $('<img src="/captcha/verify.jpg?s=' + Math.random()  + '" alt="" />');
                    var $closest = $(this).closest('.verify');
                    if($.browser.msie && $.browser.version == 6) {
                        // IE6 fix
                        if(confirm('Are you sure that you wish to generate a new verification image?')) {
                            $('img',$closest).remove();
                            $(this).parent('img','.verify').remove();
                            $closest.append($img);
                        }
                    } else {
                        $('img',$closest).remove();
                        $(this).parent('img','.verify').remove();
                        $closest.append($img);
                    }
                })
        );

        /***
         * News / Event Accordion
         */
		$('.springy').each(function(){
			root=this;
			keepopen=':first';														//what should be open by default
			if($('div.active',root).length==1){										//if a sidebar item is active
				keepopen=$('div.active',root).parent().parent().parent();			//make its great-grantparent stay open
			}
			$('ul',root).parent().not(keepopen).hide();								//hide (not first) submenus
			$(this).find('span').filter(keepopen).addClass('down');					//give first sub active state
			$(".down").parent().parent().parent().next('li').children('div').slideDown();
                       
                       $('li div a',this).click(function(e){	//hook top level clicks
				if($(this).attr("href").substring(0,1) !="/"){
                                    e.preventDefault();	
                                   // if($(this).find('span').first().hasClass('down')==false){			//only if not already active
                                            activespan=$(this).find('span').first();						//grab the icon
                                            $(activespan).addClass('down');									//make it point down
                                            $(root).children('li').each(function(){								//now loop thru all other icons
                                                    $(root).find('span').not(activespan).removeClass('down');		//make them not point down
                                            });
                                            $('ul',root).parent().slideUp();													//hide all other subs
                                            $(activespan).parent().parent().parent().next('li').children('div').slideDown();	//show this sub
                                 //   }
                                    return false;
                                }
			});
		});
		
		//show/hide theme panes
		$('.pane-toggle').click(function(){
			$(this).parent().siblings('div.content').slideToggle();
			if($(this).parent().parent().is('.hidden')){
				$(this).parent().parent().removeClass('hidden');
			}else{
				$(this).parent().parent().addClass('hidden');
			}
		});
		$('.pane').not($('.pane').eq(1)).addClass('hidden');
        if($('.pagestats').length>0) { $('.pagestats').dblclick(function() { $(this).remove(); }); }

		//truncate homepage stories
		$('.topnews a.story span').each(function() {
			if($(this).text().length>120){
				$(this).html($(this).text().substr(0,120) + '&hellip;');
			}
		});

        // Flash map
        if($('#flashMap').length>0) {
            var vars = {sXMLFile: '/stem-programme/stem-in-your-region/default.xml'};
            var params = {};
            params.wmode = "transparent";
            swfobject.embedSWF("/flash/map.swf", "flashMap", "683", "787", "9", false, vars, params);
        }
        
	});
	
}

(function ($) {
    VISIBLE_STORY_COUNT = 3;
    PAUSE_BEFORE_STORIES_PANEL = 1000;
    STORIES_FADE_IN_STAGGER_DELAY = 200;
    STORIES_SCROLL_TIME = 600;
    STORY_HEIGHT = 84;
    BACKGROUND_FADE_TIME = 1000;
    HEADLINE_SLIDE_TIME = 300;
    AUTOSCROLL_DELAY = 4000;
    CLICK_THROUGH_TO_STORY_DELAY = 1000;
    var headlineAnimationOff = {
        'left': '150px',
        'opacity': 0
    };
    var headlineAnimationOn = {
        'left': '0px',
        'opacity': 1
    };
    function Feature(mainstage, initialStoryData) {
        var storyHtml = $('<a class="main_story"><div class="transition_layer"></div><p class="alt"></p><div class="headline"><div class="headline_inner"><h1></h1><h2><span></span></h2></div></div><div id="mainstage_video"></div></a>');
        $(mainstage).html(storyHtml);
        var currentStoryData;
        var transitionLayer = $('.transition_layer', storyHtml);
        transitionLayer.fadeTo(1, 0);
        var headline = $('.headline', storyHtml);

        function showStory(storyData) {
            currentStoryData = storyData;
            if (storyData.href) {
                $(storyHtml).attr({
                    'href': storyData.href
                });
            } else {
                $(storyHtml).removeAttr('href');
            }
            if (storyData.credit) {
                $(storyHtml).attr({
                    'title': storyData.credit
                });
            }
            $(storyHtml).css({
                'background-image': 'url(' + storyData.backgroundImage + ')'
            });
            $('.alt', storyHtml).text(storyData.alt);
            $('h1', headline).text(storyData.headline);
            $('h2 span', headline).text(storyData.headline2);
            if (!storyData.headline) {
                headline.css(headlineAnimationOff);
            }
        }
        var switchHeadline = function (storyData) {
            if (storyData.href) {
                $('a.main_story', mainstage).attr('href', storyData.href);
            } else {
                $('a.main_story', mainstage).removeAttr('href');
            }
            if (storyData.credit) {
                $('a.main_story', mainstage).attr({
                    'title': storyData.credit
                });
            }
            if (storyData.headline) {
                $('h1', headline).text(storyData.headline);
                $('h2 span', headline).text(storyData.headline2);
                headline.animate(headlineAnimationOn, HEADLINE_SLIDE_TIME);
            }
        }

        function transitionToStory(storyData) {
            $('a.main_story', mainstage).css({
                'background-image': 'url(' + currentStoryData.backgroundImage + ')'
            });
            $('a.main_story .alt').text(currentStoryData.alt);
            if (storyData.credit) {
                $('a.main_story', mainstage).attr({
                    'title': storyData.credit
                });
            }
            transitionLayer.stop().css({
                'opacity': 0
            });
            transitionLayer.css({
                'background-image': 'url(' + storyData.backgroundImage + ')'
            });
            transitionLayer.fadeTo(BACKGROUND_FADE_TIME, 1, function () {
                $('a.main_story', mainstage).css({
                    'background-image': 'url(' + storyData.backgroundImage + ')'
                });
                $('a.main_story .alt').text(storyData.alt);
            });
            if (currentStoryData.headline) {
                headline.stop().animate(headlineAnimationOff, HEADLINE_SLIDE_TIME, function () {
                    switchHeadline(storyData);
                })
            } else {
                switchHeadline(storyData);
            }
            currentStoryData = storyData;
        }
		showStory(initialStoryData);
        return {
            showStory: showStory,
            transitionToStory: transitionToStory

        }
    }
	function StoriesPanel(mainstage, data, feature) {
        var currentStoryNumber = 0;
        var topVisibleTrayIndex = 0;
        var topPopulatedTrayIndex = 0;
        var bottomPopulatedTrayIndex = -1;
        var storiesPanel = $('<div class="stories_panel"><div class="stories_nav stories_nav_up"><a href="javascript:void(0)">Up</a></div><div class="stories_viewport"><div class="stories_tray"><ul class="stories"></ul></div></div><div class="stories_nav stories_nav_down"><a href="javascript:void(0)">Down</a></div></div>');
        var storiesUl = $('ul.stories', storiesPanel);
        var headline = $('.headline', mainstage);
        var lastNavigationClickTime;

        function storyNumberAtTrayIndex(i) {
            var storyNumber = ((VISIBLE_STORY_COUNT - 1) - i) % data.length;
            if (storyNumber < 0) storyNumber += data.length;
            return storyNumber;
        }

        function scrollTrayIntoPosition() {
            while (topVisibleTrayIndex < topPopulatedTrayIndex) prependStory();
            var bottomVisibleTrayIndex = topVisibleTrayIndex + VISIBLE_STORY_COUNT - 1;
            while (bottomVisibleTrayIndex > bottomPopulatedTrayIndex) appendStory();
            $('.stories_tray', storiesPanel).stop().animate({
                'top': (-topVisibleTrayIndex * STORY_HEIGHT) + 'px'
            }, STORIES_SCROLL_TIME);
        }

        function selectStory(trayIndex) {
            topVisibleTrayIndex = trayIndex - VISIBLE_STORY_COUNT + 1;
            scrollTrayIntoPosition();
            var storyNumber = storyNumberAtTrayIndex(trayIndex);
            $('li.current_story', storiesUl).removeClass('current_story');
            $('li.story_number_' + storyNumber, storiesUl).addClass('current_story');
            if (storyNumber != currentStoryNumber) {
                currentStoryNumber = storyNumber;
                feature.transitionToStory(data[storyNumber]);
                return true;
            } else {
                return false;
            }
        }

        function createStoryLi(trayIndex) {
            var storyNumber = storyNumberAtTrayIndex(trayIndex);
            var storyData = data[storyNumber];
            var story = $('<li class="story"><div class="thumbnail"><img src="" width="84" height="62" alt="" /></div><div class="title"><a></a></div></li>');
            story.addClass('story_number_' + storyNumber);
            if (storyNumber == currentStoryNumber) story.addClass('current_story');
            $('.thumbnail img', story).attr('src', storyData.thumbnail);
            $('.title a', story).attr('href', storyData.href);
            $('.title a', story).text(storyData.storyTitle);
            story.hover(function () {
                story.addClass('story_hover');
            }, function () {
                story.removeClass('story_hover');
            }).click(function () {
                disableAutoscroll();
                var storyHasChanged = selectStory(trayIndex);
                var currentTime = (new Date).getTime();
                if (storyHasChanged || lastNavigationClickTime > (currentTime - CLICK_THROUGH_TO_STORY_DELAY)) {
                    lastNavigationClickTime = currentTime;
                } else {
                    var href = $('.title a', this).attr('href');
                    if (href != null) {
                        document.location.href = href;
                    }
                }
                return false;
            })
            return story;
        }

        function prependStory() {
            topPopulatedTrayIndex -= 1;
            var story = createStoryLi(topPopulatedTrayIndex);
            storiesUl.prepend(story);
            centreStoryText(story);
            storiesUl.css({
                'top': topPopulatedTrayIndex * STORY_HEIGHT
            });
        }

        function appendStory(opts) {
            opts = opts || [];
            bottomPopulatedTrayIndex += 1;
            var story = createStoryLi(bottomPopulatedTrayIndex);
            storiesUl.append(story);
            centreStoryText(story);
            if (opts.fade) {
                story.hide();
                setTimeout(function () {
                    story.fadeIn()
                }, (bottomPopulatedTrayIndex + 1) * STORIES_FADE_IN_STAGGER_DELAY);
            }
        }

        function centreStoryText(story) {
            var title = $('.title', story);
            title.css({
                'padding-top': (STORY_HEIGHT - title.get(0).offsetHeight) / 3 + 'px'
            });
        }

        function selectNextStory() {
            selectStory(topVisibleTrayIndex + VISIBLE_STORY_COUNT);
        }

        function selectPreviousStory() {
            selectStory(topVisibleTrayIndex + VISIBLE_STORY_COUNT - 2);
        }
        var autoscrollTimer;
        var isAutoscrolling = false;
        var autoscrollIsDisabled = false;

        function startAutoscroll() {
            if (!isAutoscrolling && !autoscrollIsDisabled) {
                autoscrollTimer = setInterval(selectPreviousStory, AUTOSCROLL_DELAY);
                isAutoscrolling = true;
            }
        }

        function stopAutoscroll() {
            clearInterval(autoscrollTimer);
            isAutoscrolling = false;
        }

        function disableAutoscroll() {
            autoscrollIsDisabled = true;
            stopAutoscroll();
        }
        mainstage.append(storiesPanel);
        $('.stories_nav_up', storiesPanel).hide();
        $('.stories_nav_down', storiesPanel).hide();
        $('.stories_nav_up', storiesPanel).fadeIn();
        for (i = 0; i < VISIBLE_STORY_COUNT; i++) {
            appendStory({
                fade: true
            });
        }
        setTimeout(function () {
            $('.stories_nav_down', storiesPanel).fadeIn(function () {
                headline.wrap('<div class="headline_viewport"></div>');
            });
        }, (VISIBLE_STORY_COUNT + 1) * STORIES_FADE_IN_STAGGER_DELAY);
        $('.stories_nav_up', storiesPanel).click(function () {
            disableAutoscroll();
            selectPreviousStory();
        })
        $('.stories_nav_down', storiesPanel).click(function () {
            disableAutoscroll();
            selectNextStory();
        })
        return {
            startAutoscroll: startAutoscroll,
            stopAutoscroll: stopAutoscroll,
            disableAutoscroll: disableAutoscroll
        };
    }
    $.fn.stemFeatures = function (data) {
        var mainstage = this;
        var feature = Feature(mainstage, data[0]);
        if (data.length > 1) {
            $(function () {
                setTimeout(function () {
                    storiesPanel = StoriesPanel(mainstage, data, feature);
                    $(mainstage).hover(function () {
                        storiesPanel.stopAutoscroll();
                    }, function () {
                        storiesPanel.startAutoscroll();
                    })
                    storiesPanel.startAutoscroll();
                }, PAUSE_BEFORE_STORIES_PANEL);
            })
        }
        $(window).load(function () {
            var backgroundImages = [];
            for (var i = 0; i < data.length; i++) {
                backgroundImages[i] = new Image();
                backgroundImages[i].src = data[i].backgroundImage;
            }
        })
    var trim;
	trim = "<div id='trimTop'></div><div id='trimBottom'></div><div id='trimLeft'></div><div id='trimRight'></div>";
	$(trim).prependTo('#content');
	}
})(jQuery);

