//Global variables
var _showReelJSEnabledPage = "/_different/pages/ShowreelOverlayContent.aspx";
var _inHover = false;
var _mainCarousel;
var _thumbsCarousel;
var _toolTipXOffset = -10;
var _toolTipYOffset = -20;
var _activeFancyBoxIndex = -1;
var _hideToolTip = false;
var _buildToolTip = false;
var _inFancyboxHover = false;
var _broadcastAnimated = false, _printAnimated = false, _digitalAnimated = false;
var _broadcastMainCarousel, _printMainCarousel, _digitalMainCarousel;
var _broadcastThumbsCarousel, _printThumbsCarousel, _digitalThumbsCarousel;
var _viewerLoaded = false;

// Different Website global JavaScript
$(document).ready(InitPage);
 
 //Activates jQuery on page
 function InitPage()
 {
    $("input.labelled").focus(function(){
        if ( this.value == this.title ) {
            this.value = "";
            $(this).data("color", $(this).css("color"));
            $(this).css("color","#555");
        }
    }).blur(function(){
        if ( this.value == "" ) {
            this.value = this.title;
            $(this).css("color", $(this).data("color"));
        }
    });

    $("#siteSearchForm .text").keydown(function(event){
        if (event.keyCode == 13) {
            event.stopPropagation();
            event.preventDefault();
            $("#siteSearchForm .submit").click();
        }
    });
    
    //bind the click event to the work type filter drop downs
    $('.workSelect').click(
    function()
    {
        $(this).removeClass("filterFieldsDisabled");
    }
    );
    
    //bind the click event to the client filter drop down
    $('.clientSelect').click(
    function()
    {
        $(this).removeClass("filterFieldsDisabled");
    }
    );   
 }

 function InitFilterPanel() {
    AnimateFilterPanel();
    AnimateWorkSelectBoxes();
    AnimateFilterHeading();
    AnimateCaseStudyPanel();
    }

function InitWorkViewer() {

    $("#" + g_startWorkType + " a").addClass("selected");
    ImagePanelFade();
    AnimateWorkViewMenu();
    AnimateCarousels();
    ActivateFancyBox();
    $(".itemContainer").show();
}
 
 function ImagePanelFade()
 {
    //Image Panel fade
    $('#slides').innerfade({
        speed: 1000,
        timeout: 5000,
        type: 'random_start',
        containerheight:'387px'
    });
 }
 
 function RemoveInitalFilterState()
 {
    $("#filterPanelContents").removeClass("initalState");
    
    SwitchShowHideIconState();
 }
 
 function SetInitalFilterState()
 {
    $("#filterPanelContents").addClass("initalState");
    
    var currSrc = $(this).attr("src");
    var currAlt = $(this).attr("alt");
    var currTitle = $(this).attr("title");
    var newSrc, newAlt, newTitle;
    
    newSrc = currSrc.replace("plus", "minus");
    newAlt = currAlt.replace("Show", "Hide");
    newTitle = currTitle.replace("Show", "Hide");
    
    $(this).attr("src", newSrc);
    $(this).attr("alt", newAlt);
    $(this).attr("title", newTitle);
 }
 
 //Sets the initial state for the filter panel and binds the click event
 function AnimateFilterPanel()
 {
    $("#filterPanel").children(".showHideIcon").click(function()
        {
            $(this).parent("#filterPanel").each(SwitchFilterPanelState);
        }
    );
    $(".filterHeading").click(function()
        {
            $(this).parent("#filterPanel").each(SwitchFilterPanelState);
        }
    );
 }
 
 function AnimateCaseStudyPanel()
 {
    $("#caseStudyPanel").children(".showHideIcon").click(function()
        {
            $(this).parent("#caseStudyPanel").each(SwitchFilterPanelState);
        }
    );
    $(".caseStudyHeading").click(function()
        {
            $(this).parent("#caseStudyPanel").each(SwitchFilterPanelState);
        }
    );
 }
 
 //Switches the filter panel between open and closed
 function SwitchFilterPanelState(i)
 {
     if ($(this).children(".contents:visible").size() == 0) {
         $(this).children(".contents").slideDown();
     }
     else {
         $(this).children(".contents").slideUp();
     }
    
    $(this).children(".showHideIcon").each(SwitchShowHideIconState);
 }
 
 //Switches the show/hide icon between open and closed
 function SwitchShowHideIconState(i)
 {
    var currSrc = $(this).attr("src");
    var currAlt = $(this).attr("alt");
    var currTitle = $(this).attr("title");
    var newSrc, newAlt, newTitle;
    
    if(currSrc.match("minus"))
    {
        newSrc = currSrc.replace("minus", "plus");
        newAlt = currAlt.replace("Hide", "Show");
        newTitle = currTitle.replace("Hide", "Show");
    }
    else
    {
        newSrc = currSrc.replace("plus", "minus");
        newAlt = currAlt.replace("Show", "Hide");
        newTitle = currTitle.replace("Show", "Hide");
    }
    
    $(this).attr("src", newSrc);
    $(this).attr("alt", newAlt);
    $(this).attr("title", newTitle);
 }
 
 //Animates the work select boxes on the Our Work page
 function AnimateWorkSelectBoxes()
 {
    $(".workSelect").change(SetWorkSelectBoxState);
}

