/* Infinite carousel plugin */
$.fn.infiniteCarousel = function () {
    
    // Array hack to repeat strings
    function repeat(str, num) {        
        return new Array( num + 1 ).join( str );
    }      
        
    return this.each(function () {        
        var $wrapper = $('> div', this).css('overflow', 'hidden'),            
        $slider = $wrapper.find('> ul'),            
        $items = $slider.find('> li'),            
        $single = $items.filter(':first'),                                
        
        singleWidth = $single.outerWidth(),                            
        
        // Note: doesn't include padding or border
        visible = Math.ceil($wrapper.innerWidth() / singleWidth),
        currentPage = 1,            
        pages = Math.ceil($items.length / visible);                   
        
        // 1. Pad so that 'visible' number will always be seen, otherwise create empty items        
        if (($items.length % visible) != 0) {           
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));            
            $items = $slider.find('> li');                        
        }
       
        // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first       
        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));        
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));        
        $items = $slider.find('> li'); // reselect          
        
        // 3. Set the left position to the first 'real' item        
        $wrapper.scrollLeft(singleWidth * visible);                
        
        // 4. paging function
        function gotoPage(page) {            
            var dir = page < currentPage ? -1 : 1,                
                n = Math.abs(currentPage - page),                
                left = singleWidth * dir * visible * n;                                        
                
            $wrapper.filter(':not(:animated)').animate({               
                scrollLeft : '+=' + left            
            }, 400, function () {               
                if (page == 0) {                    
                    $wrapper.scrollLeft(singleWidth * visible * pages);                                        
                    page = pages;                
                } else if (page > pages) {                    
                    $wrapper.scrollLeft(singleWidth * visible);
                    // reset back to start position
                    page = 1;
                }      
                currentPage = page;
            });                                                  
            return false;
        }                
        
        // 4a. Create carousel navigation buttons
        $wrapper.after('<a class="carouselArrow back">&lt;</a><a class="carouselArrow forward">&gt;</a>');                 
        
        // 5. Bind to the forward and back buttons        
        $('a.back', this).click(function () {            
            return gotoPage(currentPage - 1);
        });
                        
        $('a.forward', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        // 6. create a public interface to move to a specific page
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
    });
};



// Image cycling
var imgCounter = 0;

function fadeHandler(link) {        
    // Grab imageGallery element
    var hrefArray = $("#imgGallery ul li a");        
    
    $("#imgGallery ul li a").each(function(i) { 
        // setInterval event (no parameter passed)
        if(link == null) {
            // Check for loop end
            if (imgCounter >= hrefArray.length){
                imgCounter = 0;
            }
            // assign image href and move to next element
            link = hrefArray[imgCounter];
            imgCounter++;     
        }                      
        
        // Click event (parameter passed)
        if(link == $(this).attr("href")){
            
            // cycle navigation button rollovers ( Note: "Contextualized selector" format is: $(expression, context)  )           
            $(".navigation a", "#imgGallery").each(function(i) {
                if(link == $(this).attr('href')){
                    // Button "selected" css
                    $(this).addClass('selected');                                                   
                }
                else {
                    $(this).removeClass('selected');                                                                                    
                }	        		                           
            });
   
            // Animate fade in
	        $(this).parent().stop().animate({opacity: 1.0}, 1000);
	        $(this).parent().css("z-index", 50);
        }
        else {
            // Animate fade out
            $(this).parent().stop().animate({opacity: 0.0}, 1000);
            $(this).parent().css("z-index", 1);
        }                
    }); 
};



// Element enclosing
function encloseElement(elementClass){    
    var tabHeight;
    var visiblePanelHeight = 0;
    
    // Set initial panel 
    if(elementClass == null){
        elementClass="panelOne";
    }
    
    // Identify passed in element using "attribute substring selector" 
    $("div[class*='panel']").each(function(i) {
         if($(this).attr("class") == elementClass){
            // Set element height & display            
            tabHeight = $("#panelTabs").height();
            visiblePanelHeight = $(this).height();            
            $("#panels").height(visiblePanelHeight+tabHeight);
            $(this).show();                        
        } 
        else {
            // Hide other panel(s)
            $(this).hide();
        }        
    });
}



// Font scaling functions 
var min=12;
var max=20;

