/* --------------------------------------------------------------------------
	Properties
--------------------------------------------------------------------------- */
/* --------------------------------------------------------------------------
	Functions
--------------------------------------------------------------------------- */
// Main Init
function initContent() {
    initSliders();
    initAccordion();
    initFloorplanModule();
    initQuickTabs();
}
// Init Sliders
function initSliders() {
    $('.nivo-slider').nivoSlider({
        effect: 'fade',
        manualAdvance: true
    });
    var $pagination = $('div.nivo-controlNav');
    $pagination.each(function (i) {
        var el = $(this);
        var w = el.children().length * 25 / 2;
        el.css({
            "margin-left": -w
        });
    });
}
// IE Fix for Sliding Up and Down (which still shows the image)
function setHeight(which) {
    var div = $(which);
    div.css({
        height: div.height(),
        opacity: div.css('opacity')
    });
}
// Scroll to Top
function scrollToTheTop(n) {
    var num = (typeof n == "undefined") ? 0 : n;
    $("html, body").stop().animate({
        scrollTop: num
    }, 500);
}
// Grayscale w canvas method
function grayscale(src) {
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');
    var imgObj = new Image();
    imgObj.src = src;
    canvas.width = imgObj.width;
    canvas.height = imgObj.height;
    ctx.drawImage(imgObj, 0, 0);
    var imgPixels = ctx.getImageData(0, 0, canvas.width, canvas.height);
    for (var y = 0; y < imgPixels.height; y++) {
        for (var x = 0; x < imgPixels.width; x++) {
            var i = (y * 4) * imgPixels.width + x * 4;
            var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
            imgPixels.data[i] = avg;
            imgPixels.data[i + 1] = avg;
            imgPixels.data[i + 2] = avg;
        }
    }
    ctx.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
    return canvas.toDataURL();
}
// Accordion
function initAccordion() {
    var tabs = $('.accordion li > span');
    var content = tabs.siblings();
    var parent_ul = "";
    var parent_li = "";
    var active_content = "";
    // Initialize Accordion
    content.css({
        'display': 'none',
        'overflow': 'hidden'
    });
    $('.accordion > li').css({
        'list-style': 'none'
    });
    $('.accordion li span').click(function (evt) {
        parent_ul = $(this).parent().parent();
        parent_li = $(this).parent();
        active_content = $(this).next();
        // Don't re-expand content is parent is active
        if (parent_li.hasClass('active')) {
            if ($(this).css('background-image') != 'none') {
                active_content.slideUp( /*function(){$.scrollTo(parent_ul, {duration:500, axis:'y'});}*/ );
                parent_li.removeClass('active');
            }
            return false;
        }
        // Remove all active classes then add active class to li of clicked span tag
        parent_ul.find('li').removeClass('active').filter(parent_li).addClass('active');
        // Slide up any shown content of adjacent li tags
        parent_ul.find('li > span').siblings().slideUp();
        // Slide down 'active' content
        if (parent_li.hasClass('active')) {
            active_content.slideDown();
        }
        // If another menu is a span's sibling, execute the click event
        // for the first li span inside the ul
        if (active_content.is('ul')) {
            active_content.find('li:first > span').trigger('click');
            $(this).next().find('li:first > span > a').trigger('click');
        }
    });
}

function initFloorplanModule() {
    $('#fp-list span > a').click(function () {
        $(this).parent().trigger('click');
        var path = $(this).attr('href');
        loadFPImage($('#fp-container'), path);
        return false;
    });
    // Open first button by default
    $('#fp-list > li:first > span').trigger('click');
}

function loadFPImage(container, path) {
    var $img = new Image();
    var $pdf = "pdf/floorplans/" + path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf(".")) + ".pdf";
    var $a = $('<a/>').attr({
        'href': $pdf,
        'target': '_blank',
        'rel': 'external'
    });
    var $mainContainer = $('#container');
    $mainContainer.height($('#content-container').outerHeight() + 60);
    container.stop(true, true).fadeOut(750, 'easeInOutCubic', function () {
        $(this).empty().append($img);
        $($img).load(function () {
            container.fadeIn(750, 'easeInOutCubic', function () {
                $mainContainer.css({
                    "height": "auto"
                });
            });
        }).error(function () {
            alert('File go bye-bye');
        }).attr('src', path).wrap($a);
    });
}

