///<reference path="jquery-1.2.6-vsdoc.js" />

var headlineRotateTime = 7000;
var newsExpanded = false;

$(document).ready(function() {

    rotateTimer = setInterval("headline_rotate()", headlineRotateTime);
    clearInterval(rotateTimer);
    workTimer = setInterval("work_rotate()", 8000);
    clearInterval(workTimer);
    $('#environment').append('<div id="loadingdiv"></div>');

    if ($.browser.msie) {

        //$('#newsmain').css({ "overflow": "auto" });
    }

    loadnews();                                                             //instantiate the news panel data

    $('#content').wrap('<div id="content-wrapper"></div>');
    $('#content').livequery(function() {
        //$('#content').css({ left: "0px", bottom: "0px",padding:"0px",height:"400px",width:"634px" });
    });


    $('#hide').hide();                                                      //Hide the "hide" button in the news panel (leaving only "show more" visible)

    $("#navpanel").css({ opacity: "0", left: "860px" });
    $("#content_slot").css({ opacity: "0", left: "1060px" });
    $("#news_slot").css({ opacity: "0", left: "1460px" });
    $("#content-wrapper").hide();
    $("#newspanel").css({ height: "0px" });
    $("#content_reflection").css({ height: "0px" });
    $("#news_reflection").css({ height: "0px" });
    $("#footer").css({ opacity: "0", left: "1860px" });                     //When document is ready, hide the page elements...

    $("#loadingdiv").fadeIn('fast');
    var i = new Image();
    i.onload = function() {
        $("#navpanel").css({ "background": "url(images/navpanel.gif) no-repeat 0 0" });
        $("#loadingdiv").fadeOut('fast');
        $("#navpanel").animate({ opacity: "1", left: "19px" }, "slow");
        $("#footer").animate({ opacity: "1", left: "610px" }, 700);
        $("#content_slot").animate({ opacity: "1", left: "161px" }, "slow", function() {
            $("#content_reflection").animate({ height: "100px" }, 1200);
        });
        $("#news_slot").animate({ opacity: "1", left: "138px" }, "slow", function() {
            if (!newsExpanded) $("#newspanel").animate({ height: "110px" }, 700);
            $("#news_reflection").animate({ height: "53px" }, 700);
        });
    };
    i.src = "images/navpanel.gif";                                                                     //...then animate them into place

    /* LINK MOUSE BEHAVIOURS */

    $("a").hover(function() {
        $(this).css({ "color": "#94c733" });
    },
    function() {
        $(this).css({ "color": "" });
    });

    $(".header-cell").hover(function() {
        $(this).css({ "color": "#94c733" });
    },
    function() {
        $(this).css({ "color": "" });
    });

    $("#showmore").css({ "display": "block" }).hover(function() {
        $(this).css({ "color": "#94c733" });
    },
    function() {
        $(this).css({ "color": "" });
    });

    $("#hide").hover(function() {
        $(this).css({ "color": "#94c733" });
    },
    function() {
        $(this).css({ "color": "" });
    });

    $('.pagebutton')
    .livequery('mouseover', function() {
        $(this).attr('src', "images/pagelink_hover.gif");
    })
    .livequery('mouseout', function() {
        $(this).attr('src', "images/pagelink.gif");
    });

    $('.nextpagebutton')
    .livequery('mouseover', function() {
        $(this).attr('src', "images/pagelink_next_hover.gif");
    })
    .livequery('mouseout', function() {
        $(this).attr('src', "images/pagelink_next.gif");
    });

    $('.prevpagebutton')
    .livequery('mouseover', function() {
        $(this).attr('src', "images/pagelink_prev_hover.gif");
    })
    .livequery('mouseout', function() {
        $(this).attr('src', "images/pagelink_prev.gif");
    });

    $('.careersbutton')
    .livequery('mouseover', function() {
        $(this).attr('src', "images/careers_button_hover.gif");
    })
    .livequery('mouseout', function() {
        $(this).attr('src', "images/careers_button.gif");
    });

    $(".workbutton").click(function() {
        if (!needToConfirm) $(".submenu").slideDown(200);
    });                                                                     // When user clicks on "workbutton", slides in elements with the "submenu" class 

    $(".hidesubmenu").click(function() {
        $(".submenu").slideUp(200);
    });                                                                     // When user clicks on any element with the class "hidesubmenu", hide the elements with the "submenu" class 

    $(".minimised").livequery('click', function() {
        if ($("#newsheader").is(".minimised")) expandNews();
    });


    $(".expanded").livequery('click', function() {
        //$('#news_shower').hide("slide", { direction: "down" }, 300, function() { });
        minimizeNews();

    });

    /************* PAGE APPEAR BEHAVIOUR *******************/
    var firstLoad = true;
    var linktype = "none";
    var pslide = true;
    var cslide = true;
    var careersloaded = false;                                                     // Some variables to make this all work

    function pageload(hash) {// This is the main page appearance behaviour - whenever a link is clicked it comes in here to figure out what to do
        clearInterval(rotateTimer);
        clearInterval(workTimer);
        $("#majorimageCover").stop();
        $(".chapterlink").removeClass("current");
        if ($("#newsheader").is(".expanded")) { if (hash.split('_')[0] != 'news') minimizeNews(); }

        if (hash) {
            if (firstLoad) {
                $("#content_slot").animate({ opacity: "1", left: "161px" }, "slow", function() {
                    $("#content_reflection").animate({ height: "100px" }, 1200);
                });
                firstLoad = false;
            }

            switch (hash) {//These are all of the cases that handle each of the different page types - if you want to create a new page simply add another "case" to this switch statement
                case 'work':
                    $("#workb").addClass('current'); //This is what gives the current link it's green highlight - current class is defined in alloy.css
                    if ($(".submenu").is(':hidden')) $(".submenu").slideDown(200);
                    pslide = true; //needs to slide in sub pages
                    personloaded = false; //
                    if (cslide) {
                        loadPage(hash, true, 0, true); //this does the slide out to load a new section 
                        cslide = false;
                    } else {
                        switchPage(hash, true, 0, true); //this does a simple fade to another page in the same section
                    }
                    careersloaded = false;
                    break;

                case 'product': case 'interaction': case 'strategy':
                    $("#workb").addClass("current");
                    $("#" + hash + "b").addClass('current');
                    var inum;
                    if (hash == 'product') inum = 1; if (hash == 'interaction') inum = 2; if (hash == 'strategy') inum = 3;
                    if ($(".submenu").is(':hidden')) $(".submenu").slideDown(200);
                    pslide = true;
                    personloaded = false;
                    if (cslide) {
                        loadPage(hash, true, inum, true);
                        cslide = false;
                    } else {
                        switchPage(hash, true, inum, true);
                    }
                    careersloaded = false;
                    break;

                case 'awards':
                    $("#workb").addClass('current');
                    if ($(".submenu").is(':hidden')) $(".submenu").slideDown(200);
                    pslide = true;
                    personloaded = false;
                    if (cslide) {
                        loadPage(hash, true, 4, false);
                        cslide = false;
                    } else {
                        switchPage(hash, true, 4, false);
                    }
                    careersloaded = false;
                    break;

                case 'testimonials':
                    $("#workb").addClass('current');
                    if ($(".submenu").is(':hidden')) $(".submenu").slideDown(200);
                    pslide = true;
                    personloaded = false;
                    if (cslide) {
                        loadPage(hash, true, 5, true);
                        cslide = false;
                    } else {
                        switchPage(hash, true, 5, true);
                    }
                    careersloaded = false;
                    break;

                case 'people':
                    $("#peopleb").addClass('current');
                    $(".pdiv").css({ 'background-position': '0px 0px' });
                    if ($(".submenu").is(':visible')) $(".submenu").slideUp(200);
                    cslide = true;
                    pslide = true;
                    careersloaded = false;
                    if (personloaded) {
                        unloadperson();
                    } else {
                        personloaded = true;
                        $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
                            $('#loadingdiv').fadeIn('fast');
                            $("#content-wrapper").load("people.html #content", '', function() {
                                loadpeople(false, '');
                            });
                        });
                    }
                    break;

                case 'client':
                    $("#clientb").addClass('current');
                    if ($(".submenu").is(':visible')) $(".submenu").slideUp(200);
                    pslide = true;
                    cslide = true;
                    personloaded = false;
                    careersloaded = false;
                    $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
                        $('#loadingdiv').fadeIn('fast');
                        $("#content-wrapper").load("client.html #content", '', function() {
                            var i = new Image();
                            i.onload = function() {
                                $('#loadingdiv').fadeOut('fast');
                                $('#content-wrapper').show("slide", { direction: "down" }, 300);
                            }
                            i.src = $("#majorimage").attr('src');
                        });
                    });
                    break;

                case 'contact': case 'careers': case 'connections': case 'createnews':
                    if (hash == "contact") $("#contactb").addClass('current');
                    else if (hash == "careers") $("#careersb").addClass('current');
                    else if (hash == "connections") $("#connectionsb").addClass('current');

                    if ($(".submenu").is(':visible')) $(".submenu").slideUp(200);
                    loadPage(hash);
                    pslide = true;
                    cslide = true;
                    personloaded = false;
                    break;

                case 'index': case 'home':
                    pslide = true;
                    cslide = true;
                    personloaded = false;
                    careersloaded = false;
                    loadPage('home');
                    rotateTimer = setInterval("headline_rotate()", headlineRotateTime);
                    break;

                case 't3future':
                    pslide = true;
                    cslide = false;
                    personloaded = false;
                    careersloaded = false;
                    loadPage('t3mail');
                    break;

                default:
                    if (hash.split('_')[0] == 'pitch') {
                        $("#pitchb").addClass("current");
                        if (pslide) {

                            $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
                                $('#loadingdiv').fadeIn('fast');
                                $("#content-wrapper").load("pitch_0.html .content#" + hash.split('_')[1], '', function(data) {
                                    if (!$('#navstrip').length > 0) addNav($(data).find('.content').length, hash.split('_')[1], false, 'pitch_0');
                                    var i = new Image();
                                    i.onload = function() {
                                        $("#loadingdiv").fadeOut('fast');
                                        $('#content-wrapper').show("slide", { direction: "down" }, 300);
                                    }
                                    i.src = $("#majorimage").attr('src');
                                });
                            });
                            pslide = false;
                        } else {
                            $(".content").fadeOut("fast", function() {
                                subSwitch('pitch_0', hash.split('_')[1]);
                            });
                        }
                        cslide = true;
                        personloaded = false;
                    } else if (hash.split('_')[0] == 'news') {
						$.ajax({ type: "GET", url: "news-views/stories.xml", dataType: "xml", success: function(xml) {
							$(xml).find('story').each(function(ind) {
								storiesXML = xml;
							});
						}
						});

						loadStory(hash.split('_')[1], storiesXML);
                        if ($(".submenu").is(':visible')) $(".submenu").slideUp(200);
                        $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
                            $('#loadingdiv').fadeIn('fast');
                            $("#content-wrapper").load("home.html #content", '', function(data) {
                                $('<img src="images/home' + currentWork + '.jpg" id="majorimage" alt="Welcome to The Alloy. We build profitable brands through Product Design, Interaction Design and Innovation Strategy "/>').prependTo('#content-image');
                                var i = new Image();
                                i.onload = function() {
                                    $("#loadingdiv").fadeOut('fast');
                                    $('#content-wrapper').show("slide", { direction: "down" }, 300);
                                }
                                i.src = "images/home1.jpg";
                            });
                        });
                        pslide = true;
                        cslide = true;
                        personloaded = false;
                        rotateTimer = setInterval("headline_rotate()", headlineRotateTime);

                        $("#newspanel").stop(true, true);
                        newsExpanded = true;
                        if ($("#newsheader").is(".minimised")) { expandNews(); }

                    } else if (hash.split('-')[0] == 'case') {
                        $("#workb").addClass("current");
                        if ($(".submenu").is(':hidden')) $(".submenu").slideDown(200);
                        if (cslide) {
                            $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {//animation that hides main content box
                                $('#loadingdiv').fadeIn('fast');
                                $("#content-wrapper").load('case-studies/' + hash.split('/')[1] + "/case_0.html .content#" + hash.split('_')[1], '', function(data) { //'case-studies/' + hash.split('/')[1] + "/case_0.html - this finds the right client folder and loads its html file - .content#" + hash.split('_')[1] - this goes through that file and finds the content with the case number we're looking for - so if we load page case-studies/bt/case_2 it looks for the div with id="2" and loads the content from there
                                    if (!$('#navstrip').length > 0) addNav($(data).find('.content').length, hash.split('_')[1], true, $(data).find('#0 #content-header').text());
                                    if ($("#majorimage").length > 0) {
                                        var i = new Image();
                                        i.onload = function() {

                                            $('#majorimage').remove();
                                            $('<img id="majorimage" src="' + i.src + '"/>').insertBefore('#content-header');
                                            $("#loadingdiv").fadeOut('fast');
                                            $('#content-wrapper').show("slide", { direction: "down" }, 300);
                                        }
                                        if ($.browser.msie) i.src = 'case-studies/' + hash.split('/')[1] + '/' + $("#majorimage").attr('src').split('/').pop();
                                        else i.src = 'case-studies/' + hash.split('/')[1] + '/' + $("#majorimage").attr('src');

                                        if ($('#background-images').length > 0) loadImages(hash.split('/')[0] + "/" + hash.split('/')[1] + "/case_0"); //performs image rotation on case-studies with multiple bg images

                                    } else {
                                        $("#loadingdiv").fadeOut('fast');
                                        $('#content-wrapper').show("slide", { direction: "down" }, 300);
                                    }
                                });
                            });
                            cslide = false;
                        } else {
                            if ($("#content").length > 0) {
                                $("#content").fadeOut("fast", function() {
                                    $('#loadingdiv').fadeIn('fast');
                                    subSwitch('case-studies/' + hash.split('/')[1] + '/case_0', hash.split('_')[1]);

                                });
                            } else {
                                $(".content").fadeOut("fast", function() {
                                    $('#loadingdiv').fadeIn('fast');
                                    subSwitch('case-studies/' + hash.split('/')[1] + '/case_0', hash.split('_')[1]);
                                });
                            }
                        }
                        pslide = true;
                        personloaded = false;
                    } else if (hash.split('_')[0] == 'people') {
                        $("#peopleb").addClass("current");
                        if (personloaded) {                                                                                     //if you were previously on a people page
                            loadperson(hash.split('_')[1], false);
                        }
                        else {                                                                                                  //if you were not on a people page
                            if ($('#content-wrapper').is(':visible')) {
                                $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
                                    $('#loadingdiv').fadeIn('fast');
                                    $("#content-wrapper").load(hash.split('_')[0] + ".html #content", '', function() {
                                        loadpeople(true, hash.split('_')[1]);
                                    });
                                });
                            } else {
                                $("#content-wrapper").load("people.html #content", '', function() {
                                   loadpeople(true, hash.split('_')[1]);
                                });
                            }
                        }
                    } else {
                        loadPage(hash);
                    }
            }

        } else {
            if (!firstLoad) {
                if ($(".submenu").is(':visible')) $(".submenu").slideUp(200);
                $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
                    $('#loadingdiv').fadeIn('fast');
                    $("#content-wrapper").load("home.html #content", '', function(data) {
                        var i = new Image();
                        i.onload = function() {
                            $("#loadingdiv").fadeOut('fast');
                            $('#content-wrapper').show("slide", { direction: "down" }, 300);
                        }
                        i.src = "images/home1.jpg";
                    });
                });
                pslide = true;
                cslide = true;
                clearInterval(workTimer);
                clearInterval(rotateTimer);
                rotateTimer = setInterval("headline_rotate()", headlineRotateTime);

            } else {
                personloaded = false;
                firstLoad = false;
                pslide = true;
                cslide = true;
				
                $("#content_slot").animate({ opacity: "1", left: "161px" }, "slow", function() {
                    $('#loadingdiv').fadeIn('fast');
                    $("#content-wrapper").load("home.html #content", '', function(data) {
                        currentWork = Math.floor(Math.random() * 6) + 1;
                        $('<img src="images/home' + currentWork + '.jpg" id="majorimage" alt="Welcome to The Alloy. We build profitable brands through Product Design, Interaction Design and Innovation Strategy "/>').prependTo('#content-image');
                        var i = new Image();
                        i.onload = function() {
                            $("#content_reflection").animate({ height: "100px" }, 1200);
                            $('#content-wrapper').show("slide", { direction: "down" }, "slow");
                            $('#loadingdiv').fadeOut('fast');
                        }
                        i.src = "images/home1.jpg";
                        rotateTimer = setInterval("headline_rotate()", headlineRotateTime);
                        clearInterval(workTimer);
                    });
                });
            }
        }
    }

    $.historyInit(pageload);

    $('.current').livequery('click', function() {
        minimizeNews();
    });

    $('.chapterlink').livequery('click', function() {
        clearInterval(workTimer);
        currentWork = 0;
        clearInterval(rotateTimer);
        var hash = $(this).attr('href');

        if ($("#newsheader.expanded").length > 0) minimizeNews();
        hash = hash.substr(0, hash.length - 5);
        if (hash == window.location.href.split('#')[1]) {                           //check to see if the link you clicked on is to the page that is currently open
            return false;
        } else if (window.location.href.indexOf('#') == -1 && hash == 'index') {    //check to see if the link you clicked on is to the page that is currently open (special case for the index page)
            return false;
        }

        $.historyLoad(hash);
        return false;

    });

    $('.pagelink').livequery('click', function() {
        clearInterval(workTimer);
        currentWork = 0;
        clearInterval(rotateTimer);
        var hash = $(this).attr('href');
        //hash = hash.replace(/^.*#/, '');
        if ($.browser.msie) hash = hash.split('alloy.com/')[1];
        hash = hash.split('.')[0];
        $.historyLoad(hash);
        return false;
    });

    $('#careersButton').livequery('click', function() {
        careersloaded = true;
        $.historyLoad('careers');
    });

    //functions for adding mouse behaviors to the people page
    $(".pdiv").livequery('mouseover', function() {
        var cur = $(this).attr('id');
        $(this).css({ 'background-position': '-120px 0px', 'border-color': '#94c733', 'background-color': '#94c733' });
        //$(this).animate({ 'height': '90' }, 'fast');
    });

    $(".pdiv").livequery('mouseout', function() {
        var cur = $(this).attr('id');
        $(this).css({ 'background-position': '0px 0px', 'border-color': '#8c8c8c', 'background-color': '#8c8c8c' });
        //$(this).animate({ 'height': '78' }, 'fast');
    });

    $(".pdiv").livequery('click', function() {
        $('#loadingdiv').fadeIn('fast');
        var newhash = 'people_' + $(this).attr('id');
        personloaded = true;
        $.historyLoad(newhash);
    });

    $('#loginButton').livequery('click', function() {
        var uname = $("#userBox").val().split(' ').join('');
        var upass = $("#passBox").val().split(' ').join('');

        if (uname == "" || uname == null) {
            var warning = '';
            if (upass == "" || upass == null) {
                warning += ' and password';
            }
            alert('Please type in your username' + warning);
        } else if (upass == "" || upass == null) {
            alert('Please type in your password');
        } else {
            validateUser(uname, upass);
        }
    });

    $('#newfolder').livequery('click', function() {//This is how links anywhere in the site are defined
        addFolder();
    });

    $('#deletefolder').livequery('click', function() {
        deleteItem();
    });

    $('#createfolder').livequery('click', function() {
        createFolder();
    });

    $('#cancelcreatefolder').livequery('click', function() {
        if ($('#addfolderdialogue').length > 0) {
            $('#addfolderdialogue').remove();
            $('#shader').remove();
        }
    });

    $('#refreshFiles').livequery('click', function() {
        refreshFileBrowser();
    });


    $("#createclient").livequery('click', function() {
        createClient();
    });

    $("#addclient").livequery('click', function() {
        addClient();
    });

    $('#download').livequery('click', function() {
        downloadFile();
    });

    $("#cbbutton").livequery('click', function() {
        if (needToConfirm) {
            var r = confirm('Are you sure you want to exit the client area? Exiting will stop any pending uploads and log you out of this session');
            if (r) {
                needToConfirm = false;
            } else {
                return;
            }
        }
        $("#content-wrapper #content").children().remove();
        $("#content-wrapper").load("client.html #content");
    });

    $(".remover").livequery('click', function() {
        $(this).parent().remove();
    });

    $("#adder").livequery('click', function() {
        if ($('.uploader').size() == 7) return;
        $('<div class="uploader"></div>').html('<input type=file id = "file' + $('.uploader').size() + '"class="fileInput"><div class="remover"></div>').insertBefore("#adder");
    });

    $("#upload").livequery('click', function() {
        uploadFiles();
    });


    $("#filebrowser").livequery('click', function() {
        $('.jqueryFileTree').find('LI').each(function() {
            $(this).removeClass('selected');
        });
        currentFolder = clientRoot;
        $('#curfolder').html(currentFolder.split('clients/')[1]);
    });

    $("#homeClick").livequery('click', function() {
        clearInterval(rotateTimer);
        clearInterval(workTimer);
        $.historyLoad('pitch_0'); //.historyLoad is the function that tells the browser to go into the pageload() function when a link is clicked instead of navigating to a different page
    });

    $("#homeWork").livequery('click', function() {
        var whereSlash = $("#majorimage").attr('src').lastIndexOf('/');
        var clientName = $("#majorimage").attr('src').slice(whereSlash + 1).split('_')[0];
        var caseNumber = $("#majorimage").attr('src').split('_')[1].split('.')[0];
        cslide = true;
        clearInterval(workTimer);
        clearInterval(rotateTimer);
        $.historyLoad('case-studies/' + clientName + '/case_' + caseNumber);
    });

    $('.pagebutton,.imgbutton').livequery('click', function() {
        clearInterval(workTimer);
        currentWork = 0;
        clearInterval(rotateTimer);
        var newpage = ($(this).attr('id').split('_')[1]);
        var hash = window.location.href.split('#')[1];
        if (hash == "work" || hash == "product" || hash == "interaction" || hash == "strategy" || hash == 'testimonials' || hash == 'awards') {
            if (newpage == 0) $.historyLoad('work'); if (newpage == 1) $.historyLoad('product'); if (newpage == 2) $.historyLoad('interaction'); if (newpage == 3) $.historyLoad('strategy'); if (newpage == 4) $.historyLoad('awards'); if (newpage == 5) $.historyLoad('testimonials');
        }
        if ($('.pitch').length > 0) $.historyLoad('pitch_' + newpage);
        if ($('.case').length > 0) {
            var hash = window.location.href.split('#')[1].split('.')[0].split('_')[0];
            $.historyLoad(hash.split('_')[0] + '_' + newpage);
        }
    });

    $('.prevpagebutton').livequery('click', function() {//controls what happends when previous button is pressed
        clearInterval(workTimer);
        currentWork = 0;
        clearInterval(rotateTimer);
        var newpage = parseInt($('.content').attr('id')) - 1;
        var hash = window.location.href.split('#')[1];
        if (hash == "work" || hash == "product" || hash == "interaction" || hash == "strategy" || hash == 'testimonials' || hash == 'awards') {
            if (hash == "product") $.historyLoad('work'); if (hash == "interaction") $.historyLoad('product'); if (hash == "strategy") $.historyLoad('interaction'); if (hash == "awards") $.historyLoad('strategy'); if (hash == "testimonials") $.historyLoad('awards');
        }
        if ($('.pitch').length > 0) $.historyLoad('pitch_' + newpage);
        if ($('.case').length > 0) {
            var hash = window.location.href.split('#')[1].split('.')[0].split('_')[0];
            $.historyLoad(hash.split('_')[0] + '_' + newpage);
        }
    });

    $('.nextpagebutton').livequery('click', function() {//controls what happends when next button is pressed 
        clearInterval(workTimer);
        currentWork = 0;
        clearInterval(rotateTimer);
        var newpage = parseInt($('.content').attr('id')) + 1;
        var hash = window.location.href.split('#')[1];
        if (hash == "work" || hash == "product" || hash == "interaction" || hash == "strategy" || hash == 'testimonials' || hash == 'awards') {
            if (hash == "work") $.historyLoad('product'); if (hash == "product") $.historyLoad('interaction'); if (hash == "interaction") $.historyLoad('strategy'); if (hash == "strategy") $.historyLoad('awards'); if (hash == "awards") $.historyLoad('testimonials'); if (hash == "testimonials") $.historyLoad('work');
        }
        if ($('.pitch').length > 0) {
            if (newpage > 4) newpage = 0;
            $.historyLoad('pitch_' + newpage);
        }
        if ($('.case').length > 0) {
            var hash = window.location.href.split('#')[1].split('.')[0].split('_')[0];
            $.historyLoad(hash.split('_')[0] + '_' + newpage);
        }
    });

    $('#pContact').livequery('click', function() {
        $.historyLoad('contact');
    });

    $('#prevpeep').livequery('click', function() {
        var newpeep = parseInt($("#person-container").attr('class').split('_')[1]) - 1;
        var thispeep = '';
        $(peepsXML).find('person').each(function(ind) {
            if (ind == newpeep) thispeep = $(this).attr('id');
        });
        personloaded = true;
        $.historyLoad("people_" + thispeep);
    });

    $('#nextpeep').livequery('click', function() {
        var newpeep = parseInt($("#person-container").attr('class').split('_')[1]) + 1;
        var thispeep = '';
        $(peepsXML).find('person').each(function(ind) {
            if (ind == newpeep) thispeep = $(this).attr('id');
        });
        if (thispeep == '') thispeep = 'tan';
        personloaded = true;
        $.historyLoad("people_" + thispeep);
    });

    $(".newsItem").livequery('click', function() {
        if ($("#newsheader").is(".minimised")) { expandNews(); }
        else {
            var newid = $(this).attr('id').split('_')[1];                       //find out which of the news stories it is from the number in its id
            $.historyLoad("news_" + newid);
        }
        //if (!$('.news-header-table').length > 0) {
        // $('<table summary="header for the news section" class="news-header-table"></table>').html('<tr><td class="header-cell">latest news...</td><td></td><td class="header-cell">latest views...</td><td></td></tr>').before(;
        //}
    });                                                                     //The click functionality of the news items in the newspanel

    $(".nextStory").livequery('click', function() {
        var newid = parseInt($("#news_shower").attr('class').split('_')[1]) - 1;
        if (newid == 0) { newid = $(storiesXML).find('story').length; }
        $.historyLoad("news_" + newid);
    });

    $("#saveNews").livequery('click', function() {
        var foldername = $('input#date').val().split(' ').join('');
        var imagename = $('input#image').val().split('\\').pop();
        $.ajax({
            type: "POST",
            url: "createNews.php",
            data: "title=" + ('input#title').val() + "&id=" + ($(storiesXML).find('story').length + 1) + "&textcolour=" + $('input#textcolour').val() + "&date=" + $('input#date').val() + "&description=" + $('input#description').val() + "&story=" + "<![CDATA[" + $('textarea#story').val() + "]]>" + "&folder=" + foldername + "&image=" + imagename,
            success: function(data) {
                if (data == 'true') {
                    alert('story added successfully!');                    
                } else {
                    alert(data);
                }
            }
        });
    });                                                                   //The click functionality of the "next" button for the news stories when loaded in the main panel

    $(".lastStory").livequery('click', function() {
        var newid = parseInt($("#news_shower").attr('class').split('_')[1]) + 1;
        if (newid > $(storiesXML).find('story').length) { newid = 1; }
        $.historyLoad("news_" + newid);
    });

    $("#newsleftnav").livequery('click', function() {
        $('#news_shower').fadeOut("fast");
    });

    $("#lnews, #lviews").livequery('click', function() {
        if ($("#newsheader").is(".minimised")) expandNews();
        $('#news_shower').fadeOut("fast");
    });
    //The click functionality of the "previous" button for the news stories when loaded in the main panel



});

