
/**
 * zwraca literal obiektowy z parami zmiennych z podanego formularza
 * uwzglednia pola input, select, textarea 
 * 
 * @param HTMLObject f - formularz
 */
function get_form_vars(f)
{
	function vars(){}
	$(":input[@name]", f).each(
			function()
			{
				input_type = $(this).attr("type");
				if ((input_type == "radio" || input_type == "checkbox"))
				{
					if (this.checked == true)
					{
						eval("vars.prototype." + $(this).attr("name") + " = $(this).val();");
					}
				}
				else
				{
					eval("vars.prototype." + $(this).attr("name") + " = $(this).val();");
				}
			}
		);
	return new vars();
}


function popup_window(title, content, width, height)
{
	var window_id = rand(999);
	
	function correct_overlay()
	{
		var width = $("#popup_window" + window_id).width();
		var height = $("#popup_window" + window_id).height();
		$("#popup_window" + window_id).width(width - 38).height(height - 45);
	}
	
	function onclose()
	{
		$("#popup_window" + window_id).remove();
	}
	
	
	if ((typeof width == "undefined") || (width < 1))
	{
		width = 700;
	} 
	if ((typeof height == "undefined") || (height < 1))
	{
		height = 600;
	}

	var w = '<div id="popup_window' + window_id + '"></div>';
	$("#popup_window" + window_id).remove();
	$("body").append(w);
	$("#popup_window" + window_id).dialog({ 
			    modal: true,
			    title: title,
			    width: width,
			    height: height,
			    open: correct_overlay,
			    close: onclose,
			    resizeStop: correct_overlay,
			    overlay: { 
			        opacity: 0.5, 
			        background: "black" 
			    } 
			});

	if (content.length > 0)
	{
		$("#popup_window" + window_id).html(content);
		$("#popup_window" + window_id).css("background-image", "none");
	}

	return "popup_window" + window_id;
}

function rand(n)
{
	return (Math.floor(Math.random() * n + 1));
}


function moneyFormat(value)
{
	value = Math.round(value * 100)/100;
	if (value == Math.floor(value))
	{
		value = value + ',00';
	}
	else
	{
		if (value * 10 == Math.floor(value * 10))
		{
			value = value + '0';
		}
	}
	value += '';
	return value.replace(/\./, ",").split("").reverse().join("").replace(/(\d{2})\,(\d{0,3})(\d{0,3})(\d{0,3})(\d{0,3})(\d{0,3})/, "$1,$2 $3 $4 $5 $6").split("").reverse().join("");
}


function checkRequiredFields(formObj)
{
	// sprawdzanie czy po naciśnięciu submit wymagane pola są wypełnione
	ok = true;
    $(formObj).find(".requiredField").each(function(){
			if (this.value === '')
	        {
          		ok = false;
          		$(this).css("background", "#ff9");
        	}
        	else
        	{
          		$(this).css("background", "#fff");
        	}
      	});
	if (ok)
	{
		return true;
	}
	alert('Nie wypełniono wszystkich wymaganych pól!');
    return false;
}




inits = {
	tdPointer_init: function(){
		$("tr.tr-pointer").each(
				function() {
					var url = $(this).attr("rel");
					$(this).children("td").each(
							function()
							{
								if (!$(this).hasClass("td-pointer-noclick"))
								{
									$(this).click(
											function() {
												window.location=url;
											}
										);
								}
							}
						);
					$(this).mouseover(
							function() {
								$(this).children("td").addClass("td-over");
							}
						);
					$(this).mouseout(
							function() {
								$(this).children("td").removeClass("td-over");
							}
						);
				}
			);
	},
	
	requiredField_init: function(){
		$(".requiredField[@type!='hidden']").after('<span class="redStar">*</span>');
		$("form").each(
				function()
				{
					if ($(":input", this).hasClass("requiredField"))
					{
						$(this).submit(function(){return checkRequiredFields(this);})
					}
				}
			);
	},


	
	
	lightBox_init: function ()
	{
		var groups = {};
		var groups_n = 0;
		var orig_rel = 'lightbox';
		// Create the groups
		$.each($('[@rel*='+orig_rel+']'), function(index, obj){
			// Get the group
			var rel = $(obj).attr('rel');
			// Are we really a group
			if ( rel == orig_rel )
			{	// We aren't
				rel = groups_n; // we are individual
			}
			// Does the group exist
			if ( typeof groups[rel] == 'undefined' )
			{	// Make the group
				groups[rel] = [];
				groups_n++;
			}
			// Append the image
			groups[rel].push(obj);
		});
		// Lightbox groups
		$.each(groups, function(index, group){
			$(group).lightBox();
		});
		// Done
		return true;
	},



	datepicker_init: function()
	{
		$(".datepicker").datepicker();
	},
	
	
	treemenu_init: function()
	{
		$(".treeview_menu").each(
					function()
					{
						$(this).treeview({
								persist: "cookie",
			   					cookieId: "navigationtree_" + this.id,
								control: $(".treecontrol", this),
								animated: "fast",
								collapsed: true
							});
					}
				);
	},


	tabs_init: function()
	{
		$(".tabbed").show();
		$(".tabbed > ul").tabs({cookie: {expires: 30}});
	},
	
	
	number_fields_init: function()
	{
		// ustaw pola rzeczywiste 
		$("input.real-number").realnumeric(2);
		
		// ustaw pola numeryczne naturalne
		$("input.natural-number").numeric();
	},
	
	
	search_fieldset_init: function()
	{
		$(".search_fieldset form").hide();
		$(".search_fieldset legend").each(
				 function()
				 {
				 	$(this).append(' <span style="font-size: 9px;">(kliknij)</span>');
				 	$(this).css("cursor", "pointer");
				 	$(this).click(
							function()
							{
								$(".search_fieldset form").toggle();
							}
						);
				 }
			);
	},
	
	
	all_inits: function()
	{
		this.requiredField_init();
		this.tdPointer_init();
		this.lightBox_init();
//		this.datepicker_init();
//		this.treemenu_init();
//		this.tabs_init();
		this.number_fields_init();
		this.search_fieldset_init();
	}
	
};