// called when the viewer needs to be loaded
function DisplayViewerLoading() {
    _viewerLoaded = false;
    $("#viewerLoading").fadeIn('fast');
}

// called when the viewer has loaded
function HideViewerLoading() {
    $('#viewerLoading').fadeOut('fast', function() { _viewerLoaded = true; });
}
 
 //Disables/enables work select boxes on the Our Work page, where appropriate
 function SetWorkSelectBoxState()
 {
    if($(this).val() != "-1")
    {
        $(".workSelect").not(this).addClass("filterFieldsDisabled");
        $(".clientSelect").not(this).addClass("filterFieldsDisabled");
           
        $(".workSelect").not(this).val(-1);   
    }
    else
    {
        $(".workSelect").removeClass("filterFieldsDisabled");
        $(".clientSelect").removeClass("filterFieldsDisabled");
    }
 }
 
 function AnimateFilterHeading()
 {
    $(".filterHeading").hover(function() {
        $(this).addClass("headingHover");
    }, function() {
        $(this).removeClass("headingHover");
    });
 }
 
 function AnimateFilterHeading()
 {
    $(".caseStudyHeading").hover(function() {
        $(this).addClass("headingHover");
    }, function() {
        $(this).removeClass("headingHover");
    });
 }
 
 //Hides drop down options for work filter
 function HideOptions(event)
 {
    //Get the element which now has focus
    var target = event.explicitOriginalTarget || document.activeElement;
    if(!$(target).hasClass("options"))
        $(this).siblings('.options').hide();
 }
 
 //Called by drop down options for work filter to hide itself
 function HideSelf(event)
 {
    //Get the element which now has focus
    var target = event.explicitOriginalTarget || document.activeElement;
    
    if($(target).hasClass("optionSelect"))
    {
        if($(this).siblings("#" + $(target).attr("id")).size() == 0)
            $(this).hide();
    }
    else
        $(this).hide();
 }
 
 //Animates the work viewer menu on the campaign page
 function AnimateWorkViewMenu()
 {
     //$(".menuItem a").click(OpenWorkView).attr("href","#");
 }
 
 //Opens an individual work view within the work viewer
 function OpenSpecificWorkView(workType, index) {

     var viewer;

     if (_viewerLoaded) {

         viewer = $("#" + workType);

         //In case browser is IE and the new workview is not for
         //Broadcast, pause all existing videos, since IE
         //caches all Flash objects.
         if (jQuery.browser.msie && workType != "broadcast") {
             pauseAllVideos();
         }

         if (viewer.siblings("." + workType + ":visible").size() == 0) {
             viewer.siblings(".viewer").removeClass("viewerSelected");
             viewer.siblings(".viewer." + workType).addClass("viewerSelected");
             viewer.siblings(".menuItem").children("a").removeClass("selected");
             viewer.children("a").addClass("selected");
         }

         _inHover = false;
         _activeFancyBoxIndex = -1;
         _hideToolTip = false;
         _buildToolTip = false;
         _inFancyboxHover = false;

         if (!GetAnimatedForWorkType(workType)) {
             AnimateCarousels();
             ActivateFancyBox();
         }
         else {
             var workType = GetCurrentWorkType();
             var workTypeMainCarousel = GetWorkTypeMainCarousel(workType);
             var workTypeThumbsCarousel = GetWorkTypeThumbsCarousel(workType);

             if (workTypeMainCarousel != null)
                 _mainCarousel = workTypeMainCarousel;

             if (workTypeThumbsCarousel != null)
                 _thumbsCarousel = workTypeThumbsCarousel;
         }

         JumpToCarouselIndex(_mainCarousel, index);
         JumpToCarouselIndex(_thumbsCarousel, index);

     }
     
     return false;
 }

 function OpenWorkView(event) {
 
     OpenSpecificWorkView($(this).parent(".menuItem").attr("id"), 1);
     event.stopImmediatePropagation();
     
     return false;
 }
 
 //Sets the animated value for a work type carousel
 function SetAnimatedForWorkType(workType)
 {
    if(workType == "broadcast")
        _broadcastAnimated = true;
    else if(workType == "print")
        _printAnimated = true;
    else if(workType == "digital")
        _digitalAnimated = true;
 }
 
 //Gets the animated value for a work type carousel
 function GetAnimatedForWorkType(workType)
 {
    if(workType == "broadcast")
        return _broadcastAnimated;
    else if(workType == "print")
        return _printAnimated;
    else if(workType == "digital")
        return _digitalAnimated;
 }
 
 function SetWorkTypeMainCarousel(workType, carousel)
 {
    if(workType == "broadcast")
        _broadcastMainCarousel = carousel;
    else if(workType == "print")
        _printMainCarousel = carousel;
    else if(workType == "digital")
        _digitalMainCarousel = carousel;
 }
 
 function GetWorkTypeMainCarousel(workType)
 {
    if(workType == "broadcast")
        return _broadcastMainCarousel;
    else if(workType == "print")
        return _printMainCarousel;
    else if(workType == "digital")
        return _digitalMainCarousel;
 }
 
 function SetWorkTypeThumbsCarousel(workType, carousel)
 {
    if(workType == "broadcast")
        _broadcastThumbsCarousel = carousel;
    else if(workType == "print")
        _printThumbsCarousel = carousel;
    else if(workType == "digital")
        _digitalThumbsCarousel = carousel;
 }
 
 function GetWorkTypeThumbsCarousel(workType)
 {
    if(workType == "broadcast")
        return _broadcastThumbsCarousel;
    else if(workType == "print")
        return _printThumbsCarousel;
    else if(workType == "digital")
        return _digitalThumbsCarousel;
 }
 
 function GetCurrentWorkType() {
    return $(".menuItem a.selected").parent(".menuItem").attr("id");
 }
 
 //Animates the carousels within the work viewer
 function AnimateCarousels()
 {
    SetAnimatedForWorkType(GetCurrentWorkType());

    $('.mainCarousel:visible').jcarousel({
        start: g_startIndex,
        scroll: 1,
        initCallback:   mainCarousel_initCallback,
        itemVisibleInCallback: {
            onAfterAnimation:  mainCarousel_itemVisibleInCallbackAfterAnimation
        },
        itemVisibleOutCallback: {
            onBeforeAnimation:  mainCarousel_itemVisibleOutCallbackAfterAnimation
        }
    });

    $('.thumbsCarousel:visible').jcarousel({
        start: g_startIndex,
        scroll: 3,
        initCallback:   thumbsCarousel_initCallback
    });
    
    $(".mainCarousel:visible").children(".jcarousel-item").hoverIntent(ShowItemTitle, HideItemTitle);

    //$(".mainCarousel:visible").children(".jcarousel-item").click(OpenLargeCarousel);

    $(".mainCarousel:visible").children(".jcarousel-item").click(function(e) {

        var currIndex = $(this).attr("jcarouselindex");
        $("#" + GetCurrentWorkType() + "-enlarged-item-" + currIndex).trigger("click");
        
        return false;
    });

    //var currIndex = $(this).attr("jcarouselindex");
    //$("#" + GetCurrentWorkType() + "-enlarged-item-" + currIndex).trigger("click");
    
    $(".itemLink a").click(function(e) { e.stopImmediatePropagation(); });
    
    $(".thumbsCarousel:visible").children(".jcarousel-item").click(OpenMainWork);
    
    $(".mainCarousel:visible").children(".jcarousel-item").children(".canEnlarge").hover(function(e){											  								  
		_buildToolTip = true;
		if(!_hideToolTip)
		{
		    CreateEnlargeToolTip(e, $(this));
		}
    },
	function(){	
		_buildToolTip = false;
		RemoveEnlargeToolTip();
    });	
    
    $(".mainCarousel:visible").children(".jcarousel-item").children(".canEnlarge").children(".itemLink").hover(function(e){
        _hideToolTip = true; 
        RemoveEnlargeToolTip();
    },function(e){
        _hideToolTip = false;
        
        if(_buildToolTip)
            CreateEnlargeToolTip(e, $(this).parent(".canEnlarge"));
    });
    
    $(".mainCarousel:visible").children(".jcarousel-item").children(".canEnlarge").children(".itemLink").click(function(e){e.stopPropagation();});
    
	$(".mainCarousel:visible").children(".jcarousel-item").children(".canEnlarge").mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - _toolTipYOffset) + "px")
			.css("left",(e.pageX + _toolTipXOffset) + "px");
	});	
 }
 
 //Creates the enlarge tooltip
 function CreateEnlargeToolTip(e, obj)
 {
    $("body").append("<img id='tooltip' src='/_different/i/workviewer/enlarge_tooltip.png' />");
    $("#tooltip")
	    .css("top",(e.pageY- _toolTipYOffset) + "px")
	    .css("left",(e.pageX + _toolTipXOffset) + "px")
	    .fadeIn("fast");
 }
 
 //Removes the enlarge tooltip
 function RemoveEnlargeToolTip()
 {
	$("#tooltip").remove();
 }
 
 //Opens the large carousel modal dialog
 function OpenLargeCarousel() {

     var currIndex = $(this).attr("jcarouselindex");
     $("#" + GetCurrentWorkType() + "-enlarged-item-" + currIndex).trigger("click");

     return false;
 }
 
