﻿    var currentlyScrolling = false,
    animatingPage = true, // Block behaviors until page is loaded.
    animatingMenu = false;
    var secondaryMenuOpened = false;
    $(document).ready(function () {
    
        var hash = window.location.hash.slice(1);
 
        resizeContent();
   
   
        if (hash != "") {

            loadUrl(hash);
        }
        maniMenuAnimation();
        runLoadAnimations();
        setupMenuBehaviors();



    });
    $(window).resize(function () {
        resizeContent();
    });
    $(window).bind('hashchange', function () { //detect hash change
        var hash = window.location.hash.slice(1); //hash to string (= "myanchor")
        if (hash != "") { loadUrl(hash) };
    });
    function resizeContent() {
	    var sidleeWidth =
		      $(window).width()
		    - 39;
	    $('#rightPanel').width(sidleeWidth);
	    if ($('#rightPanelFull').is(':visible')) {
		    $('#rightPanel').css('left', -sidleeWidth + 197);
	    }

	    // Resize contentPanel container to fit content and rightPanel width.
	    $('#contentPanel').width(
		      $(window).width()
		    //+ $('#rightPanel').outerWidth(true)
		    //+ 500 /* abritrary buffer to prevent float wrapping */
		    );

	    // Resize content to fit window width.
	    $('#content').width(
		      $(window).width()
		    - $('#secondaryMenu').width() // Opened menu width
		    - $('#mainMenu').width()  // Closed rightPanel
		    );

	    resizeContentBackground();

	    // Resize page height.
	    $('#page').height($(window).height());
	    $('#page #content > div.scroll > div').height($(window).height());
	    $('#page #content .contentWrap').height($(window).height());

	    centerContentVertically();
	    $('#homeContent').isotope({
	        // options
	        itemSelector: '.chosenProjects',
	        layoutMode: 'cellsByRow'
	    });

    }
    var backgroundMargin={
	    w:0,
	    h:0
    };
    function resizeContentBackground() {
	
	    var media = $("#content img.background");
	    var mediaSize={
		    h:600,
		    w:720
	    };
	
	    var holder = $('#content');
	    var holderSize = {
		    h:holder.height(),
		    w:holder.width()
	    }
	
	    // adjust media to it's parent width
	    // make sure orginal media ratio is respected
	
	
	    var tW = holderSize.w;
	    var tH = (holderSize.w / mediaSize.w) * mediaSize.h;
	
	    if(tH < holderSize.h){
		    var tH = holderSize.h;
		    var tW = (holderSize.h / mediaSize.h) * mediaSize.w
	    }
	
	    var verticalOffset = ($(window).height() - 640) / 2;
	    if (verticalOffset <= 0) verticalOffset = 0;
	
	
	    backgroundMargin={
		    w: tW/-2,
		    h: tH/-2
	    }
	    //apply height width and centers media
	    media.css({
		    'height':tH+'px',
		    'width':tW+'px',
		    'margin-left':(backgroundMargin.w)+'px',
		    'margin-top':(backgroundMargin.h)+'px'
	    });


		    /*
	    var bgImage = $("#content img.background");
	    var currentWidth = $("#content img.background").width();
	    var newWidth = $('#content').width();
	    if (newWidth < 600) {
		    return;
	    }
	    var oldWidth = bgImage.width();
	    var ratio = $(window).height() / $('#content').width();
	    if (ratio > 0.55)
		    newWidth = newWidth + (ratio - 0.55) * 900;
	    bgImage.width(newWidth);
	    */
	
    }

    function centerContentVertically() {
	    var verticalOffset = ($(window).height() - 640) / 2;
	    if (verticalOffset <= 0) verticalOffset = 0;
	    //console.log('Vertical centering offset: ' + verticalOffset);
	    $('#mainMenu ul').css('margin-top', verticalOffset);
	    $('#secondaryMenu #containerNum').css('margin-top', verticalOffset);
	    //$('#content > div.scroll > div').css('padding-top', verticalOffset);
	    //$('#content .contentWrap').css('padding-top', verticalOffset);
	
	    //$('#content img.background').css('margin-top', backgroundMargin.h-verticalOffset);
	    //$('#content img.background').css('top', -verticalOffset);
	    $('#content .alignTop').css({'top':-verticalOffset, 'position':'relative'});
	    if (verticalCenterResizeCallback) verticalCenterResizeCallback();
    }

    var verticalCenterResizeCallback = null;
    function startCenterElementVertically(elementParam) {
	    // Create a new closure to hold current value.
	    var closure = function() {
		    var element = elementParam;
		    var container = element.parent();
		    var offsetTop =  (Math.min(container.height(), $(window).height()) - element.height()) / 2;
		    if (offsetTop < 0) offsetTop = 0;
		    container.css('padding-top', offsetTop);
	    };

	    // Add closure to hash.
	    verticalCenterResizeCallback = closure;

	    // Call closure now.
	    closure();
    }

    function stopCenterElementVertically() {
	    verticalCenterResizeCallback = null;
    }
    function runLoadAnimations() {
        animateInitialMenu();
        //animateListMenu();
        //animateListLang();
        //animateListSociaux();
    }

    function animateInitialMenu() {
        var debug = false;
        if (debug) {
            $('#page').css('margin-left', '0');
            $('#content').show();
            $('#rightPanel').show().css('left', '-45px');
            animatingPage = false;
            return;
        }

        // Freeze all behaviors (hover, click) until animations are done.
        animatingPage = true;
        $('#page').delay(500).animate({ 'margin-left': "0" }, 400, function () {
            resizeContentBackground();
            //set
            //$('#rightPanelClosed,.tvIcon').hide();
            $('#content').delay(400).fadeIn(600, function () {
                // Replace adel's and nic's code below
                $('#rightPanel').show().delay(400).animate({ 'left': "-45px" }, 600, function () {
                    rightPanel.closedToPreview(function () {
                        rightPanel.previewToClosed();

                        //TODO - use callback to set 'animating' flag after preview closed.
                        // Animations are finished, enable behaviors.
                        animatingPage = false;
                    });
                });

            });
        });
    }

    function setupMenuBehaviors() {

        // Initial mouseenter event before first click.
        $('#mainMenu').mouseenter(function (e) {
            if ($('#rightPanelFull').is(':visible')) {
                rightPanel.fullToClosed();
            }
            if ($('#rightPanelPreview').is(':visible')) {
                rightPanel.previewToClosed();
            }
        });

        $('#mainMenu ul').hover(function (e) {
            if (animatingPage || animatingMenu) return false;
            $('#mainMenu li a').stop(true, false).animate({ 'color': '#7a7a7a' }, 200);

        }, function (e) {
            if (animatingPage || animatingMenu) return false;
            $('#mainMenu li a').stop(true, false).animate({ 'color': '#F8F8F8' }, 200);
        });

   
        var lastOverItem;
        $('#mainMenu li a').hover(function () {

            if (animatingPage || animatingMenu) return false;
            if ($(this).hasClass('on')) return;
            if (lastOverItem) lastOverItem.stop(true, true);
            lastOverItem = $(this);
            $(this).stop(true, true).animate({ 'color': '#F8F8F8' }, 250);
        }, function (e) {
            if (animatingPage || animatingMenu) return false;
            if ($(this).hasClass('on')) return;
            $(this).stop(true, true).animate({ 'color': '#7a7a7a' }, 250);
        });

    //    $('#mainMenu li a').click(function () {
    //        if (animatingPage || animatingMenu) return false;
    //        if (secondaryMenuOpened)
    //            expandSecondaryMenu();
    //        else
    //            setupSecondaryMenu();
    //        var id = $(this).parent().attr('id');
    //        loadPage(id);
    //        return false;
    //    });


        $('#secondaryMenu').mouseleave(function (e) {
            // Prevent collapse when leaving left of menu.
            if (e.pageX > 240) { // && ! animatingMenu) {
                animatingMenu = true;
//                collapseSecondaryMenu(function () {
//                    animatingMenu = false;
//                });
            }
        });
    }

    function setupSecondaryMenu() {
    
        if (secondaryMenuOpened) return;
        secondaryMenuOpened = true;
        animatingMenu = true;
        openSecondaryMenu(function () {
            animatingMenu = false;
        });
        setupFinalMenuBehaviors();
    };

    function setupFinalMenuBehaviors() {
        $('#mainMenu ul').unbind('mouseenter');
        $('#mainMenu ul').unbind('mouseleave');

        $('#mainMenu').mouseenter(function (e) {
            if ($('#rightPanelFull').is(':visible')) {
                rightPanel.fullToClosed();
                return;
            }
            if ($('#rightPanelPreview').is(':visible')) {
                rightPanel.previewToClosed();
                return;
            }
            if (e.pageX < 40 && !animatingMenu && !currentlyScrolling)
                animatingMenu = true;
            expandSecondaryMenu(function () {
                animatingMenu = false;
            });
        });
    }
    function maniMenuAnimation() {

        $('#mainLink li a').click(function () {
            var lval =trimit($(this).text());
            //alert(lval);
            $('#secondaryMenu').hide("fast", function () {

                $.ajax({
                    url: "secondaryMenuPage.aspx?link=" + lval,
                    cache: false,
                    success: function (html) {
                        $("#secondaryMenu").html(html);
                        $('#secondaryMenu').show("fast", function () { 
                         //secondaryMenuSetup();
                        });
                   
                    }
                });




            });
        });
  
    }
    function trimit(str) {

        if (typeof String.prototype.trim !== 'function') {
            String.prototype.trim = function () {
                return str.replace(/^\s+|\s+$/g, '');
            }

        } else {
            return $.trim(str);
        }
    }
    function secondaryMenuSetup() {
        $("#subLink a").click(function () {
            // animatingMenu = true;
            //$("#subLink a").css("border", "3px solid blue");
            var lval2 = trimit($(this).text().trim());
            //window.alert(lval2);
            $('#content').hide("fast", function () {

                $.ajax({
                    url: "contentHolderPage.aspx?link=" + lval2,
                    cache: false,
                    success: function (html) {
                        //alert("SUCC");
                        $("#content").empty();
                        $("#content").html(html);
                        $('#content').show("fast");
                        //animatingMenu = false;
                    }
                });
            });



        });

    }

    function loadUrl(urlIn)
    {
         $('#content').hide("fast", function () {

            $.ajax({
                url: "contentHolderPage.aspx?link=" + urlIn,
                cache: false,
                success: function (html) {
                    //alert("SUCC");
                    $("#content").empty();
                    $("#content").html(html);
                    $('#content').show("fast");
                    //animatingMenu = false;
                }
            });
        });
    }
