var deletedItems = new Array();

jQuery(document).ready(function() {
	jQuery("#send_mlist").click(function() { fV.validate(); /*jQuery('#ml_merkliste_form').submit() */});
	recalculateTotal();
});

function myElementValidationHandler(passed,element) {
	if (jQuery('#tablebody').children().length < 1) {
		return false;
	}
	if ( ($(element).getProperty('id')=="fdata_plz")) {
		if (passed === true ) {

			var country = "Austria";
			var shortCountryCode =  "AT";
			if ($('fdata_country').getValue() == '276') { country = "Germany"; shortCountryCode = "DE";}
			var glocation = $(element).getValue()+", "+country;
			var geocoder = new GClientGeocoder();
			geocoder.setBaseCountryCode(shortCountryCode);
			geocoder.getLocations(
				glocation,

				/*callback function*/
				function(point) {
					if ($defined(point) && 
						(point.Status.code == G_GEO_SUCCESS) &&
						$defined(point.Placemark) && 
						(point.Placemark[0].AddressDetails.Country.CountryNameCode==shortCountryCode) && 
						(point.Placemark[0].AddressDetails.Accuracy >= 5)) {
						/*reset error messages and set city field*/
						$(element).addClass('validation-passed');
						if ($defined(point.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality)) {
							$('fdata_wohnort').setProperty('value',point.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);
						} else if ($defined(point.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea)) {
							$('fdata_wohnort').setProperty('value',point.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName);
						}
						fV.resetField($('fdata_wohnort'));
						fV.validateField($('fdata_wohnort'));
						var advice = fV.getAdvice('validatePlz',element);
						if (advice) {
							if (advice.smoothHide) {
							advice.smoothHide();
						} 
						advice.setStyle('display','none');
					}
					} else {
						if (point.Status.code != G_GEO_SERVER_ERROR) {
							
							var advice = fV.makeAdvice('validatePlz', element, "Diese Postleitzahl ist falsch!", false);
							$(element).addClass('validation-failed');
							$(element).removeClass('validation-passed');
							if (advice) {
								if (advice.smoothShow) {
									advice.setStyle('margin','');
									advice.setStyle('padding','2px');
									advice.setStyle('height','');
									advice.smoothShow();
								} else {
									advice.setStyle('display','block');
								}
							}
						}
					}
				}
			);
		} else { //passed === false
		}
	}
}

function myFormValidationHandler(passed,element) {
	if (passed) {
		jQuery("#ml_merkliste_form").submit();
	}
}

function updateAmount(which) {
	
	updatePrice(which);

	var name=$(which).getProperty('id');
	var index = name.substring( name.indexOf('_')+1, name.length );
	var item = index;
	var amount = $('amount_'+item).getValue();
	if (window.location.search == "") {
		postfixSearch="?eID=ml_merkliste_pi1";
	} else {
		postfixSearch="&eID=ml_merkliste_pi1";
	}
	var url = window.location.pathname + window.location.search + postfixSearch;
	var data = Object.toQueryString( { updateItem: item,
					   amount: amount } );
	
	var myAjax = new Ajax( url , {
		data: data,
		method: 'post',
		onSuccess: function() {
//			console.log(this.response.text);
		},
		onFailure: function() {
		}
	}).request();

}

function recalculateTotal(){
	var itemPrice;
	var totalPrice=0;

	jQuery('tr.listItem').each( function(index,el) {
			//rowText = jQuery(el).text();
			//itemPrice = rowText.substring(rowText.lastIndexOf(' ')+1,rowText.length);
			
			itemPrice = (jQuery(el).children().last().text()).substring(1,100);
			if (!(isNaN(parseFloat(itemPrice.replace(',','.'))))) {
				console.log(parseFloat(itemPrice.replace(',','.')) );
				totalPrice = totalPrice + parseFloat(itemPrice.replace(',','.'));	
			}
		}
	);
	$('total').innerHTML = '&euro; ' + totalPrice.toFixed(2).toString().replace('.',',');
//console.log(totalPrice);
	if (!(totalPrice.toFixed(2) > 0)) {
		jQuery('#merklisten_table > tfoot').addClass('invisible');
		jQuery('#elements_parent').css('border-top-width','0px');
//console.log("A");
	} else {
		jQuery('#merklisten_table > tfoot').removeClass('invisible');
		jQuery('#elements_parent').css('border-top-width','1px');
//console.log("B");
	}
}