//Opens the main work onces a thumbnail has been clicked
function OpenMainWork() {

    var index = $(this).attr("jcarouselindex");
    if(_mainCarousel != null) {
        JumpToCarouselIndex(_mainCarousel, index);
    }
}
 
 //Moves a carousel to an index without sliding
 function JumpToCarouselIndex(carousel, index) {

    carousel.options.animation = 0;
    carousel.scroll(index);
    carousel.options.animation = "fast";

    // ie6 fix as the viewer images (in the work category not displayed first)
    // are not displayed without it
    $(".viewerSelected .itemContainer img").css("display", "block");
 }
 
 //Moves the thumbnails carousel to the required set
 function JumpToRequiredThumbsSet(index, animate)
 {
    if(index < _thumbsCarousel.first || index > _thumbsCarousel.last)
    {
        var requiredSet = index / 3;
        var scrollTo = (Math.ceil(requiredSet) * 3) - 2;
        
        if(!animate)
            JumpToCarouselIndex(_thumbsCarousel, scrollTo);
        else
            _thumbsCarousel.scroll(scrollTo);

    }
 }
 
 //Shows the title in the work viewer
 function ShowItemTitle()
 {
    _inHover = true;
    $(this).children(".itemContainer").children(".itemTitle").slideDown();
 }
 
 //Hides the title in the work viewer
 function HideItemTitle()
 {
    _inHover = false;
    $(this).children(".itemContainer").children(".itemTitle").slideUp();
 }
 
 /**
 * This is the callback function which receives notification
 * right after initialisation of the carousel
 */
