/*
Scripts written by Alex Dickson for Acura Multimedia (http://www.acura.com.au)

All scripts leverage the jQuery framework (http://www.jquery.com) by John Resig (http://www.ejohn.org)

*/



// global stuff 





// add this class to specify .javascript * in css for quicker css application

$('html').addClass('javascript');

// on DOM ready

$(document).ready(function(){
	$('html').addClass('dom-loaded');

    menu();
	
	if ($('body').hasClass('products')) {
	
		productDisplay();
	
	}
	
	$('a[rel=external]').newWindow();

	$('#footer-newsletter input').inputSearch( { defaultText: 'you@domain.com' } );

	$('#gallery-image').gallery();


});



// on window loaded

$(window).load(function(){  // window load
	$('html').addClass('window-loaded');

	//google analytics

	try {
		var pageTracker = _gat._getTracker('UA-693909-52');
		pageTracker._trackPageview();

	} catch(err) {};

	

});


function menu() {
    $('#menu-hawko, #menu-tubetec').hoverIntent( function() {
        $('#header ul li ul:visible').fadeOut(250);
        $(this).find('ul').stop().fadeIn(250);
    }, function() {
		
		
	});
};

   
 

function productDisplay() {


    var products = [];
	
	var downloadPath = PATH_BASE + 'downloads/';
    var imagePath = PATH_BASE + 'images/products/'
	
    setupProductDisplay();
    processListItems();

    //We have to define cycler outside the showProduct function so that it's maintained
    //in between showProduct calls. 
    var cycler = null;

    showProduct(0);
    
    function scrollProductBox() {
    
        var $scrollingDiv = $('#product-info');
 
		$(window).scroll(function(){			
			$scrollingDiv
				.stop()
				.animate( { marginTop: ($(window).scrollTop()) - 130 + 'px'}, 'slow' );			
		});

    
    }
    
    function stopScrollingProductBox() {
    
           $('#product-info').stop();

    }
    
    function setupProductDisplay() 
    {
        var productInfoBoxHtml = '<div id="product-info"><h3 class="hide-me"></h3><span id="dimensions" class="hide-me"></span><div id="product-gallery"><img alt="" src="" /></div><ul id="product-options" class="hide-me"><li id="spex-sheet"><a href="" rel="external">Download full spex sheet</a></li><li id="enlarge-image"><a href="" rel="lightbox-gallery">Enlarge image</a></li></ul><div id="product-description" class="hide-me"></div><span id="top"></span><span id="bottom"></span><span id="side"></span><span class="loading"></span></div>';
        $('#products').after(productInfoBoxHtml);
        
        
       
       
        
        
        
    }

    function processListItems() 
    {
    
   
        $('#products > li > ul > li')
                .append('<span class="product-view">View</span>')
            .each(function() 
                        {
                                products.push({
                                                id: $(this).find('h4').html(),          
                                                title: $(this).find('h4').html(),
                                                dimensions: $(this).find('.dimensions').html(),
                                                description: $(this).find('.product-description').html()
                                                });

                })
                .find('.product-view')
            .click( function()
                                {
                        
                        var $parent = $(this).parent();


                        var index = $('#products > li > ul > li').index($parent);
                        
                        showProduct(index);
                        
                        var windowResizeTimeout;
                        
                        $(window).resize(function() { 
                            console.log('resize');
                            clearTimeout(windowResizeTimeout);
                            
                            windowResizeTimeout = setTimeout(function() {
                                showProduct(index);
                                console.log('show again')
                            
                            }, 500);
                        
                         } );

                                }
                        );

    
    };

    function showFile(file)
    {
        if (file)
        {
                $('#spex-sheet').show().find('a').attr( { href: downloadPath + file  } );       
        } 
        else 
        {                                      
                $('#spex-sheet').hide();
        }
    }

    function showGallery(images)
    {
		
        if(images.length === 0)
        {
                $('#enlarge-image').hide();
                $('#product-gallery').hide();
                return;
        }

        $('#product-gallery').show();
		
		
        $.each(images, 
                        function(i, image)
                        {
                                var img = new Image();
                    img.src = imagePath + 'thumb-' + image;
                    img = null;
                });
		
		

        // set first image thumbail and enlarge link
        if (images[0])
        {
			
           // $('#enlarge-image').show().find('a').attr({ href: imagePath + images[0] });
            $('#product-gallery img').attr( { src: imagePath + 'thumb-' + images[0]} ).show();
			$('#product-gallery').css( { backgroundImage: 'url(' + imagePath + 'thumb-' + images[0] + ')' } );
			
			
			
        }
		
		
		
		
        var currentImage = 0;
        clearInterval(cycler);
         $('#enlarge-image a').attr({ href: imagePath + images[currentImage] });                 
        cycler = setInterval(
                        function() 
                        {
							
                                if (currentImage == images.length - 1) {
									
									currentImage = 0;
									
								} else {
									
									currentImage++;
								}
                             
								
								var obj = $('#product-gallery');

                    var imageSource = imagePath + 'thumb-' + images[currentImage];                  
                    obj.css('backgroundImage','url(' + imageSource  +')');          
                    obj.find('img').show().fadeOut(500, function() { $(this).attr({src: imageSource}) });
                    $('#enlarge-image a').attr({ href: imagePath + images[currentImage] });                 
                }, 3000);



        $("#enlarge-image a").slimbox({}, null, function(el) {
                                        return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
                                });
        return true;                        

    };

    function showProductInfo()
    {
        $('#product-info')
                .find('.hide-me')
                        .remove('#product-gallery, #spex-sheet')
                .show()
                .parent()
                        .find('.loading')
                .hide();
                
        return true;
    }

    function showProduct(index) 
    {
        $('#product-info')
                .show()
            .find('.hide-me, #product-gallery')
                        .hide()
            .parent()
                        .find('.loading')
                .show();

        // get data contained in the page
        $('#product-info')
                .find('h3')
                        .html(products[index].title)
                .parent()
                        .find('#dimensions')
                                .html(products[index].dimensions)
                .parent()
                .find('#product-description')
                                .html(products[index].description)
        // get id & then product extra info
        var id = $('#products > li > ul > li').eq(index).attr('id').replace(/id-/, '');
        
        var getJsonUrl = PATH_BASE + 'products/get/' + id + '/';
        
        $.getJSON(getJsonUrl,
                function(data)
                {           
                        showFile(data.file);
                        showGallery(data.images);
                        showProductInfo();
                        
                        var productInfoHeight = $('#product-info').height();
                        
                        var productInfoTop = $('#product-info').position().top;
                        
                        var viewportHeight = $(window).height();
            
                        if ((productInfoHeight + productInfoTop) > viewportHeight) {
                            stopScrollingProductBox();
                        } else {
                            scrollProductBox();
                        }
        
                               
                        

                });

    };




};


