/**
* @namespace FC
* 
* call jQuery
*/


var server = "/";

//Top navigation background rollover
FC.navRollover = function(o) {
    var element = o.element
    var theClass = o.theClass

    //Navigation background fix
    $(element).bind("mouseover", function() {
        $(this).parent().next().addClass(theClass)
    });

    $(element).bind("mouseout", function() {
        $(this).parent().next().removeClass(theClass)
    });
}

//Objects for all the rollover buttons
FC.rollovers = function() {

    if (document.images) {

        ImLeftRoll = new Image();
        ImLeftRoll.src = server + "images/buttons/images-left-on.gif";
        ImLeftOff = new Image();
        ImLeftOff.src = server + "images/buttons/images-left.gif";

        ImRightRoll = new Image();
        ImRightRoll.src = server + "images/buttons/images-right-on.gif";
        ImRightOff = new Image();
        ImRightOff.src = server + "images/buttons/images-right.gif";

        ArticlesLeftRoll = new Image();
        ArticlesLeftRoll.src = server + "images/buttons/archive-left-on.gif";
        ArticlesLeftOff = new Image();
        ArticlesLeftOff.src = server + "images/buttons/archive-left-off.gif";

        ArticlesRightRoll = new Image();
        ArticlesRightRoll.src = server + "images/buttons/archive-right-on.gif";
        ArticlesRightOff = new Image();
        ArticlesRightOff.src = server + "images/buttons/archive-right-off.gif";

        YearsLeftRoll = new Image();
        YearsLeftRoll.src = server + "images/buttons/archive-left-on.gif";
        YearsLeftOff = new Image();
        YearsLeftOff.src = server + "images/buttons/archive-left-off.gif";

        YearsRightRoll = new Image();
        YearsRightRoll.src = server + "images/buttons/archive-right-on.gif";
        YearsRightOff = new Image();
        YearsRightOff.src = server + "images/buttons/archive-right-off.gif";

        //Regions rollovers
        FormatsLeftRoll = new Image();
        FormatsLeftRoll.src = server + "images/colour5/buttons/products-left-on.gif";
        FormatsLeftOff = new Image();
        FormatsLeftOff.src = server + "images/colour5/buttons/products-left-off.gif";
        FormatsLeftInactive = new Image();
        FormatsLeftInactive.src = server + "images/colour5/buttons/products-left-inactive.gif";

        FormatsRightRoll = new Image();
        FormatsRightRoll.src = server + "images/colour5/buttons/products-right-on.gif";
        FormatsRightOff = new Image();
        FormatsRightOff.src = server + "images/colour5/buttons/products-right-off.gif";
        FormatsRightInactive = new Image();
        FormatsRightInactive.src = server + "images/colour5/buttons/products-right-inactive.gif";

        //Region rollovers
        GalleryLeftRoll = new Image();
        GalleryLeftRoll.src = server+"images/colour3/buttons/gallery-left-on.png";
        GalleryLeftOff = new Image();
        GalleryLeftOff.src = server+"images/colour3/buttons/gallery-left-off.png";
        GalleryLeftInactive = new Image();
        GalleryLeftInactive.src = server+"images/colour3/buttons/gallery-left-inactive.png";
        
        GalleryRightRoll = new Image();
        GalleryRightRoll.src = server+"images/colour3/buttons/gallery-right-on.png";
        GalleryRightOff = new Image();
        GalleryRightOff.src = server+"images/colour3/buttons/gallery-right-off.png";
        GalleryRightInactive = new Image();
        GalleryRightInactive.src = server+"images/colour3/buttons/gallery-right-inactive.png";
 
        //Home images rollovers
        HomeLeftRoll = new Image();
        HomeLeftRoll.src = server + "images/colour5/buttons/home-left-on.gif";
        HomeLeftOff = new Image();
        HomeLeftOff.src = server + "images/colour5/buttons/home-left-off.gif";
        HomeLeftInactive = new Image();
        HomeLeftInactive.src = server + "images/colour5/buttons/home-left-inactive.gif";

        HomeRightRoll = new Image();
        HomeRightRoll.src = server + "images/colour5/buttons/home-right-on.gif";
        HomeRightOff = new Image();
        HomeRightOff.src = server + "images/colour5/buttons/home-right-off.gif";
        HomeRightInactive = new Image();
        HomeRightInactive.src = server + "images/colour5/buttons/home-right-inactive.gif";
        
        //Image search rollovers
	    ImagesLeftRoll = new Image();
	    ImagesLeftRoll.src = server+"images/buttons/images-left-on.gif";
	    ImagesLeftOff = new Image();
	    ImagesLeftOff.src = server+"images/buttons/images-left-off.gif";
	    ImagesLeftInactive = new Image();
	    ImagesLeftInactive.src = server+"images/buttons/images-left-inactive.gif";
    	
	    ImagesRightRoll = new Image();
	    ImagesRightRoll.src = server+"images/buttons/images-right-on.gif";
	    ImagesRightOff = new Image();
	    ImagesRightOff.src = server+"images/buttons/images-right-off.gif";
	    ImagesRightInactive = new Image();
	    ImagesRightInactive.src = server+"images/buttons/images-right-inactive.gif";	

    }


}

//Rollovers
FC.rollover = function(targ,id,del){
	
	targ.find("img").attr("id",id);
	if(del!=1){
		
		targ.css({cursor:"pointer"});
		targ.find("img").attr("src",eval(id+"Off").src);
		
		targ.mouseover(function(){
			targ.find("img").attr("src",eval(id+"Roll").src);
		});
		targ.mouseout(function(){
			targ.find("img").attr("src",eval(id+"Off").src);
		});
		
		targ.removeClass("inactive");
	}
	else{
		targ.css({cursor:"default"});
		targ.unbind("mouseover");
		targ.unbind("mouseout");
		targ.addClass("inactive");
		targ.find("img").attr("src",eval(id+"Inactive").src);
	}
};

FC.imgRoll = function(n) {
    if (document.getElementById(n)) { document.getElementById(n).src = eval(n + "Roll").src }
}

FC.imgOff = function(n) {
    if (document.getElementById(n)) { document.getElementById(n).src = eval(n + "Off").src }
}