function initQuickTabs() {
    $('div.tabs').quicktabs();
}
/* --------------------------------------------------------------------------
	on Dom Ready
--------------------------------------------------------------------------- */
$(function () {
    // Set Properties
    var $mainContent = $("#container"),
        url = '';
    // Change hash only when anchor tags fall within specifications...
    $(document).delegate('a:not([rel=external],[href^=#],[href^=http],[href*=pdf],[href^=mailto],[class=tab-link],[class*=nivo])', 'click', function (ev) {
        location.hash = (!$.browser.msie) ? this.pathname : '/' + this.pathname;
        return false;
    });
    $(document).delegate('#start-btn', 'click', function (ev) {
        $('#close-btn').trigger('click');
    });
    // Hash Event Listener
    $(window).bind('hashchange', function () {
        url = window.location.hash.substring(1);
        if (!url) {
            return;
        }
        url = url + " #content";
        scrollToTheTop(170);
        $mainContent.stop().delay(400).animate({
            opacity: 0,
            height: 0
        }, 600, 'easeOutCubic', function () {
            $mainContent.find('#content-container').html('<p>Please wait...</>').load(url, function () {
                initContent();
                // Animate back in...
                var newHeight = $mainContent.find('#content-container').outerHeight() + 50;
                $mainContent.stop().animate({
                    opacity: 1,
                    height: newHeight
                }, 600, 'easeOutCubic', function () {
                    $mainContent.css({
                        "height": "auto"
                    });
                });
            });
        });
    });
    // Trigger hash on page load
    $(window).trigger('hashchange');
    // Set up Button
    $('#close-btn').click(function () {
        location.hash = '';
        $mainContent.animate({
            opacity: 0,
            height: 0
        }, 500, function () {
            $mainContent.find('#content-container').html('');
        });
        scrollToTheTop();
        return false;
    });
    // Call init functions...
    initContent();
});
/* --------------------------------------------------------------------------
	On Window Loaded
--------------------------------------------------------------------------- */
$(window).load(function () {
    var $container = $('#main-nav ul');
    var $navImages = $("#main-nav img");
    // var $navCaptions = $("#main-nav figcaption");
    // Clone image
    $navImages.each(function () {
        var el = $(this);
        el.css({
            "position": "absolute"
        }).clone().addClass('img-color').css({
            "position": "absolute",
            "z-index": 998,
            "opacity": "0"
        }).insertBefore(el).queue(function () {
            var el = $(this);
            el.parent().css({
                "width": this.width,
                "height": this.height
            });
            el.siblings("figcaption").css({
                "width": this.width - 30
            });
            el.dequeue();
        });
        if ($.browser.msie) {
            // if img tag has no class "no-grayscale" apply grayscale
            if (!$(this).hasClass('no-grayscale')) {
                this.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
            }
        } else {
            // if img tag has no class "no-grayscale" apply grayscale
            if (!$(this).hasClass('no-grayscale')) {
                this.src = grayscale(this.src);
            }
        }
    });
    // Fade image on mouseovers
    $("#main-nav figure").hover(function () {
        var caption = $(this).find("figcaption");
        var captionHeight = $(caption).outerHeight() + 1;
        //$(caption).stop().animate({"top":-captionHeight+"px"},400,'easeOutExpo');
        $(this).find('img:first').stop().animate({
            opacity: 1
        }, 400, 'easeOutCubic');
    }, function () {
        //$(this).find('figcaption').stop().animate({"top":0},500,'easeOutExpo');
        $(this).find('img:first').stop().animate({
            opacity: 0
        }, 500, 'easeOutCubic');
    });
    // Set up Masonry
    $container.imagesLoaded(function () {
        $container.masonry({
            itemSelector: '.nav-item',
            columnWidth: 205,
            isAnimated: !Modernizr.cssTransitions
        });
    });
    // Fade in Main Nav
    $('#main-nav').animate({
        opacity: 1
    }, 500);
});
/* On Resize Window  */
/*
$(window).resize(function(){
var $cont = $('#container');
	if ($cont.height() > 0 ){
		$cont.height($('#content-container').outerHeight() + 60);
	}
});
*/
