/*
Libra Group general JS - permanent functionality
Dependencies: jQuery 1.4.2
Date: 2010
Author: TL
*/

$(document).ready(function() {
	if ($('.ie6').length) fixPngs();
	
	quickNav.init();
	hpCarousel();
	sectionCarousel(5000);
	//sectionSliding(3000);
	jsLangMenu();
	if ($('.contact').length) setMapModals();
	if ($('#timeline').length) $('#timeline dl').timeline();
	
	heightAdjust();
	if ($('#subsidiaries').length) logoScroller();
});

var quickNav = function() {
	var that = {};
	var setHeight = function() {
		var maxHeight = 0;
		$('#quick_nav>li').each(function() {
    		maxHeight = (maxHeight < $(this).height()) ? $(this).height() : maxHeight;
		}).height(maxHeight);
	};
	var setOpacity = function() {
		$('#quick_nav').css('opacity', 0.95);
	};
	// Quick navigation hover for IE6
	function ie6Hover() {
		if ($('body').hasClass('ie6')) {
			$('#sitemap').hover(function() {
				$(this).addClass('sfhover');
			}, function() {
				$(this).removeClass('sfhover');
			});
		}
	};
	// End: Quick navigation hover for IE6
	that.init = function() {
		setHeight();
		setOpacity();
		ie6Hover();
	}
	return that;
}();

var hpCarousel = function() {
	var t;
	var that = {
		transitionTime: 1000,
		playTime: 2500,
		fading: false, // make true to disable; false to play
		num: $('#carousel li').length,
		index: 0
	};
	that.createPanel = function() {
		$('#carousel').append('<li id="carousel_panel"></li>');
		$('#carousel_panel').css('opacity', 0.9);
		$('span', '#carousel').css('opacity', 0.4);
		
		$('li:first a', '#carousel').addClass('on');
		$('li:first span', '#carousel').css('opacity', 1);
		
		that.setPanel();
	};
	that.setPanel = function() {
		that.playCarousel(that.index + 1);
	};
	that.playCarousel = function(i) {
		t = setTimeout(function() {
			that.goTo(i);
		}, that.playTime);
	};
	that.goTo = function(i) {
		if (that.index != i && !that.fading) {
			that.fading = true;
			
			var carouselItems = $('#carousel li'),
				targetEl = $('a', $(carouselItems[i])),
				existingEl = $('a', $(carouselItems[that.index]));
			
			targetEl.addClass('fading');
			
			$('span', existingEl).animate({ 'opacity':0.4 }, that.transitionTime);
			$('span', targetEl).animate({ 'opacity':1 }, that.transitionTime);
			
			$('img', targetEl).fadeIn(that.transitionTime, function() {
				existingEl.removeClass('on');
				targetEl.addClass('on').removeClass('fading');
				$(this).removeAttr('style');
				that.index = i;
				that.fading = false;
				that.playCarousel((that.index == (that.num - 1)) ? 0 : that.index + 1);
			});
		}
	};
	that.init = function (){
		if ($('#carousel').length) that.createPanel();
	};
	return that.init;
}();

var sectionCarousel = function(ms) {
	var config = {
		transitionTime: 4000,
		playTime: ms || 5000
	};
	var el = $('#section');
	if (el.length && typeof(carousel) !== 'undefined') {
		var t = setTimeout(transition, config.playTime),
			index = 0,
			lastIndex = carousel.length;
	}
	function transition() {
		var endIndex = (index === lastIndex - 1) ? 0 : index + 1;
		var faddingEl = $('<div class="section-fader" style="background: transparent url(' + carousel[endIndex] + ') no-repeat bottom left; display: none; width: 960px; height: ' + el.height() + 'px; position: absolute; top: 0; left: 0; z-index: 0;"></div>');
		el.prepend(faddingEl);
		faddingEl.fadeIn(config.transitionTime, function() {
			el.css('background-image', 'url('+carousel[endIndex]+')');
			faddingEl.remove();
			index = endIndex;
			t = setTimeout(transition, config.playTime);
		});
	}
};

var sectionSliding = function(ms) {
	var el = $('#sub_section'),
		speed = ms || 1500,
		t = setTimeout(function() {
			if (el.hasClass('first')) el.animate({left: 0}, speed);			
		}, 0);
};