//Help tooltips
FC.help = function(o) {
    var element = o.element
    var elementToFind = o.elementToFind
    var theClass = o.theClass

    $(element).each(function() {

        $(this).find(elementToFind).addClass(theClass)
        $(this).attr("tabindex", "0")

        $(this).bind("mouseover focus", function() {
            $(this).find(elementToFind).removeClass(theClass)
        });

        $(this).bind("mouseout blur", function() {
            $(this).find(elementToFind).addClass(theClass)
        });

    });
}

//Site wide flash movie strapline
FC.strapline = function() {
    var flashvars = {};
    var params = {
        wmode: "transparent"
    };
    var attributes = {};
    swfobject.embedSWF("../swf/country/" + country + "/test.swf", "flash-strapline", "367", "90", "9.0.0", "../swf/country/expressInstall.swf", flashvars, params, attributes);
}

//Case Studies/Gallery pagination (AJAX scroller)
FC.pagination = function() {

    var __$data = $(document.createElement("div"));
    var numAjaxCalls = 0;
    var finalAjaxValue;
    var pageValue = 0;
    var previous = $('a.previous');
    var next = $('a.next');
    var url = next.attr('href'); // ?
    var wrapper = $('div.wrapper');
    var parent = $('ul.parent', wrapper);

    function doSlider(isNext) {
        var __isNext = isNext,
			__isPrevOn,
			__isNextOn;

        pageValue += (__isNext) ? 1 : -1;
        wrapper.scrollTo((parent.children().get(pageValue * 3)), 500, { axis: 'x' });


        switch (pageValue) {
            case 0: // is first
                __isPrevOn = false;
                __isNextOn = true;
                break;

            case finalAjaxValue: // is last
                __isPrevOn = true;
                __isNextOn = false;
                break;

            default:
                __isPrevOn = true;
                __isNextOn = true;
        }

        setButtonStyleAndBehaviour(previous, false, __isPrevOn);
        setButtonStyleAndBehaviour(next, true, __isNextOn);

        return false

    }

    function onButtonClick(e) {
        var __isNext = e.data.direction;

        __isNext && !finalAjaxValue ? getMoreItems(next.attr('href')) : doSlider(__isNext);

        return false;
    }

    function onOffButtonClick(e) {
        return false;
    }

    function setButtonStyleAndBehaviour(button, direction, isEnabled) {

        var __$img = $('img', button),
			__css = {},
			__x;

        if (__$img.css('background-position-x')) {
            __css['background-position-x'] = __$img.css('background-position-x');
        } else {
            __x = __$img.css('background-position').split(' ')[0];
        }

        if (isEnabled) {
            button.removeClass("inactive"); // set view
            if (__css['background-position-x']) {
                __css['background-position-y'] = '-62px';
            } else {
                __css['background-position'] = __x + ' -61px';
            }
            __$img.css(__css);
            button.css({ cursor: 'pointer' });

            button.unbind();
            button.bind('click keypress', { direction: direction }, onButtonClick); // set behaviour
            button.bind('mouseenter focus', function() {
                if (__css['background-position-x']) {
                    __css['background-position-y'] = '-124px';
                } else {
                    __css['background-position'] = __x + ' -123px';
                }
                __$img.css(__css);
            });
            button.bind('mouseout blur', function() {
                if (__css['background-position-x']) {
                    __css['background-position-y'] = '-62px';
                } else {
                    __css['background-position'] = __x + ' -61px';
                }
                __$img.css(__css);
            });
        } else {
            button.addClass("inactive"); // set view
            if (__css['background-position-x']) {
                __css['background-position-y'] = '0';
            } else {
                __css['background-position'] = __x + ' 1px';
            }
            __$img.css(__css);
            button.css({ cursor: 'default' });

            button.unbind(); // set behaviour
            button.bind('click', onOffButtonClick);
        }
    }

    var getMoreItems = function(url) {
        $.ajax({
            url: url,
            dataType: "html",
            cache: false,
            success: function(html) {
                numAjaxCalls++;
                __$data.append(html);

                //add the retrieved items to the page
                parent.append(__$data.find("ul.parent").children());
                FC.pngFix(parent[0]);
                parent.width(parent.children().length * 236);

                if (__$data.find('a.next').hasClass('inactive')) {
                    finalAjaxValue = numAjaxCalls;
                    //rollover();
                }
                else {
                    next.attr('href', __$data.find('a.next').attr('href'));
                }

                __$data.empty();

                doSlider(true);
            }
        });
    }

    setButtonStyleAndBehaviour(previous, false, false);
	setButtonStyleAndBehaviour(next, true, !next.hasClass('inactive'));
}

