$(document).ready(function () {

    //Root
    //var siteRoot = "http://tescoplc.webdev.merchant.co.uk";

    //var siteRoot = "http://www.tescoplc.com";
    $('.japan h1, .japan h2, .korea h1, .korea h2').addClass('noCufon');

    Cufon.replace('#sharePrice h3, #price, #country h3, #map h3, #factoid p, #breadcrumb li.first a, .pressOffice h3, .reportTeaser h3, .teaser h3, .scroll-content-item li h3, .scroll-bar-wrap ul li, #error p.error ,#mapDetails h3, #cvi_tooltip h3, #cvi_tooltip h4, #finHighlights h3, .career-contents h3, .career-contents p.title, .career-contents p.name, .featured-story p.name');

    Cufon.replace('h1:not(.noCufon), h2:not(.noCufon)');

    tabs();

    // Mega menu
    megaMenu();

    // Tidy up the Main Nav active state
    mainNavActive();

    // Top Nav Scroller
    topNavScroll();

    akkordion();

    backToTops();

    // Homepage tooltip
    //$('li.transcript a').tooltip({ offset: [-420, -335] });

    // Video lightbox
    videoBox();

    startCarousel();

    // Main search field focus effect
    searchActive();

    // Tab search field focus effect
    tabSearch();

    // Sub Nav drop down effect
    subNavDropDown();

    // Management
    management();

    historyTimeline();

    datesToolTip();

    calToolTip();

    homePdfToolTip()

    $("#yourDetails").validate();

    // Side widgets styles
    styleFirstWidgets();

    // Ajax Rns feeds
    rnsFeeds();

    $("#sharePrice img").remove();

    //alert($.os.name);

    $('#mainNav ul li').css("cursor", "pointer");
    $('#mainNav ul li').click(function () {
        window.location = $("a", this).attr("href");
    });


    $('div.sharePrice p:nth-child(3)').css('display', 'none');
    $('div.sharePrice p:nth-child(2)').replaceWith('<h2 class="promo_header">' + $('div.sharePrice p:nth-child(2)').text() + '</h2>');

    RemoveHero();

    liScroller('#strategyList')
    liScroller('.scrollList')

    //moves CR mod to side on CR landing page
    crPageModule()

    RNSdatepicker();

    //careers > our-stories
    initCareerStories();

});

function crPageModule() {
    $('.quicklinks').append($('.crPage .moduleHolder .reportTeaser'))
};

function liScroller($select) {
    // acnhor menu scroller
    $($select+' li a').click(function () {
        var hash = this.href.split('#')[1];
        var obj = $('#' + hash).offset();
        var pos = obj.top - 60
        $('html, body').animate({ scrollTop: pos }, 'slow');
        return false;
    });
}


function akkordion(){
    //  SIMPLE ACCORDION
    //$('.akkordion div:not(:first)').hide();
    $('.akkordion div').hide();
    $('.akkordion h2').css('cursor', 'pointer').append('<span></span>')
    $('.akkordion h2').hover(
		function(){$(this).addClass('blue')},
		function(){$(this).removeClass('blue')}
		);
    $('.akkordion h2').click(function () {
        $(this).toggleClass('OpenOrdion');
        $(this).next('div').slideToggle();
    });
    //}).first().addClass('OpenOrdion');
    $('.akkordion div:last').addClass('last');
};



function RemoveHero() { //if no image on a generic page with hero
    var $heroImage = $('#aHero img').size();
	var $aHero = $('#aHero').size();
    if ($heroImage == 0  && $aHero == 1) {
        $('#aHero').remove();
        $('#main').attr('id', 'mainInner')
        var $inner = $('#introInner').html()
        $('#introInner').remove();
        $('#intro').append($inner);
    };
};

function styleFirstWidgets() {
    $('#subContent div.quicklinks').addClass('feeds')
    $('#subContent div.feeds:first').addClass('firstfeed')
    //$('.moduleHolder .w300:lt(2)').css({ 'border-top-color': 'transparent' })
};

