var g_current_shipping_method = '';
var last_form = null;
var ajax_last_txt  = '';
var ajax_timer_id = 0;
var ajax_cycle_txt = ['+...', '.+..', '..+.', '...+', '..+.', '.+..'];
var ajax_cycle_i = 0;
var ajax_cycle_btn = null;

function ajax_form_cycle()
{
	ajax_cycle_btn.value = ajax_cycle_txt[ (ajax_cycle_i++) % ajax_cycle_txt.length];
}

function ajax_form_enable(form, enabled)
{
	for( i in form.elements )
	{
		try {
			if( form.elements[i].type == 'button' || form.elements[i].type == 'submit' ) {
				if( enabled ) {
					$(form.elements[i]).removeClass('disabled');
				} else {
					$(form.elements[i]).addClass('disabled');
				}
			}
			
			form.elements[i].disabled = enabled ? '' : 'true';
		
		} catch ( e ) { }
	}
	
	if( !enabled ) {
		last_form = form;
		ajax_cycle_btn = form.elements['submit'];
		ajax_last_txt = ajax_cycle_btn.value;
		ajax_cycle_i = 0;
		ajax_timer_id = setInterval('ajax_form_cycle()', 100);
		ajax_cycle_btn.blur();
	} else {
		clearInterval(ajax_timer_id);
		ajax_cycle_btn.value = ajax_last_txt;
		ajax_cycle_btn = null;
	}
}

function ajax_form_cb(data, status, xr)
{
	if( typeof(data) != 'object' || typeof(data.status) == 'undefined' ) {
		ajax_form_enable(last_form, true);
	} else if ( data.status == 'redirect' ) {
		window.location = data.target;
	} else if ( data.status == 'error' ) {
	
		var error_str =  '<b>Uwaga:</b><ul>';
		
		for( i in data.errors ) {
			error_str += '<li>' + data.errors[i] + '</li>';
		}
		error_str += '</ul>';
		
		show_popup(last_form.elements['submit'], error_str );
		
		ajax_form_enable(last_form, true);
		
	} else if( data.status == 'success' ) {
	
	} else {
		alert('Uknown form status received');
	}
}

function ajax_form(_id)
{
	var form = document.getElementById(_id);
	
	if( ajax_cycle_btn != null ) {
	
		show_popup(form.elements['submit'], 'Aktualnie nie można przesłać formularza, poczekaj aż poprzednie zapytanie zostanie zakończone!');
		return false;
	}
	
	var variables = 'id=' + form.id + '&ajax=1&' + $(form).serialize();
	
	try {
		ajax_form_enable(form, false);
		$.post(form.action, variables, ajax_form_cb, 'json');
	} catch ( e ) { 
		alert('E:' + e.message);
		return false;
	}
	
	return false;
}

function cart_add_ex(id, btn)
{
	return cart_add(id, btn, parseInt($('#product-count')[0].value));
}

function cart_add(id, btn, count)
{
	$(btn).removeClass('ui-state-default').addClass('ui-state-disabled');
 
    $.post('/cart_add.php', 'i=' + id + '&count=' + ( count || 1 ),
		function(data)
		{
           
			if(data.status != 'OK' ) {
				alert('Nie udało się zmodyfikować koszyka\n' + data);
                return;
			}
            
            $('#cart-items').html(data.items + ' (' + data.allitems + ')');
            $('#cart-weight').html(data.weight + ' g');
            $('#cart-total').html(data.total + ' zł');
            
            $(btn).removeClass('ui-state-default').removeClass('ui-state-disabled').addClass('ui-state-active');

		}, 'json');
}

function fav_toggle(id, btn)
{
    $.post('/fav_toggle.php', 'i=' + id,
		function(data)
		{
			if(data.status != 'OK' ) {
                return;
			}
            
            $(btn).toggleClass('ui-state-default').toggleClass('ui-state-active');

		}, 'json');
}

function cart_new()
{
    window.location='/?reset=1';
}