function mainCarousel_initCallback(carousel, state) {
    _mainCarousel = carousel;
    SetWorkTypeMainCarousel(GetCurrentWorkType(), carousel);
};

/**
 * This is the callback function which receives notification
 * right after initialisation of the carousel
 */
function thumbsCarousel_initCallback(carousel, state) {
    _thumbsCarousel = carousel;
    SetWorkTypeThumbsCarousel(GetCurrentWorkType(), carousel);
    $(".thumbsCarousel:visible").children(".jcarousel-item-" + _mainCarousel.options.start).addClass("jcarousel-active-item");
    
    if ( $.browser.msie && $.browser.version.slice(0,1) == "6" ) {
        // in IE6 the thumbnails need to be "touched" after the carousel has been initialized to be shown - setting this through css has no effect.
        $(".jcarousel-skin-thumb .itemContainer img.item").css("zoom","1");
    }
};
 
 /**
 * This is the callback function which receives notification
 * when an item becomes the first one in the visible range.
 * Triggered after animation.
 */
function mainCarousel_itemVisibleInCallbackAfterAnimation(carousel, item, idx, state) {

    setTimeout("$('.mainCarousel:visible').children('.jcarousel-item-" + idx + "').children('.itemContainer').children('.itemTitle').slideDown();", 1000);
    setTimeout("if(!_inHover) $('.mainCarousel:visible').children('.jcarousel-item-" + idx + "').children('.itemContainer').children('.itemTitle').slideUp();", 3000);
    if(_thumbsCarousel != null)
    {
        JumpToRequiredThumbsSet(idx, true);
    }
    
    $(".thumbsCarousel:visible").children(".jcarousel-item").removeClass("jcarousel-active-item");
    $(".thumbsCarousel:visible").children(".jcarousel-item-" + idx).addClass("jcarousel-active-item");
};

