var ajaxContent = null;
var closeInterval = null;



function placeThePostCloseButton(event){

    if(!jQuery.fn.oneFingerScroll){
       return;
    }
    
    var posts = $("#ajaxBody .posts")[0];
    var close = $(".posts .close");                    
    var topValue = 400 - $(posts).scrollTop();
    
    
    if ( topValue < 0) {
        close.css({
            "position": "fixed !important",
            "top": "5px !important",
            "padding-top": "0px !important"
        });
    } else {
        close.css({
            "position": "fixed !important",
            "top": topValue + "px !important",                                
            right: 0,
            left: "auto"
        });
    }
    
    if (close.css("position") === "fixed") {
        close.css("left", parseInt($(".posts").css("left"), 10) + parseInt($(".posts").width(), 10) + 5);
    }
}

$(document).ready(function(){
    $(window).resize(function(){
        setPostMinHeight();
    });
});

function setPostMinHeight(origin){

    
    
    var postHeight = parseInt($('.posts .page').css('height'), 10);
    
    if(!postHeight){
        return;
    }
    
    var windowHeight = $(window).height();
    
    var minHeight = (windowHeight / 2) - 40 - 50;
        
    
    if(jQuery.fn.oneFingerScroll){
        minHeight += 150;
    }
    
    if(postHeight <= minHeight){
        $('.posts .page').css({'min-height':(minHeight + 'px')});
    }else{
        $('.posts .page').css({'min-height':'0px'});
    }

}