$(function(){
	$('#videoSlider').slides({
        generateNextPrev: true,
		generatePagination: false
	});
	$('#hero').slides({
        generateNextPrev: false,
		generatePagination: true,
		play: 8000,
		pause: 2500,
		hoverPause: true
	});
});

function tabs() {
	// setup ul.tabs to work as tabs for each div directly under div.panes
	$('ul.tabs').tabs('div.panes > div', {
		tabs: 'li'
	});
}

function backToTops() {
	$('a.backToTop').click(function() {
		$('html, body').animate({ scrollTop: 0 }, 'slow');
		return false;
	});

	$('.backToMap a').click(function() {
        var offset = $('#mainContent').offset();
	    $('html, body').animate({ scrollTop: offset.top }, 'slow');
		return false;
	});

    $('a.backtomap').click(function () {
        var offset = $('#mainContent').offset()
        $('html, body').animate({ scrollTop: offset.top }, 'slow');
        return false;
    });
}

function videoBox() {
    $('.vidThumb a, a.openVid, .content a.cbox').live('click', function () {

        var $closeBox = $('#cboxClose').detach();
        //alert($(this).attr("href"));
        $.colorbox({
            opacity: 0.53,
            height: '680px',
            width: '995px',
            scrolling: false,
            iframe: true,
            href: $(this).attr("href"),
            onComplete: function () {

                //#cboxClose move
                $('#cboxContent').append($closeBox);
                // slide up to logo
                // var $ypos = $('html').scrollTop();
                // if ($ypos < 80) { $('#colorbox').animate({ top: 98 }, 'fast') };
                Cufon.replace('#videos h2');
                startCarousel();
                homePdfToolTip();
                $('ul#videos > li').hide();
                $('ul#videos li:first').show();
                $('.vidLink').live('click', function () {
                    var vid = $(this).attr('href');
                    $('ul#videos > li').fadeOut('fast');
                    $('ul#videos li' + vid).fadeIn('fast');
                    return false;
                });
                
                $('#cboxClose').live('click', function () {
                    //stopJWPlayer();
                });
                $('.vidThumb2').hover(
					function () {
					    $(this).find('img').fadeTo('fast', '0.2');
					    var vidTitleHolder = '<div class="vidTitle"><strong>Watch video</strong><br /></div>';
					    var vidTitle = $(this).find('img').attr('alt');
					    var vidHref = $(this).find('a').attr('href');
					    $(this).append(vidTitleHolder);
					    $('.vidTitle a').attr('href', vidHref).append(vidTitle);
					    $(this).css('cursor', 'pointer');
					},
					function () {
					    $(this).find('img').fadeTo('fast', '1.0');
					    $('.vidTitle').hide().remove();
					}
				);
            }
        });
        return false;
    });
	
	$('.vidThumb').hover(
		function () {
			$(this).find('img').fadeTo('fast', '0.2');
			var vidTitleHolder = '<div class="vidTitle"><a href=""><strong>Watch video</strong><br /></a></div>';
			var vidTitle = $(this).find('img').attr('alt');
			$(this).append(vidTitleHolder);
			$('.vidTitle a').append(vidTitle);
			$(this).css('cursor', 'pointer');
		}, 
		function () {
			$(this).find('img').fadeTo('fast', '1.0');
			$('.vidTitle').hide().remove();
		}
	);

}



function rnsFeeds() {
    $('.rnsreleases .pressList p.event a').live('click', function () {
        var $linkText = $(this).text();
        var $clickUrl = $(this).attr('href');
        var $pageUrl = '/tertiary-content/rns-feed/ #mainContent'
        var $closeBox = $('#cboxClose').detach();
        $.colorbox({
            opacity: 0.53,
            height: '680px',
            width: '995px',
            scrolling: false,
            href: $pageUrl,
            onComplete: function () {
                //#cboxClose move
                $('#cboxContent').append($closeBox);
                //slide up to logo
                var $ypos = $('html').scrollTop();
                if ($ypos < 80) { $('#colorbox').animate({ top: 98 }, 'fast') };
                $('#rnsFrame').attr('src', $clickUrl);
                $('#newWindow').attr('href', $clickUrl);
                $('#rnsHead').text($linkText);
                Cufon.replace('#rnsFeeds h2');
            }
        });
        return false;
    });
}



