//Jquery - when page load
$(document).ready(function() {


    //add css to include when js enabled
    if (!($.browser.opera)) {
        $("link[href$='dummy.css']").attr('href', '/templates/default/css/system/dynamic.css');
    } else {
        loadCSS('/templates/default/css/system/dynamic.css');
    }

    //setting action tag
    var oldAction = $('#aspnetForm').attr('action');
    if (oldAction.indexOf('404.aspx') >= 0) {
        $('#aspnetForm').attr("action", "/" + oldAction);
    }



    //font replacing
    Cufon.replace('#featureCol h3, #featureCol h2, #featureCol .featureBox h3');
    Cufon.replace('.oneCol h1, .oneCol h2');
    Cufon.replace('dl.glossaryList dt span, .singleLetterQuestion, .singleLetterAnswer');

    //auto fill search field
    if ($("fieldset.searchForm .Search").val() == "")
        autoFill($("fieldset.searchForm .Search"), "Search");

    if ($(".searchToolbar .form input:text").val() == "")
        autoFill($(".searchToolbar .form input:text"), "Enter keyword(s)");

    //new window
    $(function() {
        $('a.newWindow').click(function() {
            window.open(this.href, "width=700px", "height=300px");
            return false;
        });
    });

    //print link 
    $('#featureCol').prepend('<a class="print" href="#"><span class="icon print">Print page</span> Print page </a>');
    $('#featureCol a.print').click(function() {
        window.print();
        return false;
    });

    //slide show
    sliding(("h3.directoryButton"));
    sliding(("dt.questions"));

    //blogs accordion
    $('.blogs').accordion({
        header: 'div.summary',
        active: 0,
        alwaysOpen: false,
        autoheight: false,
        animated: 'easeslide'
    });


    /*------- homepage animations --------*/
    //homepage flash
    if ($("body.mainHome").length) {

        $('.feature').after('<div class="featureFlash"><div class="featureFlashInner"></div></div><br />');
        $('.featureFlashInner').flash(
    {
        src: 'flash/HomeFlash.swf',
        width: 956,
        height: 415,
        wmode: 'transparent'
    },
    {
        version: 8
    }
    );
        $(".featureFlashInner").mousemove(function(e) {

            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            if (y < 313) {
                $(".featureFlash").css("overflow", "hidden");
                //alert("yo");
            } else {
                $(".featureFlash").css("overflow", "visible");
            }
        });


        //homepage show controls
        //create slideshow if num of splash screens greater than 1
        if ($("li.newsItem").size() > 1) {

            //number of splash screens to display
            var numItems = $("li.newsItem").size();
            //width of each element
            var itemWidth = 650;
            if ($.browser.msie && $.browser.version == "6.0") {
                itemWidth = 640;
            }

            //total width of carousel container
            var totalWidth = numItems * itemWidth;
            //margin when at last item
            var endOfLine = (totalWidth - itemWidth) * -1 + "px";



            $("body.mainHome .latestItems").css("overflow", "hidden");
            $(".latestItems ul").css("width", totalWidth + 30);

            //initial setup
            $(".summary").append('<a href="" class="previous">previous</a>');
            $(".summary").append('<a href="" class="next">next</a>');
            var marginCurr = $(".latestItems ul").css("margin-left");
            if (marginCurr == "0px") {
                $(".summary .previous").addClass("disabled");
            }
            var animating = false;

            //previous button function
            $(".summary .previous").click(function() {

                //remove any disabled classes
                $(".summary .next").removeClass("disabled");

                //only do if button not disabled and not animating
                if (!$(this).hasClass(".disabled") && !animating) {

                    //indicate that animation is happening
                    animating = true;

                    //reset margin
                    marginCur = $(".latestItems ul").css("margin-left");
                    var marginNew = (marginCur.replace("px", ""));
                    marginNew = parseFloat(marginNew) + itemWidth;
                    //animate thumbnails
                    $(".latestItems ul").animate({ marginLeft: marginNew }, 1000, null, function() { animating = false; });
                    //add disabled class if first item
                    if (marginNew == 0) {

                        $(".summary .previous").addClass("disabled");
                    }
                } //end button disabled

                return false;

            }); //end previous button click

            //next button function
            $(".summary .next").click(function() {

                //remove any disabled classes
                $(".summary .previous").removeClass("disabled");



                //only do if button not disabled
                if (!$(this).hasClass(".disabled") && !animating) {

                    //indicate that animation is happening
                    animating = true;

                    //reset margin
                    marginCur = $(".latestItems ul").css("margin-left");

                    var marginNew = (marginCur.replace("px", ""));
                    marginNew = parseFloat(marginNew) - itemWidth + "px";

                    //animate thumbnails
                    $(".latestItems ul").animate({ marginLeft: marginNew }, 1000, null, function() { animating = false; });
                    //add disabled class if last item
                    if (marginNew == endOfLine) {
                        $(".summary .next").addClass("disabled");
                    }
                }

                return false;

            });

        }
    } //end homepage






    /*------- visual styles e.g. buttons hover states --------*/
    $(".clips li:even").addClass("even");
    $('.submit_btn').hover(
        function() { // Change the input image's source when we "roll on"
            $(this).attr({
                src: '/images/interface/submit_btn_hover.gif'
            });
        },
        function() { // Change the input image's source back to the default on "roll off"
            $(this).attr({
                src: '/images/interface/submit_btn.gif'
            });
        }
        );
    $('.searchbox .submit_btn, .searchToolbar .submit_image').hover(
        function() { // Change the input image's source when we "roll on"
            $(this).attr({
                src: '/images/interface/btn_search_hover.gif'
            });
        },
        function() { // Change the input image's source back to the default on "roll off"
            $(this).attr({
                src: '/images/interface/btn_search.gif'
            });
        }
        );

    $('.send_btn').hover(
        function() { // Change the input image's source when we "roll on"
            $(this).attr({
                src: '/images/interface/send_btn_hover.gif'
            });
        },
        function() { // Change the input image's source back to the default on "roll off"
            $(this).attr({
                src: '/images/interface/send_btn.gif'
            });
        }
        );



    //landing page animation
    featureSlide(("#contentCol .feature .links ul li.animate"));
    $("#contentCol .feature .links li div").click(function(e) {
        e.stopPropagation();
    });
    //indent list items
    indentList();


    /*------- styles for image library --------*/
    //Modal box for image library 
    if (!$(".keywordLink").length) {
        $(".searchbox div.keywords").before("<a href=\"#\" class=\"button\"><span>Add keywords</span></a>");
    }

    $(".searchbox .button").click(function() {
        $(".imageLibrary div.keywords").addClass("keywordWindow").fadeIn(500).removeClass("js_hide");
        $(".keywordWindow").append('<a href="#" class="modalClose">close</a>')


        $("a.modalClose").click(function() {
            $(".keywordWindow").fadeOut(500).addClass("js_hide");
        });
        return false;
    });
    var createButton = true;
    $(".keywordCheckbox").click(function() {
        if (createButton == true) {
            $(".keywordWindow").append("<a class='button completeSearch' href='#'><span>Complete search</span></a>")
            $(".button").addClass("buttonOn")
            $(".completeSearch").removeClass("buttonOn")
            $(".submit_btn").attr({ src: '/images/interface/btn_search_hover.gif' })
            createButton = false
        }
    })
    $(".completeSearch").live("click", function(e) {

        $(".submit_btn").trigger('click')
    })


    $(".imageResults .searchToolbar .form ol li .button").click(function() {
        if (!$(".modalClose").length) {

            $(".keywords").slideDown().removeClass("js_hide");
            $(".keywords").append('<a href="#" class="modalClose">close</a>');
            $("a.modalClose").click(function() {

                $(".keywords").slideUp(500).addClass("js_hide");

                $(".modalClose").remove();
            });
        }
        return false;
    });


    //modal box - used to load images
    $(".window").colorbox({
        width: "814px", //was 800px
        height: "560px" // was 480px 
    });

    //alert for downloads
    $("p.download a.last").click(function() {
        var msg;
        msg = "This is an extrmeely large file and may take a while to download. It is only appropriate for use in high quality print publications."
        + "\n" + "Would you like to continue?";
        var agree = confirm(msg);
        if (agree)
            return true;
        else
            return false;
    });


    /* --- video player --------*/
    if ($(".videoPlayer .clips li").size() > 1) {
        $(".clips").easySlider({
            prevText: 'Previous',
            nextText: 'Next',
            vertical: true,
            continuous: false,
            controlsShow: true,
            controlsBefore: '',
            controlsAfter: '',
            controlsFade: false,
            auto: false
        });
    }

    //create slideshow if num of videos greater than 6
    if ($("ul.thumbs li").size() > 6) {


        //really bad wap of wrapping elelments in divs
        var set1 = $(".splash ul li:lt(6)");  
        var set2 = $(".splash ul li:lt(12):gt(5)"); 
        var set3 = $(".splash ul li:lt(18):gt(11)");
		$(set1).wrapAll('<div class="splashContainer">')
		$(set2).wrapAll('<div class="splashContainer">');
        $(set3).wrapAll('<div class="splashContainer">');

        //number of splash screens to display
        var numSplash = $("ul.thumbs li").length;
        numSplash = Math.ceil(numSplash / 6);
        //total width of carousel container
		
        var totalWidth = numSplash * 720 - 720;
        //margin when at last item
        var endOfLine = (totalWidth) * -1 + "px";
        //alert(endOfLine);

        //initial setup
        $(".splash").append('<a href="" class="previous">previous</a>');
        $(".splash").append('<a href="" class="next">next</a>');
        var marginCurr = $(".thumbsContainer").css("margin-left");
        if (marginCurr == "0px") {
            $(".splash .previous").addClass("disabled");
        }

        //previous button function
        $(".splash .previous").click(function() {
            //remove any disabled classes
            $(".splash .next").removeClass("disabled");

            //only do if button not disabled
            if (!$(this).hasClass(".disabled")) {

                //reset margin
                var marginCur = $(".thumbsContainer").css("margin-left");
		
                var marginNew = (marginCur.replace("px", ""));
                marginNew = parseFloat(marginNew) + 720;
                //animate thumbnails
                $(".thumbsContainer").animate({
                    marginLeft: marginNew
                }, 1000);
                //add disabled class if first item
				/*
                if (marginCurr == "0px") {
                    $(".splash .previous").addClass("disabled");
                }
				*/
            } //end button disabled
            return false;

        }); //end previous button click

        //next button function
        $(".splash .next").click(function() {

            //remove any disabled classes
            $(".splash .previous").removeClass("disabled");

            //only do if button not disabled
            if (!$(this).hasClass(".disabled")) {
                //reset margin
                marginCur = $(".thumbsContainer").css("margin-left");
                var marginNew = (marginCur.replace("px", ""));
                marginNew = parseFloat(marginNew) - 720 + "px";
                //animate thumbnails
                $(".thumbsContainer").animate({
                    marginLeft: marginNew
                }, 1000);
                //add disabled class if last item
                if (marginNew == endOfLine) {
                    $(".splash .next").addClass("disabled");
                }
            }

            return false;
        });

    }


    $(".splash ul li").click(function() {
        //set current clip to display in left col
        var currPosition = $(this).parents("ul").find("li").index(this);
        var heightofClip = ($(".videoPlayer .clips li").css("height").replace("px", ""));
        var setMargin = ((currPosition * heightofClip) * -1) + "px";
        $(".videoPlayer .player").show();
        $(".clipsContainer .clips ul").css("margin-top", setMargin);
        $(".splash").fadeOut("2000");
        $(".clipsContainer").fadeIn("2000").removeClass("hide");

        return false;
    });

    $(".button").click(function() {
        $(".clipsContainer").fadeOut("slow");
        //$(".videoPlayer .player").fadeOut();
        $(".splash").fadeIn("slow");

    });

    $(".splash ul li").hover(
        function() {
            $(this).find("div p").slideDown().removeClass("noDisplay");
        },
        function() {
            $(this).find("div p").slideUp().addClass("noDisplay");
        }
        );



    //adds tooltip to links with class tooltip
    tooltip();

	var wrapperHeight = $("#wrapperOuter").height();
    var windowHeight = $(window).height();
    if (wrapperHeight < (windowHeight + 10)) {
        footerPadding = windowHeight - wrapperHeight;
        $(".copyright").css("paddingBottom", footerPadding + 79);
    }
	
	// Sporting champions
	$('#champions-wrap').addClass('js');
	$('#champions-wrap .champions-overview').reorder();
	//Pagination
	var showPerPage = 6;
	var numberItems = $('#champions-wrap .champions-overview').children('li').size();
	var numberPages = Math.ceil(numberItems/showPerPage);
	var navigationHtml = '<div class="title"><ul>';
	var currentLink = 0;
	while(numberPages > currentLink){
		navigationHtml += '<li><a href="javascript:goToPage(' + currentLink +')">'+ (currentLink + 1) +'</a></li>';
		currentLink++;
	}
	navigationHtml += '</ul></div>';
	$('#champions-wrap').prepend(navigationHtml);
	$('#champions-wrap .title li:first').addClass('active');
	$('#champions-wrap .title a').click(function(){
		$('#champions-wrap .title li').removeClass('active');
		$(this).parent('li').addClass('active');
	});

	//Hide elements
	$('#champions-wrap .champions-overview').children().css('display','none');
	$('#champions-wrap .champions-overview').children().slice(0, showPerPage).css('display','block');

});
// end document ready

