﻿debugMode = false;

if (!window.console) {
    window.console = new function () {
        this.log = function (str) { };
        this.dir = function (str) { };
    };
}


// Keep a mapping of url-to-container for caching purposes.
var cache = {
    // If url is '' (no fragment), display this div's content.
    '': $('.bbq-default')
};
var url;

var subpage = null;
var fade = true;


$('span.client').live("click", function () {
    setSubPageElement($(this));
    return false;
});


function setSubPageElement(jqObj) {
    if (!jqObj.hasClass('active')) {
        $('span.client').removeClass('active');
        $('ul.subgallery').slideUp('slow');

        jqObj.toggleClass('active');
        jqObj.toggleClass(function () {
            if (jqObj.is('.active')) {
                jqObj.parent().find('ul.subgallery').slideDown();
                return '';
            }
            else {
                jqObj.parent().find('ul.subgallery').slideDown();
                return '.active';
            }
        });
    }
}


$('h4.awardname').live("click", function () {
    var jqObj = $(this);

    $('h4.awardname').find('span.ui-icon').removeClass('ui-icon-triangle-1-s').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-e');

    if ($(this).next().is(':visible') == false) {
        $('div.award').slideUp('slow');
        $(this).next().slideDown('slow');
        $(this).find('span.ui-icon').removeClass('ui-icon-triangle-1-s').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s');
    }
    else {
        $('div.award').slideUp('slow');
        $(this).find('span.ui-icon').removeClass('ui-icon-triangle-1-s').removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-e');
    }
});


