/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * product mengen korregieren, falls produkte im cart liegen.
 * die infos werden aus dem cookie geholt
 */
function init_ProductStockInfos(){
	$('.stockinfos .stock').each(function(){
		var theid = $(this).attr('id');
		var c = parseInt($.cookie(theid));
		//console.log(theid, c);
		if(c>=0){
			$('#'+theid+' span').html(c);
		}
	});
}

/**
 *	 Attribut Auswahl bei einem Produkt mit zwei Select Listen
 */
function init_ListAttributSelectors(){
	$('select.product_attribut_0').change(function(){
		var $this = $(this);
		var id = $this.attr('product_id') ;
		var otherclass = $this.attr('otherclass');
		var value = $this.val() ;
		var othervalue  = $this.next('select.'+otherclass).find('option:selected').val() ;
		if(typeof othervalue =="undefined") othervalue = 'ungenutzt';

		//console.log('Produkt ID = '+id+' | attribut 1 = '+value+' | attribut 2 = '+othervalue);

		// Wert als Attribut bei allen Cart Buttons der Produkte setzen
		$('.addtocart_'+id).attr('attribut_0', value) ;

		// stockinfos
		if(othervalue!="notselect"){
			$('.stockinfos_'+id+' .stock').hide();	// Alle Stock infos ausblenden
			//console.log('.product_stock_'+id+'_'+othervalue+'_'+value)
			var ele = $('.product_stock_'+id+'_'+value+'_'+othervalue) ;
			if(ele!== ''){
				ele.show();
			} else {
				$('.product_stock_'+id+'_notexist').show();
			}
		}
	});

	$('select.product_attribut_1').change(function(){
		var $this = $(this);
		var id = $this.attr('product_id') ;
		var otherclass = $this.attr('otherclass');
		var value = $this.val() ;
		var othervalue  = $this.prev('select.'+otherclass).find('option:selected').val() ;
		if(typeof othervalue =="undefined") othervalue = 'ungenutzt';

		//console.log('Produkt ID = '+id+' | attribut 1 = '+othervalue+' | attribut 2 = '+value);

		// Wert als Attribut bei allen Cart Buttons der Produkte setzen
		$('.addtocart_'+id).attr('attribut_1', value) ;

		// stockinfos
		if(othervalue!="notselect"){
			$('.stockinfos_'+id+' .stock').hide(); 	// Alle Stock infos ausblenden
			//console.log('.product_stock_'+id+'_'+othervalue+'_'+value)
			var ele = $('.product_stock_'+id+'_'+othervalue+'_'+value) ;
			if(ele.length > 0){
				ele.show();
			} else {
				$('.product_stock_'+id+'_notexist').show();
			}
		}
	});
	 
}

/**
 * click handler für alle addtocart buttons
 */
function init_AddtocartButton(btn_class, callback_success){
	$('.'+btn_class).click(function(){

		var attribut_0_title = $('#product_attribut_0_title').val();
		var attribut_1_title = $('#product_attribut_1_title').val();

		var params = {
			product_id:	$(this).attr('product_id'),
			attribut_0: $(this).attr('attribut_0'),
			attribut_1: $(this).attr('attribut_1'),
			cart_group: $(this).attr('cart_group'),
			stock_switch: $(this).attr('stock_switch'),
			quantity: $(this).attr('quantity')
		}

		if(params.attribut_0==""){
			alert('Bitte '+attribut_0_title+' wählen.');
			return false;
		}
		if(params.attribut_1==""){
			alert('Bitte '+attribut_1_title+' wählen.');
			return false;
		}
		if(params.product_id ==""){
			alert('product_id nicht angegeben');
			return false;
		}
		//console.log('params = ', params) ;


		var stockvalue_id = '#product_stock_'+params.product_id+'_'+params.attribut_0+'_'+params.attribut_1+' span' ;
		var stockvalue_id_all = '#product_stock_'+params.product_id+'_all span' ;
		var stock = parseInt($(stockvalue_id).html())  ;
		var stock_all = parseInt($(stockvalue_id_all).html())  ;
		var nstock = stock - 1;
		var nstock_all = stock_all - 1;
//
//		console.log('params.stock_switch = ', params.stock_switch) ;
//		console.log('stockvalue_id = ', stockvalue_id) ;
//		console.log('stock = ', stock) ;
//		console.log('stock_all = ', stock_all) ;
//		console.log('nstock = ', nstock) ;
//		console.log('nstock_all = ', nstock_all) ;

		if(isNaN(stock)){
			alert('Ausgewählter Artikel existiert nicht.');
			return false;
		}
		if(nstock>=0 || params.stock_switch=="always"){

			add_product_to_cart(params, callback_success );
			
			// Lagerbestand runterzählen, wenn eingestellt ist, das der produkt verkauf bei Lagerbestand = 0 gestoppt wird.
			if(params.stock_switch=="stopnull"){
				$(stockvalue_id).html(nstock);
				$(stockvalue_id_all).html(nstock_all);
				var cn = 'product_stock_'+params.product_id+'_'+params.attribut_0+'_'+params.attribut_1;
				//console.log(cn);
				$.cookie(cn, nstock, {path: '/'})
			}
		} else {
			alert('Ausgewählter Artikel nicht verfügbar.');
			//alert('Es sind nur max. '+stock+' verfügbar.');
		}
		return false;
	});

}