function subSwitch(which, newpage){
    var thispagedata = which + ".html .content#" + newpage;
    $("#content-wrapper").load(thispagedata, '', function(data) {
        var pORc = false;
        if (which != 'pitch_0') pORc = true;
        addNav($(data).find('.content').length, newpage, pORc, $(data).find('#0 #content-header').text());
        if ($("#majorimage").length > 0) {
            var i = new Image();
            i.onload = function() {

                $('#majorimage').remove();
                $('<img id="majorimage" src="' + i.src + '"/>').insertBefore('#content-header');
                $("#loadingdiv").fadeOut('fast');
                $(".content").fadeIn("fast");
            }
            if ($.browser.msie) i.src = 'case-studies/' + which.split('/')[1] + '/' + $("#majorimage").attr('src').split('/')[3];
            else i.src = 'case-studies/' + which.split('/')[1] + '/' + $("#majorimage").attr('src');
            
            if ($('.content #background-images').length > 0) loadImages(which.split('/')[0] + "/" + which.split('/')[1] + "/case_0"); //performs image rotation on case-studies with multiple bg images

        } else {
            $('#loadingdiv').fadeOut('fast');
            $(".content").fadeIn("fast");
        }
    });
}

var storiesXML = 'null';
var personloaded = false;
var storiesLoaded = false;
var nowLoad = false;
var toLoad = '';
var currentPitch = 1;