//Press Release archive
FC.pressArchive = function() {

    //Set Variables
    var baseurl = "/Templates/Private/Pages/International/ArticleTimeLine.aspx";
    var prevArticle = $(".page .archive .articles a.previous");
    var nextArticle = $(".page .archive .articles a.next");
    var wrapper = $(".page .archive .articles .wrapper");
    var wrapperInner = $(".page .archive .articles .wrapper-inner");
    var articles = $(".page .archive .articles");
    var prevYear = $(".page .archive .years a.previous");
    var nextYear = $(".page .archive .years a.next");
    var years = $(".page .archive .years-inner li.link a");
    var months = $(".page .archive .months li.link a");
    var yearsInner = $(".page .archive .years-inner");
    var monthsInner = $(".page .archive .months ol");
    var temp = $("#temp");
    var set = 0;
    var prevset = 0;
    var maxset = 0;
    var yearSet = 0;
    var visibleYears = 6;
    var articleCount = $(".page .archive .months li.selected input").val();
    var last = false;
    var diff = 0;
    var sTo = 0; //Scroll to
    var waitingIcon = "<div class='waiting'><img src='/images/waiting.gif' width='31' height='31' /></div>";
    var stepAmount = 2;

    //If the wide version is used, change the step amount
    var wide = $(".page .archive.wide");
    if (wide.length > 0) { var stepAmount = 3; }

    //Undo the "disabled" attributes
    prevArticle.attr("disabled", "");
    nextArticle.attr("disabled", "");
    prevYear.attr("disabled", "");
    nextYear.attr("disabled", "");

    //Set Rollovers
    rollover = function(targ, id, del) {
        targ.find("img").attr("id", id);
        if (del != 1) {
            targ.mouseover(function() {
                FC.imgRoll(targ.find("img").attr("id"));
            });
            targ.mouseout(function() {
                FC.imgOff(targ.find("img").attr("id"));
            });

            targ.removeClass("inactive");
        }
        else {
            targ.unbind("mouseover");
            targ.unbind("mouseout");
            targ.addClass("inactive");
        }
    };
	
    //On the wide version of the timeline, check to see if there are more years after the currently selected one and make the button active
    if (wide.length > 0) {
    
        var m = 0;
        var yearLinks = yearsInner.find("li");
        var selYear = yearsInner.find("li.selected");
        for (i = 0; i < yearLinks.length; i++) {
            if (yearLinks[i] == selYear[0]) {
                m = i;
            }
        }

        if (m > 0) {
      
            //rollover($(".page .years .next"), "YearsRight", 0);
            //nextYear.css({ cursor: "pointer" });
        }
    }

	var setStates = function(){
		
		if (articleCount <= stepAmount) {
	  
			nextArticle.find("img").attr("src", server + "images/buttons/archive-right-inactive.gif");
				
			rollover(nextArticle, "ArticlesRight", 1);
			
		} else {
			
			rollover(nextArticle, "ArticlesRight", 0);
		}
	};
	setStates();

    //disable previous articles and next years buttons
    prevArticle.find("img").attr("src", server + "images/buttons/archive-left-inactive.gif");
    //nextYear.find("img").attr("src",server+"images/international/buttons/archive-right-inactive.png");
	
    //Update the articles (based on articles left and right)
    var updateArticles = function(url, state, set) {
        var finalUrl = baseurl + url;
        var maxset = articleCount - stepAmount;

        //Work out the Maxset to be used
        if (stepAmount == 3) {
            var a = maxset / 3;
            b = Math.floor(maxset / 3);
            if (b < a) { maxset = maxset + 3 };
        }
        else {
            var a = maxset / 2;

            b = Math.floor(maxset / 2);
            if (b < a) { maxset = maxset + 2 };
        }
		
	    //If the element numbered with set does not exist, then go and get the next two articles
        if (!$('.article:eq(' + set + ')').length) {
			
			if (set <= maxset) {
                wrapperInner.css({ opacity: 0.1 });
                articles.append(waitingIcon);
                $.ajax({
                    url: finalUrl,
                    cache: false,
                    success: function(html) {
                        wrapperInner.css({ opacity: 1 });
                        $("div.waiting").remove();

                        //Load the HTML into a temporary div 
                        temp.append(html);

                        //Put all the articles into the wrapper div
                        wrapperInner.append($("#temp .article"));
						
						last = (set + stepAmount >= maxset);
		
		                if (nextArticle.attr("href") != "" || $("#temp .archive .articles a.next").attr("href") != null) {
                            nextArticle.attr("href", $("#temp .archive .articles a.next").attr("href"));
                        }
                        else { nextArticle.attr("href", "#"); }
                        wrapper.scrollTo('.article:eq(' + set + ')', 600, { axis: 'x' });

                        //Empty out the temp div
                        temp.empty();
                    }
                });
            }
            else { 
				if (set == articleCount) { 
					set = set - stepAmount; 
				} 
			}
        }
        //If the element numbered with set does exist, just jump straight to it
        else { 
            wrapper.scrollTo('.article:eq(' + set + ')', 600, { axis: 'x' }); 
        }

        // add a pointer cursor state to the previous article link (as the anchor would have had a null href on page load)
        prevArticle.css({ cursor: "pointer" });
    }

    var previousArticles = function(set) {
		
		last = false;
		
        wrapper.scrollTo('.article:eq(' + set + ')', 600, { axis: 'x' });
        if (set == 0) {
            $(".page .articles .previous img").attr("src", server + "images/buttons/archive-left-inactive.gif");
            rollover(prevArticle, "ArticlesLeft", 1);
            prevArticle.css({ cursor: "default" });
        }
    }


    //Update the years and months (based on the years left and right)
    var previousYears = function(yearUrl, state, sTo) {
        var finalUrl = baseurl + yearUrl;
        if (sTo == 0) {
            $.ajax({
                url: finalUrl,
                cache: false,
                success: function(html) {

                    //Load the HTML into a temporary div
                    temp.append(html);

                    //Update previous and next years links with the new ones from the templ div
                    prevYear.attr("href", $("#temp .years a.previous").attr("href"));
                    nextYear.attr("href", $("#temp .years a.next").attr("href"));

                    //Put all the years in the years div (removing the existing ones first)
                    var offset = sTo + 1;
                    $(".page .archive .years ol li:eq(0)").before($("#temp .years ol li:eq(0)"));
                    yearsInner.scrollTo('li:eq(' + offset + ')', 0, { axis: 'x' });
                    yearsInner.scrollTo('li:eq(' + sTo + ')', 250, { axis: 'x' });

                    //Empty out the temporary div
                    temp.empty();


                    //Reactivate the year links
                    activateYears();

                }
            });

        }
        else { yearsInner.scrollTo('li:eq(' + sTo + ')', 250, { axis: 'x' }); }
    }


    //Update the years and months (based on the years left and right)
    var nextYears = function(sTo) {
        yearsInner.scrollTo('li:eq(' + sTo + ')', 250, { axis: 'x' });
        activateYears();
    }


    var getMonths = function(url) {
        temp.empty();
        var finalUrl = baseurl + url

        years.unbind("click");
        years.bind("click", function() { return false; })

        $.ajax({
            url: finalUrl,
            cache: false,
            success: function(html) {

                //Load the HTML into a temporary div 
                temp.append(html);

                //Put all the months in the years div (removing the existing ones first)
                monthsInner.animate({ opacity: 0 }, 100, function() {
                    monthsInner.find("li").remove();
                    monthsInner.append($("#temp .months ol li"));
                    monthsInner.animate({ opacity: 1 }, 100, function() {

                        articleCount = monthsInner.find("li.selected input").val();

                        //Load the articles for the pre-selected month	
                        monthURL = monthsInner.find("li.selected").find("a").attr("href");
                        monthURL = getQS(monthURL);

                        months.unbind("click");
                        months.bind("click", function() { return false; })

                        getArticles(monthURL, articleCount);

                        //Empty out the temporary div
                        temp.empty();


                    });
                });
            }
        });
    };


    var getArticles = function(url, articleCount) {
        temp.empty();
        var finalUrl = baseurl + url

        $.ajax({

            url: finalUrl,
            cache: false,
            success: function(html) {
                set = 0;

                //Load the HTML into a temporary div 
                $("#temp").append(html);

                //Put all the articles into the wrapper div (empty first)
                wrapperInner.animate({ opacity: 0 }, 250, function() {
                    wrapperInner.empty();
                    wrapperInner.append($("#temp .article"));
                    wrapper.scrollTo('.article:eq(0)', 1, { axis: 'x' });
                    wrapperInner.animate({ opacity: 1 }, 250, function() {

                        nextArticle.attr("href", $("#temp .archive .articles a.next").attr("href"));
                        prevArticle.attr("href", $("#temp .archive .articles a.previous").attr("href"));

                        //Empty out the temporary div
                        temp.empty();


                        //Reactivate the months and years links
                        activateMonths();
                        activateYears();
						
						setStates();

                    });

                });

                $(".page .articles .previous img").attr("src", server + "images/buttons/archive-left-inactive.gif");
                rollover($(".page .articles .previous"), "ArticlesLeft", 1);

                $(".page .articles .next img").attr("src", server + "images/buttons/archive-right-off.gif");
                rollover($(".page .articles .next"), "ArticlesRight", 0);

                
            }

        });
    };




    //Button activations
    function activateNextArticle() {
        var nextArticle = $(".page .archive .articles a.next");
        nextArticle.unbind("click");
       
        nextArticle.click(function() {
			
            if (set + stepAmount < articleCount) {

                url = $(this).attr("href");
                url = getQS(url);
                if (url != "" && url != "#") {
						
					set = set + stepAmount;
					$(".page .articles .previous img").attr("src", server + "images/buttons/archive-left-off.gif");
					rollover(prevArticle, "ArticlesLeft", 0);
					updateArticles(url, "next", set);
                }

                if (set + stepAmount >= articleCount) {
                    rollover(nextArticle, "ArticlesRight", 1);
                    $(".page .articles .next img").attr("src", server + "images/buttons/archive-right-inactive.gif");
                }


                if (articleCount < 3) {
                    rollover(prevArticle, "ArticlesLeft", 1);
                    $(".page .articles .previous img").attr("src", server + "images/buttons/archive-left-inactive.gif");
                    rollover(nextArticle, "ArticlesRight", 1);
                    $(".page .articles .next img").attr("src", server + "images/buttons/archive-right-inactive.gif");
                }
            }

            return false;
        });
    }
    activateNextArticle();




    prevArticle.click(function() {
        if (set > 0) {
            if (set == articleCount) { set = set - (stepAmount * 2); }
            else { set = set - stepAmount }
            previousArticles(set);
        }
        if (articleCount > 3) {
            rollover(nextArticle, "ArticlesRight", 0);
            $(".page .articles .next img").attr("src", server + "images/buttons/archive-right-off.gif");
        }
        return false;
    });




    function activateNextYear() {
        var nextYear = $(".page .archive .years a.next");
        nextYear.click(function() {

            var amountYears = $(".page .archive .years ol li");
            diff = amountYears.length - visibleYears;

            if (sTo < diff) { sTo = sTo + 1; }
            nextYears(sTo);
            return false;
        });
    }
    activateNextYear();

    function activatePrevYear() {
    
        var initialPrevYearURL = prevYear.attr('href');
        
        // are there previous years? (href value will not exist if there are no previous years)
        if (initialPrevYearURL) {
            
            prevYear.click(function() {

                var yearUrl = $(this).attr("href");
                          
                yearUrl = getQS(yearUrl);

                if (sTo > 0) { sTo = sTo - 1; }

                previousYears(yearUrl, "previous", sTo);

                //Activate rollover for "next year"
                //$(".page .years .next img").attr("src", server + "images/buttons/archive-right-off.gif");
                //rollover($(".page .years .next"), "YearsRight", 0);
                
                return false;
           });
           
       } else {

            // disable rollover states, anchor is inactive
            rollover($(".page .years .previous"), "YearsLeft", 1);
       }
    }
    activatePrevYear();


    function activateYears() {
        var years = $(".page .archive .years-inner li.link a");
        years.unbind("click");
        years.click(function() {
            years.parent().removeClass("selected");
            $(this).parent().addClass("selected");
            url = $(this).attr("href");
            url = getQS(url);
            getMonths(url);
            return false;
        });
        var emptyYears = $(".page .archive .years-inner li.empty a");
        emptyYears.click(function() {
            return false;
        });
    }
    activateYears();


    function activateMonths() {
        var months = $(".page .archive .months li.link a");
        var emptyMonths = $(".page .archive .months li.empty a");
        months.unbind("click");
        months.click(function() {
            months.parent().removeClass("selected");
            emptyMonths.parent().removeClass("selected");
            $(this).parent().addClass("selected");

            //Get URL query string
            url = $(this).attr("href");
            url = getQS(url);

            //Get article count
            articleCount = $(this).parent().find("input").val();

            //Get Articles
            getArticles(url, articleCount);
			
            return false;
        });
        //Make "empty" months non-clicable
        emptyMonths.click(function() {
            return false;
        });
    }
    activateMonths();


    function getQS(url) {
        if (url) {
            var start = url.indexOf("?");
            var end = url.indexOf("#");
            url = url.substring(start, end);
            return url
        } else {
            return '';
        }
    }


}