/**
 * Handler zum ändern der menge und zum löschen eines carteintrages
 */
function init_CartItemActions(){
	$('.cart_accept_item').live('click', function(){
		var cart_id = $(this).attr('rel');
		var quantity = $('#cart_item_'+cart_id).find('.cart_input').val();
		var bg = $('#cart_item_'+cart_id).css("background-color");
		change_cart_quantity(cart_id, quantity, bg);
		return false;
	});
	$('.cart_delete_item').live('click', function(){
		var cart_id = $(this).attr('rel');
		delete_cart_item(cart_id);
		return false;
	});
}

/**
 * Login, Bezahlen, Angebot erstellen buttons im step 1 des carts
 */
function init_CartButtons(){
		$('#AngebotBtn').click(function(){
			$('input[name=action]').val('angebot');
		});
		$('#loginbutton').click(function(){
			$('input[name=action]').val('login');
			//alert('f');
		});
//		$('#CheckoutBtn2').click(function(){
//			$('input[name=action]').val('step2');
//		});

	}

/**
 *	bei auswahl einer payment methode wird die cartsumme neu geladen
 */
function init_PaymentSelection(){
	$('input:radio[name=payment_method]').click(function(){
		load_cart_summe();
	});
}

/**
 * Bei Lieferung, die Lieferinformationen ein/ausblenden. Kundendaten als Lieferadresse übernehmen
 */
function init_ShippingSite(){
	$('.lieferunginfos .button').click(function(){
		$('.lieferunginfos .infos-toggle').toggle();
	});

	$('#customer_as_shipping').click(function(){

		$('#shippinginfos_firstname').val($('#customer_firstname').val());
		$('#shippinginfos_lastname').val($('#customer_lastname').val());
		$('#shippinginfos_email').val($('#customer_email').val());
		$('#shippinginfos_tel').val($('#customer_tel').val());
		$('#shippinginfos_street').val($('#customer_street').val());
		$('#shippinginfos_plz').val($('#customer_plz').val());
		$('#shippinginfos_city').val($('#customer_city').val());
		if( $('#customer_street').val() !="" && $('#customer_plz').val() !="" && $('#customer_city').val() !="" ){
			$('#map_canvas').show();
			initialize_map();
			calcRoute() ;
			
		}
	});

}