function getNumber(inString) {
	while (isNaN(parseFloat(inString) && inString.length > 0)) {
		inString = inString.substring(1,100);
	}
	return inString;
}

function updatePrice(which) {
	var name=$(which).getProperty('id');
	var index = name.substring(name.indexOf('_')+1, name.length );
	var price = $('price_'+index).getText().substring($('price_'+index).getText().lastIndexOf(' ')+1,$('price_'+index).getText().length);
	var total = $(which).getValue() * parseFloat(price.replace(',','.'));

	if (isNaN(total) != true) {
		$('total_'+index).innerHTML = '&euro; ' + total.toFixed(2).toString().replace('.',',');
		recalculateTotal();
	}
}

function deleteItem(which) {
	var name=$(which).getProperty('id');
	var index = name.substring( name.indexOf('_')+1, name.length );
	var item = index;
	if (window.location.search == "") {
		postfixSearch="?eID=ml_merkliste_pi1";
	} else {
		postfixSearch="&eID=ml_merkliste_pi1";
	}
	var url = window.location.pathname + window.location.search + postfixSearch;

	var data = Object.toQueryString( { deleteItem: item } );
	
	$('delete_'+index).addClass('invisible');
//	jQuery('delete_'+index).remove();
	jQuery('item_'+index).remove();			
	recalculateTotal();
	if (jQuery('tr.listItem').length == 0) {
		$('elements_parent').remove()
		parameters = window.location.search.split('&')
		window.location = window.location.pathname + parameters[0];
		//window.location = window.location.pathname + window.location.search;
	}

	var myAjax = new Ajax( url , {
		data: data,
		method: 'post',
		onSuccess: function() {
//			console.log(this.response.text);
			$('item_'+index).remove();			
			recalculateTotal();
			if (jQuery('tr.listItem').length == 0) {
				$('elements_parent').remove()
				parameters = window.location.search.split('&')
				window.location = window.location.pathname + parameters[0];
				//window.location = window.location.pathname + window.location.search;
			}
		},
		onFailure: function() {
			$('delete_'+index).removeClass('invisible');
		}
	}).request();
	
}

function undoDelete() {
	if ($$('.hiddenItem').length > 0) {
		var item = $$('.hiddenItem')[$$('.hiddenItem').length-1];
		if ($defined(item)) {
			$('tablebody').adopt($(item));
			$(item).removeClass('hiddenItem');
			$(item).addClass('listItem');
		}
	}

	recalculateTotal();
}

function setValidPlz() {
	var advice = fV.getAdvice('validatePlz', 'fdata_plz');
	if ($(element).hasClass('invalid-plz')) {
		$(fieldname).removeClass('invalid-plz');
	}
	if (advice) {
		if (advice.smoothHide) {
			advice.smoothHide();
		} else {
			advice.setStyle('display','none');
		}
	} 
}
function setInvalidPlz(validator,fieldname) {
	$(fieldname).addClass('validation-failed');
	$(fieldname).addClass('invalid-plz');

	var advice = fV.makeAdvice('validatePlz', $(fieldname), "Diese Postleitzahl ist falsch!", false);
	advice.injectAfter($('fdata_wohnort'));
	if (advice.smoothShow) {
		advice.setStyle('margin','0');
		advice.setStyle('padding','2px');
		advice.setStyle('height','');
		advice.smoothShow();
	} else {
		advice.setStyle('display','block');
	}

}