//Archive rollover
FC.archiveRollover = function(o) {
    var element = o.element
    var element2 = o.element2
    var theClass = o.theClass

    $(element).hover(
			function() {
			    $(this).addClass(theClass)
			},

			function() {
			    $(this).removeClass(theClass)
			}
		);

    $(element2).hover(
			function() {
			    $(this).addClass(theClass)
			},

			function() {
			    $(this).removeClass(theClass)
			}
		);
}

// Counting the items in a box and setting the width
FC.setWidth = function(i, j, k, l) {

    var __containerClass = i; // pass in the class name on the container element that needs the max width set
    var __childWithWidth = j; // pass in the child objects
    var __indivWidth = l;
    var __totalWidth = 0; // set the width of the image list to 0
    var __maxHeight = 0; // set the height of the image list to 0
    var __containerWithHeight = k;

    var $imgList = $(__containerClass).find(__childWithWidth);

    __totalWidth = ($imgList.length * __indivWidth);


    // loop through the array of list items and get the biggest height
    $($imgList).each(function() {
        if (__maxHeight < $(this).height()) { __maxHeight = $(this).height(); }
    });

    //determine the number of rows by taking the total height and dividing it by the largest height and casting to an int to get rid of the remainder
    __numRows = ($(__containerWithHeight).height() / __maxHeight) | 0;

    // divide the total width by the number of rows 
    __totalWidth = __totalWidth / __numRows;


    // set the with of the container
    $(__containerClass).css("width", __totalWidth);


}