function loadnews() {
    $.ajax({ type: "GET", url: "news-views/stories.xml", dataType: "xml", success: function(xml) {
        $(xml).find('story').each(function(ind) {
            storiesXML = xml;
            var storyText = $(this).attr('summary');
            var storyTitle = $(this).attr('title');
            var storyThumb = $(this).attr('image');
            var storyDate = $(this).attr('date');
            var storyId = $(this).attr('id');
            //var storyLink = $(this).attr('title').toLowerCase().substr(0, 20).escape();
            $('<div class="newsItem" id="story_' + storyId + '"></div>').html('<a class="newshover" href="javascript: void(0)" title="' + $(this).attr('title') + '"><div class="newsThumb"><img src="news-views/files/' + storyThumb + '" alt="' + storyTitle + '"></div><div class="newsText">' + storyTitle + '<span class="newsDate"><br>' + storyDate + '</span><span class="newsBody"><br>' + storyText + '</span></div></a>').appendTo('#newscontainer');
        });
        storiesLoaded = true;
        if (nowLoad) {
            loadStory(toLoad, storiesXML);
        }
    }
    });
}

function expandNews() {
    //if ($("#newsheader").is(".expanded")) return;
    
    if ($('#newscontainer').children().size() > 12) {
        $('#newsmain').css({ "overflow": "auto" });
    }
    $('#newsmain').jScrollPane({showArrows: true});                                   // Apply "jScrollPane" method to all elements with the "scroll-pane" class - thus building the scroll bar according to jScrollPane.js
    
    $("#newspanel").css({ 'z-index': '100' });
    $("#newspanel .jScrollPaneTrack").hide();                           // Then hide the scroll bar elements so that they fade in correctly when the newspanel is first expanded
    $("#newsheader").removeClass("minimised").addClass("expanded");
    $("#showmore").fadeOut("normal");
    $("#hide").fadeIn("normal");
    $("#newspanel").animate({ height: "550px" }, 700);
    $("#newspanel .jScrollPaneTrack").animate({ right: '0px' }, 1);     // Make scrollbar appear 
    $("#newspanel .jScrollPaneTrack").fadeIn(700);
}

