/* 
	Name: Eircom Wholesale
	Date: 26th February 2010 
	Description: Common JS
	Version: 1.0 
	Author: Pete Luffman
	Author URI: http://www.merchantmarketinggroup.com
*/


$(function () {

    $('body').addClass('js');

    if ($('#home').length != 0) {
        
        finder.init();
       
        $("#slider").drawers({
        	handle : '.drawer-handle',
			content : '.drawer-content',
			equalHeights : true
        });
    }

    if ($('#management').length) mgmtteam.init();

    equalNewsHeights.init();
    equalProductsHeights.init();
    dropDownMenus.init();

    // Add breadcrumbs
    $('#breadcrumbs dd:not(#section #breadcrumbs dd)')
        .append('<a class="print-page" href="#" onclick="window.print();return false;">Print this page</a>');

    // Select list replace
    var $select = $('.downloads select');

    if ($select.length != 0) {
        $select.selectmenu({
            style: 'dropdown',
            positionOptions: {
                my: "left top",
                at: "left bottom",
                offset: "0 -1px"
            },
            menuWidth: 200,
            width: 110,
            maxHeight: 200
        });
    }

    clickableTeasers();

    // Enable modal windows

    if ($('.fancybox').length != 0) {
        $(".fancybox").fancybox({
            'width': 941,
            'height': 580,
            'autoScale': false,
            'autoDimensions': true,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'type': 'iframe',
            'overlayOpacity': '0.7',
            'titleShow': false
        });
    }
})

/*********************************************** 
				Eircom Finder
***********************************************/

var finder = {

    settings: {
        container: '#finder',
        linkList: '#slideLinks',
        panes: '.pane',
        highlightBar: '.pointer',
        colors: {
            white: '#FFF',
            grey: '#736C66'
        }
    },

    init: function () {

        var finder = this,
			settings = this.settings,
			colors = settings.colors;

        // Setup variables and elements
        var $container = $(settings.container),
			$links = $(settings.linkList).find("li a"),
			$panes = $container.find(settings.panes),
            $selects = $panes.find("dl"),
			$bar = $container.find(settings.highlightBar),
			$previous = $links.eq(0),
			$selected = $previous.addClass('current'),
			$previousPane = $panes.eq(0),
			origPos = $selected.position().top,
			listPos = parseInt($(settings.linkList).css('top').substring(0, $(settings.linkList).css('top').indexOf("px")));

        // Setup initial bar & panel viewstate	  
        $container.addClass('finder');
       
        $panes
        	.find("dd")
        	.each(function(){ $(this).data('height', $(this).outerHeight());  })
        	.css({ height: 0, opacity:0 })
       		.end()
       		.filter(':not(:first)').hide();
        	
        $bar.css('top', listPos);

        // Setup link events
        $links.hover(
            function () {
                $el = $(this);

                // Move highlight bar
                topPos = $el.position().top;
                if (topPos !== origPos) finder.moveBar($bar, topPos + listPos);

                // Change link colours
                finder.textCol(($previous, $selected), colors.grey);
                finder.textCol($el, colors.white);
            },
	        function () {
	            $previous = $el;

	            // Return to original position	    	
	            if (topPos !== origPos) finder.moveBar($bar, origPos + listPos);
	            finder.textCol($previous, colors.grey);
	            finder.textCol($selected, colors.white);

	        }
        ).click(
            function () {

                $selected = $(this).addClass('current');
                $selectedPane = $($selected.attr("href"));

                $previous.removeClass('current');

                // Show selected pane
                $previousPane.fadeOut(150);
                $selectedPane.fadeIn(150);

                origPos = $selected.position().top;

                $previousPane = $selectedPane;

                return false;
            }
        );

        // Create 'Select lists'
        $selects.click(
            function () {
            	var $dd = $(this).find("dd");

                $(this)
                    .addClass("open")
                    .find("dd")
                    .animate({ height : $dd.data('height'), opacity : 1 }, 100, function () { $(this).parent().addClass("open") });

               $("#slides").css('overflow', 'visible');
            }
        );

        $selects.hover(
            function () {
                $(this).addClass("hover");
            },
            function () {
                $(this)
                    .find("dd")
                    .animate({ height : 0, opacity : 0 }, 100, function () { $(this).parent().removeClass("hover open") });

                $("#slides").css('overflow', 'hidden');
            }
        );
    },

    textCol: function (elm, col) {
        //        $(elm).stop().animate({
        //            color: col
        //        }, 200)
        $(elm).css('color', col);
    },

    moveBar: function (elm, pos) {
        //        $(elm).stop().animate({
        //            top: pos
        //        }, 200)

        if (jQuery.support.opacity) {
            $(elm)
            .stop()
            .css({ 'top': pos, 'opacity': 0 })
            .animate({
                opacity: 1
            }, 100)
        }
        else {
            $(elm).css('top', pos);
        }
    }
};

	
/*********************************************** 
                Equal heights for news
***********************************************/

