var e = ['header','footer','section','aside','nav','article','figure','figcaption','hgroup','menu','summary','command','datalist','source','audio','video'];
for(var i = 0; i < e.length; i++) document.createElement(e[i]);

$(document).ready(function(){
	
	var baseUrl = 'http://'+document.domain+'/';
	var lang = $("html").attr('lang');

	/*** Search ***/
	var ts = $('#topsearch .searchfield,#mainsearch');
	var tsv = ts.val();
	var ps = $('#produktsuche .searchfield');
	var psv = ps.val();
	ts.focus(function(){ ts.val() == tsv ? ts.val('').addClass('active') : false });
	ts.blur(function(){ ts.val() == '' ? ts.val(tsv).removeClass('active') : false });
	ps.focus(function(){ ps.val() == psv ? ps.val('').addClass('active') : false });
	ps.blur(function(){ ps.val() == '' ? ps.val(psv).removeClass('active') : false });
	
	//*** Block empty search request ***/
	$('#topsearch,#produktsuche').submit(function(){
		var value =  $(this).find("input:first-child").val();
		if(value == '' || value == tsv || value == psv)return false;
	});
	
	/*** AJAX Search ***/
	var g = $('#produktsuche .suggestions');
	$('#produktsuche .searchfield').keyup(function() {
		g.addClass('loading')
		var value = $(this).val();
		if(value==''){
			if (this.timer) {
				clearTimeout(this.timer);
			}
			g.removeClass('loading');
			g.fadeOut();
		}else{
			if (value != lastValue) { 
				g.fadeIn();
				if (this.timer) {
					clearTimeout(this.timer);
				}        
				this.timer = setTimeout(function () {
					g.addClass('loading');
					$.get(baseUrl+(lang == 'en' ? 'en/search/productsearch/' : 'de/suche/produktsuche/'), {
							search:""+value+""
						},function(data){
							g.removeClass('loading');
							g.html(data);
						}
					);
				},600);
				var lastValue = value;
			} 
		}
	});
	$(document.body).click(function(event) {
		var clicked = $(event.target);
		if (!(clicked.is('#suggestions') || clicked.parents('#suggestions').length || clicked.is('#searchbar'))) {
			g.fadeOut();
		};
	});
	
	/*** produktsuche kategorie switch ***/
	$("#produkt-kategorien").change(function(){
		if($("#produkt-kategorien").val().length){
			var loc = $("#produkt-kategorien").val();
			window.location.href = baseUrl+loc;
		}
	});
	
	/*** Slideshow ***/
	if($('#home').length){
		var i;
		for(i=2;i<7;i++){
			$('#visual').append('<img src="assets/images/visual/visual-'+i+'-'+lang+'.png" alt="Visual '+i+'"/>');
		}
		$('#visual img').css("opacity","0");
		$.fn.cycle.defaults = { 
			fx:'fade',
			timeout:8000,
			speed:1000,
			activePagerClass: 'activeCustomer',
			cssBefore:{"opacity":"1"},
			cssAfter:{"opacity":"0"}
		};
		$('#visual').cycle();
	};
	
	/*** Merkzettel ***/
	$("#merkzettel a").fancybox({
		'autoScale' 		: false,
		'transitionIn'		: 'fade',
		'transitionOut'		: 'fade',
		'type'				: 'iframe',
		'onStart'			: pauseCycle,
		'onClosed'			: resumeCycle
	});
	
	$('#merkzettel-content').bind('resize',function(){
		height = $('#merkzettel-content').height()+125;
		$('#fancybox-wrap').height(height);
	});
	
	function pauseCycle(){
		if($('#home').length)$('#visual').cycle('pause');
	};
	function resumeCycle(){
		initMerken();
		if($('#home').length)$('#visual').cycle('resume'); 
	};
	
	var mUrl = baseUrl+(lang == 'en' ? 'en/contact/inquiry-form/clipboard/' : 'de/kontakt/anfrageformular/merkzettel/');

	function initMerken(){
		$.getJSON(
			mUrl
			,{
				 action:'check'
				,produkt:$('#main h1').text()
				,nocache:Math.random()
			}
			,function(data){
				if(data.msg == 'found'){
					$('#produktbuttons .merken').addClass('remove');
				}else{
					$('#produktbuttons .merken').removeClass('remove');
				}
			}
		);
	};

	function remove(e){
		$.ajax({
			 url: mUrl
			,data:{
				 action:'remove'
				,produkt:$('#main h1').text()
				,nocache:Math.random()
			}
			,beforeSend: function(){
				$(e.target).append('<span class="loading"></span>');
			}
			,complete: function(){
				$('span').remove('.loading');
				$(e.target).toggleClass('remove');
			}
		});
	};

	function add(e){
		$.ajax({
			 url: mUrl
			,data:{
				 action:'add'
				,produkt:$('#main h1').text()
				,partner:$('#ansprechpartner h4').text()
				,nocache:Math.random()
			}
			,beforeSend: function(){
				$(e.target).append('<span class="loading"></span>');
			}
			,complete: function(){
				$('span').remove('.loading');
				$(e.target).toggleClass('remove');
			}
		});
	};

	if($('#produktbuttons .merken').length){
		initMerken();
		$('#produktbuttons .merken').click(function(e){
			e.preventDefault();
			if(!$(e.target).hasClass('remove')){
				add(e);
			}else{
				remove(e);
			}
		});
	};
	
	/*** Produkt Tooltip ***/
	if($('#tooltip').length){
		$('#produktbuttons span').hover(function(){
				$('#tooltip').fadeIn('fast');
			},function(){
				$('#tooltip').fadeOut('fast');
			}
		);
	};
	
	/*** Anfrageformular ***/
	function checkItems(){
		if($('#anfrageformular .produktangaben').length <=1){
			$('#anfrageformular .delete').hide();
			$("#akkordeon").accordion("activate",$('#anfrageformular h3:first'));
		}else{
			$('#anfrageformular .delete').show();
		}
		$('#anfrageformular h3').each(function(index) {
			$(this).find('.nr span').text(index+1);
			$(this).find('.nr').unbind();
			$(this).find('.delete').unbind();
			$(this).find('.nr').bind('click',function(e) {
				e.preventDefault();
			});
			$(this).find('.delete').bind('click',function(e) {
				removeItem(e)
			});
		});
		
		$("#akkordeon").accordion('destroy').accordion();
		$("#akkordeon").accordion();
		
	};
	function removeItem(e){
		e.preventDefault();
		produkt = $(e.target).parent().next().find('div:first input').val();
		$.ajax({url: mUrl,data:{
				 action:'remove'
				,produkt: produkt
				,nocache:Math.random()
				,complete: function(){
					$(e.target).parent().next().remove();
					$(e.target).parent().remove();
					checkItems();
				}
		}});
	}
	
	function additem(product){
		$('#akkordeon').append($('#examplefields h3').clone());
		$('#akkordeon').append($('#examplefields .produktangaben').clone());
			
		if(product!=''){
			$('#anfrageformular .produktangaben:last div:first select').remove();
			$('#anfrageformular .produktangaben:last div:first label').after('<input type="text" value="'+product+'" name="produkt[]" readonly/>');
		};
		checkItems();
		$("#akkordeon").accordion();

	};
	
	if($('#anfrageformular').length){
		$.getJSON(mUrl,{
				 action:'getlist'
				,nocache: Math.random()
			},function(produkt){
				if(produkt.msg == 'found'){
					$.each(produkt.data,function(index, val) {
						if(val.name.length){
							additem(val.name);
						}
					})
				}else{
					additem('');
				}
			}
		);
		$('#anfrageformular #add').bind('click',function(e) {
			e.preventDefault();
			additem('');
		});
		checkItems();
	};
	
	/*   table styling [start]  */
	$('table tr:first-child, table tr td:first-child').addClass('first');	
	$('table tr:odd').addClass('odd');
	$('table tr:even').addClass('even');
	$('table tr:last-child, table tr td:last-child').addClass('first');	
	/*   table styling [end]  */

	/*  aehnliche produkte  */
	if(!$('#aehnliche-produkte ul li').length){
		$('#aehnliche-produkte').css( 'display','none');
	}

    /*    FORM VALIDATION    */
	if($("#anfrageformular").length){
		$.validator.messages.required = "Bitte f&uuml;llen Sie dieses Feld korrekt aus!";
		$.validator.messages.email = "Bitte geben Sie eine g&uuml;ltige E-Mail Adresse ein!";
		$.validator.messages.option = "Bitte w&auml;hlen Sie min. eine Antwort aus!";
		$("#anfrageformular").validate();
	}
});