function minimizeNews() {
    if ($("#newsheader").is(".minimised")) return;      //check if it already is minimized, and if it is, break out of the function

    $("#newsheader").removeClass("expanded").addClass("minimised");
    $("#hide").fadeOut("normal");
    $("#showmore").fadeIn("normal");
    if ($('#news_shower').is(':visible')) $('#news_shower').fadeOut("slow");
    $("#newspanel").animate({ height: "110px" }, 700);
    /* Make scrollbar disappear */
    if($("#newspanel .jScrollPaneContainer").length>0){
        $("#newspanel .jScrollPaneTrack").fadeOut(700);
        $("#newspanel .jScrollPaneTrack").animate({ right: '-100px' }, 1);
        $("#newspanel .jScrollArrowUp").fadeOut(700);
        $("#newspanel .jScrollArrowUp").animate({ right: '-100px' }, 1);
        $("#newspanel .jScrollArrowDown").fadeOut(700);
        $("#newspanel .jScrollArrowDown").animate({ right: '-100px' }, 1);
        $("#newsmain")[0].scrollTo(0);
    }
}

function newslinks(num,stories) {
    $('<div id="newsnavstrip"></div>').html('').html('<div id="newsleftnav">back to news and views</div><div id="rightnav"></div>').appendTo('#news_shower');

    $('<div class="nextStory"></div>').html('<a href="javascript: void(0)" title="Next news story"></a>').appendTo('#news_shower #rightnav'); //add next button except when this is the last news story
    //if (num == $(stories).find('story').length - 1) $('<div class="nextplaceholder"></div>').appendTo('#news_shower #rightnav');
    if (num > 0) $('<div class="lastStory"></div>').html('<a href="javascript: void(0)" title="Previous news story"></a>').appendTo('#news_shower #rightnav'); //add prev. button except when this is the first news story
}