var equalNewsHeights = {

    init: function () {
        equalNewsHeights.equalHeight('#recent_news .row1');
        equalNewsHeights.equalHeight('#recent_news .row2');
        equalNewsHeights.equalHeight('#recent_news .row3');
    },

    equalHeight: function (classRef) {

        var tallest = '';

        $(classRef).each(function () {
            if ($(this).outerHeight() > tallest) {
                tallest = $(this).outerHeight();
            }
        });

        if ($.browser.msie && $.browser.version.substr(0, 1) == "6") {
            $(classRef).height(tallest);
        }
        else {
            $(classRef).css("min-height", tallest);
        }
    }

}


/*********************************************** 
Equal heights for products home
***********************************************/

var equalProductsHeights = {

    init: function () {
        equalProductsHeights.equalHeight('#product-sections li');
    },

    equalHeight: function (classRef) {

        var tallest = '';

        $(classRef).each(function () {
            if ($(this).height() > tallest) {
                tallest = $(this).height();
            }
        });

        //compensate for cufon height difference
        tallest = tallest;

        if ($.browser.msie && $.browser.version.substr(0, 1) == "6") {
            $(classRef).height(tallest);
        }
        else {
            $(classRef).css("min-height", tallest);
        }
    }

}
	
/*********************************************** 
    Main menu drop downs
***********************************************/

var dropDownMenus = {
    init: function () {
		
		var $menu = $('#mainmenu');
		var $footer = $('#footerlinks');
		var $listItems = $('ul li.parent', $menu);
		var speed = 100;
		
        $listItems.each(function(){             
             var $dropdown = $('<span class="dropdown"/>')
                .click(function () {
                        var $listItem = $(this).parent();
                        
                        if(!$listItem.hasClass('active')) {
                            $('li.expanded > ul', $menu)
                                .slideToggle(speed,
                                    function () {
                                        $(this).parent().removeClass('expanded').find('ul').remove();
                                    });
            
                        if (!$listItem.hasClass('expanded')) {
                            var link = $(this).parent().find('> a').attr('title');
                            link = link.replace(' ', '-');
        
                            $listItem.addClass('expanded');
                            
                            $('ul.' + link, $footer)
                                .clone()
                                .addClass('expanded')
                                .appendTo($listItem)
                                .slideToggle(speed);
        
                        }
                        else {
                            $('ul', $listItem).slideToggle(speed,
                                function () {
                                     $listItem
                                        .removeClass('expanded')
                                        .find('ul')
                                        .remove();
                                }
                            );
                        }
        
                        return false;
                    }
                });

            $dropdown.insertAfter($("a:first", $(this)));
        });

        

        $('body').click(
            function () {
                $('li.expanded > ul', $menu).slideToggle(speed,
                    function () {
                        $(this)
                        	.parent()
                        	.removeClass('expanded')
                        	.end()
                        	.remove();
                    }
		        );
            }
        );
    }
}

/*********************************************** 
Clickable hover state for feature boxes
***********************************************/