//Media Landing Scroller ------------------------------------------
FC.scroller = function(o){

	var __right = $(o.right);
	var __left = $(o.left);
	var __container = $(o.container);
	var __scrollAmount = o.amount;
	var __current = 0;
	var __contentBoxes = $(o.items);
	var __itemClass = o.itemClass;
	var __rollover = o.rollover;
	
	
	var __max = Math.floor(__contentBoxes.length/__scrollAmount);
	__max = __max*__scrollAmount;

	//Make left rollover inactive
	FC.rollover(__left,__rollover+"Left",1);
	
	//Activate the right rollover only if there are more items than the scroll amount
	if(__contentBoxes.length<=__scrollAmount){
		FC.rollover(__right,__rollover+"Right",1);
	}
	else{
		FC.rollover(__right,__rollover+"Right",0);	
	}
	
	
	//Make sure the scroller is at the start
	__container.scrollTo( __itemClass+':eq('+0+')', 500, {axis:'x'});
	
	//If the amount of items is divisible by the scroll amount, then the max should be the scrollamount less
	if(__max==__contentBoxes.length){
		__max=__max-__scrollAmount;
	}
	
	
	//Left scroller button
	__left.bind("click keypress", function(){
		//If the current is more than the minimum
		if(__current>0){
			
			//Activate right rollever if there only if there are more items than the scroll amount
			if(__contentBoxes.length>__scrollAmount){
				FC.rollover(__right,__rollover+"Right",0);
			}
			//Scroll to the previous items
			__current = __current-__scrollAmount;
			__container.scrollTo( __itemClass+':eq('+__current+')', 500, {axis:'x'});	
		}
		
		//If the current is equal to the minimum, then disable the left rollover and activate the right rollover
		if(__current==0){
			FC.rollover(__left,__rollover+"Left",1);
			
			if(__contentBoxes.length>__scrollAmount){
				FC.rollover(__right,__rollover+"Right",0);
			}
		}

		
		return false;
	});
	

	//Right scroller button
	__right.bind("click keypress", function(){
		
		//If current is less than the max
		if(__current<__max){
			
			//If the max is reached, then disable the right rollover
			if(__current==(__max-__scrollAmount)){
				FC.rollover(__right,__rollover+"Right",1);
			}
			
			//Activate left rollover
			FC.rollover(__left,__rollover+"Left",0);
			
			//Scroll to the next results
			__current = __current+__scrollAmount;
			__container.scrollTo( __itemClass+':eq('+__current+')', 500, {axis:'x'});

		}
		
		return false;
	});

}




//Inspire Me Landing Scroller ------------------------------------------
FC.ajaxScroller = function(o){

	var __right = $(o.right);
	var __left = $(o.left);
	var __container = $(o.container);
	var __panelContainer = __container.find("div.wrapper-inner");
	var __scrollAmount = o.amount;
	var __current = 0;
	var __contentBoxes = $(o.items);
	var __itemClass = o.itemClass;
	var __rollover = o.rollover;
	var __url = "/Templates/Public/Pages/Country/GalleryListingUI.aspx";
	var __widthIncrease = "785";
	var __counter = 0;
	var __leftCounter = 0;
	var __last = 0;
	var __deactivateRight = false;
	var __eof = false;
	var __lastCounter = 1000;
	var __active = false; 
	
	//Check to see if the right hand button is inactive (first instance on page load)
	var __rightActive = __right.hasClass("inactive");
	
	
	
	
	
	
	
    function rightButton(){

	    __counter ++;
	    
        var __call;
        
        //Check to see if the next item to scroll to is the current last one - if it is then we can make an AJAX call
        if(__counter>__last){
            __last = __counter;
            __call = true;
        }
        else{
            __call = false;
            
        }
        
        //Activate the left button
        FC.rollover(__left,__rollover+"Left",0);
        
        //Temporarily disable the right button until AJAX call is complete



        
        //Make AJAX call
            if(__call==true && __eof==false){
                $.ajax({
                    url:__url+"?p="+__counter,
                    dataType: "html",
                    cache: false,
                    success: function(html) {
                        
                        var __results = html;
                        var __newPanels = $(__results).find("div.panel");
                        var __newWidth = __widthIncrease * (__counter+1);
                        __panelContainer.css({"width":__newWidth+"px"});
                        __panelContainer.append(__newPanels);
                        __container.scrollTo( __itemClass+':eq('+__counter*__scrollAmount+')', 500, {axis:'x'});

                        
                        //Find "next" button in results to see if it's inactive - if inactive then we need to unbind the right button
                        var __newNext = $(__results).find("a.next");
                        if(__newNext.hasClass("inactive")==true){
                            FC.rollover(__right,__rollover+"Right",1); 
                            __right.unbind().bind("click",function(){return false;});
                            __eof = true;
                            __deactivateRight = true;
                            __lastCounter = __counter;
                        }
                        
                        __active = false;
                       
                    }
        	    
        	    
                });
            }
            //Scroll to next set without making AJAX call
            else{
                if(__counter == __lastCounter){
                    FC.rollover(__right,__rollover+"Right",1); 
                    __right.unbind().bind("click",function(){return false;});
                    __deactivateRight = true;
                }

                __container.scrollTo( __itemClass+':eq('+__counter*__scrollAmount+')', 500, {axis:'x'});
                
                __active = false;
      
            }
   
    
    }
	
	
	
	
	
	
	
	
	
	
	//If the button isn't inactive (it's active) then proceed with the call
	if(__rightActive==false){
	
	    FC.rollover(__right,__rollover+"Right",0);
        
        //Right button event
	    __right.bind("click",function(){ 
	        if (__active == true) {
	            return false 
	        }
	        __active = true
	        
	        rightButton();   
	        return false;
	    });
	    
	    //Left button event
	    __left.bind("click",function(){
            
            
            //Find out if the right button is at the last one.
            if(__deactivateRight==true){
                FC.rollover(__right,__rollover+"Right",0);
                //Right button event
                __right.bind("click",function(){
                    if (__active == true) {
                        return false 
                    }
	                __active = true  
                    rightButton();   
                    return false;
                });
                __deactivateRight=false;
            }

            
            //If the counter is above zero, then decrease counter and scroll to that amount
	        if(__counter>0){
	            __counter--;
	            __container.scrollTo( __itemClass+':eq('+__counter*__scrollAmount+')', 500, {axis:'x'});
	        }
	        //If the counter is zero, scroll to the beginning and de-activate the button
	        if(__counter==0){
	            FC.rollover(__left,__rollover+"Left",1);
	            __container.scrollTo( __itemClass+':eq(0)', 500, {axis:'x'});  
	        }
	        return false;
	    
	    });
	
    }
	
	
	/*
	var __max = Math.floor(__contentBoxes.length/__scrollAmount);
	__max = __max*__scrollAmount;

	//Make left rollover inactive
	FC.rollover(__left,__rollover+"Left",1);
	
	//Activate the right rollover only if there are more items than the scroll amount
	if(__contentBoxes.length<=__scrollAmount){
		FC.rollover(__right,__rollover+"Right",1);
	}
	else{
		FC.rollover(__right,__rollover+"Right",0);	
	}
	
	
	//Make sure the scroller is at the start
	__container.scrollTo( __itemClass+':eq('+0+')', 500, {axis:'x'});
	
	//If the amount of items is divisible by the scroll amount, then the max should be the scrollamount less
	if(__max==__contentBoxes.length){
		__max=__max-__scrollAmount;
	}
	
	
	//Left scroller button
	__left.bind("click keypress", function(){
		//If the current is more than the minimum
		if(__current>0){
			
			//Activate right rollever if there only if there are more items than the scroll amount
			if(__contentBoxes.length>__scrollAmount){
				FC.rollover(__right,__rollover+"Right",0);
			}
			//Scroll to the previous items
			__current = __current-__scrollAmount;
			__container.scrollTo( __itemClass+':eq('+__current+')', 500, {axis:'x'});	
		}
		
		//If the current is equal to the minimum, then disable the left rollover and activate the right rollover
		if(__current==0){
			FC.rollover(__left,__rollover+"Left",1);
			
			if(__contentBoxes.length>__scrollAmount){
				FC.rollover(__right,__rollover+"Right",0);
			}
		}

		
		return false;
	});
	

	//Right scroller button
	__right.bind("click keypress", function(){
		
		//If current is less than the max
		if(__current<__max){
			
			//If the max is reached, then disable the right rollover
			if(__current==(__max-__scrollAmount)){
				FC.rollover(__right,__rollover+"Right",1);
			}
			
			//Activate left rollover
			FC.rollover(__left,__rollover+"Left",0);
			
			//Scroll to the next results
			__current = __current+__scrollAmount;
			__container.scrollTo( __itemClass+':eq('+__current+')', 500, {axis:'x'});

		}
		
		return false;
	});*/

}