var datetimepicker_options = {
	closeText: 'schließen',
	prevText: '&#x3c;zurück',
	nextText: 'Vor&#x3e;',
	currentText: 'heute',
	monthNames: ['Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
	monthNamesShort: ['Jan','Feb','Mär','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
	dayNames: ['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag'],
	dayNamesShort: ['So','Mo','Di','Mi','Do','Fr','Sa'],
	dayNamesMin: ['So','Mo','Di','Mi','Do','Fr','Sa'],
	weekHeader: 'Wo',
	dateFormat: 'dd.mm.yy',
	firstDay: 1,
	isRTL: false,
	showMonthAfterYear: false,
	yearSuffix: '',
	minDate: +3
//	,
//	beforeShowDay: function(date) {
//			var day = date.getDay();
//			return [(day != 1 && day != 2)];
//		}
};

function init_DatetimePicker(){
	
	$.datepicker.setDefaults(datetimepicker_options);
 
	$('.datetimepicker').datetimepicker(datetimepicker_options);
}

function delete_cart_item(cart_id){

	var params = {
		'ajax':'1',
		'controller':'ajax',
		'modul':'shop2',
		'action':'delete_cart_item',
		'id':XDCMS.project_id,
		'cart_id':cart_id
	}
	$.ajax({
		url: '/projects/index.php',
		dataType: 'json',
		data : params,
		success: function(ret){
			if(ret.status=="success"){
				load_cart_summe();
				$('#cart_item_'+cart_id).stop().animate({backgroundColor: '#ffDDDD'}, 300, function(){
					$(this).slideUp();
				}) ;
			}
		}
	});

}

function change_cart_quantity(cart_id, quantity, bg){

	var params = {
		'ajax':'1',
		'controller':'ajax',
		'modul':'shop2',
		'action':'change_quantity',
		'id':XDCMS.project_id,
		'cart_id':cart_id,
		'quantity':quantity,
		'canchange_quantity':1
	}
	if(quantity =="" || quantity == 0){
		alert('Bitte geben Sie die gewünschte Menge an.');
		return false;
	}

	$.ajax({
		url: '/projects/index.php',
		dataType: 'html',
		data : params,
		success: function(ret){
			$('#cart_item_'+cart_id).html(ret);
			load_cart_summe();
			$('#cart_item_'+cart_id).stop().animate({backgroundColor: '#90EE90'}, 300).animate({backgroundColor: bg}, 300);
		}
	});
	return false;
}

function load_cart_summe(entfernung){
	var url = '/projects/index.php';
	var params='ajax=1&controller=ajax&modul=shop2&id='+XDCMS.project_id+'&action=get_cart_summe&entfernung_meter='+entfernung ;
	params += '&shipping_method='+$('input:radio[name=shipping_method]:checked').val();
	params += '&payment_method='+$('input:radio[name=payment_method]:checked').val();

	$.ajax({
		url: url,
		data : params,
		success: function(ret){
			$('#amountinfos').html(ret);
		}
	});

}

function load_cart_block(withslide, cart_id){
	var url = '/projects/index.php';
	var params='ajax=1&template=cart_block.html&controller=cart&modul=shop2&id='+XDCMS.project_id ;
	$.ajax({
		url: url,
		data : params,
		success: function(ret){
			if(withslide){
				//$(cart_id).hide().html(ret).slideDown();
				$(cart_id).hide().html(ret).show();
			} else {
				$(cart_id).html(ret);
			}
		}
	});
}

function add_product_to_cart(params, success_callback ){

	var defaults={
		ajax:				'1',
		controller:			'ajax',
		modul:				'shop2',
		action:				'add_product_to_cart',
		id:					XDCMS.project_id,
		quantity:			1,
		accumulate:			1,
		attribut_0:			'ungenutzt',
		attribut_1:			'ungenutzt',
		cart_group:			'',
		product_id:			''
	};

	var params=$.extend(defaults, params);
	
	var url = '/projects/index.php';

	$.ajax({
		url: url,
		dataType: 'json',
		data : params,
		success: success_callback
	});

	return false;
}



var directionDisplay;
var directionsService ;
var map;


function initialize_map() {
		geocoder = new google.maps.Geocoder();
		directionsDisplay = new google.maps.DirectionsRenderer();
		var thecenter = new google.maps.LatLng('51.45336','6.72996');
		var myOptions = {
		  zoom:14,
		  mapTypeId: google.maps.MapTypeId.ROADMAP,
		  center: thecenter
		}
		map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		directionsDisplay.setMap(map);

		setCenter();
	}

function calcRoute() {
	var shippinginfos_street = $('#shippinginfos_street').val();
	var shippinginfos_plz = $('#shippinginfos_plz').val();
	var shippinginfos_city = $('#shippinginfos_city').val();

	var destination = shippinginfos_street+', '+shippinginfos_plz+' '+shippinginfos_city ;
	//console.log(destination);

	var start = startadresse;
	var request = {
		origin:start,
		destination: destination,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
			// den wert in meter, ins Formularfeld schreiben
			$('#entfernung_meter').val(response.routes[0].legs[0].distance.value);
			$('#entfernung_text').val(response.routes[0].legs[0].distance.text);
			$('#entfernung_text').html(response.routes[0].legs[0].distance.text);

			load_cart_summe(response.routes[0].legs[0].distance.value);

			if( response.routes[0].legs[0].distance.value > max_liefer_radius){
				var msg = '<div class="MsgBoxWarn"><strong>Achtung!</strong><br /> Wir liefern höchsten bis zu einer Entfernung von <strong>'+(max_liefer_radius/1000)+' km</strong><br />Der von Ihnen angegebene Lieferort hat einen Lieferweg von <strong>'+response.routes[0].legs[0].distance.text+'</strong>.<br>Bitte sprechen Sie uns hinsichtlich Ihrer Lieferung an.</div>';
				openLightbox(msg);
			} else {
				var cost_netto = calcRadiusAmount(response.routes[0].legs[0].distance.value);
				var cost_brutto = cost_netto * (1 + radius_vat/100) *100
				var cost_vat = cost_netto * (radius_vat/100)
				cost_brutto = Math.round(cost_brutto) / 100 ;
				var cost_str =  cost_brutto.toFixed(2)+''  ;
				cost_str  = cost_str.replace('.', ',');
				var sum = 0;
				var sum_str = '';
				var abholen = $('#abholprodukt').val();
				$('.shippinginfos').show();
				$('.lieferkosten').show();
				if(abholen == 1){
					sum = cost_brutto*2;
					//sum_str = sum+'';
					sum_str = sum.toFixed(2).replace('.', ',') ;
					$('.shippinginfos .lieferung span').html(cost_str);
					$('.shippinginfos .abholung span').html(cost_str);
					$('.shippinginfos .totalshipping span').html(sum_str);
					cost_vat = cost_vat*2;

					// in der Produktdetailansicht
					$('#lieferung_value').html('&euro; '+cost_str);
					$('#abholen_value').html('&euro; '+cost_str);
					$('#shippingcosts_sum').html('&euro; '+sum_str);
					
				} else {
					$('.shippinginfos .lieferung span').html(cost_str);
					sum = cost_brutto ;
					$('.shippinginfos .totalshipping span').html(cost_str);

					// in der Produktdetailansicht
					$('#shippingcosts_sum').html('&euro; '+cost_str);

				}
			}

			// werte im dom anzeigen
			// #lieferung_value
			// #abholen_value
			// #shippingcosts_sum

		}
	});
}