function clickableTeasers() {

    if($('.boxRow').length) {
        
        var $boxes = $('.boxRow .box');

        $boxes.each(function() {
            var $box = $(this);
            var $anchor = $('.featureImage a', $box);
            var $teaser = $('.teaser', $box);

            if($anchor.length && $teaser.length) {
                $teaser
                	.css({ 
                		cursor : 'pointer', 
                		opacity : 0
                	})
                	.click(function() {
	                    var href = $anchor.attr('href');
	                    
	                    if(href != null && href != '' && !$anchor.hasClass('fancybox')) {
	                        
	                        if($anchor.attr('target') == '_blank') {
	                            //open in a new window
								window.open(href);
	                        } else {
	                            //open in current window
	                            window.location = href;  
	                        } 
	                                   
	                    }   
	                    
	                    if($anchor.hasClass('fancybox')) {
	                        //trigger fancybox
	                        $anchor.click();
	                    }             
	                })
	                .hover(
	                	function() {
	                		$teaser.stop().animate({ opacity : 1 }, 200);
	                	},
	                	function() {
	                		$teaser.stop().animate({ opacity : 0 }, 200);
	                	}
	                );
            }
        })
    }

}

/*********************************************** 
			Equal column heights
***********************************************/

(function($) {

    $.equalHeights = function(el, options) {

        var base = this;
        var maxHeight = 0;
        
        base.$el = $(el);
		
		base.$el.bind("removeHeights", function() { 
			base.$el.css({ 'height' : '', 'min-height' : '' }); 
		});	
				
        base.init = function() {
			
			base.options = $.extend({},$.equalHeights.defaultOptions, options);
			
            if($.browser.msie && $.browser.version.substr(0,1) == "6") 
				base.options.useMinHeight = false;
			
			var heightProperty = base.options.useMinHeight ? 'min-height' : 'height';
			
			base.$el
				.each(function(){
				
					var thisHeight = $(this).outerHeight();		
					
					if(thisHeight > maxHeight) {
						maxHeight = thisHeight;
					}
					
				})
				.css(heightProperty, maxHeight);
        };
        
        base.init();
        
        return maxHeight;
    };
    
    $.equalHeights.defaultOptions = {
        'useMinHeight' : 'true'
    };

    $.fn.equalHeights = function(options) {
        return this.each(function() {
            (new $.equalHeights(this, options));
        });
    };


})(jQuery);


/*********************************************** 
			Drawers
***********************************************/


(function($) {

    $.drawers = function(el, options) {

        var base = this;
        base.$el = $(el);
	
        base.init = function() {
	
            base.options = $.extend({},$.drawers.defaultOptions, options);
			
			var	$container = base.$el,
				$handles = $(base.options.handle, $container),
				$content = $(base.options.content, $container);
			
			if(base.options.equalHeights) { 
				$.equalHeights($content, { useMinHeight : false });
			}
			 	
			function slideDown(el) {
				
				var $thisHandle = $(el);
				
				$handles
					.next()
					.stop(true)
					.animate({ height: 0 }, 200) //Remove all "active" state and slide up the immediate next container
					.end()
					.parent()
					.removeClass('drawer-active')
				
				$thisHandle
					.parent()
					.addClass('drawer-active')
					.end()
					.next()
					.stop(true)
					.animate({ height: $thisHandle.next().data('height') }, 200);
			};
			
			$content
				.each(function(){ $(this).data('height', $(this).outerHeight());  })
				.filter(':not(:first)')
				.height(0); //Hide/close all containers
			
			$handles
				.hover(function(){ slideDown(this); })
				.filter(':first')
				.parent()
				.addClass('drawer-active'); //Add "active" class to first trigger
        };
        
        base.init();
    };

    $.drawers.defaultOptions = {
        'handle' : '.title',
		'content' : '.description',
		'activeClass' : 'drawer-active',
		'equalHeights' : false
    };

    $.fn.drawers = function(options) {
        return this.each(function() {
            (new $.drawers(this, options));
        });
    };


})(jQuery);