var jsLangMenu = function() {
    var that = {
        el: $('#lang')
    };
    that.createMenu = function() {
        var options = $('option', that.el),
			html = $('<ul class="select" style="overflow: hidden;">\
						<li class="chosen"><a href="javascript:void(0);"></a></li>\
						<li class="options">\
							<div style="position: relative;">\
								<ul></ul>\
							</div>\
						</li>\
					</ul>');
		
		if ($('.ie6').length || $('.ie7').length) $('div', html).css('width', '92px');

        options.each(function() {
            var specialStyle = '';
            if ($(this).val() == 'cn') {
                specialStyle = " style='font-family:\"Arial Unicode MS\",MHei;'";
            }
            var newOption = $('<li rel="' + $(this).val() + '"' + specialStyle + '>' + $(this).text() + '</li>');

            if ($(this).val() == that.el.val()) {
                newOption.addClass('selected');
                $('li.chosen a', html).text($(this).text());
            }

            $('li.options ul', html).append(newOption);
        });

        // hide original controls
        $('#lang, .langSelect').hide();

        $('#aspnetForm').append(html);

        $('ul.select:not(ul.active)').hover(function() {
            $(this).addClass('active');
            $('li.chosen').addClass('hovered');
            if ($('.ie6').length) $('ul', 'li.options').show();
            that.addHandler($('li.chosen'));
        }, function() {
        	if ($('.ie6').length) $('ul', 'li.options').slideUp();
            $('li.options').slideUp(function() {
                $('li.chosen').removeClass('hovered');
                $('ul.select').removeClass('active');
            });
        });
    };
    that.addHandler = function(el) {
        var parent = el.parent();

        $('ul.select:not(parent)').css('overflow', 'hidden');

        if (parent.css('overflow') == 'hidden') {
            parent.css('overflow', 'visible');

            $('li.options', parent).css({ 'display': 'block', 'opacity': '0.95' });

            $('li:not(li.chosen)', parent).click(function() {
                $('.selected', parent).removeClass('selected');

                $(this).addClass('selected');
                $('a', el).text($(this).text()).attr('title', $(this).text());

                $('option[value="' + $(this).attr('rel') + '"]', parent.parent()).attr('selected', true);
                
                if ($('.ie6').length) $('ul', 'li.options').slideUp();
                $('li.options', parent).slideUp(function() {
                    parent.css('overflow', 'hidden');
                    $('#aspnetForm').submit();
                });
                $('li:not(li.chosen)', parent).unbind('click');
            });
        }
    };
    that.init = function() {
        if (that.el.length) {
            $('head').append('<style type="text/css">ul.select li.hovered { -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; } ul.select li.options { -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; }</style>');
            that.createMenu();
        }
    };
    return that.init;
} ();

var heightAdjust = function() {
    var that = {
        viewport: window,
        threshold: 720,
        displaySize: null
    };
    that.setSize = function(size, type) {
        if (size === that.displaySize) return false;

        that.displaySize = size;
        var sectionHeight = (size === 'normal') ? 350 : 399,
        	scrollBarHeight = (size === 'normal') ? 264 : 313;

        if (type === 'onload') {
            $('#section').css('height', sectionHeight);
            $('.section-fader, #section').css('height', sectionHeight);
            $('#sub_section').css('height', (sectionHeight - 50));
            $('#sub_section_wide').css('height', (sectionHeight - 50));
            if ($('#carousel').length) $('#carousel').css('height', sectionHeight);
            if ($('#timeline').length) {
            	$('#timeline').css('height', sectionHeight);
            	$('#sub_section #timeline').css('height', (sectionHeight - 50));
        	}
        	if ($('#scrollbar-wrapper').length) $('#scrollbar-wrapper').css('height', scrollBarHeight);
        } else {
            $('#section').animate({ height: sectionHeight });
            $('.section-fader, #section').animate({ height: sectionHeight });
            $('#sub_section').animate({ height: (sectionHeight - 50) });
            $('#sub_section_wide').animate({ height: (sectionHeight - 50) });
            if ($('#carousel').length) $('#carousel').animate({ height: sectionHeight });
            if ($('#timeline').length) {
            	$('#timeline').css('height', sectionHeight);
            	$('#sub_section #timeline').css('height', (sectionHeight - 50));
        	}
        	if ($('#scrollbar-wrapper').length) $('#scrollbar-wrapper').css('height', scrollBarHeight);
        }

        
		// other elements to resize
		if ($('.vLine').length) $('.vLine').css('height', sectionHeight);
		if ($('.hotspot_vLine').length) $('.hotspot_vLine').css('height', sectionHeight);
    };
    that.getSize = function(type) {
        var type = (type !== 'onload') ? 'onresize' : type,
			size = ($(that.viewport).height() >= that.threshold) ? 'large' : 'normal';
        that.setSize(size, type);
    };
    that.init = function() {
        that.getSize('onload');
        $(that.viewport).bind('resize', that.getSize);
    };
    return that.init;
} ();