/* ---------- Functions -------- */



//auto fill search field
function autoFill(id, v) {
    $(id).attr({
        value: v
    }).focus(function() {
        if ($(this).val() == v) {
            $(this).val("").css({
                color: "#333"
            });
        }
    }).blur(function() {
        if ($(this).val() == "") {
            $(this).val(v);
        }
    });

}

//QA toggle
function sliding(id) {
    $(id).click(function() {
        //show next sibling
        $(this).toggleClass("open").next().slideToggle("fast");
        return false;
    });
}

// Landing page slider
function featureSlide(id) {
    $(id).click(function() {
        if (!$(this).hasClass("open")) {
            $(this).siblings().fadeOut("fast");
            $("#contentCol .landing .links").css({
                height: "260px",
                backgroundImage: "url(/../images/interface/grey_transparency_dark_bg.png)",
                backgroundPosition: "left bottom"
            });

            //target ie
            //alert("The browser version is: <span>" + jQuery.browser.version + "</span>");
            if ($.browser.msie) {
                version = $.browser.version;
                //target ie6
                if (version == "6.0") {
                    $("#contentCol .feature .links").css({
                        backgroundColor: "#253037",
                        filter: "alpha(opacity=80)"
                    });
                    $("#contentCol .feature .links li a").css({
                        filter: "alpha(opacity=100)"
                    });
                }
            }
            //set newWidth
            if ($.browser.msie && $.browser.version <= 6) {
                var newWidth = "525px";
            } else {
                newWidth = "515px";
            }

            $("#contentCol .feature .links").animate({
                width: newWidth,
                backgroundPosition: "-30px bottom"
            }, 400)
            $(this).children("div").fadeIn(1000).removeClass("js_hide");
            $("#contentCol .feature .links").prepend('<a href="#" class="js_close">Close</a>');
            $(this).addClass("open");

            //close
            $('#contentCol .feature .links .js_close, #contentCol .feature .links h2.close a').click(function() {

                // return to default values
                $("#contentCol .feature .links .js_close").remove();
                $("#contentCol .feature .links li").show();
                $('#contentCol .feature .links div').hide();
                $("#contentCol .feature .links").css({
                    width: "",
                    backgroundPosition: "",
                    backgroundImage: ""
                });

                /* browser bug fixes */
                if ($.browser.msie) {
                    version = $.browser.version;
                    //target ie6
                    if (version == "6.0") {
                        $("#contentCol .feature .links").css({
                            backgroundColor: "",
                            filter: "alpha(opacity=100)"
                        });
                    } //end ie 6

                    //target ie7
                    if (version == 7) {
                        if (!$("li:first-child").hasClass("open")) {
                            $("#contentCol .feature .links ul:first li:first-child").css("paddingLeft", "15px");
                            $("#contentCol .feature .links ul li ul li").css("paddingLeft", "");
                        }
                        $("#contentCol .feature .links").css({
                            backgroundColor: "transparent",
                            filter: ""
                        });
                    } // end ie7
                }

                //remove open class
                $('li.open').removeClass("open");
                //re-indent
                indentList();

                return false;
            }); // end close button

        }
        return false;
    });
}