function loadStory(newid, stories) {
    if (!storiesLoaded) {
        nowLoad = true;
        toLoad = newid;
        return false;
    }
    generateStory(stories, newid);
}

function generateStory(stories, newid) {
    
    var currentStory = 'null';
    
    $(stories).find('story').each(function(ind) {
        if ($(this).attr('id') == newid) {
            currentStory = $(this);            
        }
    });

    var sTitle = $(currentStory).attr('title');
    var sText = $(currentStory).text();
    var sDate = $(currentStory).attr('date');
    var sImage = $(currentStory).attr('image').split('.')[0];
    var sStyle = $(currentStory).attr('style');
    
    //if (!$('#content-image').length > 0) {                                                       //if there is no content-image div, create one
    //   $('#content').html('').html('<div id="content-image"></div>');
    //}
    $("#loadingdiv").fadeIn('fast');
    
	var i = new Image();
    i.onload = function() {
        $("#loadingdiv").fadeOut('fast');
        $('#news_shower').html('').removeClass().addClass('newsStory_' + newid);
        $('#news_shower').css({ 'background-image': 'url(news-views/files/' + sImage + '.jpg)', 'background-color': '#fff', 'background-position': 'left top', 'background-repeat': 'no-repeat' });

        $('<div id="newsScroll"></div>').appendTo('#news_shower');
        $('<div id="news-header"></div>').html(sTitle).css({ 'color': sStyle }).appendTo('#newsScroll');
        $('<div id="news-date"></div>').html(sDate).css({ 'color': sStyle }).appendTo('#newsScroll');
        $('<div id="news-text"></div>').html(sText).css({ 'color': sStyle }).appendTo('#newsScroll');
        newslinks(newid, stories);
		
        $('#news_shower').show("slide", { direction: "down" }, 300, function() {
            $('#newsScroll').jScrollPane({showArrows: true});
            $("#news_shower .jScrollPaneTrack").hide();
            $("#news_shower .jScrollPaneTrack").animate({ right: '0px' }, 1);
            $("#news_shower .jScrollPaneTrack").fadeIn(700);
        });
    }
    i.src = 'news-views/files/' + sImage + '.jpg';
}

var peepsXML = 'null';//variable that holds all data loaded from people xml

function loadpeople(doI, name) { //Function that loads the main people page with all of the faces on it...
    $('#people-table-wrapper').html('');
    personloaded = true;
    $.ajax({ type: "GET", url: "people/people.xml", dataType: "xml", success: function(xml1) {//function to load the xml from the people.xml file
    $(xml1).find('person').each(function(ind) {//for loop that loops through each person in the people.xml file
            peepsXML = xml1;
            var pId = $(this).attr('id');
            var pName = $(this).attr('name');
            $('<div class="pdiv" id="' + pId + '"></div>').css({ 'background': '#8c8c8c url(people/cv_' + pId + '_thumb.gif) no-repeat 0 0' }).html('<a href="#people_'+pId+'" title="'+pName+'"><div class="peepName">' + pName + '</div></a>').appendTo('#people-table-wrapper'); //this writes the actual html of each box on the people page

        });
        if(doI){ loadperson(name, true);}
        else {
            $('#loadingdiv').fadeOut('fast');
            $('#content-wrapper').show("slide", { direction: "down" });
        }
    }
    });
}