var setMapModals = function() {
	$('a.modal').click(function(e) {
		e.preventDefault();
		var url = $(this).attr('href'),
			mW = 684,
			mH = 378,
			html = $('<div class="modal_content"><img src="'+url+'" width="'+mW+'" height="'+mH+'" /></div>');
		
		html.css({ 'width': mW, 'height': mH, 'margin-top': -(mH + 80) / 2, 'margin-left': -(mW + 80) / 2 })
			.prepend('<a href="#" class="close_modal"><img src="/images/modal/close.png" title="Close modal" alt="Close" /></a>');
		
		$('body').append(html).append('<div id="modal_overlay" />');
		
		$('#modal_overlay').css('opacity', '0.8').fadeIn();
		
		html.fadeIn();
		
		return false;
	});
	
	//Close Popups and Fade Layer
	$('a.close_modal, #modal_overlay').live('click', function() { //When clicking on the close or fade layer...
		$('#modal_overlay , .modal_content').fadeOut(function() {
			$('#modal_overlay, .modal_content, a.close_modal').remove();  //fade them both out
		});
		return false;
	});
};

var logoScroller = function() {
	var that = {
		el: $('#subsidiaries')
	}
	
	that.setup = function() {
		that.el.parent().css({ 'overflow':'hidden', 'position':'relative' }).append('<div id="scrollbar-wrapper"><div id="scrollbar"></div></div>');
		that.elHeight = that.el.outerHeight(true);
		that.elParentHeight = that.el.parent().innerHeight();
		$('img', that.el).css('opacity', '0.7');
		
		that.setHandler();
		
		window.setTimeout(function() {
			that.setStartPosition();
		}, 1000);
	};
	
	that.setHandler = function() {
		$('#scrollbar').slider({
			min: 0,
			max: 100,
			orientation: 'vertical',
			value: 100,
			slide: function() {
				that.el.css('top', that.newPosition(parseInt($(this).slider('option', 'value'), 10)) + 'px');
			}
		}).parent().height(that.elParentHeight - 36); // padding allowance
	};
	
	that.newPosition = function(slideValue) {
		return ((that.elHeight - that.el.parent().innerHeight()) / -100) * (-slideValue + 100);
	};
	
	that.setStartPosition = function() {
		that.el.animate({ 'top':that.newPosition(50) + 'px' }, 1500);
		$('#scrollbar a').animate({ 'bottom':'50%' }, 1500);
	};
	
	that.init = function() {
		if (that.el.length) that.setup();
	};
	
	return that.init();
};

var fixPngs = function() {
    if ($('#sub_section').length) DD_belatedPNG.fix('#sub_section');
    if ($('#sub_section_wide').length) DD_belatedPNG.fix('#sub_section_wide');
	if ($('img.floatLeft').length) DD_belatedPNG.fix('img.floatLeft');
	if ($('.globalReach').length) {
		DD_belatedPNG.fix('#section, #worldmap_hotspots em');
	}
	if ($('.timeLine').length) {
	    DD_belatedPNG.fix('#tl_first, #tl_last, #tl_first.no_more, #tl_last.no_more, #dd_prev, #dd_next, #dd_prev.no_more, #dd_next.no_more, .marker, .prev_story, .next_story, #libra_global li a');
	}
};