//Called when an item is no longer in the visible range
function mainCarousel_itemVisibleOutCallbackAfterAnimation(carousel, item, idx, state) {

    if (typeof item.getElementsByTagName === "function") {
        var htmlElArray = item.getElementsByTagName('object');

        if (htmlElArray.length > 0) {
            pauseVideo(htmlElArray[0].id);
        }
    }
}

function pauseAllVideos() {
    $("object[id*='PreviewVideobroadcastFl']").each(function() {
        var thisObject = $(this).get();
        var id = thisObject[0].id;
        
        pauseVideo(id);
    });
}

function pauseVideo(videoObjectId) {
    var el = swfobject.getObjectById(videoObjectId);

    if (el != null) {
        try{
            el.pauseVideo();
        } catch(e)
        { }
    }    
}

//Activates the fancy box
function ActivateFancyBox() {
    
    $("a." + GetCurrentWorkType() + "Enlargements").fancybox({
        'frameWidth': 860,
        'frameHeight': 484,
        'hideOnContentClick': false,
        'imageScale': false,
        'treatImageAsInline': true,
        'padding': 45,
        'callbackOnShow' : fancybox_callbackOnShow,
        'callbackOnClose' : fancybox_callbackOnClose
    });
}

//Adds a title to the fancybox
function AddTitleToFancyBox()
{
    var title = $("#fancy_img").attr("title");
    if(title != null && title != '')
    {
        $("#fancy_inner").append("<div id='fancyTitle'>" + title + "</div>");
    }
}

//Removes a title from the fancybox
function RemoveTitleFromFancyBox()
{
    $("#fancyTitle").remove();
} 

//Adds a visit website link to the fancybox
function AddLinkToFancyBox()
{
    var currItem = $("#fancy_img").attr("item");
    if(currItem != null && currItem != '' && !isNaN(currItem))
    {
        if($("#" + GetCurrentWorkType()  + "-enlargements-link-" + currItem).size() == 1)
        {
            var link = $("#" + GetCurrentWorkType()  + "-enlargements-link-" + currItem);
            var href = link.attr("href");
            var title = link.attr("title");
            var text = link.text();
            
            $("#fancy_content").append("<div class='itemLink'><a href='" + href + "' title='" + title + "' target='_blank'>" + text + "</a></div>");
        }
    }
}

//Called when a fancybox image is shown
function fancybox_callbackOnShow() {
    
    _inFancyboxHover = false;
    SetActiveFancyBoxIndex();
    AddLinkToFancyBox();
    RemoveTitleFromFancyBox();
    AddTitleToFancyBox();
    $("#fancy_title").hide();
    setTimeout("$('#fancyTitle').slideDown();", 1000);
    setTimeout("if(!_inFancyboxHover) $('#fancyTitle').slideUp();", 3000);
    
    $("#fancy_content").hoverIntent(function(){
        _inFancyboxHover = true;
        $("#fancyTitle").slideDown();
    },function(){
        _inFancyboxHover = false;
        $("#fancyTitle").slideUp();
    });
}

