/**
 * DB Bahn Anreisebutton JavaScript
 * Copyright (c) 2009, namics (deutschland) gmbh. All rights reserved.
 * Code licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */

var ANREISE = {
	imgBaseUrl : '/common/view/static/v8/img/anreisebutton/',
	imgTextureSuffix : 'jpg', // Suffix for texture background images
	imgTransSuffix : 'gif', // Suffix for all transparent images

	buttons : {
		metal : {
			typo : 'typo-a',
			submit : 'link',
			icons : true,
			logo : true
		},
		lightplastic : {
			typo : 'typo-b',
			submit : 'link',
			icons : true,
			logo : true
		},
		darkplastic : {
			typo : 'typo-a',
			submit : 'link',
			icons : true,
			logo : true
		},
		print : {
			typo : 'typo-print',
			submit : 'link',
			icons : false,
			logo : true
		},
		'visual-ice' : {
			typo : 'typo-b',
			submit : 'start',
			icons : false,
			logo : false
		},
		'visual-regio' : {
			typo : 'typo-b',
			submit : 'start',
			icons : false,
			logo : false
		}
	},

	sizes : {
		l : 'large',
		m : 'medium',
		s : 'small',
		xs : 'xs',
		sq : 'square'
	},

	init: function() {
		if(jQuery( 'div.travelbutton' ).length > 0) {
		// Show JavaScript enabled text blocks
		jQuery( 'div.travelbutton' ).addClass( 'js' );

		// Add event listener for form
		var obj = document.getElementById( 'buttonForm' );
		jQuery( '#buttonForm' ).click( ANREISE.buttonListener ).bind( 'focusout', ANREISE.inputValidator );
		// I'd seriously wish the blur event would bubble
		if ( obj && obj.addEventListener ) {
			obj.addEventListener( 'blur', ANREISE.inputValidator, true );
		}
		// Add event listener for IE
		if ( obj && obj.attachEvent ) {
			obj.attachEvent( 'blur', ANREISE.inputValidator );
			// IE doesn't bubble clicks on images
			jQuery( '.imgSelection img' ).click( function() {
				oPrev = jQuery( this ).prev();
				oPrev.click();
				ANREISE.toggleVisual( oPrev );
			});
		};
		// Add listener for link terms and conditions
		jQuery( '#termslink' ).click( function() { jQuery( '#terms' ).show(); } );
			jQuery( '#terms' ).click( function() { jQuery( '#terms' ).hide() } );

			// Init TypAhead
			var minChars = jQuery('#qf-bhf-typeahead-minchars').val();
	        var delay = jQuery('#qf-bhf-typeahead-delay').val();
	        var reqUrl = jQuery('#qf-bhf-typeahead-requrl').val();

			new FSuggest({
					loc: 'preset-address',
					type: 'S',
					minChar: minChars,
					requestURL: reqUrl,
					stopDelay: delay,
					requestType: 'js'
				});
		}
	},

	/* Universal listener for form events */
	buttonListener: function( e, sId ) {
		var event = e || window.event, k = new BAHN.KeyObject( event ), sId = ( sId ) ? sId : k.oTarget.id, jTarget = jQuery( k.oTarget );
		sId = ( !sId && jTarget.hasClass( 'opener' ) ) ? 'opener' : sId;
		if ( sId.indexOf('bg-') === 0 ) {
			sId = 'bg';
		}
		else if ( sId.indexOf( 'hl-' ) === 0 ) {
			sId = 'hl';
		}
		else if ( sId.indexOf( 'image-' ) === 0 ) {
			sId = 'visual';
		}

		switch( sId ) {
			// Toggle address field for preset departure or destination point
			case 'preset-dest' :
			case 'preset-dept' :
				ANREISE.toggleAddress( 'show' );
				break;
			case 'preset-none' :
				ANREISE.toggleAddress( 'hide' );
				break;

			// Toggle size of dashed preview bannner
			case 'size-sq' :
			case 'size-l' :
			case 'size-m' :
			case 'size-s' :
			case 'size-xs' :
				ANREISE.toggleSize( sId );
				break;

			// Amend default action for h2|h3.opener
			case 'opener' :
				ANREISE.setExpanded( jTarget );
				break;

			// Toggle background image
			case 'bg' :
				ANREISE.toggleBg( jTarget );
				break;
			// Toggle text image
			case 'hl' :
				ANREISE.toggleText( jTarget );
				break;
			// Toggle visual
			case 'visual' :
				ANREISE.toggleVisual( jTarget );
				break;
			default :
				if( k.oTarget.nodeName.toLowerCase() === 'button' ) {
					// Set form action
					var submitUri = jQuery( '#fsu' ).val();
					submitUri = submitUri.replace( '--1--', jQuery( 'input.size:checked' ).val());
					submitUri = submitUri.replace( '--2--', jQuery( 'input.language:checked' ).val());
					jQuery( '#buttonForm' ).attr( 'action', submitUri );

					// Submit form
					this.submit();
				}
				break;
		}
	},

	// Validate certain input fields onblur
	inputValidator: function( e ) {
		var event = e || window.event, k = new BAHN.KeyObject( event ), sId = k.oTarget.id, sVal = jQuery( k.oTarget ).val();
		switch( sId ) {
			case 'email' :
				// RegEx for email validation according to RFC 3696
				var rEmail = /^([a-z0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&\'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)$/i;
				ANREISE.inputFeedback( sId, rEmail.test( sVal ) );
				break;
			case 'url' :
				// RegEx for URL validation
				var rURL = /^((http\:\/\/|https\:\/\/)(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)([\/]?([a-z0-9!#$%&\'\.*+\/=?^_`{|}~-]*))$/i;
				ANREISE.inputFeedback( sId, rURL.test( sVal ) );
				break;
			case 'name' :
				// Field must not be empty
				var rNotEmpty = /\w+.?/i;
				ANREISE.inputFeedback( sId, rNotEmpty.test( sVal ) );
				break;
			default :
				break;
		}
	},

	// Give input validation feedback
	inputFeedback: function( sId, state ) {
		var sFeedback = ( state ) ? 'pass' : 'fail', obj = jQuery( '#' + sId );

		// Set aria-invalid attribute
		obj.attr( 'aria-invalid', !state );

		// Create feedback element if it doesn't exist
		if ( obj.next().length === 0 || !obj.next().hasClass( 'feedback' ) ) {
			obj.after( '<span class="feedback ' + sFeedback + '"></span>' );
		}
		else {
			// Otherwise just set the class
			obj.next().attr( 'class', 'feedback ' + sFeedback );
		}
	},

	// show|hide the preset address field
	toggleAddress: function( action ) {
		var action = ( action === 'show'), oAddress = jQuery( '#preset-address-cont' );
		( action ) ? oAddress.addClass( 'selected' ) : oAddress.removeClass( 'selected' );
		BAHN.updateBuffer();
	},
	// Change the size of the preview box
	toggleSize: function( sId ) {
		jQuery( '#size-preview' ).attr( 'class', sId );
	},
	// Set the aria-expanded attribute on h2|h3.opener
	setExpanded: function( obj ){
		var sExpanded = ( obj.next().css( 'display' ) === 'block' ) ? 'true' : 'false';
		obj.attr( 'aria-expanded', sExpanded );
	},

	// Toggle the background image
	toggleBg: function( obj ) {
		var i = 0, aContainer = [ 'button-preview-img', 'button-preview-submit' ], aAlt = [ '', 'Button' ], aSize = jQuery( '#preview' ).attr( 'class' ).match( /(size-)([\w]*)/ ), sSize = aSize[2], sTexture = obj.val(), sLang = jQuery( '#langField' ).val(), oLogo = jQuery( '#buttonLogo' );
		if ( sSize === 's' || sSize === 'xs' ) {
			ANREISE.buttons[ sTexture ].submit = 'link';
		}
		if ( sSize === 'sq' ) {
			ANREISE.buttons[ sTexture ].logo = true;
		}
		// Logo source
		var sLogo = ( ANREISE.buttons[ sTexture ].logo === true ) ? oLogo.attr( 'src' ) : '';
		var aSrc = [
			ANREISE.imgBaseUrl + ANREISE.sizes[ sSize ] + '/button-' + sSize + '-bg-' + sTexture + '.' + ANREISE.imgTextureSuffix, // Background texture
			ANREISE.imgBaseUrl + ANREISE.sizes[ sSize ] + '/button-' + sSize + '-' + ANREISE.buttons[ sTexture ].submit + '-' + sLang + '.' + ANREISE.imgTransSuffix // Button
		];
		// Set parent's class
		jQuery( '#preview' ).attr( 'class', 'size-' + sSize + ' ' + sTexture );
		while ( aContainer[i] ) {
			oContainer = jQuery( '#' + aContainer[i] );
			// Create image element if it doesn't exist
			if ( !oContainer.length ) {
				jQuery( '#button-preview' ).append( '<img id="' + aContainer[i] + '" src=' + aSrc[i] + ' alt="' + aAlt[i] + '" />' );
			}
			else if ( aSrc[i] !== oContainer.attr( 'src' ) ) {
				// Replace image
				oContainer.load( function() { jQuery( this )
					.removeClass( 'hide' ) } )
					.addClass( 'hide' )
					.attr( 'src', aSrc[i] );
			}
			i++;
		}
		// Set hidden input fields for background texture, button/link, and logo
		jQuery( '#imgBg' ).val( aSrc[0] );
		jQuery( '#imgButton' ).val( aSrc[1] );
		jQuery( '#imgLogo' ).val( sLogo );

		// Adjust text image
		if ( oText = jQuery( 'input[name="text"]:checked' ) ) {
			ANREISE.toggleText( oText );
		}
		// Adjust visual
		if ( oVisual = jQuery( 'input[name="image"]:checked' ) ) {
			ANREISE.toggleVisual( oVisual );
		}
		// Allways show the logo on the square button
		if ( ANREISE.buttons[ sTexture ].logo ) {
			oLogo.show();
		}
	},

	// Toggle text
	toggleText: function( obj ) {
		var oTextContainer = jQuery( '#button-preview-text' ), sId = obj.attr( 'id' ) || 'hl-10', aSize = jQuery( '#preview' ).attr( 'class' ).match( /(size-)([\w]*)/ ), sSize = aSize[2], sTexture = jQuery( 'input[name="bg"]:checked' ).val() || 'metal', sLang = jQuery( '#langField' ).val(), sTypo = ANREISE.buttons[ sTexture ].typo || 'typo-a';
		if ( ( sSize === 's' || sSize === 'xs' ) && ( sTexture === 'visual-ice' || sTexture === 'visual-regio' ) ) {
			sTypo = 'typo-visual';
		}
		if ( sId === 'hl-10' && sSize !== 's' ) {
			return false;
		}
		var src = ANREISE.imgBaseUrl + ANREISE.sizes[ sSize ] + '/' + sTypo + '/button-' + sSize + '-' + sId + '-' + sTypo + '-' + sLang + '.' + ANREISE.imgTransSuffix;
		// Create image element if it doesn't exist
		if ( !oTextContainer.length ) {
			jQuery( '#button-preview' ).append( '<img id="button-preview-text" class="' + sTypo + '" src=' + src + ' alt="" />' );
		}
		else {
			// Replace image
			oTextContainer.attr( 'alt', obj.next().text() )
				.attr( 'class', sTypo + ' hide' )
				.load( function() { jQuery( this ).removeClass( 'hide' ) } )
				.attr( 'src', src );
		}
		// Set hidden input fields for text image
		jQuery( '#imgText' ).val( src );
	},

	// Toggle visual on button
	toggleVisual: function( obj ) {
		if ( obj.length === 0 ) {
			return false;
		}
		var oVisualContainer = jQuery( '#button-preview-visual' ), aSize = jQuery( '#preview' ).attr( 'class' ).match( /(size-)([\w]*)/ ), sSize = aSize[2], sTexture = jQuery( 'input[name="bg"]:checked' ).val() || 'lightplastic', sLang = jQuery( '#langField' ).val(), sVal = obj.val();
		var bNoImage = ( sTexture === 'print' || sTexture.indexOf( 'visual' ) === 0 );
		if ( bNoImage ) {
			jQuery( 'input[name="image"]:first' ).click();
			jQuery( 'input[name="image"]:gt( 0 )' ).attr( 'disabled', 'disabled' ).parent().addClass( 'disabled' );
		}
		else {
			jQuery( 'input[name="image"]' ).removeAttr( 'disabled' ).parent().removeClass( 'disabled' );
		}
		if ( sVal === '' || bNoImage ) {
			oVisualContainer.remove();
			// Set hidden input fields for text image
			jQuery( '#imgVisual' ).val( '' );
			return false;
		}
		var src = ( sVal === '1' ) ?
			ANREISE.imgBaseUrl + ANREISE.sizes[ sSize ] + '/images-' + sSize + '-' + sVal + '-' + sTexture + '.' + ANREISE.imgTextureSuffix :
			ANREISE.imgBaseUrl + ANREISE.sizes[ sSize ] + '/images-' + sSize + '-' + sVal + '.' + ANREISE.imgTransSuffix;
		// Create image element if it doesn't exist
		if ( !oVisualContainer.length ) {
			jQuery( '#button-preview' ).append( '<img id="button-preview-visual" class="img-' + sVal + '" src=' + src + ' alt="' + obj.next().find( 'img' ).attr( 'alt' ) + '" />' );
		}
		else {
			// Replace image
			oVisualContainer.attr( 'alt', obj.next( 'img' ).attr( 'alt' ) )
				.attr( 'class', 'img-' + sVal + ' hide' )
				.load( function() { jQuery( this ).removeClass( 'hide' ) } )
				.attr( 'src', src );
		}
		// Set hidden input fields for text image
		jQuery( '#imgVisual' ).val( src );
	}
};

jQuery(document).ready(function() {
	ANREISE.init();
});