//landing page arrow indents
function indentList() {
 var setMargin = 10;
    $('#contentCol .feature .links li.animate').each(function(i) {
		
        setMargin = setMargin + 5;
        $(this).css("margin-left", setMargin + "px");
    });
	

}

//Randomise sporting champions
$.fn.reorder = function() {
	function randOrd() { return(Math.round(Math.random())-0.5); }
	return($(this).each(function() {
		var $this = $(this);
		var $children = $this.children();
		var childCount = $children.length;
		if (childCount > 1) {
			$children.remove();
			var indices = new Array();
			for (i=0;i<childCount;i++) { indices[indices.length] = i; }
			indices = indices.sort(randOrd);
			$.each(indices,function(j,k) { $this.append($children.eq(k)); });
		}
	}));
}


/* Tooltip - written by Alen Grakalic (http://cssglobe.com)
* for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
*/
this.tooltip = function() {
    /* CONFIG */
    xOffset = 10;
    yOffset = 20;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result
    /* END CONFIG */
    $("a.tooltip").hover(function(e) {
        this.t = this.title;
        this.title = "";
        $("body").append("<p id='tooltip'>" + this.t + "</p>");
        $("#tooltip")
        .css("top", (e.pageY - xOffset) + "px")
        .css("left", (e.pageX + yOffset) + "px")
        .fadeIn("fast");
    },
    function() {
        this.title = this.t;
        $("#tooltip").remove();
    });
    $("a.tooltip").mousemove(function(e) {
        $("#tooltip")
        .css("top", (e.pageY - xOffset) + "px")
        .css("left", (e.pageX + yOffset) + "px");
    });
};

var loadCSS = function(file) {
    var link = document.createElement('link');
    link.href = file;
    link.rel = 'stylesheet';
    link.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(link);
};


//Pagination for Sporting champions
function goToPage(pageNum){
	var showPerPage = 6;
    startFrom = pageNum * showPerPage;
	EndOn = startFrom + showPerPage;
	$('#champions-wrap .champions-overview').children().css('display','none').slice(startFrom,EndOn).css('display','block');
}