$(function () {
    if (!$.browser.msie || parseInt($.browser.version, 10) > 7) {
        
        // Get the ajax content holder
        ajaxContent = $("#ajaxBody");
        
        // Register the footer links
        $("#Footer a").click(function () {
            
            // Get the link
            var link = $(this).attr("href");
            
            // get the page id
            var pageId = link.split("page_id=")[1] * 1;
            
            

            // Check we dont want to open a store locator page
            if (true || pageId != 109 &&
                pageId != 210 &&
                pageId != 208 &&
                document.location.href.indexOf("=210") == -1 &&
                document.location.href.indexOf("=208") == -1 &&
                document.location.href.indexOf("=109") == -1
                )
            {
                ajaxReloadContentForUrl(link);

                return false;
                
            }
        });
        
        
        
        $.History.bind(function (state) {
            
            if (state === "") {
                $(".close").click();
            } else {
                var location = document.location.href;
                var tmpLink = location.split(/\?|\#/);
                
                if (tmpLink.length === 3) {
                    tmpLink[1] = "#";
                } else if (tmpLink.length === 2) {
                    tmpLink[1] = "#" + tmpLink[1];
                }
                
                var link = tmpLink.join("").replace("#", "?");
                
                hideAjaxStuff();
                
                // Show the loading overlay
                $(".loader").css({ "opacity": 0, "display": "block" }).animate({ "opacity": 0.7 }, 100);
                
                // Register the ajax error function
                ajaxContent.fadeOut(250).ajaxError(function () {
                    // Hide the loader
                    $(".loader").animate({ "opacity": 0 }, 100, function () { $(this).css("display", "none"); });
                    
                    showAjaxStuff();
                });
                
                // Get the page
                $.get(link, function (data) {
                    // Hide the loader          
                    $(".loader").animate({ "opacity": 0 }, 100, function () { $(this).css("display", "none"); });
                    // Try to match the content
                    var source = data.substring(data.indexOf("<!-- CONTENT START -->"), data.indexOf("<!-- CONTENT END -->"));
                    
                    // Replace the content
                    ajaxContent.html(source).fadeIn(250);
                    
                    // Removing the additional twitter box... what the ...
                    $(".twitterToolsContainer").eq(0).remove();

                    /******************************************
                    <just copied>
                    */
                    //
                    
                    var minTop = "50%";
                    
                    $window = $(window);
                    var posts = $(".posts");
                    
                    var interval;
                    var abortInterval;
                    
                    var mouseDownHandler = function () {
                        
                        var $this = $(this);
                        
                        abortInterval = false;
                        
                        setTimeout(function () {
                            
                            if (abortInterval) return;
                            
                            if(interval){
                                clearInterval(interval);
                            }
                            
                            interval = setInterval(function () {
                                
                                $this.triggerHandler("click");
                                
                            }, 150);
                            
                        }, 250);
                        
                    };
                    
                    var mouseUpHandler = function () {
                        
                        abortInterval = true;
                        
                        if (interval) {
                            clearInterval(interval);
                        }
                        
                    };
                    
                    posts.append($("<div/>", {
                        "class": "buttonTop",
                        css: {
                            left: parseInt(posts.css("left"), 10) + parseInt(posts.outerWidth(), 10) - (parseInt(posts.css("padding-right"), 10) - 5)
                        },
                        click: function () {
                            
                            if($window.scrollTop() - 50 < 0){                            
                                $window.scrollTop(0);
                            }else{
                                $window.scrollTop($window.scrollTop() - 50);
                            }
                        },
                        mousedown: mouseDownHandler,
                        mouseup: mouseUpHandler
                    }), $("<div/>", {
                        "class": "buttonBottom",
                        css: {
                            left: parseInt(posts.css("left"), 10) + parseInt(posts.outerWidth(), 10) - (parseInt(posts.css("padding-right"), 10) - 5)
                        },
                        click: function () {
                            $window.scrollTop($window.scrollTop() + 50);
                        },
                        mousedown: mouseDownHandler,
                        mouseup: mouseUpHandler
                    }));
                    
                    var close = $(".posts .close");
                    
                    $('body').bind('touchmove', function(event) {
                        
                        if(closeInterval == null){
                            closeInterval = window.setInterval("placeThePostCloseButton()", 250);
                        }
                        placeThePostCloseButton(event);
                    
                    });
                    
                    
                    $window.scroll(function (e) {
                        
                        var scrollTop = parseInt($window.scrollTop(), 10);
                        var windowHeight = $window.height();
                        
                        if (scrollTop + 5 > parseInt(close.parent().offset().top, 10)) {
                            close.css({
                                "position": "fixed",
                                top: 5
                            });
                        } else {
                            close.css({
                                "position": "absolute",
                                top: 0,
                                right: 0,
                                left: "auto"
                            });
                        }
                        
                        if (close.css("position") === "fixed") {
                            close.css("left", parseInt($(".posts").css("left"), 10) + parseInt($(".posts").width(), 10) + 5);
                        }
                        
                    }).resize(function () {
                        
                        var val = minTop;
                        var posts = $(".posts");
                        var leftNav = $(".leftNav");
                        var minSpaceBottom = Math.max(leftNav.height() - 50, posts.children(".close").height() + 10);
                        var body = $("body");
                        var windowHeight = $(window).height();
                        var scrollTop = parseInt($(window).scrollTop(), 10);
                        
                        var rightPosts = parseInt(posts.css("left"), 10) + parseInt(posts.outerWidth(), 10) - (parseInt(posts.css("padding-right"), 10) - 5);
                        
                        if ($(".close").css("position") === "fixed") {
                            $(".close").css("left", rightPosts);
                        }
                        
                        if (windowHeight < minTop + minSpaceBottom + 95) {
                            val = windowHeight - minSpaceBottom - 95;
                        }
                        
                        
                        leftNav.css({
                            top: val
                        });
                        
                        $(".posts").css({
                            top: val
                        });
                        
                        $(".buttonTop, .buttonBottom").css("left", rightPosts);
                        
                    });
                    
                    
                    /******************************************
                    </just copied>
                    */
                    //
                    
                    $("html,body").css("overflow", "auto");
                    
                    window.setTimeout(function () {
                        $("html,body").css("overflow", "auto");
                    }, 1000);
                    
                    //register navi links
                    
                    ajaxContent.find(".leftNav a").click(function () {
                        
                        // Get the link
                        var link = $(this).attr("href");
                        
                        // get the page id
                        var pageId = link.split("page_id=")[1] * 1;
                        ajaxReloadContentForUrl(link);
                        return false;
                        
                    });
                    
                    myInitStoreLocator();
                    initOriginalStoreLocator();
                    initStoresOverlayFunctions();
                    initContact7FormForMaria();
                    $('.posts .page').height('undefined');
                    setPostMinHeight();
                    
                    // Overwrite the close function
                    ajaxContent.find(".close").click(function () {
                        // Fade out the content
                        ajaxContent.fadeOut(250, function () {                            
                            showAjaxStuff();                            
                            $("html, body").css("overflow", "hidden");
                            
                        });
                        
                        return false;
                    });
                    
                    // Make content scrollable in iPad
                    if (jQuery.fn.oneFingerScroll) {
                        $(window).resize(function () {
                            var posts = $("#ajaxBody .posts");
                            posts.oneFingerScroll();
                            var windowH = $(window).height();
                            var padding = parseInt(posts.css("padding-top").match(/[\d\.]+/g), 10);
                            var footerH = $("#Footer").height();
                            posts.height(windowH - padding - footerH);
                        });
                        
                        $(window).trigger("resize");
                    }
                });
            }
        });
    }
});

var waitForTheMisterioisBTimer;

var showAndHideSelector = "#Shop, #TT-Target, .button.back, .button.forward, .twitterToolsContainer, .dropdownContainer:eq(1), .infoButton, .hotspot";

var hideAjaxStuff = function () {
    // Hide the shop link, the facebook box and the scroll buttons
    
    $('.infoOverlay').hide();
    
    $(showAndHideSelector)
        .stop()
        .animate({ opacity: 0 }, 250, function () {
            $(this).css("display", "none");
        });

    waitForTheMisterioisBTimer = window.setInterval(function() {
        if (B.controller) {
            
            B.controller.stopTimer();

            window.clearInterval(waitForTheMisterioisBTimer);
        
        }

    }, 100);
    
};

var showAjaxStuff = function () {
    // Show the shop link, the facebook box and the scroll buttons
    $(showAndHideSelector)
        .stop()
        .css("display", "block")
        .animate({ opacity: 1 }, 250);


    // Force the mysterious "B" to hide scrollbars
    B.needOverflowY = false;
    $(window).trigger("resize");

    
    waitForTheMisterioisBTimer = window.setInterval(function () {
        if (B.controller) {
            B.controller.startTimer();

            window.clearInterval(waitForTheMisterioisBTimer);
        }

    }, 100);
    
};


var ajaxReloadContentForUrl = function (link) {
    
    var splittedStuff = link.split("?");

    $.History.go(splittedStuff[1]);

};
