﻿var _prm = Sys.WebForms.PageRequestManager.getInstance();
var _elPostBackItem = null;
var _blContinueAutoNavigation = true;
var _blTopDownThumbsAnimationBusy = false;
var _intContentNewHeight = 0;
var _intThumbsNewHeight = 0;
var _blCarouselOpen = false;
var _toggleThumbsButton;
var _intVideoID = 0;
var _defaultTitle = window.document.title;
var _activePanel = null;

Sys.Application.add_init(OnApplicationInitHandler);

function OnApplicationInitHandler(sender, args) {
    // Declare thumbstoggle- and close button.
    _toggleThumbsButton = $("#toggleThumbsButton");

    // Register event handlers.
    RegisterEventHandlers();

    // Get video id.
    _intVideoID = $('#elements').find("input:first + input").val();

    // Set default active panel.
    _activePanel = $get($('#elements div:first').attr('id'));

    // Show playbutton if project has video.
    ShowOrHidePlayButton();

    // Set the page title.
    SetPageTitle();

    // Start project timer automatic countdown to next project.
    if (1 < $('#pnlProjectsThumbs').find('li').length) {
		StartProjectTimerCountdown();
	} else {
		$('#projecttimer').hide();	
	}

    // Initialize carousel if not IE6.
    if (!(Sys.Browser.agent == Sys.Browser.InternetExplorer && Sys.Browser.version < 7))
        $('.infiniteCarousel').infiniteCarousel();
}
/// Registers handlers for events of multiple elements and for the pageLoaded Event.
function RegisterEventHandlers() {
    // Register mouseup event handlers for Next and Previous Project buttons.
    $("#lbNextProject").mouseup(function() {
        StopAutoCountdownToNextProject();
    });
    $("#lbPrevProject").mouseup(function() {
        StopAutoCountdownToNextProject();
    });
    $("#page").live("mouseup", function() {
        StopAutoCountdownToNextProject();
    });

    // Show thumbnail toggle button after some time.
    if (1 < $('#pnlProjectsThumbs').find('li').length) {
		setTimeout('slideInToggleThumsButton()', 500);
	}

    // Register click event handler for toggle button, which shows the thumbnails infinite carrousel panel.
    _toggleThumbsButton.click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        ShowHideThumbsBox();
        return false;
    });

    // Add PageRequestManager event handlers.
    _prm.add_initializeRequest(OnInitializeRequestHandler);
    _prm.add_pageLoaded(OnPageLoadedHandler);
}
/// Handles the initialization of a asynchronous postback event.
function OnInitializeRequestHandler(sender, args) {
    // Get reference to element which is the cause of a AsyncPostBack.
    _elPostBackItem = args.get_postBackElement();

    // Stop countdown and auto navigation when a specific project is requested via a ajax historypoint url.
    if (_elPostBackItem.id == "scriptmanager")
        StopAutoCountdownToNextProject();
}
/// Raised after all content on the page is refreshed, as a result of either a synchronous or an asynchronous postback.
function OnPageLoadedHandler(sender, args) {
    var arrUpdatedPanels = args.get_panelsUpdated();
    var elElements = $get('elements');

    if (arrUpdatedPanels.length == 3) {
        // Project was chosen from thumbnail box.
        ShowHideThumbsBox();

        // Set default active panel.
        _activePanel = $get($('#hfActivePanelID').val());

        // Get video id.  
        _intVideoID = $(_activePanel).find("input:first + input").val();

        // Show playbutton if project has video.
        ShowOrHidePlayButton();

        // Set the page title.
        SetPageTitle();
    }

    if (arrUpdatedPanels.length == 2) {
        // Get reference to updated panel.
        _activePanel = arrUpdatedPanels[0];

        if (_elPostBackItem.id == 'lbNextProject') {
            // Next project button is clicked.

            // If needed append the panel to the container to make it the last node, needed for animation.
            var divCount = 0;
            for (var i = 0; i < elElements.childNodes.length; i++) {
                if (elElements.childNodes[i].nodeType == 1)
                    divCount++;

                if (_activePanel != elElements.childNodes[i] && divCount == 2)
                    elElements.appendChild(_activePanel);
            }

            // Perform content switch and animate to the left.
            PerformContentSwitchAndAnimations(elElements, "left");
        } else {
            // Previous project button is clicked or scriptmanager caused a postback for a ajax historypoint url.

            // Insert the panel to the container as the first node, needed for animation.
            elElements.insertBefore(_activePanel, elElements.childNodes[0]);

            // Perform content switch and animate to the right.
            PerformContentSwitchAndAnimations(elElements, "right");
        }

    }
}
/// Resets the Title panel of next or previous item.
/// Positions the projects container panels.
/// Loads the project content in the Flash movie.
/// Animates the html elements.
function PerformContentSwitchAndAnimations(elElements, strDirection) {
    // Set position values according to direction.
    var strPosition1, strPosition2, strPosition3;

    if (strDirection == "right") {
        strPosition1 = "-910px";
        strPosition2 = "910px";
        strPosition3 = "0px";
    } else {
        strPosition1 = "0px";
        strPosition2 = "910px";
        strPosition3 = "-910px";
    }

    // Get ListItem ID.
    var intListItemID = $(_activePanel).find("input:first").val();
    _intVideoID = $(_activePanel).find("input:first + input").val();

    // Position the panels so that the old is visible and the new is outside the left or right border.
    elElements.style.left = strPosition1;

    // Set the page title.
    SetPageTitle();

    // Show a playbutton if project has video otherwise hides it if already showing.
    ShowOrHidePlayButton();

    // When animating to the right, position element first before animating.    
    if (strDirection == "right")
        $('.visual_content_flash').css("left", strPosition1);
    if (strDirection == "left")
        $('.visual_content_flash').css("left", strPosition2);

    // Animate flash panel.
    $('.visual_content_flash').animate({ left: '0px' }, {
        queue: false, duration: 700, easing: 'easeInOutExpo'
    });

    // Animate to make the new visible and the old outside the left or right border.
    $('#elements').stop().animate({
        left: strPosition3
    }, {
        queue: false, duration: 700, easing: 'easeInOutExpo', complete: function() {
            // Hide the thumbs panel.
            if (_blCarouselOpen) ShowHideThumbsBox();

            // Start countdown and navigating to next project.
            // Do not start when a specific project is requested via a ajax historypoint url.
            if (_blContinueAutoNavigation)
                StartProjectTimerCountdown();
        }
    });

}
/// Show a playbutton if project has video otherwise hides it if already showing.
function ShowOrHidePlayButton() {
    if (swfobject.getFlashPlayerVersion().major >= 9) {
        if (_intVideoID > 0) {
            // Clear and add no flash text.
            $('.visual_content_flash').html('<img src="/_images/play-button.png" alt="Play Button" />');
            $('.visual_content_flash img:first').click(LoadVideoInFlash);
        } else {
            // Clear.
            $('.visual_content_flash').empty();
        }
    } else {
        // Clear.
        $('.visual_content_flash').empty();
    }
}
/// Set the page title.
function SetPageTitle() {
    window.document.title = $(_activePanel).find(".visual_title").text() + ' - ' + _defaultTitle;
}
/// Loads the project video inside flash.
function LoadVideoInFlash() {
    // Stop countdown.
    StopAutoCountdownToNextProject();

    if (_intVideoID > 0) {
        // Clear and add no flash text.
        $('.visual_content_flash').html('<div id="noFlashContent"></div>');

        // Render Flash Object in HTMl page using swfobject.js.
        var flashvars = {};
        flashvars.videoID = _intVideoID;
        var params = {};
        params.wmode = "transparent";
        params.allowScriptAccess = "sameDomain";
        var attributes = {};
        attributes.id = "swfProjectVideoplayer";
        attributes.styleclass = "swfFloatLeft";
        swfobject.embedSWF("/_swf/ProjectVideoplayer.swf", "noFlashContent", "670", "380", "9.0.0", false, flashvars, params, attributes);
    } else {
        // Clear.
        $('.visual_content_flash').empty();
    }

    // Set the page title. (this gets set to hash value after click).
    SetPageTitle();
}
/// Function for showing / hiding the thumbnails carousel.
function ShowHideThumbsBox() {
    var picNewTopPosition = 0;
    if (!_blTopDownThumbsAnimationBusy) {
        _blTopDownThumbsAnimationBusy = true;
        StopAutoCountdownToNextProject();

        if (document.getElementById("pnlProjectsThumbs").offsetHeight < 115) {
            _intThumbsNewHeight = 115;
            picNewTopPosition = 70;
        } else {
            _intThumbsNewHeight = 0;
            picNewTopPosition = 0;
        }

        $(".visual_content").fadeOut(100);
        $(".visual_element").animate({
            top: picNewTopPosition + 'px'
        }, {
            queue: false, duration: 500, easing: 'easeInOutExpo'
        });

        $(".project_thumbs").css({ "overflow": "hidden" });
        var ttb = _toggleThumbsButton;
        ttb.css("background", "none");
        ttb.width(0);
        $("#pnlProjectsThumbs").animate({
            height: _intThumbsNewHeight + 'px'
        }, {
            queue: false, duration: 500, easing: 'easeInOutExpo', complete: function() {
                _blTopDownThumbsAnimationBusy = false;
                if (document.getElementById("pnlProjectsThumbs").offsetHeight == 115) {
                    $(".project_thumbs").css({ "overflow": "visible" });
                    ttb.height(380);
                    ttb.width(910);
                    $(".visual_content").fadeOut(100);
                    _blCarouselOpen = true;
                    ttb.css("background", "url('../_images/thumbstoggle-close.png') no-repeat 10px 120px");
                } else {
                    ttb.height(90);
                    setTimeout('slideInToggleThumsButton()', 500);
                    $(".visual_content").fadeIn(150);
                    _blCarouselOpen = false;
                    ttb.css("background", "url('../_images/thumbstoggle.png') no-repeat 10px 10px");
                }
            }
        });
    }
}
/// Function for projecttimer automatic countdown to next project
function StartProjectTimerCountdown() {

    var opacityValue = 10;
    var pt = $("#projecttimer");
    pt.width("0px");
	pt.animate({
        width: 0
    }, {
        queue: false,
        duration: 2000,
        easing: "jswing",
        complete: function() {
            pt.css("opacity", (opacityValue / 10));
   			pt.css("filter", "alpha(opacity=" + (opacityValue * 10) + ")");
			pt.animate({
				width: 910
			}, {
				queue: false,
				duration: 10000,
				easing: "jswing",
				complete: function() {
					__doPostBack('lbNextProject', '');
					pt.fadeOut();
				}
			})
        }
    })

}
/// Function for stopping the countdown
function StopAutoCountdownToNextProject() {
    // Set boolean to false, so that the auto navigating to the next project stops.
    _blContinueAutoNavigation = false;

    var pt = $("#projecttimer");
    pt.stop();
    pt.fadeOut();
}

// Function for sliding in the toggleThumbs button whichs shows and hides the thumbnail carousel.
function slideInToggleThumsButton() {
    _toggleThumbsButton.css("background-position", "-500px 10px");
    _toggleThumbsButton.width(200)
    _toggleThumbsButton.animate({
        backgroundPosition: "(10px 10px)"
    }, {
        queue: false,
        duration: 1000,
        easing: "easeInOutExpo"
    });
}