function loadperson(selected, needsPopUp) {
    personloaded = true;
    var peep = '';
    var selnum = 0;
    var peepslength = 0;
    
	$(peepsXML).find('person').each(function(ind) {
        if ($(this).attr('id') == selected) {
            peep = $(this);
            selnum = ind;
        }
        peepslength=ind;
    });

    if ($("#person-container").length > 0) $("#person-container").html('').removeClass().addClass("person_" + selnum);
    else $('<div id="person-container" class="person_' + selnum + '"></div>').appendTo('#peoplepage').hide();

    $('<img id="peepphoto" src="people/cv_' + peep.attr('id') + '.jpg">').css('display', 'none').appendTo('#person-container');
    $('<div id="person-header"></div>').html(peep.attr('name')).css('display', 'none').appendTo('#person-container');
    $('<div id="person-title"></div>').html(peep.attr('role')).css('display', 'none').appendTo('#person-container');
    $('<div id="person-text"></div>').html(peep.text()).css('display', 'none').appendTo('#person-container');
    $('<div id="peeps-back-button"></div>').html('<div id="bbutton"><a class="pagelink" href="people.html">Key People</a>&nbsp;\\&nbsp;<span style="font-weight:normal;">' + peep.attr('name') + '</span></div><div id="rightnav"></div>').css('display', 'none').appendTo('#person-container');

    $('<div id="nextpeep">next ></div>').appendTo("#rightnav");
    if (selnum != 0) $('<div id="prevpeep">< prev</div>').appendTo("#rightnav");
        
    var i = new Image();
    i.onload = function() {
        $("#loadingdiv").fadeOut('fast');
        if (needsPopUp) {//if we're on a different page and the content needs to pop-up into the frame, then do this 
            $("#people-table-wrapper").hide();
            $("#person-container").show();
            $("#person-header").show();
            $("#person-title").show();
            $("#person-text").show();
            $('#peepphoto').show();
            $('#peeps-back-button').show();
            $('#content-wrapper').show("slide", { direction: "down" }, 300);//code for animating the pop-up
        } else {
            if ($.browser.safari) {//if this is loading in safari - code is slightly different
                $("#person-header").hide();
                $("#person-text").hide();
                $("#person-title").hide();
                $('#peepphoto').hide();
                $('#peeps-back-button').hide();
                $("#people-table-wrapper").hide("slide", { direction: "up" }, 400, function() {
                    $("#person-container").fadeIn("fast");
                    $("#person-header").fadeIn("fast");
                    $("#person-title").fadeIn("fast");
                    $("#person-text").fadeIn("fast");
                    $('#peepphoto').fadeIn("fast", function() {
                        $('#peeps-back-button').fadeIn("fast");
                    });
                });
            } else {//browsers other than safari do this
                $("#people-table-wrapper").hide("slide", { direction: "up" }, 400, function() {
                    $("#person-container").fadeIn("fast");
                    $("#person-header").fadeIn("fast");
                    $("#person-title").fadeIn("fast");
                    $("#person-text").fadeIn("fast");
                    $('#peepphoto').fadeIn("fast", function() {
                        $('#peeps-back-button').fadeIn("fast");
                    });
                });
            }
        }
    };
    i.src = 'people/cv_' + peep.attr('id') + '.jpg';    
}

function unloadperson() {// when in a specific person, this function clears that person and loads the main people table
    $('#person-container').fadeOut("fast", function() {
        personloaded = false;
        $('#person-container').remove();
        $("#people-table-wrapper").show("slide", { direction: "up" }, 400);
        $(".pdiv").each(function() {
            $(this).css({ 'background-color': '#8c8c8c' });
        });
    });
}




var clientRoot='';
var clientName = '';
var currentFolder = '';
var needToConfirm = false;

window.onbeforeunload = function() {
    if (needToConfirm) {
        return "By clicking OK, you will stop any pending uploads and log you out of this session.";
    }
}

function validateUser(uname, upass){//Checks for valid username and password and then draws the client page with the file tree and file controls
    $.ajax({
        type: "POST",
        url: "validateClient.php",
        data: "uname=" + uname + "&pass=" + upass,
        success: function(data) {
            if (data == 'baduser') {
                alert('Please enter a valid username and password');
                return;
            } else if (data == 'badpass') {
                alert('Please enter a valid username and password');
                return;
            } else if (data == "Alloy") {
                clientName = "All Access";
                clientRoot = "../client1/";
            } else {
                clientName = data.split("_").join(" ");
                clientRoot = "../client1/" + data + "/";
            }            
            currentFolder = clientRoot;
            $("#clientIntro").hide();
            $('<div id="clientFiles"></div>').html('<div id="fileTitle">Client area <span id="clientName">|' + clientName + '</span></div>').appendTo('#clientArea');
            $("#clientFiles").append('<div id="clientleft"></div>');
            $('<div class="fileheader" id="leftHeader"></div>').html('Your Files').appendTo("#clientleft");
            refreshFileBrowser();
            $('<div id="newfolder" class="filebutton" title="New Folder"></div>').appendTo("#clientleft");
            $('<div id="deletefolder" class="filebutton" title="Delete Item"></div>').appendTo("#clientleft");
            $('<div id="refreshFiles" class="filebutton" title="Refresh File Browser"></div>').appendTo("#clientleft");

            if (uname == 'alloy') $('<div id="addclient" class="filebutton" title="Add a new client"></div>').appendTo("#clientleft");

            $('<div id="download" class="filebutton" title="Download File"></div>').appendTo("#clientleft");
            $('<div id="upload" class="filebutton" title="Upload Files"></div>').appendTo("#clientleft");
            $('<div class="fileheader" id="rightHeader"></div>').html('<span style="color:#94c733;">Current Folder: </span><span id="curfolder"> ' + currentFolder.split('client1/')[1] + '</span>').appendTo("#clientleft");
            $('<div id="client-back-button"></div>').html('<div id="cbbutton"></div>').hide().appendTo('#clientArea');
            $('#client-back-button').show("slide", { direction: "down" }, 400);
        }
    });        
}

function addClient() {
    if ($('#addfolderdialogue').length > 0) return;
    $('<div id="shader"></div>').appendTo('body');
    $('<div id="addfolderdialogue" style="height:170px;"></div>').html('<b>Add a client</b><br/><p style="padding-right:10px;text-align:right;line-height:30px;">Client Name:<input type="text" id="newclientname"><br/>Username:<input type="text" id="newclientuname"><br/>Password:<input type="text" id="newclientpass"></p><p><input type="button" value="Create" id="createclient"><input type="button" value="Cancel" id="cancelcreatefolder"></p>').appendTo('#shader');
}

function createClient() {
    var newName = $('input#newclientname').val().split(' ').join('_');
    $.ajax({
        type: "POST",
        url: "createClient.php",
        data: "name=" + newName + "&uname=" + $('input#newclientuname').val() + "&pass=" + $('input#newclientpass').val(),
        success: function(data) {
            if (data == 'true') {
                alert('Client added successfully!');
                refreshFileBrowser();
                $('#addfolderdialogue').remove();
                $('#shader').remove();
            } else {
                alert(data);
            }
        }
    });
}

