/*
 * jQuery shuffle 
*/
 
(function($){

	$.fn.shuffle = function() {
		return this.each(function(){
			var items = $(this).children();
			itemsShuffle = $.shuffle(items)
			return (items.length) ? $(this).html(itemsShuffle) : this;
		});
	}
	
	$.shuffle = function(arr) {
		for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
		return arr;
	}
	
})(jQuery);

// $ UI Datepicker / Timepicker
$(function($) {
	$.datepicker.regional['de'] = {
		prevText:        'zurück',
		nextText:        'weiter',
		monthNames:      ['Jänner','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
		dayNames:        ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
		dayNamesMin:     ['So','Mo','Di','Mi','Do','Fr','Sa'],
		firstDay:        1,
		buttonText:      '',
		isRTL:           false
	};
	$.datepicker.regional['en'] = {
		buttonText:      'Calendar'
	};
	$.datepicker.regional['fr'] = {
		prevText:        'préc',
		nextText:        'suiv',
		monthNames:      ['Janvier','Février','Mars','Avril','Mai','Juin','Juillet','Août','Septembre','Octobre','Novembre','Décembre'], 
		dayNames:        ['Dimanche','Lundi','Mardi','Mercredi','Jeudi','Vendredi','Samedi'], 
		dayNamesMin:     ['Di','Lu','Ma','Me','Je','Ve','Sa'],
		firstDay:        0,
		buttonText:      'Calendrier',
		isRTL:           false
	};
	$.datepicker.regional['it'] = {
		prevText:        'prec',
		nextText:        'succ',
		monthNames:      ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'], 
		dayNames:        ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'], 
		dayNamesMin:     ['Do','Lu','Ma','Me','Gi','Ve','Sa'], 
		firstDay:        1,
		buttonText:      'Calendario',
		isRTL:           false
	};
	$.datepicker.setDefaults($.datepicker.regional[$('html').attr('lang')]);
	$.datepicker.setDefaults({
		buttonImage:     '/fileadmin/template/img/datepicker.gif',
		buttonImageOnly: true,
		dateFormat:      'yy-mm-dd', // ISO 8601
		minDate:         ((new Date().getHours() < 17) ? '0d' : '1d'), // nach 17 Uhr wird nur noch der morgige Tag zur Auswahl angeboten
		showOn:          'both',
		showOtherMonths: true,
		beforeShowDay:  function(date) {
			if (date.getDay() == 0 || date.getDay() == 6) { 
				return [false,""]; 
			} else {
				return [true, ""];
			}
		}
	});
	
	$.timepicker.regional = {
		'en': {
			currentText:   'Now',
			closeText:     'Done',
			ampm:          false,
			timeOnlyTitle: 'Choose time',
			timeText:      'Time',
			hourText:      'Hour',
			minuteText:    'Minute',
			secondText:    'Second',
			timezoneText:  'Time zone',
			buttonText:    'Time'
		},
		'de': {
			currentText:   'jetzt',
			closeText:     'Ok',
			ampm:          false,
			timeOnlyTitle: 'Zeit wählen',
			timeText:      'Zeit',
			hourText:      'Stunde',
			minuteText:    'Minute',
			secondText:    'Sekunde',
			timezoneText:  'Zeitzone',
			buttonText:    ''
		}
	};
	
	$.timepicker.setDefaults($.timepicker.regional[$('html').attr('lang')]);
	$.timepicker.setDefaults({
		buttonImage:     '/fileadmin/template/img/timepicker.gif',
		buttonImageOnly: true,
		stepHour: 1,
		stepMinute: 15,
		stepSecond: 10,
		hourMin: 8,
		hourMax: 16,
		minuteMax: 59,
		timeFormat:    'hh:mm'
	});
});


function addPickers() {
	$('input').each(
		function() {
			element = $(this);
			parentcol = element.parents('#col0, #col1').attr('id');
			replacement = element.clone();
			element.replaceWith(replacement);
			if(element.hasClass('date')) {
				replacement.datepicker({buttonImage: '/fileadmin/template/img/datepicker_' + parentcol + '.gif'});
				if(replacement.val() == '') {
					replacement.datepicker('setDate', new Date());
				}
				

			} else if (element.hasClass('time')){replacement.timepicker({timeFormat:    'hh:mm', buttonImage: '/fileadmin/template/img/timepicker_' + parentcol + '.gif'});}
			else if (element.hasClass('datetime')) {replacement.datetimepicker();}
			$('#date-selector').datepicker('setDate', new Date());

			
		}
	);
}

$(document).ready(function() {
	//fbIframe = $('#fbiframe iframe').detach();
	//fbIframe.attr('frameborder','0');
	//$('#fbiframe').append(fbIframe);
	//benötigt das shuffle plugin von zeile 1
	$('#col3').shuffle();
	toolTip();
	addPickers();
	$('#smalllogin.login h2').click(function() {
		if($(this).hasClass('active')) {
			$('#smalllogin h2').removeClass('active');
			$('#smalllogin #smalllogindiv').hide();
		}
		else {
			$(this).addClass('active');
			$('#smalllogindiv').show();
		}
	
	});
	
	if($('form[name=transportrouten] #mf_country_origin').val() == '') {
		$('form[name=transportrouten] #mf_country_destination').prop('disabled', 'true');
	}
	
	//$(".layout1 #col1 span.label").hide();
/*
	noneSelectedText = {
		'de' : '--- Bitte wählen Sie ---',
		'en' : '--- Please select ---'
	}
	

	$('select[multiple]').multiselect({
		selectedList: 10,
		noneSelectedText: noneSelectedText[$('html').attr('lang')]
	});
	
	$('.layout0 select:not(select[multiple])').multiselect({
		multiple: false,
		selectedList: 1,
		minWidth: 'auto'
	});
	
	$("#mf_country, #mf_country_origin, #mf_country_destination, #mf_transportationtype").multiselect({
		classes : "ui-dropdown"
	});
*/
	// wrap span-Element into a.button
	$('a.button:not(:has(input))').wrapInner('<span />');
	// menu
	$('#menu>ul>li:has(ul)').hover(
		function() {
			$(this).addClass('hover');
		},
		function() {
			$(this).removeClass('hover');
		}
	); 

	// Language selection
	$('#lang .cur a').live(
		'click',
		function(e) {
			e.preventDefault();
			//wenn nur eine sprache eingestellt, soll nichts ausklappen
			if($('#lang ul li').length > 1) {
				if ($('#lang').hasClass('on')) {
					$('#lang').removeClass('on');
				} else {
					$('#lang').addClass('on');
				}
			}
		}
	);
	$('html').live(
		'click',
		function(e) {
			if ($(e.target).closest('#lang.on')[0] == null ) {
				$('#lang').removeClass('on');
			} 
			if ($(e.target).closest('#smalllogin h2, #smalllogindiv')[0] == null ) {
				$('#smalllogin h2').removeClass('active');
				$('#smalllogin #smalllogindiv').hide();
			}
			
		}
	);

	$('#lang li:not(.cur)').live(
		'click',
		function(e) {
			$('#lang li').removeClass('cur');
			$(this).addClass('cur');
			$('#lang').removeClass('on');
		}
	);
	
	// lib.MEDIA
	$('#media').ready(function() {
		$.ajax({
			type: 'GET',
			url: window.location.href,
			data: 'type=71629',
			dataType: 'xml',
			success: function(xml) {
				$(xml).find('media>img').each(
					function() {
						$('<img />')
							.attr('src',    $(this).attr('src'   ))
							.attr('width',  $(this).attr('width' ))
							.attr('height', $(this).attr('height'))
							.load(function(){
								// static: new images will be appended to the bottom of the list
								$('#media').append($(this));
								// random: new images will be added randomly to the list 
								// $('#media>img:nth-child(' + Math.ceil(Math.random() * $('#media>img').length) + ')').after($(this));	
								$('#media').cycle(
									{
										fx:     'fade',
										timeout: 10000,
										speed:   2000,
										random:  0      // does not work with with $.cycle.lite.min.js
										                // but we don't care, because the preloading would mix up and brake the slideshow anyways
									}
								);
							});
					}
				);
				
			}
		});
	});
	
	// Random Bildwechsler Startseite
	$('.layout1 #media img').addClass('hide');
	
	var paras = $('.layout1 #media img');
	var rand = Math.floor(Math.random() * paras.length);
	paras.eq(rand).removeClass().addClass('show');
	
	
	// Sky Verlinkung
	//$('a[href^="tel"]').attr('href', $(this).attr('href').replace(/tel/, 'callto'));
	$('a[href^="tel"]').each(function() {
		$(this).attr('href', $(this).attr('href').replace(/tel/, 'callto'));
	});
	
	// Verlinkung der Hauptmenues
	$('#menu ul li ul li').css('cursor', 'pointer');
	$('#menu ul li ul li').bind(
		'click',
		function() {
			window.location.href = $('a', this).attr('href');
		}
	);
	
	
	
	var input = $('#search #q, #col1 form input[type=text], #col1 form input[type=password], #smallloginform .input input, #col1 form select');
	input.bind(   
		'click focus change',
		function() {
			$(this).parent().find('label').css('visibility', 'hidden');
		}
	);
	input.bind(
		'blur',
		function() {
			if ($(this).val() == '') {
				$(this).parent().find('label').css('visibility', 'visible');
			}
		}
	);
	input.each(
		function(){
			if($(this).val() != '') {
				$(this).parent().find('label').css('visibility', 'hidden');
			}
		}
	);
	
	// Google Site Search fix
	$('#search form, [name=tx_indexedsearch]').bind(
		'submit', 
		function (e){
			var form   = $(this);
			var action = form.attr('action');
			$(this).attr(
				'action',
				action + ((action.indexOf('?') == '-1') ? '?' : '&') + 'q=' + encodeURIComponent($('[name="tx_indexedsearch[sword]"]', form).val())
			);
		}
	);
	
	$('form').submit(function() {
		$(this).attr('action', $(this).attr('action')+'#path');
	});
	
	$('#menu li.menu63 a, #menu2 li.menu63 a').each(function() {
		$(this).attr('href', $(this).attr('href') + '#path');
	})
	
	
	//fuer Rechnungsstatus und Offertanfrage
	
	$('input[value="rechnungsstatus"]').parent().find('tbody tr').bind(
		'click',
		function() {
			$(this).parents('table').find('tr').not('#formtr').removeClass('checked');
			$(this).addClass('checked');
			$('input[type=radio]', this).prop('checked', true);	
			if($(this).next().attr('id') != 'formtr') {
				$('#formtr').remove();
				if(typeof(label) == 'undefined') {
					label = $('.tx-thmailformplus-pi1 #notinlistform .textarea .label').text();
					submitButton = $('.tx-thmailformplus-pi1 #notinlistform .submit').html();
				}
				formTr = '<tr id="formtr" class="checked"><td colspan="'+(parseInt($(this).find('td').length))+'"><label for="mf_bemerkung">'+label+'</label><textarea id="mf_bemerkung" cols="15" rows="3" name="mf_bemerkung"></textarea></br>'+submitButton+'</td></tr>';				
				$(this).after(formTr);
				$('#formtr').slideDown('slow');
			}
		
	});
	
	oTextarea = $('fieldset.textarea');
	$('fieldset.textarea').remove();
	
	$('input[value="ladungssuche"],input[value="lkwsuche"],input[value="offertarchiv"]').parent().find('tbody tr').bind(
		'click',
		function() {
			$(this)
				.addClass('checked')
				.parents('table').find('tr').not('#formtr').removeClass('checked');
			$('input[type=radio]', this).prop('checked', true);
			if($(this).next().attr('id') != 'formtr') {
				$('#formtr').remove();
				if(typeof(label) == 'undefined') {
					label = $('.tx-thmailformplus-pi1 div.textarea span.label label').text();
					submitButton = $('.tx-thmailformplus-pi1 .submit').html();
				}				
				formTr = '<tr id="formtr" class="checked"><td colspan="'+(parseInt($(this).find('td').length))+'">'+oTextarea.html()+'</td></tr>';
				$(this).after(formTr);				
				if(buttontitle = $('#formtr input').parents('tr').prev().find('img').attr('title')) {
					$('#formtr input').val(buttontitle);
				}			
				if(formlabel = $('#formtr input').parents('tr').prev().find('img').attr('data-formlabel')) {
					$('#formtr label').text(formlabel);
				}				
				$('#submit2').click(function(){	
					$('#formular').submit();
				})
				$('#formtr').slideDown('slow');
			}		
	});
	
	$('#mf_country_origin.onchangesubmit').change(
		function() {
			$('input[name="submitted"]').val('0');
			$('#formular').submit();
		}
	);	
	
	$('#country_origin.onchangesubmit').change(
		function() {
			$('#quick_transportrouten').attr('action',window.location.href);
			$('#quick_transportrouten').submit();
		}
	);	
		
	
	$('div.submit .button input[type=submit]').click(function(){
		$('#suchergebnis input[type=radio]').prop('checked', true);
	})
	
	
	$('.tx-thmailformplus-pi1 table.hover').find('th:first-child, td:first-child').hide();
	
	$('#notinlist').bind(
		'click',
		function() {
			$('#notinlistform').slideDown();
		}
	)
	if(
		$('#notinlistform span.error').length > 0 ||
		$('#mf_reference_tirolia2').val() != '' ||
		$('#mf_reference_user2').val() != '' ||
		$('#mf_invoice_sum2').val() != '' ||
		$('#mf_bemerkung2').val() != ''
	) {
		$('#notinlistform').show();
		if($('#notinlist').position()!=null) {
			$(window).scrollTop($('#notinlist').position().top);
		}


	}	
	
	$('rating-cancel').hide();
	
	$('.praemie').bind(
		'click',
		function(){
			$('input[type=radio]', this).prop('checked', true);
		}
	)
	
	$('#mediaImgOverlay').bind(
		'click',
		function(){
			document.location.href = $(this).attr('data-href');
		}
	)
	
	// feedbackformular
	$('#auswahl input[type=radio]').rating({required: true});
});



function toolTip() {
	//title und alt text bei media entfernt, damit der standard browsertooltip nicht aufpoppt => kundenwunsch
	$('#media img')
		.attr('title','')
		.attr('alt','');
	
	var jqueryTooltip = $('<div id="jqueryTooltip" ></div>');
	$('body').append(jqueryTooltip);
	$('img[title]:not([title=""]), #mediaImgOverlay[title]:not([title=""])').hover(function(e) {
		var ae = $(this);
		var title = ae.attr('title');
		ae.attr('title', '');
		ae.data('titleText', title);
		jqueryTooltip.html(title);
		var _t = e.pageY + 20;
		var _l = e.pageX + 20;
		jqueryTooltip.css({ 'top':_t, 'left':_l });
		jqueryTooltip.show(0);
	}, function() {
		var ae = $(this); 
		jqueryTooltip.hide(0);
		var title = ae.data('titleText');
		ae.attr('title', title);
	}).mousemove(function(e) {
		var _t = e.pageY + 20;
		var _l = e.pageX + 20;
		jqueryTooltip.css({ 'top':_t, 'left':_l });
	});
}

$(document).ready(function() {
	if (
		$('form[name=transportrouten] select:first-child').val() != '' &&
		$('form[name=transportrouten] select:nth-child(2)').val() != '' &&
		$('table.tabtransportrouten').length > 0 
	){
		_gaq.push([
			'_trackEvent',
			'Transportrouten - ' + $('html').attr('lang'),
			'submit',
			'Transportrouten ' + $('form[name=transportrouten] #mf_country_origin option:selected').text() + '-' + $('form[name=transportrouten] #mf_country_destination option:selected').text()
		]);
	}
});








/*
$(document).ready(function() {
	$('body').toggle(
		function() { $(this).css('font-size', '14px'); },
		function() { $(this).css('font-size', '16px'); },
		function() { $(this).css('font-size', '12px'); }
	);
});
*/
