// default.js

function ajaxRequest(pageId,action,resultid,reload,param1,param2) {
	var inlineid='ajax';
	var url=MyUrl;
	
	$.ajax( {
		url: url,
		type:'post',
		data: {
			ajaxAction:action,
			pageId:pageId,
			param1:param1,
			param2:param2
		},
		success: function(data) {
			if(data) {
				if(resultid==undefined)
					$('.'+inlineid).html(data);
				else
					$('#'+resultid).html(data);
			}
		},
		complete:function() {
			if(reload)
				location.reload();
		}
	});
}

function clearInput(ele,val) {
	var currentVal = $(ele).attr('value');
	if(currentVal==val)
		$(ele).attr('value','');
}

function resetInput(ele,val) {
	var currentVal = $(ele).attr('value');
	if(currentVal == '')
		$(ele).attr('value',val);
		
}

function searchformsubmit(modellDefault,manuDefault,hintModellLength) {
	var manuVal = $("#searchManufactor").attr('value');
	var modellVal = $("#searchModellNr").attr('value');
	
	var send=true;
	if(modellVal.length<3)
		alert(hintModellLength);
	if(modellVal==modellDefault || modellVal.length<3)
		send=false;
	if(send && manuVal==manuDefault)
		$("#searchManufactor").attr('value','');
	if(send) {
		showWaitingDiv();
		document.searchbox.submit();
	}
}

function deviceArticleGroupSubmit($errortext) {
	//$("#device-article-group-select").attr('value')=='' && 
	if($("#articleGroupSearch").attr('value') != '' && $("#articleGroupSearch").attr('value').length<3) {
		alert($errortext)
	}
	else {
		if($("#articleGroupSearch").attr('value') != '') {
			$('#device-article-group-select-div li').removeClass('active');
		}
		submitFormAjax('device-article-group-form','device-article-group-result');
	}
}
function submitFormAjax(formid,resultid,addToBasket) {
	$.ajax({
		type: "POST",
		url: MyUrl,
		data: $("#"+formid).serialize(), // serializes the form's elements.
		beforeSend: function( xhr ) {
			showWaitingDiv();
		},
		success: function(data)
		{
			if(resultid!=undefined)
				$('#'+resultid).html(data);
			else {
				if(addToBasket) {
					addToBasketComplete(data);
				}
			}
			
		},
		complete: function() {
			hideWaitingDiv();
			$("a.fancy-inline-dyn").fancybox();	
		}
	});
	//return false; // avoid to execute the actual submit of the form.
}
function addToBasketComplete(data) {
	var x = eval('(' + data + ')');
	jQuery(document).ready(function() {
		$.fancybox(
			'<h2>'+x.headline+'</h2><p>'+x.text+'</p>',
			{
	        	'autoDimensions'	: false,
				'width'         		: 350,
				'height'        		: 'auto',
				'transitionIn'		: 'none',
				'transitionOut'		: 'none'
			}
		);
	});
	refreshBasketLabel();
}
function refreshBasketLabel() {
	ajaxRequest(0,'reloadbasket','basket-menu',undefined,undefined,undefined);
}
function addToBasket(artnr) {
	$('#add-to-basket-artnr').attr('value',artnr);
	submitFormAjax('add-to-basket-form',undefined,true);
}

function clearBasket() {
	ajaxRequest(pageId,'clearbasket');
}
function removeArticleBasket(artnr) {
	ajaxRequest(0,'removearticlebasket',undefined,true,artnr);
}
function reloadArticleBasket(artnr) {
	count = $('#basket-'+artnr).attr('value');
	ajaxRequest(0,'reloadarticlebasket',undefined,true,artnr,count);
}

$(document).ready(function() {
	$('#device-article-group-select-div a').bind('click',function() {
		if($(this).attr('rel')) {
			$('#device-article-group-select-div li').removeClass('active');
			$(this).parent().addClass('active');
			$('#articleGroupSearch').attr('value','');
			$('#articleGroup').attr('value',$(this).attr('rel'));
			deviceArticleGroupSubmit();
		}
	});
	
	$('input.basket-count').bind('blur',function() {
		reloadArticleBasket($(this).attr('article'));
	});
	$("a.fancy-inline-dyn").fancybox();
	
	$("a.fancy-inline").fancybox({
    	'width'        		: 800,
		'height'       		: 400,
		'autoDimensions'	: false
	});
	
	$("a.fancy-searchbox-hint").fancybox({
		'width'        		: 400,
		'height'        	: 'auto',
		'autoDimensions'	: false
    });
	
	//home slideshow
	$('#content-home-slideshow').cycle({
		fx: 'fade',
		timeout: 5000,
		delay:-2000,
		speed:2000
	});
	
	// autocomplete suche
	var searchModell = $('#searchModellNr').attr('value');
	var searchManufactor = $('#searchManufactor').attr('value');
	$('#searchModellNr').bind('keyup',function() {
		searchModell = $(this).attr('value');
	});
	$('#searchManufactor').bind('keyup',function() {
		searchManufactor = $(this).attr('value');
	});
	$('#searchModellNr').bind('focus',function() {
		$(this).autocomplete({
			source: encodeURI(MyUrl+"?ajaxAction=shop_suchanfrage_autocomplete&type=modell&manufactor="+searchManufactor),
			minLength: 2,
			delay:100,
			search: function() {
			},
			select: function(event,ui) {
				searchModell = ui.item.value;
			}
		});
	});
	$('#searchManufactor').bind('focus',function() {
		$(this).autocomplete({
			source: encodeURI(MyUrl+"?ajaxAction=shop_suchanfrage_autocomplete&type=manufactor&modell="+searchModell),
			minLength: 2,
			delay:100,
			search: function() {
			},
			select: function(event,ui) {
				searchManufactor = ui.item.value;
			}
		});
	});
	
	$(".checkout-shipping-radio").bind("click",function() {
		$('#basket-shipping-choose').hide();
		$('.basket-shipping').hide();
		$('#basket-shipping-'+$(this).attr("rel")).show();
	});
});