//Called when a fancybox is closed
function fancybox_callbackOnClose()
{
    UpdateCarouselFromFancyBox();
}

//Sets the current fancy box index
function SetActiveFancyBoxIndex()
{
    _activeFancyBoxIndex = $("#fancy_img").attr("item");
}

//Updates the main carousel based on the current fancy box state
function UpdateCarouselFromFancyBox()
{
    if(_mainCarousel != null && (_activeFancyBoxIndex != -1 && _activeFancyBoxIndex != null && _activeFancyBoxIndex != ''))
    {
        JumpToCarouselIndex(_mainCarousel, _activeFancyBoxIndex);
    }
}

// Initilises the who we are pop panels
function InitWhoWeAre() {

    $(".profilePopUp a:not(.closePopUp)").click(function(e) {
        e.stopImmediatePropagation();
        return true;
    });

    $(".whoweare li").click(function() {
        var newPopup = $(this).children(".popUpWrap");
        var isVisible = newPopup.is(":visible");

        if (!isVisible) {

            // position the panel for ie6 only
            if (jQuery.browser.msie && jQuery.browser.version == "6.0") {
                newPopup.css("top", $(this).css("top"));
                newPopup.css("left", $(this).css("left"));

                $(".popUpWrap").hide();
                newPopup.show();
            }
            else {
                $(".popUpWrap").fadeOut();
                newPopup.fadeIn();
            }
        }

        return false;
    });

    $(".popUpWrap .closePopUp").click(function(e) {
    
        if (jQuery.browser.msie && jQuery.browser.version == "6.0")
            $(this).parents(".popUpWrap").hide();
        else
            $(this).parents(".popUpWrap").fadeOut();
            
        e.stopPropagation();
        return false; 
    });

    $(".profilePanels li").hoverIntent(function() {
        $(this).find(".staffName").slideDown(100);
    },
    function() {
        $(this).find(".staffName").slideUp();
    });
}

function printArticleFormatting()
{
    $('.div.greenPanel').removeClass('greenPanel');
}

//Method responsible for enabling the showreel overlay box
function EnableShowreelOverlayBox() {
    var attributes = { 'hideOnOverlayClick': true, 'hideOnContentClick': false, 'frameWidth': 578, 'frameHeight' : 370, 'callbackOnShow': OnShowreelOverlayLoaded, 'overlayOpacity' : 0.5 };

    //In case JS is enabled, since it arrived here, redirect link to open fancybox.
    $("a.showreelOverlayBox").attr("href", _showReelJSEnabledPage);
    $("a.showreelOverlayBox").fancybox(attributes);
}

//Enable Showreel tabs once the overlay box is loaded
function OnShowreelOverlayLoaded() {
    //Wait for the UI Tabs to configure properly, before displaying the content
    $("div#fancy_inner div#fancy_ajax").css("display", "block");

    $("#tabs").tabs({ select: OnShowreelTabSelected, selected : 0 });
}

//Once a tab is selected, pause the other video
function OnShowreelTabSelected(event, ui) {
    var selectedPanel = ui.panel;
    var siblingPanel = $(selectedPanel).siblings("div.ui-tabs-panel");

    siblingPanel.each(function() {
        var flashObjectID = $(this).children("object").attr("id");
        pauseVideo(flashObjectID);
    });
}

//Set a Click Event Handler to the Facebook Share button
function SetFacebookShareBtnClickHandler() {
    $("a.addthis_button_facebook").click(FacebookBtnClicked);
}

//Once the Facebook button is clicked, open a new sized window.
function FacebookBtnClicked() {
    window.open($(this).attr("href"), null, "width=550, height=450");
    return false;
}

// hides all the non visible images on the home page scroller
// to avoid the horrible looking jump when loading the page
function HideNonVisibleSlides() {
    var slides = $("#slides").find("a");
    //$(slides).filter(function () { return $(this).attr("style") == "display:none"; }).attr("style", "display:none");
    $(slides).attr("style", "display:none");
}

function StripHiddenClass() {
    var slides = $("#slides");
    if ($(slides).hasClass("fixHeight")) {
        $(slides).removeClass("fixHeight");
    }
}