/**
* searchInput v1 // 2009.07.09 // jQuery 1.1.2+
* <http://www.alexanderdickson.com/2009/07/jquery-plugin-inputsearch/>
* 
* @author    Alexander Dickson <http://www.alexanderdickson.com/>
*/

(function($){  
  $.fn.inputSearch = function(options) {   
    var defaults = {
		defaultText: 'Search',
		dullClass: 'dulled'		
	};	
	var options = $.extend(defaults, options);   
    return this.each(function() {  
	   var obj = $(this);	   
	   if ( ! obj.val()) {
	   		obj.addClass(options.dullClass);
			obj.val(options.defaultText);
		};		
		obj.focus(function() {
			if (obj.val() == options.defaultText) {
				obj.removeClass(options.dullClass);
				obj.val('');
			};	
		});
		obj.blur(function() {		
			if ($.trim(obj.val()) == '') {
				obj.addClass(options.dullClass);
				obj.val(options.defaultText);
			};
		});	   
	 });
  };  
 })(jQuery); 


// plugin to open links with new window
// author: Alex Dickson
 (function($){  
  $.fn.newWindow = function(options) {   
    var defaults = {
		titleText: 'Link opens in a new window'		
	};	
	var options = $.extend(defaults, options);   
     return this.each(function() {  
	   var obj = $(this);	   
	   if (options.titleText) {   
		   if (obj.attr('title')) {
				var newTitle = obj.attr('title') + ' (' + options.titleText + ')';
		   } else {
				var newTitle = options.titleText;   
		   };		   
		   obj.attr('title', newTitle);		   
	   };
	   obj.click(function(event) {
	   	  event.preventDefault();  
		  var newBlankWindow = window.open(obj.attr('href'), '_blank');
		  newBlankWindow.focus();
		}); 
	   });
  };  
 })(jQuery); 
 
 
 
 // plugin to cycle images and display text
// author: Alex Dickson
 (function($){  
  $.fn.gallery = function(options) {       
	var defaults = {
		imagesList: '#thumbnails ul',
		textElement: '#gallery-text',
		interval: 5000		
	};		
	var options = $.extend(defaults, options);      
	var obj = $(this);	   	    
	var $imagesList = $(options.imagesList);
	var $textElement = $(options.textElement);		
	var imagesData = [];	
	function loadImage(id) {
	
		if ( ! imagesData[id].preloaded) {				
			showLoading();	
			var image = new Image();			
			$(image).load(function() {
				imagesData[id].preloaded = true;
				hideLoading();
				showImage(id);	
			});			
			// load the image into the cache
			image.src = imagesData[id].src;
		} else {			
			showImage(id);			
		};									
	};
	
	function showImage(id) {
		
		var imageSource = imagesData[id].src;			
		obj.css('backgroundImage','url(' + imageSource  +')');		
		obj.find('img').show().fadeOut(500, function() { $(this).attr({src: imageSource}) });				
		$imagesList.find('li.active').removeClass('active');
		$imagesList.find('li').eq(id).addClass('active');		
		
		
		
		// show new text
		
		$textElement.find('h3, p').fadeOut(250, function() {
			$textElement.find('h3').html(imagesData[id].title);
			$textElement.find('p').html(imagesData[id].description);
			$textElement.find('h3, p').fadeIn(250);
		});
		

		
	};
	
	function showLoading() {	
		if ( ! $('#gallery-loading').length) {
			obj.append('<div id="gallery-loading" title="loading... please wait."></div>');
		};
		$('#gallery-loading').fadeIn(250);
	}
	
	function hideLoading() {
		$('#gallery-loading').fadeOut(250);		
		
	};
	
	return this.each(function(i) {
		
		showLoading();
		  	 			
	    $imagesList.find(' > li').each(function(i) {						
			// get all data
			imagesData[i] = {
				src: $(this).find('a').attr('href'),
				title: $(this).find('h3').html(),
				description: $(this).find('p').html(),							
				preloaded: false
			};
			
			$(this).find('a').click(function(event) {
				event.preventDefault();
				// stop the cycle of images
				clearInterval(cycle);				
				var imageIndex = $imagesList.find('a').index($(this));								
				loadImage(imageIndex);				
				$imagesList.find('li.active').removeClass('active');
				$(this).parent('li').addClass('active');								
			});	
		});				
		
		hideLoading();
		
		var currentImage = 0;		
		// start cylce
		var cycle = setInterval(function() {			
			if (currentImage == imagesData.length - 1) {			
				currentImage = 0;				
			} else {				
				currentImage ++;				
			};
			
			loadImage(currentImage);								
		}, options.interval);									  
	 });	
  };  
 })(jQuery); 








