/*
 *
 *	Menu.js file that handles the functionalities of menu and scrollable, draggable pages.
 *
 */

var pageUrls = ['page-include/welcome.php','page-include/whyUs.php','page-include/services.php',
                'page-include/clients.php','page-include/faq.php','page-include/connect.php'];

var Menu = new function() {
    return {
        // properties
        selectedTab: null,
        selectedPage: null,
        pages: [],
        $this : null,

        // methods
        init: function() {
            $this = this;

            // add click function to the tab and choose the default tab
            $('#menu ul li').bind('click', this.setSelection);

            // Check the hash tag in the url and display the selected page
            var selection = location.hash.split('!')[1];
            if (!selection) selection = 'welcome';
            this.selectedPage = $('div#' + selection + 'Page');
            $('#menu ul li#' + selection + 'Tab').trigger('click');

            // initialize draggable
            /*
            $('div#scrollable').draggable({
                axis: "x" /*,
                helper: function(){
                    // Create an invisible div as the helper. It will move and
                    // follow the cursor as usual.
                    return $('<div></div>').css('opacity',0);
                },
                create: function(){
                    // When the draggable is created, save its starting
                    // position into a data attribute, so we know where we
                    // need to revert to.
                    var $scrollable = $(this);
                    $scrollable.data('startleft',$scrollable.position().left);
                },
                drag: function(event, ui){
                    // During dragging, animate the original object to
                    // follow the invisible helper with custom easing.
                    $(this).stop().animate({
                        left: ui.helper.position().left
                    },500,'easeOutCirc');
                } 
            });*/

            
            // Add zoom function to the whyUsMessage divs
            //zoomOnHover($('div.whyUsMessage'));

            // initiates the endless loop effect
            this.initEndlessLoop();

            // Bind a function to right/left arrow
            $('.askQ').live('click', this.clickAskQ);
            //$('div.leftArrow img').live('click', this.clickLeftArrow);

            // start the tooltip
            /*
            $("[title]").mbTooltip({
                opacity : .90, //opacity
                wait:100, //before show
                ancor:"mouse", //"parent"
                cssClass:"default", // default = default
                timePerWord:70, //time to show in milliseconds per word
                hasArrow:false,
                color:"white",
                imgPath:"images/",
                shadowColor:"black",
                fade:500
            });*/

        },
        setSelection: function($e) {
            // ensure $e is not null
            if (!$e) return;

            //$this = $e.data.element;
            $this.selectedTab = $($e.currentTarget);

            // remove selected class from other tags and add it to this tag
            $('#menu ul li').removeClass('selected');
            $this.selectedTab.addClass('selected');

            // set the hash tag in url
            $this.refreshUrl();
            
            // hide the last page and display the current page
            var $index = $this.selectedTab.index();
            $this.slide($('div#mainContent'));
            $this.selectedPage = $('div#mainContent div.page:eq(' + $index + ')');
            $this.selectedPage.show('slow');
        },
        // TODO: Make the auto scrollling work!
        slide: function($e) {
            // ensure $e is not null
            if (!$e) return;
            
            // slide the scrollable div to the selected div
            var hash = location.hash;
            var currentLeft = $('#scrollable').css('left').split('px')[0];
            //alert('Old: '+ currentLeft);
            currentLeft = isNaN(currentLeft)? 0: currentLeft;
            var newLeft = $this.selectedTab.index() * -1000;
            //alert(newLeft);
            var movement = newLeft - currentLeft;
            //alert('Old: '+ currentLeft + ', New: '+ newLeft + ', Move: '+ movement);
            // determine if the shortest way to the target div is to the right or left, and make the move.
            
            if (movement == 0) {}

            // TODO need to work on this part........
            else if (movement >= -4500 && movement <= 4500) {
                
            }
            else if (movement < -3500) {
                newLeft = newLeft + 6000;
            }
            else {
                // work on this area
                //(6 - $this.selectedTab.index()) * 1000;
                //newLeft = 4990 - movement;
                newLeft = currentLeft - 1000;
            }
            $('div#scrollable').animate({
                left : newLeft + 'px'
            }, 1000, function() {
                $this.adjustScrollableLeft()
            });
            
            
            // load the page
            $this.loadPage($('div#' + getPageIdByIndex($this.selectedTab.index())));
            
            // update the menu
            $this.updateMenu(newLeft);
        },
        clickAskQ: function() {
            var left = $('div#scrollable').css('left').split('px')[0];
            var newLeft = (left > 0) ? 1000: -5000;
            $this.updateMenu(newLeft);
            $('div#scrollable').animate({
                left : newLeft + 'px'
            }, 1000, function() {
                $this.adjustScrollableLeft()
            });
        },
        clickRightArrow: function() {
            // check which div is displayed and move to the next div to the right.
            var left = $('div#scrollable').css('left').split('px')[0];
            var newLeft = 0;
            if (left > 10000)
                newLeft = 1000;
            else if (0 < left && left <= 1000) 
                newLeft = 0;
            else if (left == 'auto' || (-1000 < left && left <= 0))
                newLeft = -1000;
            else if (-2000 < left && left <= -1000 )
                newLeft = -2000;
            else if (-3000 < left && left <= -2000)
                newLeft = -3000;
            else if (-4000 < left && left <= -3000)
                newLeft = -4000;
            else if (left <= -4000)
                newLeft = -5000;
            // continue...
            $this.updateMenu(newLeft);
            $('div#scrollable').animate({
                left : newLeft + 'px'
            }, 1000, function() {
                $this.adjustScrollableLeft()
            });
        },
        clickLeftArrow: function() {
            // check which div is displayed and move to the next div to the left.
            var left = $('div#scrollable').css('left').split('px')[0];
            var newLeft = 0;
            if (left == 'auto' || (0 <= left && left < 1000 ))
                newLeft = 1000;
            else if (-1000 < left  && left < 0)
                newLeft = 0;
            else if (-2000 <= left && left < -1000)
                newLeft = -1000;
            else if (-3000 <= left && left < -2000)
                newLeft = -2000;
            else if (-4000 <= left && left < -3000)
                newLeft = -3000;
            else if (left < -4000)
                newLeft = -4000;
            else if (left >= 1000)
                newLeft = 2000;
            
            $this.updateMenu(newLeft);
            $('div#scrollable').animate({
                left : newLeft + 'px'
            }, 1000, function() {
                $this.adjustScrollableLeft()
            });
        },
        initEndlessLoop: function () {

            // Listen for the mouse movement and adjust the left property of scrollable div if needed.
            var clicking = false;

            $('#scrollable').mousedown(function(){
                clicking = true;
            });

            $(document).mouseup(function(){
                clicking = false;
            })

            $('#scrollable').mousemove(function(){
                if(clicking == false) return;

                // Mouse click + moving logic here
                $this.adjustScrollableLeft();
            });
        },
        adjustScrollableLeft: function() {
            //alert('here!');
            var strLeft = $('#scrollable').css('left').split('px')[0];
            var newLeft;

            if (isNaN(strLeft)) return;
            else {
                var left = parseInt(strLeft);
                
                if (left > 1000) {
                    newLeft = left - 6005;
                    $('#scrollable').css({left: newLeft + "px"});
                }
                else if (left < -4000) {
                    newLeft = left + 6005;
                    $('#scrollable').css({left: newLeft + "px"});
                }
                
            }
            
            // update the menu section with the correct selected tab
            $this.updateMenu(left);
            
        },
        updateMenu: function(left) {
            if (-500 < left && left <= 500) {
                $this.resetSelectedTab($('#menu ul li#welcomeTab'));
                $this.refreshUrl();
            }
            else if (-1500 < left && left <= -500) {
                // set the selection in the menu and load the page with ajax call
                $this.resetSelectedTab($('#menu ul li#whyUsTab'));
                $this.loadPage($('div#whyUsPage'));
                $('div#whyUsPage div#whyUsMessageContainer').fadeIn(100)
                //$.fn.disableTooltip();
                $this.refreshUrl();
            }
            else if (-2500 < left && left <= -1500) {
                $this.resetSelectedTab($('#menu ul li#servicesTab'));
                $this.loadPage($('div#servicesPage'));
                $('div#servicesContainer').fadeIn(100, function(){
                    // initiate the JScrollPane
                    $('.scroll-pane').jScrollPane({
                        showArrows: true,
                        verticalGutter: 7,
                        verticalDragMinHeight: 20,
                        verticalDragMaxHeight: 20,
                        verticalArrowPositions: 'split'
                    });
                });
                $this.refreshUrl();
            }
            else if (-3500 < left && left <= -2500) {
                $this.resetSelectedTab($('#menu ul li#clientsTab'));
                $this.loadPage($('div#clientsPage'));
                $('div#clientsContainer').fadeIn(100);
                $this.refreshUrl();
            }
            else if ((left <= -3500 && -4500 < left) || 1500 < left) {
                $this.resetSelectedTab($('#menu ul li#faqTab'));
                $this.loadPage($('div#faqPage'));
                $('div.faqContainer').fadeIn(100);
                $this.refreshUrl();
            }
            else if (( 500 < left && left <= 1500) || left <= -4500 ) {
                $this.resetSelectedTab($('#menu ul li#connectTab'));
                $this.loadPage($('div#connectPage'));
                $('div#connectContainer').fadeIn(100);
                $this.refreshUrl();
            }
        },
        resetSelectedTab: function($e) {
            $('#menu ul li').removeClass('selected');
            $this.selectedTab = $e;
            $e.addClass('selected');
        },
        loadPage: function($e) {
            if ($e.html() == '') {
                var index = getPageIndexById($e.attr('id'));
                var $dataType = 'html';
                var $contentType = 'text/html';
                
                // Load the page with ajax call
                $.ajaxSetup({
                    cache: 'false',
                    dataType: $dataType,
                    contentType: $contentType
                });
                var ajax_load = "<div />";
                $e.html(ajax_load).load(pageUrls[index]);
            }
            $e.fadeIn('slow');

            // remove the tooltip
            $('div#mainContent').attr('tooltipenable', 'false');
        },
        refreshUrl: function() {
            switch ($this.selectedTab.index()) {
                case 0:location.hash = '!welcome';break;
                case 1:location.hash = '!whyUs';break;
                case 2:location.hash = '!services';break;
                case 3:location.hash = '!clients';break;
                case 4:location.hash = '!faq';break;
                case 5:location.hash = '!connect';break;
            }
        }
    };
}();

// Common page methods

getPageIdByIndex = function($index) {
    var id = null;
    switch ($index) {
        case 0:id = 'welcomePage';break;
        case 1:id = 'whyUsPage';break;
        case 2:id = 'servicesPage';break;
        case 3:id = 'clientsPage';break;
        case 4:id = 'faqPage';break;
        case 5:id = 'connectPage';break;
    }
    return id;
}

getPageIndexById = function($id) {
    var index = -1;
    switch ($id) {
        case 'welcomePage':index = 0;break;
        case 'whyUsPage':index = 1;break;
        case 'servicesPage':index = 2;break;
        case 'clientsPage':index = 3;break;
        case 'faqPage':index = 4;break;
        case 'connectPage':index = 5;break;
    }
    return index;
}