//Media Landing Region Load (for the region drop downs) ------------------------------------------
FC.regionLoad = function(){
   var __pageId = $(".MediaPageIdClass");
	var __right = $(".regions .other-formats a.next");
	var __left = $(".regions .other-formats a.previous");
	var __selector = $(".regions select");
	var __container = $(".regions .region")
	var __targ = $(".regions #other-formats");
	var __otherFormatsUrl = "/Templates/Private/Pages/Country/OurMediaByRegionForUI.aspx?";
	var __temp = $("#temp");
	var __submit = $(".regions input");
	var __waiting = document.createElement("img");
	__waiting.src="/images/colour5/waiting.gif";
	__waiting.style.margin = "50px 0 0 350px";
	
	//Hide submit button
	__submit.hide();
	
	//Disable the rollovers
	FC.rollover(__left,"FormatsLeft",1);
	FC.rollover(__right,"FormatsRight",1);
	
	//When the drop down changes value, get the QS of the URL and make an AJAX call.
	__selector.bind("change", function(){

		
		if(__selector[0].selectedIndex!=0){
			
			var __url = escape(__selector.val());
			__container.animate({height:"180px"},500,function(){
				
			__targ.append(__waiting);
															  
				$.ajax({
				   
					url: __otherFormatsUrl+"MediaPageIdForRegion="+ __pageId[0].value +"&r="+__url,
					cache: false,
					success: function(html){
	
							
							__targ.fadeOut("fast",function(){
	
								__targ.empty();
								__temp.append(html);

								__targ.append(__temp.find(".temp-regions").contents());
								__temp.empty();
								
								//Reactivate the scroller function
								FC.scroller({
									right : ".region .region-media a.next",
									left : ".region .region-media a.previous",
									container : ".region .region-media .scroller",
									amount : 3,
									items : ".region .region-media .scroller .content-box",
									itemClass : ".content-box",
									rollover : "Formats"
								});
								
								
									__targ.fadeIn("fast");
									reloadSifr();

							})
	
					}
				
				});
				
			});
		
		}

		
	});
	
};