function insertTooltip() {
	var toolTipCode = '<div class="tooltip">Download PDF (2.1Mb)</div>';
	$('li.transcript').append(toolTipCode);
}

function megaMenu() {
	
	var megaConfig = {
         interval: 50,
         sensitivity: 4,
         over: addMega,
         timeout: 200,
         out: removeMega
    };
	$("li.mega").hoverIntent(megaConfig);
	$("li.langSelect").hoverIntent(megaConfig);
	function addMega(){
	    $(this).addClass("hovering");
	    $(this).prev().addClass('previous');
	}
	function removeMega(){
	    $(this).prev().removeClass('previous');
	    $(this).removeClass("hovering");
	}
}



function mainNavActive() {

    var classes = ["first", "second", "third", "fourth", "fifth", "sixth"];
    $('#mainNav > ul > li.mega').each(function (i) {
        $(this).addClass(classes[i % classes.length]);
    });

	$('#mainNav > ul > li:first').addClass('leftRound');
		
	$('#mainNav > ul > li:last').addClass('rightRound');

	if ($('#mainNav li').hasClass('active')) {
	    $('#mainNav li.active').prev().children('a').css('border-right-color', 'transparent');
	}
}

function topNavScroll() {

    $(".iphone #topNavScroll, .unknown #topNavScroll, .ipod #topNavScroll ").remove();

	$(window).scroll(
  		function() {
  			var menu = $('#topNavScroll');
  			if (($(window).scrollTop() > 150) && !menu.is(':visible')) menu.fadeIn();
  			else if (($(window).scrollTop() < 150) && menu.is(':visible')) menu.fadeOut();
  		}
  	);
	
	$('li.backToTop').click(function() {
		$('html, body').animate({ scrollTop: 0 }, 'slow');
		return false;
	});
}

function startCarousel() {
	$('.videoCarousel').jCarouselLite({
        btnNext: ".next",
        btnPrev: ".prev",
        circular: false,
        vertical: true,
		visible: 4
    });	
}