var checkoutFinalNoError = true;
// order formular
$(document).ready(function(){
	$("#checkoutForm #name").bind("blur",function () {
		validName = validateText($(this),$('#checkoutForm #nameInfo'),1,'Name muss angegeben werden');
	});
	$("#checkoutForm #street").bind("blur",function () {
		validStreet = validateText($(this),$('#checkoutForm #streetInfo'),1,'Strasse muss angegeben werden');
	});
	$("#checkoutForm #streetNumber").bind("blur",function () {
		validStreet = validateText($(this),$('#checkoutForm #streetNumberInfo'),1,'Hausnummer muss angegeben werden');
	});
	$("#checkoutForm #zipcode").bind("blur",function () {
		validZip = validateRegex($(this),$('#checkoutForm #zipcodeInfo'),'PLZ muss aus 5 Ziffern bestehen',/^([0-9]){5}$/);
	});
	$("#checkoutForm #city").bind("blur",function () {
		validCity = validateText($(this),$('#checkoutForm #cityInfo'),1,'Ort muss angegeben werden');
	});
	$("#checkoutForm #email").bind("blur",function () {
		validEmail = validateRegex($(this),$('#checkoutForm #emailInfo'),'Email-Adresse ist nicht g'+unescape("%FC")+'tig',/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
	});
	$('#checkoutForm #terms').bind("click",function() {
		validateTerms($(this),$('#checkoutForm #termsInfo'), 'Sie m'+unescape("%FC")+'ssen die Allgemeinen Gesch'+unescape("%E4")+'ftsbedingungen akzeptieren, sowie die Informationen zum Widerrufsrecht in Kenntnis genommen haben');
	});
	$('#checkoutForm .checkout-shipping input').bind("click",function() {
		validateShipping($(this),$('#checkoutForm #shippingInfo'),'Sie m'+unescape("%FC")+'ssen eine Versandart / Zahlungsweise ausw'+unescape("%E4")+'hlen');
	});
	
	// On Submitting
	$('#checkoutForm').submit(function(){
		checkoutFinalNoError = true;
		checkoutFinalNoError = validateCheckoutForm();
		if(!checkoutFinalNoError)
			alert('Bitte erg'+unescape("%E4")+'nzen Sie bitte die fehlenden Angaben (rot markiert)');
		return checkoutFinalNoError;
		//submitCheckoutForm();
	});
	
	
});

$(document).ready(function() {
	$('#checkout-final-button').live("click",function() {
		$('#checkoutForm').trigger('submit');
	});
});

function testtest() {
	return false;
}

function submitCheckoutForm() {
	checkoutFinalNoError = true;
	checkoutFinalNoError = validateCheckoutForm();
	if(!checkoutFinalNoError)
		alert('Bitte erg'+unescape("%E4")+'nzen Sie bitte die fehlenden Angaben (rot markiert)');
	return checkoutFinalNoError;
}

function validateCheckoutForm() {
	validateText($("#checkoutForm #name"),$('#checkoutForm #nameInfo'),1,'Name muss angegeben werden');
	validateText($("#checkoutForm #street"),$('#checkoutForm #streetInfo'),1,'Strasse muss angegeben werden');
	validateText($("#checkoutForm #streetNumber"),$('#checkoutForm #streetNumberInfo'),1,'Hausnummer muss angegeben werden');
	validateRegex($("#checkoutForm #zipcode"),$('#checkoutForm #zipcodeInfo'),'PLZ muss aus 5 Ziffern bestehen',/^([0-9]){5}$/);
	validateText($("#checkoutForm #city"),$('#checkoutForm #cityInfo'),1,'Ort muss angegeben werden');
	validateRegex($("#checkoutForm #email"),$('#checkoutForm #emailInfo'),'Email-Adresse ist nicht g'+unescape("%FC")+'tig',/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/);
	validateTerms($('#checkoutForm #terms'),$('#checkoutForm #termsInfo'), 'Sie m'+unescape("%FC")+'ssen die Allgemeinen Gesch'+unescape("%E4")+'ftsbedingungen akzeptieren, sowie die Informationen zum Widerrufsrecht in Kenntnis genommen haben');
	validateShipping($('#checkoutForm .checkout-shipping input'),$('#checkoutForm #shippingInfo'),'Sie m'+unescape("%FC")+'ssen eine Versandart / Zahlungsweise ausw'+unescape("%E4")+'hlen');
	if(checkoutFinalNoError) {
		$('#checkout-final-button').hide();
		return true;
	}
	else
		return false;
}

//validation functions
function validateRegex(field,info,errorTxt,regex){
	//testing regular expression
	a = field.val();
	//var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	filter = regex;
	//if it's valid email
	if(!filter.test(a)){
		field.addClass("error");
		info.text(errorTxt);
		info.addClass("error");
		info.show();
		checkoutFinalNoError = false;
	}
	else {
		field.removeClass("error");
		info.removeClass("error");
		info.hide();
	}
	
}
function validateText(field,info,minlength,errorTxt){
	//if it's NOT valid
	if(field.val().length < minlength){
		field.addClass("error");
		info.text(errorTxt);
		info.addClass("error");
		info.show();
		checkoutFinalNoError = false;
	}
	//if it's valid
	else{
		field.removeClass("error");
		info.removeClass("error");
		info.hide();
	}
}
function validateTerms(field,info,errorTxt) {
	if(field.attr('checked') == 'checked') {
		field.removeClass("error");
		info.removeClass("error");
		info.hide();
	}
	else {
		field.addClass("error");
		info.text(errorTxt);
		info.addClass("error");
		info.show();
		checkoutFinalNoError = false;
	}
}
function validateShipping(fields,info,errorTxt) {
	if($('#checkoutForm .checkout-shipping input:checked').length>0) {
		info.removeClass("error");
		info.hide();
	}
	else {
		info.text(errorTxt);
		info.addClass("error");
		info.show();
		checkoutFinalNoError = false;
	}
}

//shop assistent
$(document).ready(function() {
	$("#shop-assisent-form select.shop-assisent-select").bind('change',function() {
		$("#shop-assisent-form").submit();
	});
});

//pagination fuer result tabelle
$(document).ready(function() {
	if($("#searchresult-device").length>0) {
		$("#searchresult-device").tablesorter({
			headers: { 
				0: { sorter: false},
				1: { sorter: false},
				2: { sorter: false},
				3: { sorter: false},
				4: { sorter: false}
			}
		}).tablesorterPager({
			container: $(".searchresult-pager"),size:20
		});
	}
	if($("#searchresult-article").length>0) {
		$("#searchresult-article").tablesorter({
			headers: { 
				0: { sorter: false},
				1: { sorter: false},
				2: { sorter: false},
				3: { sorter: false},
				4: { sorter: false}
			}
		}).tablesorterPager({
			container: $("#searchresult-pager-article"),size:20
		}); 
	}
});

// mouseover + link + onclick bei result tabelle
$(document).ready(function() {
	$("#searchresult-device tr").live("mouseenter",function() {
		$(this).addClass("result-tr-hover");
	});
	$("#searchresult-device tr").live("mouseleave",function() {
		$(this).removeClass("result-tr-hover");
	});
	$("#searchresult-device tr").live("click",function() {
		document.location.href=$(this).find("a:first").attr("href");
	});
	
});

// spinner - loading
$.fn.spin = function(opts) {
  this.each(function() {
    var $this = $(this),
        data = $this.data();

    if (data.spinner) {
      data.spinner.stop();
      delete data.spinner;
    }
    if (opts !== false) {
      data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
    }
  });
  return this;
};

var opts = {
  lines: 12, // The number of lines to draw
  length: 7, // The length of each line
  width: 4, // The line thickness
  radius: 10, // The radius of the inner circle
  color: '#000', // #rgb or #rrggbb
  speed: 1, // Rounds per second
  trail: 60, // Afterglow percentage
  shadow: false // Whether to render a shadow
};

function showWaitingDiv() {
	$("body").append('<div id="waiting-div"><div id="spinner"></div>');
	$("#waiting-div").bind("click",function() {
		$(this).remove();
	});
	$("#waiting-div").spin();
}
function hideWaitingDiv() {
	$("#waiting-div").remove();
}

$(document).ready(function() {
	$('#trusted-shop').html('<a target="_blank" href="https://www.trustedshops.de/bewertung/info_X0FD7F8281DA17588FBC1A623F8CA0415.html" title="Kundenbewertungen von ersatzteile-24.com einsehen"><img class="bewertung" alt="Kundenbewertungen von ersatzteile-24.com" border="0" src="https://www.trustedshops.com/bewertung/widget/widgets/X0FD7F8281DA17588FBC1A623F8CA0415.gif"/></a>');
	$('#paypal-logo').html('<!-- PayPal Logo --><a href="https://www.paypal-deutschland.de/privatkunden/los-geht-es-mit-paypal.html" target="_blank"><img src="https://www.paypal-deutschland.de/external/logocenter-update/logo-paypal-200x55.gif" border="0" alt="Logo PayPal empfohlen"></a><!-- PayPal Logo -->');
});