$('#case-studies-body a[href^=#], #news-body a[href^=#], #portfolio-body a[href^=#]').live('click', function (e) {
    fade = false;
    var state = {};

    // Get the id of this .bbq widget.
    id = 'sub';

    // Get the url from the link's href attribute, stripping any leading #.
    url = $(this).attr('href').replace(/^#/, '');

    // Set the state!
    state[id] = url;
    $.bbq.pushState(state);
});


$('a.readmore').live("click", function () {

    var keyword = $(this).attr('rel');

    $('a.readmore').fadeOut(250);

    if ($('#mc_body').attr('class') == 'bodynarrow') {
        $('#mc_body').switchClass("bodynarrow", "bodywide", 500);
    }
    else {
        $('#mc_body').switchClass("bodywide", "bodynarrow", 500);
    }

    $(this).parent().parent().switchClass(keyword + "-copy", keyword + "-copy_expanded", 500);

    setTimeout(function () {
        $('.expanded_text').fadeIn(250);
    }, 500);
});



$('a.readmore_capabilities').live("click", function () {

    var keyword = $(this).attr('rel');

    $('a.readmore').fadeOut(250);

    if ($('#mc_body').attr('class') == 'bodynarrow') {
        $('#mc_body').switchClass("bodynarrow", "bodyfull", 500);
    }
    else {
        $('#mc_body').switchClass("bodyfull", "bodynarrow", 500);
    }

    //$(this).parent().parent().switchClass(keyword + "-copy", keyword + "-copy_expanded", 500);
    $('#capabilities_intro').fadeOut(250);
    setTimeout(function () {
        $('.expanded_text').fadeIn(250);
        $('#mc_body').tinyscrollbar();


    }, 500);
});




$('#news-body span.client').live("click", function () {

    var keyword = $(this).attr('rel');

    $('a.readmore').fadeOut(250);

    if ($('#mc_body').attr('class') == 'bodywide') {
        $('#mc_body').switchClass("bodywide", "bodyfull", 500);
    }
    else {
        //$('#mc_body').switchClass("bodyfull", "bodynarrow", 500);
    }

    //$(this).parent().parent().switchClass(keyword + "-copy", keyword + "-copy_expanded", 500);

    setTimeout(function () {
        $('.expanded_text').fadeIn(250);
        //$('#mc_body').tinyscrollbar();


    }, 500);


    $('#currentwork-body').animate({
        'marginTop': '0'
    });

});





$('#currentwork-body span.client').live("click", function () {

    var keyword = $(this).attr('rel');

    $('a.readmore').fadeOut(250);

    if ($('#mc_body').attr('class') == 'bodywide') {
        $('#mc_body').switchClass("bodywide", "bodyfull", 500);
    }
    else {
        //$('#mc_body').switchClass("bodyfull", "bodynarrow", 500);
    }

    //$(this).parent().parent().switchClass(keyword + "-copy", keyword + "-copy_expanded", 500);

    setTimeout(function () {
        $('.expanded_text').fadeIn(250);
        //$('#mc_body').tinyscrollbar();


    }, 500);


    $('#currentwork-body').animate({
        'marginTop': '0'
    });

});








$(function () {

    $('#mc_body').tinyscrollbar();




    $('img.award[title]').tooltip({
        effect: 'fade',

        // make fadeOutSpeed similar to the browser's default
        fadeOutSpeed: 100,
        position: 'top center',
        offset: [-20, 0],

        // the time before the tooltip is shown
        predelay: 400
    }).dynamic({ bottom: { direction: 'down', bounce: true} });

    var bodyoffset = $('#mc_body').outerWidth();

    $('#imgHide').click(function () {
        bodyoffset = $('#mc_body').outerWidth() - 0;

        $('#mc_body').animate({
            left: '-=' + bodyoffset
        }, 500);
        $("#arrow_hide").fadeOut();
        $("#arrow_show").fadeIn();
    });

    $('#imgShow').click(function () {
        $('#mc_body').animate({
            left: '0'
        }, 500);
        $("#arrow_show").fadeOut();
        $("#arrow_hide").fadeIn();
    });

    fade = true;

    // Reload page every time hash changes
    $(window).bind('hashchange', function (e) {
        loadPage();
    });

    $('#readmoretoggle').click(function () {
        if ($('#mc_body').attr('class') == 'bodynarrow') {
            $('#mc_body').switchClass("bodynarrow", "bodywide", 500);
        }
        else {
            $('#mc_body').switchClass("bodywide", "bodynarrow", 500);
        }
    });

    $('nav ul a').click(function () {
        $('#case_studies_pics').fadeOut(500);
        $('#portfolio_pics').fadeOut(500);
        $('#news_pics').fadeOut(500);
        $('nav ul a').removeClass();
        $(this).addClass('active');
        fade = true;
        $('#imgShow').click();
    });

    $('a#casestudieslink').click(function () {
        cycleStart("case_studies")
    });

    $('a#portfoliolink').click(function () {
        cycleStart("portfolio")
    });

    $.ajax({
        url: "/js/mcohen.json",
        dataType: 'json',
        success: function (data) {

            $.each(data, function (index, value) {
                $('#left_pics').append("<div class=\"bgleft\" style=\"background:url('/img/bg/" + data[index].bgleft + "');\"></div>");
                $('#right_pics').append("<div  class=\"bgright\" style=\"background:url('/img/bg/" + data[index].bgright + "');\"></div>");
            });

            var startIndex = $("nav a[href$='" + getSubPageFragment() + "']").index("nav a");

            startIndex = Math.max(0, startIndex);

            if (fade) {
                try {
                    $('#left_pics, #right_pics').cycle({
                        fx: 'fade',
                        speed: 500,
                        timeout: 0,
                        pagerAnchorBuilder: function (idx, slide) {
                            //return selector string for existing anchor 
                            return 'nav li:eq(' + idx + ') a';
                        },
                        onPagerEvent: function (zeroBasedSlideIndex, slideElement) {
                            window.location.hash = ($('nav li:eq(' + zeroBasedSlideIndex + ') a').attr('href'));
                        },
                        startingSlide: startIndex
                    });

                }
                catch (err) {
                    console.log(err);
                }
            }
        }

    });

    // Since the event is only triggered when the hash changes, we need to trigger
    // the event now, to handle the hash the page may have loaded with.

    $(window).trigger('hashchange');


    function isSubPage() {
        if ($.param) {
            var keyword = $.param.fragment().replace("/", "").replace("!", "");
            var isSubPage = false;
            if (keyword.indexOf("=&") == -1) { isSubPage = false; }
            else { isSubPage = true; }
            return isSubPage;
        }
        else {
            return false;
        }
    }

    function getSubPageFragment() {

        var s = '';

        if ($.param) {
            var keyword = $.param.fragment().replace("/", "").replace("!", "");

            if (keyword.indexOf("=&") == -1) {
                s = keyword;
            }
            else {
                s = keyword.substr(0, keyword.indexOf("=&"));
            }
        }
        return s;
    }


    function getKeyword() {
        var kw = '';

        if (isSubPage()) { kw = getSubPageFragment(); }
        else { kw = $.param.fragment().replace("/", "").replace("!", ""); }

        if (kw == "" || kw == "home") { kw = "home"; }

        return kw;
    }

    function loadPage() {

        if ($.deparam) {
            subpage = $.deparam.fragment().sub;
        }

        if (getKeyword() == "home") {
        }
        else {
            $("#animation-area").stop(true, true);
            $("#animation-area").hide(0);
        }

        $('nav ul a').removeClass();
        $('nav ul a[href="#!' + getKeyword() + '"]').addClass('active');

        var currClass = '';
        var newClass = '';

        if (fade) {
            $.getJSON('/js/mcohen.json', function (data) {

                // Create container for this url's content and store a reference to it in
                // the cache.
                //cache[$.param.fragment()] = $('<div class="bbq-item"/>');

                var obj = data[getKeyword()];

                var fadeTime = 500;
                var animTime = 500;

                if ($('#mc_body').css('left').replace('px', '') != "0") {
                    $('#mc_body').animate({
                        left: 0
                    }, 500);
                }

                if ($('#mc_body').attr('class') == obj.width) {
                    // Don't animate anything if widths are the same
                    $('#mc_body_text').fadeOut(fadeTime, function () {
                        $('#mc_body_text').load('/html/' + obj.hash + '.html').fadeIn(fadeTime);
                        loadBody(obj);
                    });
                }

                else {
                    if ($('#mc_body').attr('class') == 'bodynarrow' && obj.width == 'bodywide') {
                        currClass = "bodynarrow";
                        newClass = "bodywide";
                    }
                    else if ($('#mc_body').attr('class') == 'bodynarrow' && obj.width == 'bodyfull') {
                        currClass = "bodynarrow";
                        newClass = "bodyfull";
                    }
                    else if ($('#mc_body').attr('class') == 'bodywide' && obj.width == 'bodynarrow') {
                        currClass = "bodywide";
                        newClass = "bodynarrow";
                    }
                    else if ($('#mc_body').attr('class') == 'bodywide' && obj.width == 'bodyfull') {
                        currClass = "bodywide";
                        newClass = "bodyfull";
                    }
                    else if ($('#mc_body').attr('class') == 'bodyfull' && obj.width == 'bodynarrow') {
                        currClass = "bodyfull";
                        newClass = "bodynarrow";
                    }
                    else if ($('#mc_body').attr('class') == 'bodyfull' && obj.width == 'bodywide') {
                        currClass = "bodyfull";
                        newClass = "bodywide";
                    }
                    else {
                        currClass = "bodynarrow";
                        newClass = obj.width;
                    }

                    //currClass = $('#mc_body').attr('class');
                    //newClass = obj.width;
                    $('#mc_body_text').hide(0, function () {
                        $('#mc_body').switchClass(currClass, newClass, animTime, function () {
                            loadBody(obj);
                        });
                    });
                }
            });
        }
    }

    function loadBody(obj) {

        if (obj.top) {
            $('#mc_body_text').css('top', obj.top);
        }
        else {
            $('#mc_body_text').css('top', 'auto');
        }

        $('#mc_body').tinyscrollbar_update();
        $('#mc_body_text').load('/html/' + obj.hash + '.html', function (data, stat, req) {

            $("a.fancybox").fancybox({
                cyclic: true,
                titlePosition: 'over',
                titleFormat: formatTitle,
                onComplete: function () {
                    $('.fancy-ico[title]').tooltip({
                        effect: 'fade',
                        fadeOutSpeed: 100
                    });
                    //$('.fancy-link[rel]').tooltip();



                }
            });

            if (subpage != null) {
                setSubPageElement($('span.client a[href="#' + subpage + '"]').parent());
            }

            if (getKeyword() == "case-studies") { cycleStart("case_studies"); }
            else if (getKeyword() == "portfolio") { cycleStart("portfolio"); }
            else if (getKeyword() == "news-awards") { cycleStart("news"); }


            $('ul.subgallery').each(function (index) {
                $('li', this).each(function (i) {

                    // FUTURE: Dynamically number gallery items.

                    //setTimeout(function () {
                    //$(this).children('a.fancybox').text(i + 1);
                    //}, 100);
                });
            });

            $('#mc_body').tinyscrollbar_update();

        }).fadeIn(500);

    }

    function cycleStart(section) {
        $('#' + section + '_pics').fadeIn(500);

        var startIndex = $("ul.client span.client a[href$='" + subpage + "']").index("ul.client span.client a");

        startIndex = Math.max(0, startIndex);

        $('#' + section + '_pics').cycle({
            fx: 'fade',
            speed: 500,
            timeout: 0,
            pagerAnchorBuilder: function (idx, slide) {
                //return selector string for existing anchor 
                return 'ul.client span.client a:eq(' + idx + ')';
            },
            startingSlide: startIndex
        });
    }


    function formatTitle(title, currentArray, currentIndex, currentOpts) {
        //return "<div id=\"fancybox-title-over\"><div id=\"titleindex=\">" + (currentIndex+1) + "<div id=\"titletext\">" + title + "</div></div>";
        //return "<div id=\"fancybox-title-over\"><div id=\"titleindex\">" + currentIndex + "</div><div id=\"titletext\">" + title + "</div>";

        if (title == '') {
            title = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec enim tortor, sit amet egestas ligula. Curabitur sapien erat, hendrerit a vulputate in, pretium eget metus. ';
        }

        return "<div id=\"fancybox-title-over\"><div id=\"titleindex\">" + (currentIndex + 1) + " of " + currentArray.length + "</div><div id=\"titletext\">" + title + "</div>";
    }

});

