$(document).ready(function() {
    var newHash = '',
        $contentContainer = $('#content-container'),
        $content = $('#content'),
        $bgImage = $('#bgimage');

    var FullscreenrOptions = {  width: 800, height: 500, bgID: '#bgimg' };
    jQuery.fn.fullscreenr(FullscreenrOptions);

    var isSubmenuLoaded = false;
    var isContentLoaded = false;
    var isContentShown = false;

    menuWidth();
    adjustImageSize($bgImage);
    contentDimension();
    $(window).bind('resize.Menu', function(e) {
        menuWidth();
        contentDimension();
        adjustImageSize($('#bgimage'));
    });

    $(window).bind('hashchange', function() {
        newHash = window.location.hash.substring(1);
        if (newHash && newHash.length != 0) {
            $('#menu ul li').each(function () {
                $(this).removeClass('current');
            })
            var hashSplit = newHash.split('/'); //just get first element of hash
            $('#menu a[href$="#' + hashSplit[0] + '"]').parent().addClass('current');
            isContentLoaded = false;
            isSubmenuLoaded = false;
            $contentContainer.fadeOut(1000, function() {
                $(window).trigger('contentFadedOut');
            });
        } else {
            $contentContainer.hide();
        }

    });

    $(window).bind('loadContentDone', function() {
        $.log('e: loadContentDone')
        isContentLoaded = true;
    });

    $(window).bind('loadSubMenusDone', function() {
        $.log('e: loadSubMenusDone')
        isSubmenuLoaded = true;
    });

    $(window).bind('contentFadedOut', function() {
        $.log('e: contentFadedOut')
        loadSite(newHash);
        isContentShown = false;
    });

    $(window).bind('contentFadedIn', function() {
        $.log('e: contentFadedIn')
        isContentShown = true;
        $('form').jqTransform();
    });

    $(window).bind('loadSubMenusDone loadContentDone contentFadedOut', function() {
        $.log('e: loadSubMenusDone loadContentDone contentFadedOut')
        if (isAllDone()) {
            if (typeof _gaq !== "undefined" && _gaq !== null) {
                _gaq.push(['_trackPageview', newHash]);
            }
            $.log('all loaded!')
            $contentContainer.fadeIn(1000, function() {
                $(window).trigger('contentFadedIn');
            });
        }
    });

    function isAllDone() {
        return (isSubmenuLoaded && isContentLoaded && !isContentShown);
    }

    $("#menu ul li a").delegate("a", "click", function() {
        window.location.hash = $(this).attr("href");
        //event.preventDefault();
    });

    $("#submenu a").live("click", function() {
        window.location.hash = $(this).attr("href");
        //event.preventDefault();
    });

    $('#menu ul li a').each(function() {
        $(this).hover(
            function(e) {
                $(this).stop().animate({
                    'line-height': "80px",
                    'opacity': "0.5"
                }, 300)
            },
            function(e) {
                $(this).stop().animate({
                    'line-height': "90px",
                    'opacity': "1"
                }, 500)
            }
        );
    });

    function loadSite(site) {
        isContentLoaded = false;
        isSubmenuLoaded = false;
        loadSubmenus(site);
        loadContent(site);
    }

    function loadSubmenus(site) {
        $.getJSON('index.php/' + site + '/submenus', function(data) {
            $('div#submenu ul.submenu').html('');
            $.each(data, function(subKey, subArray) {
                $.each(subArray, function(key, val) {
                    //$.log(key + ': ' + val);

                });
                var elem = '<li><a href="' + ci_base_url + '#' + subArray.link + '">' + subArray.title + '</a></li>'
                $('div#submenu ul.submenu').append(elem);

            });
            $(window).trigger('loadSubMenusDone');
        });
    }

    function isSubPage(site) {
        return (site.split('/').length > 1)
    }

    function loadContent(site) {
        $.getJSON('index.php/' + site, function(data) {
            $.log('Getting content for: ' + site);
            $.each(data, function(key, val) {
                //$.log(key + ': ' + val);
            });
            $content.html(data.html);
            $(window).trigger("loadContentDone");
        });
    }

    function menuWidth() {
        $('#menu ul').width($(window).width() - $('#menu #logo').outerWidth(true) - $('#icons').outerWidth(true) - $('#jplayer').outerWidth(true));
    }

    function contentDimension() {
        //alert('contentDimension();');
        $contentContainer.width($(window).width() - $contentContainer.offset().left - 30);
        if ($contentContainer.width() > 1400) {
            $contentContainer.width('1400');
        } else {
        }
        //$contentContainer.height($(window).height() - $contentContainer.offset().top - 30);
        $contentContainer.height($(window).height() - $("#menu").offset().top - $("#menu").height() - 60 + 'px');
        //$('#content').height($(window).height() - $('#content').offset().top - 30);
    }

    function adjustImageSize($img) {
        var w_w = $(window).width(),
            w_h = $(window).height(),
            r_w = w_h / w_w,
            i_w = $img.width(),
            i_h = $img.height(),
            r_i = i_h / i_w,
            new_w,new_h,
            new_left,new_top;

        if (r_w > r_i) {
            new_h = w_h;
            new_w = w_h / r_i;
        }
        else {
            new_h = w_w * r_i;
            new_w = w_w;
        }

        $img.css({
            width : new_w + 'px', //Resize image
            height : new_h + 'px', //Resize image
            left : (w_w - new_w) / 2 + 'px',
            top : (w_h - new_h) / 2 + 'px'
        });
    }

    /** basket functions **/
    $(window).bind('showbasket', function() {
        $.ajax({
            type: "GET",
            url: ci_base_url + 'index.php/shop/showBasket',
            context: document.body,
            success: function(response) {
                var items = [];
                $('#basketlist').children().remove();
                if ($('div#basket').css('left') == '20px') {
                    $('div#basket').animate({
                        left: '-120px'
                    });
                } else {
                    $('div#basket').animate({
                        left: '20px'
                    });
                }
                $.each(response, function(key, item) {
                    //items.push('<li>' + item.type + ' ' + item.name + '<a href="#" onclick="removeBasketItem(\'' + key + '\');"><img src="' + ci_base_url + 'assets/images/cancel.png" alt="cancel" /></a></li>');
                    items.push('<li>' + item.name + '<a href="#" onclick="removeBasketItem(\'' + key + '\');"><img src="' + ci_base_url + 'assets/images/cancel.png" alt="cancel" /></a></li>');
                });
                $('#basketlist').append(items.join(''));
            }
        });
    });

    $("#icons a img").mouseover(
        function() {
            $(this).attr("src", $(this).attr('src').substring(0, $(this).attr('src').length - 4) + "_hover.png");
        }).mouseout(function() {
            $(this).attr("src", $(this).attr('src').substring(0, $(this).attr('src').length - 10) + ".png");
        });

    $('a#basketicon').bind('click', function(event) {
        event.preventDefault ? event.preventDefault() : event.returnValue = false;
        $(window).trigger('showbasket');
        return false;
    });

    $(window).trigger('hashchange');
});

function removeBasketItem(key) {
    //alert(key);
    $.ajax({
        type: "POST",
        url: 'index.php/shop/removeBasketItem/' + key,
        context: document.body,
        success: function(response) {
            if (response) {
                $(window).trigger('showbasket');
            } else {
                alert('Artikel konnte nicht aus dem Warenkorb entfernt werden');
            }
        }
    });
    $(window).trigger('showbasket');
}