function show_image(id, title)
{
	var img = $("#image-img")[0];
	
	img.src = "/img/please-wait.gif";
	
	img.onload = function() {
		if( img.height < 50 ) {
			return;
		}
		$("#image-dialog").dialog('option', 'width', img.width + 60 + 'px');
		$("#image-dialog").dialog('option', 'height', img.height + 110 + 'px');
		$("#image-dialog").dialog('option', 'position', 'center');
		$("#image-img").parent().height(img.height + 20);
	}
	
	$("#image-dialog").dialog('option', 'width', '300px');
	$("#image-dialog").dialog('option', 'height', '200px');
	$("#image-dialog").dialog('option', 'position', 'center');
	$("#image-dialog").dialog('option', 'title', title);
	$("#image-dialog").dialog('open');
	
	img.src = "/file/" + id + "/0/" + id + ".png";
}

function mask_show(on)
{
	$('#mask').fadeIn('fast');
}

function mask_hide()
{
	$('#mask').fadeOut('fast');
}

function cart_select_toggle(cb)
{
	$('input[name^=remove]').attr('checked', cb.checked);
}

function cart_shipping_toggle(obj)
{
	var id = null;
	var tmp = 0;
	
	if( typeof(obj) == 'string' ) {
		id = obj;
	} else {
		id = obj.currentTarget.id;
	}
	
	if( id == '' ) {
	
	}
	else
	{
		if( g_current_shipping_method != '') {
			$('#' + g_current_shipping_method).removeClass('selected');
		}
		
		g_current_shipping_method = id;
		tmp = $('#' + g_current_shipping_method).addClass('selected').attr('title');
		
		$('#abs-total').html((parseFloat(tmp) + parseFloat($('#cart-total').attr('title'))).toFixed(2) + ' zł');
	}
	
	try {
		if(typeof(obj.currentTarget) == 'object') {
			cart_update();
		}
	}catch(e){}
}

function fix_cart_buttons(s, c)
{
	if( c != 1 ) {
		$('td.button').click(cart_shipping_toggle);
	}
	
	if( typeof(s) == 'string' ) {
		cart_shipping_toggle(s);
	} else if( g_current_shipping_method != '') {
		cart_shipping_toggle(g_current_shipping_method);
	}
}

function cart_remove_selected()
{
	var c = $('input[name^=remove]:checked');
	var r = [];
	
	if( c.length == 0 ) {
		return;
	}
	
	mask_show('cart-full');
	
	for( var i=0; i<c.length; i++) {
		r.push(c[i].value);
	}
	
	$.post('cart_mod.php', 'postage=' + g_current_shipping_method + '&full=1&remove=' + r.join(",") + "&remarks=" + $('#cart-remarks').val(), 
		function(data)
		{
			$('#cart-table-parent').html(data);
			fix_cart_buttons(null);
			mask_hide();
		}, 'text');
		
	
		
	return false;
}

function cart_update(confirm)
{
	var c = $('input[name^=uq]');
	var r = [];
	
	if( c.length == 0 ) {
		return;
	}
	
	mask_show('cart-full');
	
	for( var i=0; i<c.length; i++) {
		r.push(c[i].name + '=' + c[i].value);
	}
	
	$.post('cart_mod.php', 'postage=' + g_current_shipping_method + '&full=1&' + r.join("&") + "&remarks=" + $('#cart-remarks').val(), 
		function(data)
		{
			$('#cart-table-parent').html(data);
			
			if( confirm ) {
				document.location = '/cart-confirm';
			} else {
				fix_cart_buttons(null);
				mask_hide();
			}
		}, 'text');

	return false;
}

function show_popup(parent, txt)
{
	var off = 0;
	var pop = $('#popup');
	
	if( typeof(parent) == 'object' ) { 
		off = $(parent).offset();
	} else {
		off = $('#' + parent).offset();
	}
	
	pop.html(txt);
	
	pop[0].style.left = (parseInt(off.left) - 6) + 'px';
	pop[0].style.top = (parseInt(off.top) - pop.height() - 25) + 'px';
	
	pop.fadeIn('slow');
}

function hide_popup()
{
	$('#popup').fadeOut('slow');
}

function cart_edit()
{
	document.location = '/cart';
	return false;
}

function cart_confirm()
{
	document.location = '/cart-confirm';
	return false;
}