function searchActive() {
	$('#search').addClass("idleField");
	$('input#searchBox').focus(function() {
		$('#search').removeClass("idleField").addClass("focusField");
		if (this.value == this.defaultValue){ 
			this.value = '';
		}
		if(this.value != this.defaultValue){
			this.select();
		}
	});
	$('input#searchBox').blur(function() {
		$('#search').removeClass("focusField").addClass("idleField");
		if ($.trim(this.value) == ''){
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
}

function tabSearch() {
	$('input#searchpr').focus(function() {
		if (this.value == this.defaultValue){ 
			this.value = '';
		}
		if(this.value != this.defaultValue){
			this.select();
		}
	});
	$('input#searchpr').blur(function() {
		if ($.trim(this.value) == ''){
			this.value = (this.defaultValue ? this.defaultValue : '');
		}
	});
}

function subNavDropDown() {

    $('#subNav > ul > li:nth-child(4), #subNav > ul > li:nth-child(7), #subNav > ul > li:nth-child(10), #subNav > ul > li:nth-child(13), #subNav > ul > li:nth-child(16), #subNav > ul > li:nth-child(19)').addClass('clear');

    $('#subNav > ul > li > ul > li:nth-child(4), #subNav > ul li > ul > li:nth-child(7), #subNav > ul li > ul > li:nth-child(10), #subNav > ul li > ul > li:nth-child(13), #subNav > u li > ull > li:nth-child(16), #subNav > ul li > ul > li:nth-child(19)').addClass('clear');

    $('#subNav > ul > li').addClass('sub');
    $('ul.thirdLevel').parent().addClass('hasSubNav');
	$('li.sub').hover(
		function () {
			$(this).addClass('subHover');
		}, 
		function () {
			$(this).removeClass('subHover');
		}
	);
	
	var subConfig = {
         interval: 0,
         sensitivity: 4,
         over: subNavSlideDown,
         timeout: 0,
         out: subNavSlideUp
    };
	
	$('.hasSubNav').hoverIntent(subConfig);
	
	function subNavSlideDown() {
		$(this).addClass('subActive');
		var thirdNav = $(this).find('ul.thirdLevel');
		thirdNav.show()
	}
	
	function subNavSlideUp() {
		$(this).removeClass('subActive');
		$('#subNav .thirdLevel').hide();
	}
}

function management() {
	
	var management = $('#management');
	
	$('#management li').addClass('group');
	$('#management li:nth-child(3n+1)').addClass('mA');
	$('#management li:nth-child(3n+2)').addClass('mB');
	$('#management li:nth-child(3n)').addClass('mC');
	$('#management li:nth-child(3n+1)').addClass('clear');
	
	management.addClass('nonExpand');
	
	var personPanelDesc = '<div id="personPanel"></div>';
	$('#mgTeam').append(personPanelDesc);
		
	var boardConfig = {
		 interval: 200,
		 sensitivity: 4,
		 over: showPanel,
		 timeout: 300,
		 out: hidePanel
	};
	
	hoverMode();
	
	$('a#expandAll').toggle(function() {
		management.removeClass('nonExpand').addClass('expanded');
		$(this).text('Close all');
		$('#management li').unbind().hoverIntent();
	}, function() {
		management.removeClass('expanded').addClass('nonExpand');
		$(this).text('Expand all');
		hoverMode();
	});
	
	
	function hoverMode() {
		if (management.hasClass('nonExpand')) {
			$(".nonExpand li").hoverIntent(boardConfig);
		}
	}
	
	function showPanel() {
		var personPanel = $('#personPanel');
			
		$(this).addClass('active');
			
		var personDesc = $(this).find('p').clone();
		personPanel.append(personDesc);
			
		var lowerArea = $('#mgTeam').height() - 190;
		var vertPos = $(this).position();
			
		if (vertPos.top < lowerArea) {
			personPanel.css('top', vertPos.top);
			if ($(this).hasClass('mA')) {
				personPanel.css('left', '320px').fadeTo('fast', '0.96');
			}
			if ($(this).hasClass('mB')) {
				personPanel.css('left', '640px').fadeTo('fast', '0.96');
			}
			if ($(this).hasClass('mC')) {
				personPanel.css('left', '320px').fadeTo('fast', '0.96');
			}
		}
		if (vertPos.top >= lowerArea) {
			personPanel.css('top', vertPos.top - 190);
			if ($(this).hasClass('mA')) {
				personPanel.css('left', '320px').fadeTo('fast', '0.96');
			}
			if ($(this).hasClass('mB')) {
				personPanel.css('left', '640px').fadeTo('fast', '0.96');
			}
			if ($(this).hasClass('mC')) {
				personPanel.css('left', '320px').fadeTo('fast', '0.96');
			}
		}
	}
		
	function hidePanel() {
		$('#personPanel').fadeTo('fast', '0.0').hide().empty();
		$(this).removeClass('active');
	}
}

function historyTimeline() {

    	
	var yearWidth = $('.scroll-content-item li').width();
	
	// Grab decade widths
	var twenty = ($('#twenty-fifty ul li').size()) * yearWidth;
	var sixty = ($('#sixty ul li').size()) * yearWidth;
	var seventy = ($('#seventy ul li').size()) * yearWidth;
	var eighty = ($('#eighty ul li').size()) * yearWidth;
	var ninety = ($('#ninety ul li').size()) * yearWidth;
	var noughty = ($('#noughty ul li').size()) * yearWidth;
	var twentytens = ($('#twentytens ul li').size()) * yearWidth;
	
	var scrollBkgndWidth = $('.scroll-bar-wrap ul').width();
	
	//scrollpane parts
	var scrollPane = $( ".scroll-pane" ),
		scrollContent = $( ".scroll-content" );
			
	var timeLineWidth = twenty + sixty + seventy + eighty + ninety + noughty + twentytens;
	scrollContent.css('width', timeLineWidth);	
	
	var twentyRatio = (twenty / timeLineWidth);
	var sixtyRatio = (sixty / timeLineWidth);
	var seventyRatio = (seventy / timeLineWidth);
	var eightyRatio = (eighty / timeLineWidth);
	var ninetyRatio = (ninety / timeLineWidth);
	var noughtyRatio = (noughty / timeLineWidth);
	var twentytenRatio = (twentytens / timeLineWidth);
		
	$('li.twenty').css('width', Math.round(scrollBkgndWidth * twentyRatio));
	$('li.sixty').css('width', Math.round(scrollBkgndWidth * sixtyRatio));
	$('li.seventy').css('width', Math.round(scrollBkgndWidth * seventyRatio));
	$('li.eighty').css('width', Math.round(scrollBkgndWidth * eightyRatio));
	$('li.ninety').css('width', Math.round(scrollBkgndWidth * ninetyRatio));
	$('li.noughty').css('width', Math.round(scrollBkgndWidth * noughtyRatio));
	$('li.twentytens').css('width', Math.round(scrollBkgndWidth * twentytenRatio));
	
	$('.scroll-content-item li:nth-child(4n+1)').addClass('A');
	$('.scroll-content-item li:nth-child(4n+2)').addClass('B');
	$('.scroll-content-item li:nth-child(4n+3)').addClass('C');
	$('.scroll-content-item li:nth-child(4n)').addClass('D');
	
	//var dateInfo = '<div id="dateInfo"></div>';
	//$('#history').append(dateInfo);
	
	var timelineConfig = {
		 interval: 200,
		 sensitivity: 4,
		 over: showPanel,
		 timeout: 300,
		 out: hidePanel
	};
		
	$(".scroll-content-item li").hoverIntent(timelineConfig);
	
	function showPanel() {
		//var datePanel = $('.dateInfo');
		$(this).addClass('active');
		Cufon.replace('.scroll-content-item li h3');
		var datePanel = $(this).find('div');
		//datePanel.append(dateDesc);

		var pingPos = $(this).position();

		if (pingPos.left < 500 && $(this).parent().parent().attr('id') != 'twentytens') {
			//datePanel.css('top', '0');
			//datePanel.css('left', 170);
			var newDatePanel = datePanel.clone();
			$(this).parent().parent().append(newDatePanel);
			newDatePanel.css('top', pingPos.top);
			newDatePanel.css('left', pingPos.left + 170);
			newDatePanel.addClass('extraDiv');
			newDatePanel.fadeTo('fast', '0.9');
		}
        if (pingPos.left >= 500 || $(this).parent().parent().attr('id') == 'twentytens') {
			//datePanel.css('top', '0');
			//datePanel.css('left', -230);
			var newDatePanel = datePanel.clone();
			$(this).parent().parent().append(newDatePanel);
			newDatePanel.css('top', pingPos.top);
			newDatePanel.css('left', pingPos.left - 230);
			newDatePanel.addClass('extraDiv');
			newDatePanel.fadeTo('fast', '0.9');
        }
	}
	
	function hidePanel() {
	    $('.dateInfo').fadeTo('fast', '0.0').hide();
	    $('.extraDiv').remove();
		$(this).removeClass('active');
		Cufon.replace('.scroll-content-item li h3');
	}
	
	
	//build slider
	var scrollbar = $( ".scroll-bar" ).slider({
		slide: function( event, ui ) {
			if ( scrollContent.width() > scrollPane.width() ) {
				scrollContent.css( "margin-left", Math.round(
					ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
				) + "px" );
			} else {
				scrollContent.css( "margin-left", 0 );
			}
		}
	});
		
	//append icon to handle
	var handleHelper = scrollbar.find( ".ui-slider-handle" )
	.mousedown(function() {
		scrollbar.width( handleHelper.width() );
	})
	.mouseup(function() {
		scrollbar.width( "100%" );
	})
	.append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
	.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
		
	//change overflow to hidden now that slider handles the scrolling
	scrollPane.css( "overflow", "hidden" );
		
	//size scrollbar and handle proportionally to scroll distance
	function sizeScrollbar() {
		var remainder = scrollContent.width() - scrollPane.width();
		var proportion = remainder / scrollContent.width();
		//var handleSize = scrollPane.width() - ( proportion * scrollPane.width() );
		var handleSize = $('.ui-slider-handle').width();
		scrollbar.find( ".ui-slider-handle" ).css({
			width: handleSize,
			"margin-left": -handleSize / 2
		});
		handleHelper.width( "" ).width( scrollbar.width() - handleSize );
	}
		
	//reset slider value based on scroll content position
	function resetValue() {
		var remainder = scrollPane.width() - scrollContent.width();
		var leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 :
			parseInt( scrollContent.css( "margin-left" ) );
		var percentage = Math.round( leftVal / remainder * 100 );
		scrollbar.slider( "value", percentage );
	}
		
	//if the slider is 100% and window gets larger, reveal content
	function reflowContent() {
		var showing = scrollContent.width() + parseInt( scrollContent.css( "margin-left" ), 10 );
		var gap = scrollPane.width() - showing;
		if ( gap > 0 ) {
			scrollContent.css( "margin-left", parseInt( scrollContent.css( "margin-left" ), 10 ) + gap );
		}
	}
		
	//change handle position on window resize
	$( window ).resize(function() {
		//resetValue();
		//sizeScrollbar();
		//reflowContent();
	});
	//init scrollbar size
	setTimeout( sizeScrollbar, 10 );//safari wants a timeout
}

function calToolTip() {

    var calTipConfig = {
        interval: 200,
        sensitivity: 4,
        over: showTip,
        timeout: 500,
        out: hideTip
    };

    $("li.event").hoverIntent(calTipConfig);

    function showTip() {
        var tipPos = $(this).offset();
        var calTip = $(this).find('div');
        calTip.append('<span class="pointer"></span>');
        calTip.css('top', tipPos.top - 10).css('left', tipPos.left - 178).fadeIn('fast');
    }

    function hideTip() {
        var calTip = $(this).find('div');
        calTip.fadeOut('fast');
        calTip.find('.pointer').remove();
    }
}


function datesToolTip() {
	
	var tipHolder = '<div class="dateTipholder"></div>';
	$('body').append(tipHolder);
	
	var datesTip = $('.dateTipholder');
	datesTip.css('display', 'none');
	
	var datesTipConfig = {
		 interval: 200,
		 sensitivity: 4,
		 over: showTip,
		 timeout: 300,
		 out: hideTip
	};
		
	$("td.action").hoverIntent(datesTipConfig);
	
	function showTip() {
		var tipCopy = $(this).find('img').attr('alt');
		datesTip.append(tipCopy);
		datesTip.append('<span class="pointer"></span>');
		var tipPos = $(this).offset();
		datesTip.css('top', tipPos.top - $(this).height() - 9).css('left', tipPos.left - (datesTip.width()/1.25)).fadeIn('fast');
	}
	
	function hideTip() {
	    datesTip.fadeOut('fast').empty();
	}

}



function homePdfToolTip() {

    var tipHolder;

    var datesTip;

    var pdfTipConfig = {
        interval: 200,
        sensitivity: 4,
        over: showTip,
        timeout: 300,
        out: hideTip
    };

    $(".vidLinks li.transcript").hoverIntent(pdfTipConfig);

    function showTip() {
        tipHolder = '<div class="pdfTipholder"></div>';
        $('body').append(tipHolder);
        datesTip = $('.pdfTipholder');
        datesTip.css('display', 'none');
        var tipCopy = 'Download PDF'
        //var tipCopy = tipCopy + ' <small>(' + $(this).find('a').attr('title') + 'mb)</small>';
        var tipCopy = tipCopy + ' <small>(1.5mb)</small>';
        datesTip.append(tipCopy);
        datesTip.append('<span class="pointer"></span>');
        var tipPos = $(this).offset();
        datesTip.css('top', tipPos.top - $(this).height() + 2).css('left', tipPos.left - (datesTip.width() / 2)).fadeIn('fast');
    }

    function hideTip() {
        datesTip.fadeOut('fast', function () {
            $(this).remove();});
    }

}

function RNSdatepicker() {
    if ($("#from").html() != null) {
        var dates = $("#from, #to").datepicker({
            defaultDate: "+1w",
            changeMonth: true, changeYear: true,
            numberOfMonths: 1,
            dateFormat: 'dd-mm-yy',
            onSelect: function (selectedDate) {
                var option =
					instance = $(this).data("datepicker"),
					date = $.datepicker.parseDate(
						instance.settings.dateFormat ||
						$.datepicker._defaults.dateFormat,
						selectedDate, instance.settings);
                dates.not(this).datepicker("option", option, date);
            }
        });
    }

//  this.id == "from" ? "minDate" : "maxDate",
}

/********************************************************/
/**career > our stories**/
function initCareerStories() {
    $('.tabs-stories').show();
    //dropdown filters contents
    $('ul.stories-list li .content p.role').each(function () {
        populateDropdown($('.tabs-stories .filters .role'), $(this).html());
        populateDropdown($('select.test'), $(this).html());
    });
    
    $('ul.stories-list li .content p.country').each(function () {
        populateDropdown($('.tabs-stories .filters .country'), $(this).html());
    });
    //dropdown filters function
    $('.tabs-stories .filters .role').bind('change', function () {
        filterStories('p.role', $(this).children('option:selected').attr('value'));
        $('.tabs-stories .filters .country option').removeAttr('selected');
        $('.tabs-stories .filters .country option:first').attr('selected', 'selected');
    });
    $('.tabs-stories .filters .country').bind('change', function () {
        filterStories('p.country', $(this).children('option:selected').attr('value'));
        $('.tabs-stories .filters .role option').removeAttr('selected');
        $('.tabs-stories .filters .role option:first').attr('selected', 'selected');
    });
    //paging
    $('ul.stories-list li').addClass('active');
    addPaging();
}

function populateDropdown(selector, optionvalue) {
    if (selector.find('option[value="' + optionvalue + '"]').html() == null) {
        selector.append('<option value="' + optionvalue + '">' + optionvalue + '</option>');
    }
}

function filterStories(selector, selected_option) {
    $('ul.stories-list li').hide();
    $('ul.stories-list li').removeClass('active');
    if (selected_option != '') {
        $('ul.stories-list li').each(function () {
            if ($(this).children('.content').children(selector).html() == selected_option)
                $(this).addClass('active');
        });
    }
    else {
        //show all
        $('ul.stories-list li').addClass('active');
    }
    //reset styling
    $('ul.stories-list li').removeClass('right');
    var index = 1;
    $('ul.stories-list li.active').each(function () {
        if ((index % 2) == 0) $(this).addClass('right');
        index++;
    });
    //show active items and add paging
    $('ul.stories-list li.active').show();
    addPaging();
}

function addPaging() {
    var itemsperpage = 4;
    //how many pages
    $('.careers-page .paging ul').html('');
    var numpages = Math.ceil($('ul.stories-list li.active').length / itemsperpage);
    if (numpages > 1) {
        for (var i = 1; i <= numpages; i++) {
            $('.careers-page .paging ul').append('<li><a href="#">' + i + '</a>');
        }
        $('.careers-page .paging span').html('Pages');
        //show first page
        $('ul.stories-list li.active:gt(' + (itemsperpage - 1) + ')').hide();
        $('.careers-page .paging ul li').removeClass('active');
        $('.careers-page .paging ul li:first').addClass('active');
    }
    else $('.careers-page .paging span').html('');
    //page click
    $('.careers-page .paging ul li a').live('click', function () {
        var pg = $(this).html();
        $('ul.stories-list li.active').show();
        var pagestart = (pg - 1) * itemsperpage;
        var pageend = (pg * itemsperpage) - 1;
        $('ul.stories-list li.active:lt(' + (pagestart) + ')').hide();
        $('ul.stories-list li.active:gt(' + (pageend) + ')').hide();
        $('.careers-page .paging ul li').removeClass('active');
        $(this).parents('li').addClass('active');
        return false;
    });
}


/**career > our stories**/
/********************************************************/
