var mouseTimer;
var mouseStat = false;
var cColorPicker;

$(document).ready(function(){
	
	$('.colorPickerContainer').show();
	$('.colorPickerContainer a').attr('title', 'Farbauswahl');
	$('#previewContainer iframe').attr('src', getSourceCode(false))
	
	// Slider initialisieren
	if (typeof $().slider == 'function') {
		$('#textLengthSlider').slider({
			min: 10,
			max: 120,
			value: $('#textbox-size').val(),
			slide: function(event, ui) {
						$('#textbox-size').val(ui.value);
						$('#searchkeyword').attr('size', ui.value)
						updatePreview()
					}
		});
		
		
		$('#boxWidthSlider').slider({
			min: 60,
			max: 1000,
			value: $('#boxWidth').val(),
			slide: function(event, ui) {
						$('#boxWidth').val(ui.value);
						updatePreview()
			}
		});
		
		$('#boxHeightSlider').slider({
			min: 60,
			max: 1000,
			value: $('#boxHeight').val(),
			slide: function(event, ui) {
						$('#boxHeight').val(ui.value);
						updatePreview()
			}
		});
		
	}
	
	// Titel der Themenbereiche (Navigation) animieren
	function initNavigation( speed ) {
		$('.module .content .topic:not(.opened) ul').hide( speed );
		$('.module .content .topic.active ul').slideToggle( speed );
	}
	
	/*$('.module .content .topic:not(.opened) a.button').click(function(event){
		event.preventDefault();
		if ( $(this).parent().attr('class') == 'topic active' ) return 0;
		$('.module .content .topic.active').removeClass('active');
		$(this).parent().toggleClass('active');
		initNavigation('normal');
	});*/
	
	$('.module .content .topic a.button').click( function( event ) {
		event.preventDefault();
		return false;
	});

	//initNavigation(0);

	// Dropdown-Feld animieren
	$('#webmaster-navigation').click(function(event){
		$('#webmaster-navigation .content').slideToggle("fast");
	});
	
	// Suchfeld-Text ausblenden
	var bKeyword = 'BLZ, Ort oder Postleitzahl eingeben ...';
	
	$('#searchkeyword').focus(function(){
		if ( $(this).attr('value') == bKeyword ) {
			$(this).attr('value', '');
		}
	}).blur(function() {
		if ( $(this).attr('value') == '' ) {
			$(this).attr('value', bKeyword);
		}
	});
	
	$('.searchSubmit').click(function(){
		$('#searchkeyword').focus();
	});
	
	
	
	// Gibt den Quellcode fuer das iFrame oder die URL zurueck
	function getSourceCode( is_iframe ){
	
		var background = '#FFF';
		if ( typeof $('#background-color').val() != 'undefined') background = $('#background-color').val();
		var text_color = '#000';
		if ( typeof $('#text-color').val() != 'undefined') text_color = $('#text-color').val();
		var size = '30';
		if ( typeof $('#textbox-size').val() != 'undefined') size = $('#textbox-size').val();
		var siteURL = 'http://www.blz-aktuell.de/suche.php?';
		var output = '';
		
		if ( is_iframe ) {
			output += '<iframe src="';
		}
		
		output += siteURL + 
					'background-color=' + background.replace('#', '') + '&' +
					'text-color=' + text_color.replace('#', '') + '&' +
					'textbox-size=' + size;
		
		if ( is_iframe ) {
			output += '" width="' + $('#boxWidth').val() + '" height="' + $('#boxHeight').val() + '" style="overflow: hidden !important; border: none !important" scrolling="no" />';
		}
		
		return output;
		
	};
	
	// Aktualisiert die iFrame-Quelle und den Quellcode
	var updateTimer;
	gotToUpdate = true;
	
	function writeCode ( ) {
		if ( gotToUpdate == false ) return 0;
		$('#previewContainer iframe').attr('src', getSourceCode(false))
		$('#downloadContainer .sourceCode').val(getSourceCode(true));
		gotToUpdate = false;
	};

	function updatePreview ( ) {
		gotToUpdate = true;
		clearTimeout(updateTimer);
		updateTimer = setTimeout(writeCode, 450);
	};
	
	writeCode();
	
	
	$('#searchToolAssistant .textfield').change(function(){
		gotToUpdate = true;
		writeCode();
	});
	

	
	// Farbauswahl
	$('.colorPicker').hide();
	
	if ( typeof $().farbtastic == 'function' ) {
		$('#colorPicker1').farbtastic(function callback(color){
			$('#background-color').css({'background-color':color}).val(color);
			$('#previewBackground').css({'background-color':color});
			updatePreview();
		});
	
		$('#colorPicker2').farbtastic(function callback(color){
			$('#text-color').css({'background-color':color}).val(color);
			$('#previewContainer .languageSelection').css({'color':color});
			updatePreview();
		});
	}

	
	$('a.colorField').click(function(event) {
		event.preventDefault();
		var isVisible = false;
		if ($(this).next().is(':visible')) isVisible = true;
		$('.colorPicker').hide();
		if ( !isVisible ) $(this).next().show();
		$(this).next().mouseleave();
	});
	
	$('#textbox-size').change(function(){
		if ( $(this).val() > 120 ) $(this).val( 120 );
		if ( $(this).val() < 10 ) $(this).val( 10 );
		$('#textLengthSlider').slider('value', $(this).val());
		$('#searchkeyword').attr('size', $(this).val());
		updatePreview();
	});


	$('#boxWidth').change(function(){
		if ( $(this).val() > 1000 ) $(this).val( 1000 );
		if ( $(this).val() < 60 ) $(this).val( 60 );
		$('#boxWidthSlider').slider('value', $(this).val());
		updatePreview();
	});

	$('#boxHeight').change(function(){
		if ( $(this).val() > 1000 ) $(this).val( 1000 );
		if ( $(this).val() < 60 ) $(this).val( 60 );
		$('#boxHeightSlider').slider('value', $(this).val());
		updatePreview();
	});

	
	
	// Farbauswahl automatisch ausblenden
	$('.colorPicker').mouseenter(function() {
		mouseStat = true;
	});
	
	$('.colorPicker').mouseleave(function(){
		clearInterval(mouseTimer);
		cColorPicker = $(this);

		mouseTimer = setInterval('if (!mouseStat) { $(cColorPicker).hide(); clearInterval(mouseTimer) }', 800);
		mouseStat = false;
	});
	
	$('#settingsContainer #background-color').change(function(){
		alert('asd');
	});
	
	// Formular Vorschau-Automation
	$('#searchkeyword').attr('size', $('#textbox-size').val());
	
	
	// Quellcode-Download
	$('#downloadContainer .sourceCode').bind('focus click', function(){
		$(this).select();
	});
	
	
	// Unterstuetze internationale Suche im Formular
	$('.searchForm .languageSelection input[type="radio"]').change(function(){
		var language;
		language = $(this).attr('value');
		//alert(language);
		$('#nameFilterSelection a').each(function(){
			var cURL = $(this).attr('href'); // Lese aktuelle URL
			var nURL = cURL.replace(/country:[\w]{1,2}/g, "country:" + language); // Erstelle neue URL
			$(this).attr('href', nURL); // Schreibe neue URL
		});
		
	});
	
	// Tabulatoren und Content Tables IDs zuweisen
	counter = 1;
	$('.ibanTool .tabs li').each(function(){
		$(this).addClass('tabid-' + counter);
		counter++;
	});
	
	counter = 1;
	$('.ibanTool .contentTables .contentTable').each(function(){
		$(this).addClass('tableid-' + counter);
		counter++;
	});

	// Contenttables ausblenden und ersten einblenden
	$('.ibanTool .contentTables .contentTable').hide();
	$('.ibanTool .contentTables .contentTable:first-child').show().addClass('active');
	
	// Ersten Tab aktivieren 
	$('.ibanTool .tabs li:first-child').addClass('active');
	
	// Tab-Interaktion
	$('.ibanTool .tabs li a').click(function(event){
		event.preventDefault();
		
		// Breche ab, falls geklickter Tab schon aktiv ist
		if ( $(this).parent().attr('class').match('active') ) return 0;
		
		$('.ibanTool .tabs .active').removeClass('active');
		$(this).parent().addClass('active');
		
		// Blende Content Table ein
		currentID = getID($(this).parent().attr('class'));
		$('.ibanTool .contentTables .contentTable.active').removeClass('class').hide();
		$('.ibanTool .contentTables .contentTable[class*="tableid-' + currentID +'"]').show().addClass('active');
	});
	
	$('.ibanTool input[name="validateIban"]').click(function(event){
		event.preventDefault();
		
		myValidator = new ibanTool();
		IBAN = $(this).parents().children('#ibanValue').val();
		
		results = myValidator.validate(IBAN);
		
		// Blende Ergebnisse aus und leere Listen
		$('.contentTable .validationResults').hide();
		$('.contentTable .validationResults > div').hide();
		$('.contentTable .validationResults ul').empty();
		
		// Blende Hinweise aus
		$('.contentTable p.hint').hide('fast');
		
		// Ermittle Gültigkeit der IBAN
		if ( results.Invalid.length == 0 ) {
			// IBAN ohne Fehler
			$('.contentTable .validationResults .result').attr('class', '').addClass('result valid').text('Die IBAN ist gültig');
		} else {
			// IBAN Fehlerhaft
			$('.contentTable .validationResults .result').attr('class', '').addClass('result invalid').text('Die IBAN ist nicht gültig');
		}
		
		// Schreibe Ergebnisse
		results.Valid.each(function ( value ) {
			$('.contentTable .validationResults .valid ul').append('<li>' + value + '</li>');
		});
		
		results.Invalid.each(function ( value ) {
			$('.contentTable .validationResults .invalid ul').append('<li>' + value + '</li>');
		});
		
		// Blende Ergebnisse ein
		$('.contentTable .validationResults ul:not(:empty)').parents('div.results').show(0);
		$('.contentTable .validationResults').show(300, function() {
			$('#findInstitutes').mouseenter(function( e ){
				$('body').append('<div id="findInstitutesHint">Nutzen Sie unsere BLZ-Suche, um weitere<br />Standorte dieser Institution zu finden.</div>');
				$('#findInstitutesHint').css('position', 'absolute').css('left', e.pageX + 10).css('top', e.pageY + 10);
			});
			
			$('#findInstitutes').mousemove(function( e ){
				$('#findInstitutesHint').css('left', e.pageX + 10).css('top', e.pageY + 10);
			});
			
			$('#findInstitutes').mouseleave(function( e ) {
				$('#findInstitutesHint').remove();
			})
		});
		
	
		
	});
	
	$('.ibanTool input[name="generateIBAN"]').click(function(event){
		event.preventDefault();
		
		myGenerator = new ibanTool();

		with ( myGenerator ) {
			BankCode = $('.ibanTool #ibanBankCode').val();
			AccountNumber = $('.ibanTool #ibanAccountNumber').val();
			genRes = generate($('.ibanTool #ibanLanguageSelection').val());
		}
		
		if ( genRes.Invalid.length > 0 ) {
			$(this).parents('.contentTable').children('.result').empty().append('<div class="genresults results invalid"><ul></ul></div>');
			
			genRes.Invalid.each(function(val){
				$('.ibanTool .contentTable .genresults.invalid ul').append('<li>' + val + '</li>');
			});
		} else {
			$('div.ibanTool .result').hide().empty().append('<p class="iban"><span>IBAN (elektronisch): </span>' + myGenerator.IBAN + '</p>')
											 .append('<p class="iban"><span>IBAN (Papierformat): </span>' + myGenerator.IBANtoPaper() + '</p>').show('fast');
		}
	});
	
	
	if ( $('#LinkCloud').length > 0) {
		
		$('#LinkCloud a').each(function ( obj ) {
			$(this).css('fontSize', getRandomPixels(11, 19));
		});
		
	}
	
});

function getRandomPixels( min, max )
{
	var diff = max - min;
	return ( min + Math.round( Math.random() * diff ) ) + 'px';
}


function funExists( value ) {
	if ( typeof(value) != 'function' ) return false;
	return true;
}

function getID ( value ) {
	var regexCID = /[a-zA-Z0-9]*-([0-9]*)/;
	results = regexCID.exec( value );
	
	if ( results.length == 0 ) return null;
	
	return results[1];
}

// Suchfeld animieren
/*searchboxWidth = $('#keyword').width();
searchboxText = $('#keyword').attr('value');

$('#keyword').focus(function(){
	$(this).stop();
	if ( $(this).attr('value') == searchboxText ) $(this).attr('value', '');
	$(this).animate({width: searchboxWidth + 20});
}).blur(function(){
	$(this).stop();
	$(this).animate({width: searchboxWidth});
	if ( $(this).attr('value') == '' ) $(this).attr('value', searchboxText);
});*/

