
function trim(str) {
    return str.replace(/^\s+|\s+$/g, '') ;;
}
function blurLink(theObject){
	theObject.blur();
}
function mfFormFieldBlur(e)
{
	if (e.type == 'text')
		e.value = trim(e.value);
}

function wishListAdd(id)
{
	$.getJSON("/wishlist.php", { id: id, action: 'add' }, function(data){
		if(data["status"]=='OK') {
			$('.do-listy-zyczen','#item'+data["id"]).hide();
			$('.z-listy-zyczen','#item'+data["id"]).show();
		} 
	} );
	return false;
}
function wishListRemove(id)
{
	$.getJSON("/wishlist.php", { id: id, action: 'remove' }, function(data){
		if(data["status"]=='OK') {
			$('.z-listy-zyczen','#item'+data["id"]).hide();
			$('.do-listy-zyczen','#item'+data["id"]).show();
		} 
	} );
	return false;
}

function wishBasketAdd(id)
{
	$.getJSON("/basket.php", { id: id, action: 'add' }, function(data){
		if(data["status"]=='OK') {
			alert("Nagroda dodana do koszyka.");
			$('.do-koszyka','#item'+data["id"]).hide();
			$('.z-koszyka','#item'+data["id"]).show();
			reloadBasket();
		} 
		if(data["status"]=='PRESENT') {
			alert("Nagroda już jest w koszyku.");
			reloadBasket();
		} 
		if(data["status"]=='TOOMUCH') {
			alert("Brakuje ci "+data["points"]+" punktów, aby zamówić tą nagrodę.");
			reloadBasket();
		} 
	} );
	return false;
}
function wishBasketRemove(id)
{
	$.getJSON("/basket.php", { id: id, action: 'remove' }, function(data){
		if(data["status"]=='OK') {
			alert("Nagroda usunięta z koszyka.");
			$('.do-koszyka','#item'+data["id"]).show();
			$('.z-koszyka','#item'+data["id"]).hide();
			reloadBasket();
		} 
	} );
	return false;
}
function wishBasketRemoveAll()
{
	$.getJSON("/basket.php", { action: 'removeall' }, function(data){
		if(data["status"]=='OK') {
			alert("Nagrody usunięte z koszyka.");
			$('.do-koszyka').show();
			$('.z-koszyka').hide();
			reloadBasket();
		} 
	} );
	return false;
}