order = {
	calkowitaWartoscZamowienia: 0,
	kosztDostawy: 0,
	kosztPlatnosci: 0,
	
	change_koszt_dostawy: function(kd)
	{
		this.kosztDostawy = kd;
		this.fill_order_value_form();
	},

	change_koszt_platnosci: function(kp)
	{
		this.kosztPlatnosci = kp;
		this.fill_order_value_form();
	},
	
	fill_order_value_form: function()
	{
		if (typeof this.calkowitaWartoscZamowienia != 'number')
		{
			return false;
		}
		
		if (typeof this.kosztDostawy != 'number')
		{
			return false;
		}
		
		if (typeof this.kosztPlatnosci != 'number')
		{
			return false;
		}
		
		var kp = this.kosztPlatnosci;
		if (this.kosztDostawy <= 0)
		{
			kp = 0;
		}
		
		$("#sum_koszt_dostawy").empty().append('<span class="cena_txt">' + moneyFormat(this.kosztDostawy) + "</span> zł");
		$("#sum_koszt_platnosci").empty().append('<span class="cena_txt">' + moneyFormat(kp) + "</span> zł");
		$("#sum_c_wartosc").empty().append('<span class="cena_txt">' + moneyFormat(this.calkowitaWartoscZamowienia + this.kosztDostawy + kp) + "</span> zł");
	},
	
	
	confirm_order: function(f)
	{
		sposob_dostawy = "";
		$("input[@name=sposob_dostawy]").each(
			function() {
					if (this.checked)
					{
						sposob_dostawy = $(this).val();
					}
				}
		);
		if (sposob_dostawy.length < 1)
		{
			alert("Wybierz sposób dostawy!");
			return false;
		}

		sposob_platnosci = "";
		$("input[@name=sposob_platnosci]").each(
			function() {
					if (this.checked)
					{
						sposob_platnosci = $(this).val();
					}
				}
		);
		if (sposob_platnosci < 1)
		{
			alert("Wybierz sposób płatności!");
			return false;
		}

		dowod_ksiegowy = "";
		$("input[@name=dowod_ksiegowy]").each(
			function() {
					if (this.checked)
					{
						dowod_ksiegowy = $(this).val();
					}
				}
		);
		if (dowod_ksiegowy < 1)
		{
			alert("Wybierz rodzaj dowodu księgowego!");
			return false;
		}
		
		
		if ($("#accept_reg").attr("checked") != true)
		{
			alert("Musisz zaakceptować Regulamin sklepu!");
			return false;
		}
		
		$("#confirm_order_submit").hide().after('<p id="confirm_order_wait_txt"><img class="left" src="' + base_url + 'img/ajax-loader.gif" alt="" /> proszę czekać, trwa składanie zamówienia...<p>');
		
		
		
		fv = get_form_vars(f);
		$.post(base_url + "order/place_order",
				fv, 
				function(xml)
				{
					pre = $("pre", xml).text();
					if (pre.length > 0)
					{
						alert(pre);
					}

					error = $("error", xml).text();
					if (error.length > 0)
					{
						alert(error);
						$("#confirm_order_wait_txt").remove();
						$("#confirm_order_submit").show();
						return false;
					}

					var form_action;
					form_action = $("form_action", xml).text();

					var add_form_data;
					add_form_data = $("add_form_data", xml).text();

					$("#confirm_order form").attr("action", form_action);
					$("#confirm_order form > #add_form_data").empty().prepend(add_form_data);
					$("#confirm_order form").submit();

					$("#confirm_order_wait_txt").remove();
					$("#confirm_order_submit").show();
				}
			);
		
		return false;
	}
}






// uruchamia kod po zaladowaniu dokumentu
$(document).ready(
		function()
		{
			// ukryj wszystkie elementy, ktore sa deafultowo ukryte- sa klasy hide_default
			$(".hide_default").hide();

			inits.all_inits();
			
			if ($.browser.msie)
			{
				$("ul#grupy_poziom li a").css("white-space", "nowrap");
			}
		}
	);

