﻿(function($) {

	var Takeda = {
		isPE: false,
		isPrint: false,

		start: function() {
			this.warmUp();

			// =Master
			this.utilityBox();
			this.flyOuts();
			this.sideNav();
			this.topLink();
			this.iemLinks();

			// =Search
			this.searchBox();

			// =Main
			this.homeCycler();
			this.homeTeasers();
			this.twoColumnsPage();
			this.rightTeasers();
			this.coloredBoxes();

			if( $('#carousel').length ){
				this.sectionCycler();
			}

			// =General
			this.roundCorners();
			this.fixLineBreaks();

			// =PE
			if( this.isPE ) { this.fixPE(); }

			// =Print
			this.enablePrint();
		},

		warmUp: function() {
			// Special classes for the first and last list items
			$('li:first-child', '#nav').addClass('first-child');
			$('li:last-child', '#nav').addClass('last-child');

			// Remove empty paragraphs from teasers
			$('.teaser p').filter(function() { return $.trim($(this).html()) === '' }).remove();

			// =PE
			this.isPE = ( $("#scWebEditRibbon").length > 0 );

			// =Print
			this.isPrint = (window.opener && !window.opener.closed && (window.name == 'printWin2' || window.name == 'printFrontPage'));
		},

		// =Master
		utilityBox: function() {
			// Font resize
			$('span.fontResize').fontResize({
				onResize: function() {
					Takeda.afterFontResize();
				}
			});

			// Classes for placeholder styling
			$('.inputSearch').bind('focus', function(){ $(this).addClass('focused'); });
			$('.inputSearch').bind('blur', function(){ $(this).removeClass('focused'); });
		},

		flyOuts: function() {
			// Flyouts
			var $flyouts = $('#selLang, #selLand'),
				$uls = $flyouts.find('ul'),
				$zusammen = $flyouts.add($uls),
				timer = new Array();

			$flyouts.bind('click', function(){
				var $ul = $(this).find('ul');
				$ul.stop(true,true).slideDown('fast');
			});

			$zusammen.hover( flyMouseIn, flyMouseOut );

			function flyMouseIn() {
				flyMouseCommon($(this));
			}

			function flyMouseOut() {
				var $ul = flyMouseCommon($(this));

				timer[$ul.attr('id')] = setTimeout( $.proxy( function(){
					$(this).stop(true,true).slideUp('fast');
				}, $ul ) , 1000 );
			}

			function flyMouseCommon($el) {
				var $ul = ( $el.is($uls) ) ? $el : $el.find('ul');
				var t = timer[$ul.attr('id')];
				if( t ) { clearTimeout(t); }

				return $ul;
			}
		},

		sideNav: function() {
			// Remove classes from active children parents
			$activeChildren = $('#subnavi li.active');
			$activeChildren.parents('li.active').removeClass('active');

			// Ensure minimum height
			if( $('#subnaviRange').outerHeight() < $('#cntHeader').outerHeight() ) {
				$('#subnaviRange').height($('#cntHeader').height() + 100);
			}
		},

		topLink: function() {
			$('a[href="#top"]').bind('click', function(e){
				e.preventDefault();
				$('html,body').animate({scrollTop:$(this.hash).offset().top}, 200);
			});
		},

		iemLinks: function() {
			var extLinks = [
				'.disclaimer1_class',
				'.disclaimer2_class',
				'.disclaimer3_class',
				'.disclaimer4_class'
			],
			$extLinks = $(extLinks.join(', '));

			$extLinks.attr('class', 'external');

			var intLinks = [ '.tableCol3 td a' ],
			$intLinks = $(intLinks.join(', '));

			$intLinks.attr('class', 'internal');
		},

		// =Search
		searchBox: function() {
			// Pairs of inputs and their submit buttons
			var $inputs = $('#searchForm > .inputSearch, #q'),
				$buttons = $('#searchForm > .btnSearch, #b');

			// Submit the form on [ENTER]
			$inputs.bind('keypress', function(e){
				if(e.keyCode == '13') {
					e.preventDefault();
					submitSearch($(this).val());
				}
			});

			// Submit the form on button press
			$buttons.bind('click', function(e){
				e.preventDefault();
				var i = $buttons.index($(this));
				submitSearch($inputs.eq(i).val());
			});

			function submitSearch(words) {
				// Sanitize
				words = $.trim(words);

				// Escape
				words = $('<span />').text(words).html();

				if( words == '' ) {
					return;
				}

				// What URL are we submitting the form to?
				var loc = '/';
				var q = "q=" + encodeURIComponent(words);

				if($('#Categories').length) {
					var c = $('#Categories').val();
					if(c.length !== 0) {
						q += "&categories=" + encodeURI(c);
					}
				}

				if($('#local').length) {
					var l = $('#local').val();
					if(l.length !== 0) {
						loc += l;
					}
				}

				loc += 'search.aspx?' + q + '&filter=0';

				// window.location for reliability
				window.location.href = loc;
			}
		},


		// =Main
		homeCycler: function() {
			// Get the speed
			var speed = $('#cycler > input[name="cycler_speed"]').val();

			var args = {
				fx: 'fade',
				pause: true,
				timeout: (speed < 0) ? 0 : speed*1000
			}

			// Page Editor compatibility mode
			if(this.isPE == true) {
				var $pager = $('<div />').attr('class', 'spager clearfix');
				$('#cycler').prepend($pager);
				args.pager = $('#cycler > .spager');
				args.timeout = 0;
			}

			$('#cycler > .portal').cycle(args);
		},

		homeTeasers: function() {
			// Pipeline Teaser
			var $controls = $('#teasers .pipeline .control'),
				$popups = $('#teasers .pipeline .popup');

			Takeda.pipelineTeaser($controls, $popups);

			// Fluid images
		    $('#teasers > .teaser img.image').load(function(){
				var $img = $(this);
				$img.attr('width', $img.width()).attr('height', $img.height());
			});
		},

		twoColumnsPage: function() {
			if( $('#cntArea').hasClass('grid_4') ) {
				// Fix the column widths to fit
				$('#subnaviRange').css({
					'width' : '187px',
					'margin-left' : '6px'
				});
			}
		},

		rightTeasers: function() {
			var $controls = $('#cxtArea .pipeline .control'),
				$popups = $('#cxtArea .pipeline .popup');

			Takeda.pipelineTeaser($controls, $popups);
		},

		coloredBoxes: function() {
			$('.twoColsRange').children('.colsFull,.colsRange').equalHeights();
		},

		pipelineTeaser: function($controls, $popups) {
			$controls.each(function(){
				var $that = $(this);

				// All elements inside the .control div activate the popups
				$(this).children().bind('click', function(e){
					e.preventDefault();
					$popups.hide();

					var i = $controls.index($that);
					$popups.eq(i).fadeIn('fast');
				});
			});

			$popups.find('.close').bind('click', function(e){
				e.preventDefault();
				$(this).parent('.popup').fadeOut('fast');
			});

			$popups.corner("2px");
		},

		sectionCycler: function() {
			// Get the speed
			var speed = $('#autoplay').val();

			var args = {
				fx: 'fade',
				pause: true,
				timeout: (speed < 0) ? 0 : speed*1000
			}

			// Page editor compatiblity mode
			if(this.isPE == true) {
				var $pager = $('<div />').attr('class', 'spager clearfix');
				$('#carousel').parents('div').first().prepend($pager);
				args.pager = $('.spager');
				args.timeout = 0;
			}

			$('#carousel').cycle(args);

		},

		// =General
		roundCorners: function() {
			// Round corners for Left Menu
			$('#subnavi h2').wrap('<div class="cornerWrapH2"></div>');
			$('#subnavi .cornerWrapH2').corner("top 4px");

			// Round corners for Section Page Teasers
			$('.twoColsRange > div').corner("top 4px");

			// Round corners for content H2
			$('#cntArea .fullRange h2').wrap('<div class="cornerWrapH2"></div>');
			$('#cntArea .cornerWrapH2').corner("top 4px");

			// Round corners for Right Column Teasers
			$('#cxtArea .teaser h2').wrap('<div class="cornerWrapH2"></div>');

			// Round corners for Homepage Teasers
			var noBg = ['.crisis'];
			$('#teasers .teaser').not(noBg.join(' ')).find('h2:first').wrap('<div class="cornerWrapH2"></div>');

		},

		fixLineBreaks: function() {
			// In tables
			$('table p > br').before('<span class="br">&nbsp;</span>');

			// In teasers
			$('.teaser .cornerWrapH2').next().filter('br').remove();
		},

		afterFontResize: function() {
			// Make selLang & selLand arrow match the input box height
			var $boxes = $('#selLand, #selLang');

			$boxes.each(function(){
				var $textbox = $(this).find('div.float-l').first(),
					$image = $(this).find('img').first(),
					$dropdown = $(this).find('ul').first(),
					newHeight = $textbox.outerHeight() - 2, // The border
					diff = newHeight - $image.height();

				// Adjust image dimensions (1:1)
				$image.width(newHeight).height(newHeight);

				// Container size
				$(this).width($(this).width() + diff);

				// Dropdown size & position
				$dropdown.width($dropdown.width() + diff).css('top', (newHeight) + 'px');
			});

			// Fix the Pipeline Teaser
			$('.teaser.pipeline .control').each(function(){
				var newDim = $(this).find('.dropdown').outerHeight() - 2;

				// Adjust image dimensions (1:1)
				$(this).find('img').width(newDim).height(newDim);
			});
		},

		// =PE
		fixPE : function() {
			// Add 'isPE' class to our root element
			$('html').addClass('isPE');

			$.fixPE({
				'after' : Takeda.fixPE_after()
			});
		},

		fixPE_after: function() {
			// Hide font resize
			$('#utilityBox .fontResize').hide();

			// Apply z-index fix for (some of the) homepage divs
			var divIndex = 4990;
			$('#contentHome #teasers div').each(function() {
				$(this).css('zIndex', divIndex);
				divIndex -= 10;
			});

			// Make some spacing for section page divs
			$('#cntArea .scLooseFrameZone').each(function() {
				var oM = $(this).css('margin-top').replace("px", "");
				$(this).css('margin-top', oM + 30 + 'px');
			});

			// Hide header placeholder
			$('#ph__maincontent_header').css('display', 'none');
		},

		// =Print
		enablePrint: function() {
			// Handle click on print
			var $print_links = $('a.print-page, a.print-front-page');

			var args = {
				'title': 'printWin2',
				'width': 700,
				'height': 600
			};

			$print_links.bind('click', function(e){
				e.preventDefault();

				if($(this).hasClass('print-front-page')) {
					args.title = 'printFrontPage';
					args.width = 1020;
				}

				preparePrint(args.title, args.width, args.height);
			});

			if(this.isPrint) {
				// So, what do you want to modify on the print page?
				// Insert the print CSS as a normal CSS file (keep the old madness)
				$('head').append('<link rel="stylesheet" href="/css/skins/takeda/print.css" type="text/css" media="screen" />');

 				// Add the close links
 				var closeWindowLabel = '';

				if( $('#printCloseWindowLabel').length > 0 ) {
					closeWindowLabel = $('#printCloseWindowLabel').val();
				}

 				if(closeWindowLabel == '') {
 					closeWindowLabel = "Close window";
 				}

 				var $close_link = $('<a class="close-print" href="#" title="'+closeWindowLabel+'">'+closeWindowLabel+'</a>');
 				$('.btmPagetop').append($close_link);

 				// Move logo below breadcrumb
 				var $header = $('#header');
 				var $new_header = $header.clone().insertAfter($('#headBox'));
 				$header.remove();

 				// Add close link to header
 				$new_header.append($close_link.clone());

				// Remove some elements
				$('a.print-page, a.print-front-page').parent().remove();
				$('.btmPagetop > a').not($close_link).remove();
			}

 			var $close_links = $('a.close-print');

			$close_links.bind('click', function(e){
				e.preventDefault();
				window.close();
			});
		}
	}

	$(document).ready(function(){
		Takeda.start();
	});

})(jQuery);