//Media landing page AJAX calls
FC.mediaLanding = function(){
	
	var __formatsUsed = $(".formats-used ul.formats li a");
	var __formats = $("div.main .other-formats a");
	var __heroCont = $("div.main div.hero-container");
	var __hero = $("div.main div.hero");
	var __otherFormatsCont = $("div.main div.other-formats-container");
	var __otherFormats = $("div.main div.other-formats");
	var __heroTemp = document.createElement("div");
	var __formatsTemp = document.createElement("div");
	var __formatsUrl = "/Templates/Private/Pages/Country/FormatDetailListForUI.aspx";
	var __heroUrl = "/Templates/Private/Pages/Country/FormatDetailHeroForUI.aspx";
	var __listContainer = ".contentwrapper > ul";
	var __listItems = "li";
	var __listContainerWithHeight = ".formats-wrapper";
	var __waiting = document.createElement("img");
	__waiting.src="/images/colour5/waiting-alt.gif";
	__waiting.width="31";
	__waiting.height="31";
	__waiting.style.position = "absolute";
	__waiting.style.left = "350px";
	__waiting.style.top = "100px";
	__waiting.style.display="block";
	__waiting.id="waiting";
	
	
	$(__hero).attr('aria-live', 'polite').attr('aria-channel', 'main').attr('aria-atomic', 'true').attr('tabindex', '0');
	
	
	function callHero(url){
		
		if(url){
			
			$(__heroCont).append(__waiting);
			
			__hero.fadeOut("fast",function(){

				//Call the selected hero
				$.ajax({
					
					url:url,
					cache: false,
					success:function(html){
						
							$(__heroCont).find("#waiting").remove();				   
							$(__heroTemp).empty();
							$(__heroTemp).append(html);
							
							__hero.empty();
							
							var __contents = $(__heroTemp).find("#hero").contents();
							
							__hero.append(__contents);
							__hero.fadeIn("fast",function(){reloadHeroSifr();});

					}
					   
				});
			
			});
		
		}	
	}

	function callFormats(url){
		
		
		
		__otherFormats.fadeOut("fast",function(){
											   
			$(__otherFormatsCont).append(__waiting);								   
			//Call the other formats
			$.ajax({
			   
				url:url,
				cache: false,
				success: function(html){

						$(__otherFormatsCont).find("#waiting").remove();			   
						$(__formatsTemp).empty();
						$(__formatsTemp).append(html);								   
					
						__otherFormats.empty();
						
						var __contents = $(__formatsTemp).find("#formats .other-formats").contents();
						
						__otherFormats.append(__contents);
						
						__otherFormats.fadeIn("fast", function(){
							
							var __selectedFormat = __otherFormats.find("li a.selected");
							
							if(__selectedFormat.length>0){
								var __selectedFormatUrl = __selectedFormat.attr("href");
								__selectedFormatUrl = FC.getQS(__selectedFormatUrl);
								//__selectedFormatUrl = __selectedFormatUrl.split("&");
								callHero(__heroUrl+__selectedFormatUrl);
							}
							
						
							
							activateOtherFormats();
							CSBfleXcroll("formats-scroller");
							//if($(__listItems).length!=0){FC.setWidth(__listContainer, __listItems, __listContainerWithHeight, 115);} //set the width of the DIV
						});
						
						
					
	
				}
			});
			
		});
		
	}
	

	//Bind the calls to the right hand format links
	function activateFormats(){
		__formatsUsed.bind("click", function(){
			var __url = $(this).attr("href");
			__url = FC.getQS(__url);
			//__url = __url.split("&");
			callFormats(__formatsUrl+__url);
			return false;
											 
		});
	}
	activateFormats();
	
	
	//Bind the calls to the other formats links
	function activateOtherFormats(){
		__formats = $("div.main .other-formats a");
		__formats.bind("click", function(){
			var __url = $(this).attr("href");
			__url = FC.getQS(__url);
			callHero(__heroUrl+__url);
			
			__formats.removeClass("selected");
			$(this).addClass("selected");
			
			return false;								 
		});		
	}
	activateOtherFormats();

	

}

//Get Query String -----------------------------------------------
FC.getQS = function(url) {
    var start = url.indexOf("?");
    var end = url.length;
    url = url.substring(start, end);
    return url
}

//Get individuals ------------------------------------------------
FC.findName = function(o){

	var __button = o.button;
	var __input = o.input;
	var __target = o.target;
	var __inner = o.inner;
	var __url = "/Templates/Public/Pages/Country/Individuals.aspx";
	
	var __waiting = document.createElement("img");
	__waiting.src="/images/colour4/waiting.gif";
	__waiting.height="31";
	__waiting.width="31";
	__waiting.style.position="absolute";
	__waiting.style.height="31px";
	__waiting.style.width="31px";
	__waiting.style.left="300px";
	__waiting.style.top="20px";
	__waiting.style.margin="0";
	__waiting.id="waiting";
	
	__button.hide();
	
	var __peopleTemp = document.createElement("div");
	
	__input.bind("keyup", function(e){
		
		if($(this).val().length>2){
			
			var __qS = $(this).val();
			
			__inner.fadeOut("fast",function(){

				__target.append(__waiting);
			
				//Call list of people
				$.ajax({
				   
					url:__url+"?q="+__qS,
					cache: false,
					success: function(html){
						
						__target.find("#waiting").remove();
						
						$(__peopleTemp).empty();
						$(__peopleTemp).append(html);
						var __newStuff = $(__peopleTemp).find("ul");
						__inner.empty();
						__inner.append(__newStuff);
						__inner.fadeIn("fast");
						
					}
					
				});
			
			});
		
		}

	})
	

}

//Show/hide formats on homepage ------------------
FC.homeFormats = function(o) {

    var __targ = o.targ;
    var __inner = o.inner;
    var __button = o.button;
    var __closeButton = o.closeButton;
    var __state = 0;

    var __height = __targ.height();


    __targ.animate({ height: "0px" }, 0);
    __inner.animate({ opacity: 0 }, 0);


    __button.bind("click", function() {


        if (__state == 0) {
            __targ.animate({ height: __height }, 500, function() {
                __inner.animate({ height: __height }, 0);
                __inner.animate({ opacity: 1 }, 500);

            });
            __state = 1;
        }
        else {
            __inner.animate({ opacity: 0 }, 500, function() {
                __targ.animate({ height: "0px" }, 500);
            });
            __state = 0;
        }

        return false;


    });

    __closeButton.bind("click", function() {
        __inner.animate({ opacity: 0 }, 500, function() {
            __targ.animate({ height: "0px" }, 500);
        });
        __state = 0;
        return false;
    });
}

//Show/Hide browse on gallery pages
FC.gallery = function(o) {

    var __panel = o.panel;
    var __button = o.button;
    var __wrapper = o.wrapper;
    var __closeButton = o.closeButton;
    var __state = 1;



    __panel.animate({ opacity: 1 }, 0, function() {
        __wrapper.animate({ height: "228px" }, 0, function () {
            $("body").removeClass("js");
        });
    });


    __button.bind("click", function() {


        if (__state == 0) {
            __button.addClass("active");
            __wrapper.animate({ height: "228px" }, 500, function() {
                __panel.animate({ opacity: 1 }, 500);

            });
            __state = 1;
        }
        else {
            __panel.animate({ opacity: 0 }, 500, function() {
                __wrapper.animate({ height: "0px" }, 500, function() {
                    __button.removeClass("active");
                });
            });
            __state = 0;
        }
        return false;

    });


    __closeButton.bind("click", function() {
        __panel.animate({ opacity: 0 }, 500, function() {
            __wrapper.animate({ height: "0px" }, 500, function() {
                __button.removeClass("active");
            });
        });
        __state = 0;
        return false;
    });


}

