//declearation of a unique namespace so to avoid conflicts and global variables
if(!BeefeaterRooms) var BeefeaterRooms = {};
else if (typeof (BeefeaterRooms) != 'object')
    throw new Error('BeefeaterRooms is not an object!');

$(function () {
    BeefeaterRooms.init = function () {
        //This corresponds to the images used and all images should be the same 
        var nImageWidth = 1600;
        var nImageHeight = 1200;

        //This is used to stop interaction during animation
        var bAnimating = false;
        var bNavClicked = false;
        var bFaderFade = true;

        //Animation speeds
        var nTranSpeed = 1900;
        var nFadeSpeed = 1000;

        //Overlay fade speed
        var nOverlayIn = 1000;
        var nOverlayOut = 500;

        //Distance betweet images
        var nRadias = 1700;

        var nWidthCenter;
        var nHeightCenter;

        var bHash = false;

        //Offset images around the edge of the circle
        var nStartingAngle = -90;

        var baseRoom = 0;
        var newRoom = whichRoom();
        var oldRoom;

        //JSON file location
        var imagesJSON = '/etc/designs/tabletable/json/backgrounds.json';

        //Array to hold all the rooms data, see 'roomData' function
        var aData = new Array();

        //Count how many elements to include by the class name room
        var nHowMany = $('.room').length;

        //Image holder reference
        var background;
        
        //OS detection
        var os = navigator.platform.substring(0,3);

        //Private methods
        function loadImages() {
            $.ajax({

                // Params for AJAX request
                type: 'GET',
                url: imagesJSON,
                dataType: 'json',

                // Sucessful callback
                success: function (json) {
                    //Put all images in to an array
                    for (var i = 0; i < json.images.length; i++) {
                        aData[i].image = json.images[i].src;
                        aData[i].className = json.images[i].className;
                        aData[i].fade = json.images[i].fade;
                    };

                    //Fade overlay to specify opacity
                    $('#overlay').fadeTo(0, aData[newRoom].fade);

                    //Fill #images with images
                    insertImages();
                },
                error: function () {
                    alert('Failed to load file ' + imagesJSON);
                }
            });
        };

        //Insert image into #background
        function insertImages() {
            for (var i = 0; i < aData.length; i++) {
                $('.images').eq(i).append('<img src="' + aData[i].image + '" />').find('img').ready(function () {
                    //Maybe also check to see if nav item has been clicked
                    aData[i].imageLoaded = true;
                    bindClick(i);
                });
            };
        };

        // bind the hover event so we know to do a transition onhashchange
        function bindClick(i) {
            $('.room').click(function () {
                if (bAnimating) {
                    return false;
                }
            }).hover(
                function () {
                    bNavClicked = true;
                },
                function () {
                    bNavClicked = false;
                });
        }

        // this gets executed whenever the hash URL is updated and is responsible for the inpage AJAX load of content
        function bindHashChange() {
            //Bind transition click
            $(window).bind('hashchange', function (e) {
                if (bNavClicked && !bAnimating) {
                    // this will only be done from clicking one of the navigation links (not from a browser back button)
                    setRoomAndImageOnInPageLoad();
                    // do the transistion
                    $('#overlay').fadeOut(nOverlayOut, function () {
                        //Fadeout content... well it looks that way anyway, we are really fading in the image overlay
                        $('#fader').fadeIn(nFadeSpeed, function () {
                            $('#content').html('').hide();
                            $(this).hide();
                            $('#footer').hide();
                            $('.bottom-divider').hide();

                            //Animate
                            background.animate({ left: (document.documentElement.clientWidth / 2) - aData[newRoom].x - (background.width() / 2), top: 0 - aData[newRoom].y - nHeightCenter }, nTranSpeed, function () {
                                bFaderFade = true;
                                loadPageContent();
                                //this helps stops IE7 flicker
                                $('#overlay').css({'position':'fixed'});
                            });
                        });
                    });
                    //this helps stops IE7 flicker
                    $('#overlay').css({'position':'absolute'});
                }
                else if (!bNavClicked) {
                    bFaderFade = false;
                    // just reload the content (but don't do a window.reload as IE7 hates that!
                    // turn the click off (thus disabling transitions again)
                    // this will only be done from the browser back button normally
                    setRoomAndImageOnInPageLoad();
                    // don't do the animation, just load the content
                    loadPageContent();
                }
            });
        }

        function positionImages() {
            //Remove any dynamic styles before arranging images
            $('.images').removeAttr('style');

            for (var i = 0; i < aData.length; i++) {
                $('.images').eq(i).css({ 'left': aData[i].x + nWidthCenter, 'top': aData[i].y + nHeightCenter });
            };
        };

        // this is only called from the bindHashChange function and is responsible for setting all the navigation / background images / setting the current page et al
        function setRoomAndImageOnInPageLoad() {
            bHash = false;
            bAnimating = true;
            // turn the click off (thus disabling transitions again)
            bNavClicked = false;
            //trigger analytics tracking
            //google analytics
            //_gaq.push(['_trackEvent', 'Global Nav', $(this).html()]);
            var pageIdx = getPageIndex();
            var currentLink;
            if (pageIdx > 0) {
                // return the current link
                currentLink = $('#global-nav li a.room')[pageIdx - 1];
            }

            //Pick correct image for fader
            faderImage();
            centerImage($('#fader'));

            //Make sure the appropriate element has current on it
            $('#header').find('.current').removeClass('current');
            $(currentLink).addClass('current');

            oldRoom = newRoom;
            newRoom = whichRoom();

            $('.images').eq(newRoom).css({ 'display': 'block' });
        }

        function loadPageContent() {
            $.ajax({

                //Params for AJAX request
                type: 'GET',
                url: aData[newRoom].page,
                dataType: 'html',

                //Sucessful callback
                success: function (html) {
                    //Convert ajax html string to html code 
                    var content = $(html).find('#content').html();

                    //Place new code in place
                    $('#content').html(content);
                    $('body').removeAttr('class').addClass(aData[newRoom].className);
                    
                    //Fires the tracking code
                    try{_gaq.push(['_trackEvent', 'Global Nav', aData[newRoom].page]);} catch(err){}
                    try{sc_trackPageview(aData[newRoom].page.replace(/(#\/)|(.html)/g,'').replace(/\//g,':'));} catch(err){}

                    //Reset the layout
                    if (!bHash) resetLayout();
                    
                    //Bind javascript funtions to relative elements, these functions are found in common.js
                    var conHeight = parseInt($('#container').height());
                    footerPosition(conHeight);
                    autoclearInputFields();
        
                    //These functions are found in form-validation.js
                    if ($('body').is('.template5')) {
                        formValidator();
                        datepicker();
                    };
                },
                error: function () {
                    alert('Failed to load page ' + aData[newRoom].page);
                }
            });
            suggestion();
        };

        function resetLayout() {
            //Swap current image with position of new image
            swapImages();

            //Position all the images around the new image
            positionImages();

            //Make sure new image is showing
            $('.images').eq(newRoom).css({ 'display': 'block' });

            //Align background to viewpoint
            background.css({ 'top': (nImageHeight / 2) - 50 });
            centerImage(background);

            //Put new image in the overlay
            faderImage();

            //Turn everything back on and fade in
            if(bFaderFade) $('#fader').show();
            $('#content').show();
            $('#footer').show();
            $('.bottom-divider').show();
            $('#fader').fadeOut(nFadeSpeed, function () {
                //Fade overlay to specify opacity
                $('#overlay').fadeTo(nOverlayIn, aData[newRoom].fade, function () {
                    bAnimating = false;

                    //window.location = aData[newRoom].page;
                });
            });

            //Bind javascript funtions to relative elements, these functions are found in common.js
            var conHeight = parseInt($('#container').height());
            footerPosition(conHeight);
            autoclearInputFields();
            
            //These functions are found in form-validation.js
            if($('body').is('.template5'))
            {
                formValidator();
                datepicker();   
            };
        };

        function swapImages() {
            var tempX = aData[oldRoom].x;
            var tempY = aData[oldRoom].y;

            aData[oldRoom].x = aData[newRoom].x;
            aData[oldRoom].y = aData[newRoom].y;

            aData[newRoom].x = tempX;
            aData[newRoom].y = tempY;
        };

        //Decide what the new room will be depending where current class has just been placed
        function whichRoom() {
            var room = 0;

            for (var i = 0; i < $('#global-nav li').length; i++) {
                if ($('#global-nav .room').eq(i).hasClass('current') == true) room = i + 1;
            };

            return room;
        };

        //Room data object
        function roomData() {
            var i = {
                imageLoaded: false,
                pageLoaded: false,
                image: 'no image',
                page: 'no page',
                className: 'no class',
                order: 0,
                x: 0,
                y: 0
            }

            return i;
        };

        //Position all images around a circle layout, trig rules!!
        function positionsXY() {
            var nAmount = nHowMany - 1;
            var nAngleOffset = nStartingAngle * (Math.PI / 180);
            var nRadian = (360 / nAmount) * (Math.PI / 180);

            //Calulate other image position based on the circle layout
            for (var i = 0; i < nAmount; i++) {
                var nAngle = nRadian * i;
                var x = nRadias * Math.cos(nAngle + nAngleOffset);
                var y = nRadias * Math.sin(nAngle + nAngleOffset);

                aData[i + 1].x = Math.floor(x);
                aData[i + 1].y = Math.floor(y);
            };
        };

        function faderImage() {
            $('#fader').html('').append('<img src="' + aData[newRoom].image + '" />');
        };

        // gets the current page index (0 = home)
        // this function must only be used AFTER the href's of the .room links have been changed
        function getPageIndex() {
            var pageIndex = 0;
            if (window.location.hash != "") {
                var returnIndex = 0;
                var temp = window.location.href.split('#');
                var sPage = temp[1];

                $('.room').each(function () {
                    var href = $(this).attr('href').substring(1);
                    if (href == sPage) {
                        returnIndex = pageIndex;
                    };
                    pageIndex++;
                });
                return returnIndex;
            }
            else {
                return pageIndex;
            }
        }

        //Public methods
        return {
            setup: function () {
                //Check to see if a hash is present on the url
                if (window.location.hash != "") {
                    bHash = true;

                    var temp = window.location.href.split('#');
                    var sPage = temp[1];

                    $('.current').removeClass('current');
                    $('.room').each(function () {
                        if ($(this).attr('href') == sPage) {
                            $(this).addClass('current');
                        };
                    });

                    baseRoom = newRoom;
                    newRoom = whichRoom();
                };

                //Setting up page, insert backgrounds div and wrap container in a wrapper for positioning perpose
                $('#container').before('<div id="backgrounds" />').before('<div id="overlay" />').before('<div id="fader" />').wrap('<div id="wrapper" />');
                $('body').css({ 'overflow': 'hidden' });

                //Add reference to background div
                background = $('#backgrounds');

                //Using a image overlay as the fade solution as IE can't fade out nested divs using jQuery fadeOut method
                $('#fader').css({ 'height': nImageHeight, 'display': 'none' });

                background.css({ 'top': (nImageHeight / 2) - 50 });

                nWidthCenter = (background.width() / 2) - (nImageWidth / 2);
                nHeightCenter = (background.height() / 2) - (nImageHeight / 2);

                //Setup empty divs for images and setup data array
                for (var i = 0; i < nHowMany; i++) {
                    background.append('<div class="images"></div>');
                    var room = new roomData();
                    room.position = i;
                    room.page = $('.room').eq(i).attr('href');
                    aData.push(room);
                };

                //Setup hash href for back/forward button functionality
                $('.room').each(function () {
                    var temp = $(this).attr('href');
                    $(this).attr('href', '#' + temp);
                });

                //Bind empty click to .room to stop unwanted actions before images have loaded
                $('.room').bind('click', function () {
                    //Could trigger a loading image
                });

                //Load images, workout positions, position images, center the image and bind the click
                loadImages();
                positionsXY();

                if (bHash && baseRoom != newRoom) loadPageContent();

                if (newRoom > 0) {
                    oldRoom = 0;
                    swapImages();
                    //Remove any dynamic styles before arranging images
                    $('.images').removeAttr('style');
                };

                positionImages();

                //This function is found in common.js
                centerImage(background);
                //bindClick();

                //back/forward button support
                // $(window).bind('hashchange', function(e) {
                // if(!bNavClicked) window.location.reload(true);
                // });
                bindHashChange();

                //Only turn on first image
                $('.images').eq(newRoom).css({ 'display': 'block' });

                //Center background dependent on window size and trigger on window resize
                $(window).resize(function () {
                    centerImage(background);
                });
            }
        };
    } ();

    //OS detection
    var OS = navigator.platform.substring(0,3);

    //Initiate room transition functionality but not for IE6
    if (!ie6 && OS == "Win" || OS == "Mac" || OS == "win" || OS == "mac") BeefeaterRooms.init.setup();
});