function addFolder() {
    if ($('#addfolderdialogue').length > 0) return;
    $('<div id="shader"></div>').appendTo('body');
    $('<div id="addfolderdialogue"></div>').html('<b>Add folder to:</b><br/><span style="line-height:25px;font-size:11px"> ' + currentFolder + ' </span><br/>Name:<input type="text" id="newfoldername"><p><input type="button" value="Create" id="createfolder"><input type="button" value="Cancel" id="cancelcreatefolder"></p>').appendTo('#shader');
}

function deleteItem() {
    var selobject = $('.selected').children(':first').attr('rel');
    if (!selobject){alert('Nothing selected! Please select something to delete first');return;}
    var go = confirm('Are you sure you want to delte ' + selobject + '?');
    if (go) {
        $.ajax({
            type: "POST",
            url: "deleteFolder.php",
            data: "folder=" + selobject,
            success: function(data) {
                refreshFileBrowser();
                $('#rightHeader').html('Upload Files to: <span style="color:#94c733;"> ' + clientRoot.split('client1/')[1] + '</span>');
            }
        });
    } else {
        return false;
    }
}

function downloadFile() {
    var selobject = $('.selected').children(':first').attr('rel');
    if (!selobject) { alert('Please select a file to download'); return; }
    if (selobject.indexOf('.') == -1) { alert('You cannot download entire folders. Please select a file to download'); return; }
    window.open("download.php?file=" + selobject, '_blank');
}

function uploadFiles() {
    $('<div id="shader"></div>').appendTo('body');
    $('<div id="upbox"></div>').html('<div id="uploaddialogue"></div>').appendTo('#shader');
    myFlash = $.flash({ swf: 'NasUploader15.swf', height: 300, width: 410, flashvars: { varget: 'dossierup=' + currentFolder } });
    $('#uploaddialogue').html(myFlash);
}

function removeUpload() {
    $('#shader').remove();
    refreshFileBrowser();
}

function refreshFileBrowser() {//function that draws the file tree on the page
    $("#filebrowser").remove();
    $('<div id="filebrowser"></div>').insertAfter("#leftHeader");
    $("#filebrowser").fileTree({
        root: clientRoot,
        script: 'jqueryFileTree.php',
        folderEvent: 'dblclick',//what type of event opens a folder
        selectEvent: 'click',//what type of event selects a file
        expandSpeed: 300,
        collapseSpeed: 300,
        expandEasing: 'easeInOutCubic',
        collapseEasing: 'easeInOutCubic',
        multiFolder: false
    }, function(file) {//tells function what to do when you double click on file
        downloadFile();
    });
}

function createFolder() {
    var newdir = $('#newfoldername').attr('value');
    if (newdir == '') {
        alert('Please give the folder a name');
        return;
    }
    $.ajax({
        type: "POST",
        url: "createFolder.php",
        data: "folder=" + currentFolder + newdir,
        success: function(data) {
            if (data == 'true') {
                refreshFileBrowser();
            } else {
                alert(data);
            }
        }
    });
    $("#addfolderdialogue").remove();
    $('#shader').remove();    
}

function loadPage(hash, navvar, digit, rotate){ //
    $('#content-wrapper').hide("slide", { direction: "down" }, 300, function() {
        $('#loadingdiv').fadeIn('fast');
        $("#content-wrapper").load(hash + ".html #content", '', function(data) {
            if (hash == 'home') {
                currentWork = Math.floor(Math.random() * 6) + 1;
                $('<img src="images/home' + currentWork + '.jpg" id="majorimage"/>').prependTo('#content-image');
            }
            if ($("#majorimage").length > 0) {
                var i = new Image();
                i.onload = function() {
                    $("#loadingdiv").fadeOut('fast');
                    $('#content-wrapper').show("slide", { direction: "down" }, 300);
                    if (navvar) {
                        addNav(6, digit, false, '');
                    }
                    if (hash == "awards") {
                        $("#awards").jScrollPane({showArrows: true});
                        $("#awards-list .jScrollPaneTrack").animate({ right: '1px' }, 1);     // Make scrollbar appear
                        $("#awards-list .jScrollPaneTrack").fadeIn(700);
                    } else if (hash == "testimonials") {
                        $("#testimonials").jScrollPane({showArrows: true});
                    } else if (hash == "careers") {
                        $("#careers").jScrollPane({showArrows: true});
                    }
                }
                i.src = $("#majorimage").attr('src');
            } else {
                $('#content-wrapper').show("slide", { direction: "down" }, 300);
                $('#loadingdiv').fadeOut('fast');
                if (hash == "awards") {
                    $("#awards").jScrollPane({showArrows: true});
                } else if (hash == "testimonials") {
                    $("#testimonials").jScrollPane({showArrows: true});
                    //if ($.browser.msie) $('#testimonials').css({ 'overflow': 'scroll' });
                } else if (hash == "connections") {
                    //$("#partners").jScrollPane();
                }
            }
            if (rotate) loadImages(hash);
        });
    });
    
}

function switchPage(hash, navvar, digit,rotate){
    if($(".content").length>0){
        $(".content").fadeOut("fast", function() {
            $('#loadingdiv').fadeIn('fast');
            $("#content-wrapper").load(hash + ".html #content", '', function(data) {
                var i = new Image();
                i.onload = function() {
                    $("#loadingdiv").fadeOut('fast');
                    $("#content").fadeIn("fast");
                    if (navvar) {
                        addNav(6, digit, false, '');
                    }
                }
                i.src = $("#majorimage").attr('src');
                
                if (hash == "awards") {
                    $("#awards").jScrollPane({showArrows: true});                    
                } else if (hash == "testimonials") {
                    $("#testimonials").jScrollPane({showArrows: true});
                }else if (hash == "careers") {
                    $("#careers").jScrollPane({showArrows: true});
                }
                
               if (rotate) loadImages(hash);
            });
        });
    } else {
    $("#content").fadeOut("fast", function() {
        $('#loadingdiv').fadeIn('fast');
        $("#content-wrapper").load(hash + ".html #content", '', function(data) {
            var i = new Image();
            i.onload = function() {
                $("#loadingdiv").fadeOut('fast');
                $("#content").fadeIn("fast");
                if (navvar) {
                    addNav(6, digit, false, '');
                }
            }
            i.src = $("#majorimage").attr('src');
            
            if (hash == "awards") {
                $("#awards").jScrollPane({showArrows: true});
            } else if (hash == "testimonials") {
                $("#testimonials").jScrollPane({showArrows: true});
            } else if (hash == "careers") {
                $("#careers").jScrollPane({showArrows: true});
            }
           
            if (rotate) loadImages(hash);
        });
    });
    }
}

function headline_rotate() {
    clearInterval(workTimer);
    currentPitch++;
    if (currentPitch > 6) currentPitch = 1;     //change this value if you want to cycle through a number of different number of images on the home page
    var i = new Image();
    i.onload = function() {
        $("#majorimage").fadeOut('slow', function() {
            $("#majorimage").remove();
            $('<img src="images/home' + currentPitch + '.jpg" id="majorimage">').css('display', 'none').fadeIn('slow').prependTo("#content-image");            
        });
    }
    i.src = 'images/home' + currentPitch+'.jpg';
}

var currentWork = 0;
var imgArray = [];