FC.galleryBrowse = function(o) {

    var __inputs = o.inputs;
    var __state = 0;
    var __temp;

    __inputs.bind("click", function() {

        var __chk = $(this).attr("checked")

        if (__chk == true) {
            $(this).parent().addClass("selected");
            $(this).parent().find("input").attr("checked", "checked");
        }
        else {
            $(this).parent().removeClass("selected");
            $(this).parent().find("input").attr("checked", "");
            $(this).parent().find("li").removeClass("selected");
        }

    });

}

//Case study/gallery page AJAX calls (when checkboxes are clicked the content updates automatically)
FC.galleryLanding = function () {

    var __galleryUrl = "gallery-browse.html?qs=";
    var __checkboxes = $(".gallery-browse input:checkbox");
    var __temp = $("#temp");
    var __listContainer = $(".grid");

    /* scroller width call */
    var __listItems = ".g-panel";
    var __listContainerWithHeight = ".grid";

    var __extendedQS = "";

    __checkboxes.bind("click", function () {

        alert("checked")


        // create the extended query string
        $(__checkboxes).each(function () {
            if (this.checked) {
                __extendedQS = __extendedQS + "&amp;qs=" + $(this).val();
            }

        });

        //Call the other formats
        $.ajax({

            url: __galleryUrl + $(this).val() + __extendedQS,
            cache: false,
            success: function (html) {
                __extendedQS = "";
                __listContainer.fadeOut("fast", function () {
                    __listContainer.empty();
                    __temp.append(html);

                    __listContainer.fadeIn("fast", function () {

                        __listContainer.append($("#temp ul.imgCont"));

                        CSBfleXcroll("formats-scroller");
                        //if ($(__listItems).length != 0) { FC.setWidth(__listContainerWithHeight, __listItems, __listContainerWithHeight, 239); } //set the width of the DIV

                    });

                });

            }


        });

    });


}

// nest document.ready() calls in here if jQuery is included FC.$ is jQuery
$(function() {

    //Add JS class to body for all pages
    $("body").addClass("js");

    //Navigation rollover for all pages
    if ($(".navigation").length != 0) {
        FC.navRollover({
            element: ".navigation a",
            theClass: "nobg"
        });
    }

    //Setup rollover objects for all pages
    FC.rollovers();
    
    //Press archive for Press Centre
    if ($(".archive").length != 0) {
        FC.pressArchive();
        FC.archiveRollover({
            element: ".months li",
            element2: ".years li",
            theClass: "hover"
        });
    }


    
    if ($(".helpbutton").length != 0) {
        FC.help({
            element: ".helpbutton",
            elementToFind: ".help",
            theClass: "hidden"
        });
    }


    if ($(".regions").length != 0) {
        //FC.setWidth(".flexcroll > ul", "li", ".formats-wrapper", 115);
    }

    if ($(".grid").length != 0 && $(".gallery-pagination").length == 0) {
        //FC.setWidth(".grid", ".g-panel", ".grid", 239);
    }

    if ($(".related-campaigns").length != 0) {
        //FC.setWidth(".related-campaigns .wrapper", ".campaign", ".related-campaigns", 230);
    }
    
    //Home page scroller
    if ($(".home-wrapper").length != 0) {
        FC.scroller({

            right: ".home-wrapper ul.next li a",
            left: ".home-wrapper ul.prev li a",
            container: ".home-wrapper .scroller",
            amount: 3,
            items: ".home-wrapper .scroller ul li",
            itemClass: ".photo",
            rollover: "Home"

        });
    }
    
    //Inspire me landing page - Gallery scroller
    if ($(".gallery").length != 0) {
        FC.ajaxScroller({

            right: ".gallery .panels a.next",
            left: ".gallery .panels a.previous",
            container: ".gallery .panels .wrapper",
            amount: 5,
            items: ".gallery .panels .panel",
            itemClass: ".panel",
            rollover: "Gallery"

        });
    }

	//Search results scroller
	if($("div.images .scroller").length!=0){
		FC.scroller({
		
			right : ".images ul.next a",
			left : ".images ul.prev a",
			container : ".images .scroller",
			amount : 4,
			items : ".images .scroller ul li",
			itemClass : "li",
			rollover : "Images"
		
		});
	}    
    
    //Our Media landing page Regions AJAX
    if ($(".regions").length != 0) {
        FC.regionLoad();
    }

    //Our Media landing page formats AJAX
    if ($(".other-formats").length != 0) {
        FC.mediaLanding();
    }
    
    //Contact us people search
	if($(".search-hint").length!=0){
		FC.findName({
			input : $(".search-hint input.text"),
			target : $("div.result .padding"),
			button : $(".search-hint input.submit"),
			inner : $("div.result .padding .result-inner")
		});
	}
    
    //Homepage formats show/hide
    if ($(".home-formats").length != 0) {
        FC.homeFormats({
            targ: $(".home-formats"),
            inner: $(".home-formats-list"),
            button: $(".button.left.colour5"),
            closeButton: $(".home-formats h2 a.close")
        });
    }
        
    //Homepage - set the height of the homepage carousel container
    /*if ($(".home-inner").length != 0) {
        $(".home-inner").css("height", "360px");
    }*/

    //Case study/gallery AJAX content pagination
    if ($(".gallery-pagination").length != 0) {
        FC.pagination();
    }
    
    
    //Case study/gallery browse options (checkboxes)
    if($(".gallery-browse").length!=0){
        
        
		//FC.galleryLanding();
		
		//Show.hide browse options
		FC.gallery({
            panel : $(".gallery-browse"),
            wrapper : $(".gallery-browse-wrapper"),
            button : $(".browse-button"),
            closeButton : $(".close-gallery-js a")
        });
            
        //Browse options - "all" checkboxes		
		FC.galleryBrowse({
            inputs : $(".gallery-browse-scroll input")	
        });
		
	}
	
	//PNG Fix for all pages
    FC.pngFix("../images/bg/clear.gif");
});


function clickButton(e, buttonid) {

    var evt = e ? e : window.event;

    var bt = document.getElementById(buttonid);

    if (bt) {

        if (evt.keyCode == 13) {

            bt.click();

            return false;

        }

    }

}