function reloadBasket()
{
	$.getJSON("/basket.php", { action: 'get' }, function(data){
		if(data["status"]=='OK') {
			$('tbody','.basketitems').html('');
			var razem = 0;
			if (data['items']) {
				for(i=0;i<data['items'].length;++i) {
					row = data['items'][i];
					h = '<tr class="item' + row['uid'] + '">';
					h = h + '<td class="n1">' + (row['category']?row['category']+' ':'') + row['producer'] + ' ' + row['name'] + '</td>';
					h = h + '<td class="n2">' + Math.ceil(row['pricebrutto']) + '</td>';
					h = h + '<td class="n3"><a href="#" onclick="return wishBasketRemove(' + row['uid'] + ');">usuń</a></td>';
					h = h + '</tr>';
					$('tbody','.basketitems').append(h);
					razem = razem + Math.ceil(row['pricebrutto']);
				}
				h = '<tr class="razem">';
				h = h + '<td class="n1">Razem:</td>';
				h = h + '<td class="n2">' + razem + '</td>';
				h = h + '<td class="n3">&nbsp;</td>';
				h = h + '</tr>';
				$('tbody','.basketitems').append(h);
				$('.mojStatusKoszyk').html(data['items'].length);
				$('.koszyk').addClass('koszykYes');
				$('.koszyk').removeClass('koszykNo');
			} else {
				$('.mojStatusKoszyk').html('0');
				$('.koszyk').addClass('koszykNo');
				$('.koszyk').removeClass('koszykYes');				
			}
		} 		 
	} );
	return false;
}
function mfFormValidate(f)
{
	//return true;
	o = '';
	for (i=0;i<f.elements.length;++i) {
		field = f.elements[i];
		if (field.name.substring(0,2) != '__') {
			rf = f.elements['__required[' + field.name + ']'];
			if (rf) {
				if (rf.value>0) {
					if (field.type == 'text' || field.type == 'password') {
						field.value = trim(field.value);
						if (field.value.length <1) {
							alert ("Pole '"+f.elements['__caption[' + field.name + ']'].value +"' musi zostać wypełnione!");
							return false
						}
					}
					if (field.type == 'checkbox') {
						if (!field.checked) {
							alert ("Pole '"+f.elements['__caption[' + field.name + ']'].value +"' musi zostać zaznaczone!");
							return false
						}
					}
					if (field.type == 'select-one') {
						if (!field.options[field.selectedIndex].value) {
							alert ("Wybierz wartość w polu '"+f.elements['__caption[' + field.name + ']'].value +"'!");
							return false
						}
					}
				}
			}
			if (f.elements['__validate[' + field.name + ']'] && (field.type == 'text' || field.type == 'password')) {
				if (field.value.length >0) {
					pattern = new RegExp(f.elements['__validate[' + field.name + ']'].value,"i");
					//alert(pattern);
					var m = pattern.exec(f[field.name].value);
					if (m == null) {
						alert ("Pole '"+f.elements['__caption[' + field.name + ']'].value +"' ma zły format danych!");
						return false
					}
				}
			}
			if (f.elements['__validateFunction[' + field.name + ']'] && (field.type == 'select-one' || field.type == 'text' || field.type == 'password')) {
				if (field.value.length >0) {
					eval("m=" + f.elements['__validateFunction[' + field.name + ']'].value + "('"+ f[field.name].value +"');" );
					if (!m) {
						alert (f.elements['__validateAlert[' + field.name + ']'].value);
//						alert ("Podaj prawidłowy numer Pesel lub zgłoś klienta drogą mailowa/telefoniczną (w takim przypadku Doradca ME po odbytym spotkaniu,  zarejestruje klienta w Twoim imieniu w systemie Money Friends)");
						return false
					}
				}
			}
//			o = o + field.name + '\n';
		}
	}
	//alert (o);
	return true;
}

function tableFilter (url)
{
	f = document.forms['filterForm'];
	if (typeof f == 'object') {
		f.action = url;
		f.submit();
		return false;
	} else {
		return true;
	}
}

function validatePESEL(p)
{
	n = trim(p);
	if (n.length != 11 || (/[^0-9]/).test(n) || n == '00000000000')
	{
		return false;
	}
 
	arrSteps = new Array(1, 3, 7, 9, 1, 3, 7, 9, 1, 3);
	intSum = 0;
	for (ii = 0; ii < 10; ii++)
	{
		intSum += arrSteps[ii] * n.charAt(ii);
	}
	intt = 10 - intSum % 10;
	intControlNr = (intt == 10)?0:intt;
	if (intControlNr == n.charAt(10))
	{
		return true;
	}
	return false;
}
function validateloantype(p)
{
	var o = document.tx_mf_applicationForm.realtystatus;
	if (o && p!='gotowkowy') {
		if(o.options[o.selectedIndex].value == '')
			return false;
	}
	return true;
}
function moreUnmore(t)
{
    t.parents('tr').next().toggle();
    t.toggleClass('unmore');
    return false;
}

var mfOnLoad = {
    start: function(){
        this.tables();
    },

    tables: function(){
        $('table.mfTable .hidden').hide();
        $('table.mfTable .unmore').removeClass('unmore');
        $('table.mfTable .more').bind('click', function(){
            var $self = $(this);
            $self.parents('tr').next().toggle();
            $self.toggleClass('unmore');
            return false;
        })
    }

}

$(function(){ mfOnLoad.start(); });