function loadImages(hash) {
    currentWork = 0;
    imgArray = [];
    var filename = hash + '.html #background-images';
    $('#imgholder').html('');
    $('#imgholder').load(filename, '', function(data) {
        $('#imgholder').find('.bgimg').each(function(ind) {
            imgArray[ind] = $(this).attr('src');
        });
        if (hash == 'interaction') {
            workTimer = setInterval("interaction_rotate()", 6000);
        } else if (hash.split('/')[0] == "case-studies") {
            var thisimgurl = hash.split('/')[0] + "/" + hash.split('/')[1] + "/";
            workTimer = setInterval("work_rotate('" + thisimgurl + "')", 6000);
        } else {
            if ($.browser.msie) workTimer = setInterval("work_rotate('images/')", 6000);
            else workTimer = setInterval("work_rotate('')", 6000);
        }
    });    
}

function work_rotate(thisurl) {
    clearInterval(rotateTimer);
    currentWork++;
    if (imgArray[currentWork] == $('#majorimage').attr('src')) currentWork++;
    if (currentWork > imgArray.length-1) currentWork = 0;
    var i = new Image();
    var k;
    i.onload = function() {
        $("#majorimage").fadeOut('fast', function() {
            $("#majorimage").remove();
            if ($('#content-image-test').length > 0) $('<img src="' + k + '" id="majorimage">').css('display', 'none').fadeIn('slow').prependTo("#content-image-test");
            else $('<img src="' + k + '" id="majorimage">').css('display', 'none').fadeIn('slow').prependTo("#content-image");
        });        
    }
    if ($.browser.msie) {
        i.src = thisurl + imgArray[currentWork].split('/').pop();
        k = i.src;
    } else {
        i.src = thisurl + imgArray[currentWork];
        k = i.src;        
    }
      
}

function interaction_rotate() {
    clearInterval(rotateTimer);
    currentWork++;
   
    if (imgArray[currentWork] == $('#majorimageCover').attr('src')) currentWork++;
    if (currentWork > imgArray.length - 1) currentWork = 0;
    
    var j = new Image();
    j.onload = function() {
        $("#majorimage").remove();
        $('<img src="' + imgArray[currentWork].split('.').join('b.') + '" id="majorimage">').prependTo("#content-image");
        var i = new Image();
        i.onload = function() {
            $("#majorimageCover").fadeOut('slow', function() {
                $("#majorimageCover").animate({ opacity: 0 }, 1500, function() { 
                    $('<img src="' + imgArray[currentWork] + '" id="majorimageCover">').css('display', 'none').animate({ opacity: 1 }, 1).fadeIn('slow').insertAfter("#majorimage");
                });
            });
        }
        i.src = imgArray[currentWork];
    }
    j.src = imgArray[currentWork].split('.').join('b.');
}


function addNav(pages, index, left, name) {
    var type;
    if ($('.content').length > 0){ type = '.';}
    else if ($('#content').length > 0){ type = '#';}
    
    $('<div id="navstrip"></div>').html('<div id="rightnav"><table id="pagelink-table"><tr class="navtable"></tr></table></div>').appendTo(type + 'content');
    
    if (left) {
        if ($(type+'content').attr('id') == 0) {
            $('<div id="leftnav"></div>').html('<a href="work.html" class="pagelink">Our Work</a>&nbsp;\\&nbsp;' + name ).appendTo("#navstrip");
            if (pages > 1) $('<td class="nextpagebutton"></td>').appendTo('.navtable');
        } else {
        var thishash = window.location.href.split('/')[4];
        //alert(thishash);                                                                                                           //This relies on the folder structure of the case studies to always remain the same
            $('<div id="leftnav"></div>').html('<a href="work.html" class="pagelink">Our Work</a>&nbsp;\\&nbsp;<a href="case-studies/' + thishash + '/case_0.html" class="pagelink">' + name + '</a>&nbsp;\\&nbsp;'+$('#content-header').text()).appendTo("#navstrip");

            for (var i = 1; i < pages; i++) {
                if ($.browser.safari && i == 6) {
                    if (index != 5) $('<td class="nextpagebutton"></td>').appendTo('.navtable');
                    else $('<td class=spacer></td>').appendTo('.navtable');
                    break;
                } else {
                    if (i == 1 && index != 1) $('<td class="prevpagebutton"></td>').appendTo('.navtable');
                    if (i == index) {
                        if (index == 1) $('<td class=spacer></td>').appendTo('.navtable');                                                                          //if this is the first of the content pages, don't add a "previous" arrow to the end, just add a spacer
                        $('<td class="activebutton"></td>').appendTo('.navtable');                                                                                      //either way, put the active button into place
                        if (index == (pages - 1)) $('<td class=spacer></td>').appendTo('.navtable');                                                                  //if this is the last of the content pages, don't add a "next" arrow to the end, just add a spacer
                    } else {
                        $('<td class="pagebutton" id="pb_' + i + '"></td>').appendTo('.navtable');
                    }
                    if (i == (pages - 1) && index != (pages - 1)) {
                        $('<td class="nextpagebutton"></td>').appendTo('.navtable');
                    }
                }
            }
        }
    } else {
        var maybeWork = window.location.href.split('#')[1];
        if (maybeWork == 'interaction' || maybeWork == 'product' || maybeWork == 'strategy' || maybeWork == 'testimonials' || maybeWork == 'awards') {
            if (!$("#navstrip").length > 0) $('<div id="navstrip"></div>').html('<div id="rightnav"><table id="pagelink-table"><tr class="navtable"></tr></table></div>').appendTo(type + 'content');

            $('<div id="leftnav"></div>').html('<a href="work.html" class="pagelink">Our Work</a>&nbsp;\\&nbsp;' + maybeWork).appendTo("#navstrip");         
        }
        
        for (var i = 0; i < pages; i++) {
            if ($.browser.safari && i == 6) {
                if (index != 5) $('<td class="nextpagebutton"></td>').appendTo('.navtable');
                else $('<td class=spacer></td>').appendTo('.navtable');
                break;
            } else {
                if (i == 0 && index != 0) $('<td class="prevpagebutton"></td>').appendTo('.navtable');
                if (i == index) {
                    if (index == 0) $('<td class=spacer></td>').appendTo('.navtable');                                                                          //if this is the first of the content pages, don't add a "previous" arrow to the end, just add a spacer
                    $('<td class="activebutton"></td>').appendTo('.navtable');                                                                                      //either way, put the active button into place
                    //if (index == (pages - 1)) $('<td class=spacer></td>').appendTo('.navtable');                                                                  //if this is the last of the content pages, don't add a "next" arrow to the end, just add a spacer
                } else {
                    $('<td class="pagebutton" id="pb_' + i + '"></td>').appendTo('.navtable');
                }
                if (i == (pages - 1)) {
                    $('<td class="nextpagebutton"></td>').appendTo('.navtable');
                }
            }
        }
    }
}

$.fn.image = function(src, f) {
    $("#loadingdiv").fadeIn('fast');
    return $(this).each(function() {
        var i = new Image();
        i.onload = f;
        i.src = src;
        $(this).css({ "background": "url(" + src + ") no-repeat 0 0" });
        //alert('ok');
    });
}

$.fn.loadbg = function(f) {
    $("#loadingdiv").fadeIn('fast')
    var src = $("#majorimage").attr('src');
    return $(this).each(function() {
        var i = new Image();
        i.onload = f;
        i.src = src;
    });
}