function increaseFontSize() {  // need to add jquery "onclick" handler 
    var box = $('.box');
    
    // Set font size on all elements with ".box" class
    for(i=0;i<box.length;i++) {
        if(box[i].style.fontSize) { // check the element has the "fontSize" property
            var s = parseInt(box[i].style.fontSize.replace("px","")); //grab it's fontSize value
        } 
        else {
            var s = 12;
        }
        if(s!=max) {  // check range
            s += 1;   // increment fontSize
        }
        box[i].style.fontSize = s+"px";           
    }
     
    //Check page for "panels"
    if($('#panelBody') != null){
        var visiblePanel
        
        // Determine visible panel
        $("div[class*='panel']").each(function(i) {
        if($(this).is(':visible')) {
            visiblePanel = $(this).attr("class"); 
            }
        });                         
        
        // Invoke panel resizing function
        encloseElement(visiblePanel);            
    }
}
function decreaseFontSize() {    
    var box = $('.box');    
        
    for(i=0;i<box.length;i++) { // loop through all p elements
        if(box[i].style.fontSize) { // check the element has the "fontSize" property
            var s = parseInt(box[i].style.fontSize.replace("px","")); //grab it's fontSize value            
        } 
        else {
            var s = 12;
        }
        if(s!=min) {  // check range
            s -= 1;   // increment fontSize 
        }
        box[i].style.fontSize = s+"px";
    }
    
    //Check page for "panels"
    if($('#panelBody') != null){
        var visiblePanel;

        // Determine visible panel
        $("div[class*='panel']").each(function(i) {
        if($(this).is(':visible')) {
            visiblePanel = $(this).attr("class");
            }
        });                         
 
        // Invoke panel resizing function
        encloseElement(visiblePanel);
    }
}


/* Navigation area rollovers */
function attachNavEvents(parent, navClass) {
    $(parent).mouseover(function() {        
        //console.info("Value of navClass is: " + navClass);
        if(navClass.indexOf("-over") == -1){                
            $(this).removeClass(navClass);
            $(this).addClass(navClass + "-over");
        }        
    }).mouseout(function() {               
        $(parent).removeClass(navClass + "-over");
        $(parent).addClass(navClass);
    });        
}


// Jquery "ready()" function shorthand
$(function() {
    
    // "Font scaling" Button events 
    $(".minus").click(function(event){              
        decreaseFontSize();      
    });    
    $(".plus").click(function(event){              
        increaseFontSize();
    });
    
    
    /* Attach navigation tab events */
    $("#navigation ul li a").each(function(i) {
        attachNavEvents($(this), $(this).attr("class"));   	        		                           
    });
    
    
    // intialise gallery resources 
	$('div#imgGallery ul li').css({opacity: 0.0});
	$('div#imgGallery ul li:first').css({opacity: 1.0});
	$('div#imgGallery .navigation a:first').addClass('selected');
	
    // Initialize imageGallery 
    fadeHandler();
    var timer = window.setInterval("fadeHandler()", 8000);    					

    /* Gallery button events */
    $(".galleryBtn").hover(
        function () {
            $(this).addClass('galleryBtnR');
        }, 
        function () {
            $(this).removeClass('galleryBtnR');
        }
    );
       	
	$(".galleryBtn").click(function(event){        
        event.preventDefault();
        
        $("#imgGallery .navigation a").each(function(i) {
            if(event.target.href == $(this).attr('href')){
                // Button "selected" css
                $(this).addClass('galleryBtnR');
                
                // Interrupt image cycling
                window.clearInterval(timer);
                
                // invoke image Cycle                   
                fadeHandler(this.href);                                  
            }
            else {
                $(this).removeClass('galleryBtnR');                                                                                    
            }	        		                           
        });                          
    });
    
    
    
    // Initialize "Panels"
    encloseElement();
          
    // "Element enclosing" Button event
    $("#panelTabs a").click(function(event){              
        encloseElement($(this).attr("class"));
        event.preventDefault();                
    });
        
                            
    // Initialize "Carousel" 
    $('.infiniteCarousel').infiniteCarousel();
    $('.carouselArrow').css({opacity: 0.0});
      
    // Carousel button events
    $('.infiniteCarousel').hover(function () {
        $('.infiniteCarousel a').stop().css({opacity: 0.0}).animate({opacity: 1.0}, 1000);	  
    }, function () {
        $('.infiniteCarousel a').stop().animate({opacity: 0.0}, 1000);        
    }); 
        
    // Carousel item(s) overlay
    $('.wrapper ul li a span').hover(
        function () {                                                        
            // potential issue, as ie displays one style for both
            $(this).children(':second').slideDown(300); 
        },
        function () {            
            $(this).children(':second').slideUp(300);                                     
        }                      
    );
    
    
    /* Footer animation & overlay (element's position resets to page bottom as it expands) */
    $('#animatedFooter').hover(function()  {
        $(this).stop().animate({bottom: '0px', height:'440px'},{duration:'1000', queue:'no'});
        },
        function() {
            $(this).stop().animate({bottom: '0px', height:'64px'},{duration:'1000', queue:'no'});                        
    });
}); 