function setCenter() {
	var address = startadresse;
	geocoder.geocode( {'address': address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
		} else {
			alert("Geocode was not successful for the following reason: " + status);
		}
	});
}

function calc_price(){
	var $ele = $('.price_calculator #product_quantity');
	var ergebnis = 0;
	var amount = parseFloat($ele.attr('amount')) * 100;
	var minorder = parseInt($ele.attr('minorder'));
	var quantity = $ele.val();
	if(quantity=='' || typeof quantity == undefined) return false;
	quantity = parseInt(quantity);
	if(quantity < minorder){
		alert('Die Mindestbestellmenge darf nicht unterschritten werden') ;
		$ele.val(minorder);
		return false;
	}

	ergebnis = (quantity * amount) / 100 ;
	ergebnis = ergebnis.toFixed(2).replace('.', ',');

	//console.log(value, amount, ergebnis);

	$('.price_calculator .amount_sum .value').html('&euro; '+ergebnis);
	$('.addtocart-handler').attr('quantity', quantity) ;
}


function calcRadiusAmount(r){
	var calc_amount;
	for(var i=radius_arr.length-1; i>=0; i--){
		var meter = radius_arr[i]*1000 ;
		//console.log(meter, r)
		if(r >= meter){
			calc_amount = radius_amounts[i];
			break;
		}
	}
	//console.log(calc_amount);
	return calc_amount ;
}

function initShippingCalculator(){
	directionsService = new google.maps.DirectionsService();
	var shippinginfos_street = $('#shippinginfos_street').val();
	var shippinginfos_plz = $('#shippinginfos_plz').val();
	var shippinginfos_city = $('#shippinginfos_city').val();
	//console.log(shippinginfos_street);
	//console.log(shippinginfos_plz);
	//console.log(shippinginfos_city);
	if( shippinginfos_street !="" || shippinginfos_plz !="" || shippinginfos_city !="" ){
		//$('#lieferadresse_result').html(shippinginfos_street+'<br>'+shippinginfos_zip+' '+shippinginfos_city)
		$('#map_canvas').show();
		initialize_map();
		calcRoute() ;
	}


	$('#shippinginfos_street, #shippinginfos_plz, #shippinginfos_city').blur(function(){
		var test = $(this).val();
		//console.log(test);
		if(test!=""){
			$('#map_canvas').show();
			initialize_map();
			calcRoute();
		}
	});
}
 
//function init_ShippingSelection(){
//	$('.back_to_selection').live('click', function(){
//
//		$('#shipping_select_box').show();
//		$('#lieferungform').hide();
//
//	});
//
//	$('#shipping_selection input:radio').click(function(){
//
//		$('.back_to_selection').show();
//		$('#lieferungform, #liefertermin, #lieferunginfos').hide();
//
//		// hide selectionlist
//		//$('#shipping_select_box').hide();
//
//		// hide  all forms
////		$('#shipping_selection input:radio').each(function(){
////			$('#'+$(this).val()+'form').hide();
////		});
////		// show
//		var shipping_method = $(this).val() ;
//		if( shipping_method=="lieferung" || shipping_method=="versand"){
//			$('#lieferungform').show();
//			setTimeout('initShippingCalculator()',1000);
//		}
//		if( shipping_method=="lieferung"){
//			$('#liefertermin').show();
//		}
//
////		console.log(shipping_method);
////		var ele = '#'+shipping_method+'form';
////		$(ele).show(0, function(){
////			if(shipping_method=="lieferung"){
////				initialize_map();
////				calcRoute() ;
////			}
////		});
//		//return false;
//	});
//}
