var BULK_PREFIX = 'hurtownia';
var spinnerString = "<p>Wczytywanie... <img src='/img/spinner.gif' alt='Wczytywanie' /><\/p>";
var fileFieldNumber = 0;

// account -> user order details & account -> user history
function updateOrderDetails(order_id) {
	$('order_details_container').removeClassName('hidden');
	$('order_details').update(spinnerString);
	new Ajax.Updater("order_details", "/account/update-order-details/",
		{ method: 'get', parameters: { order_id: order_id }, evalScripts: true }
	);
}

// account -> update order details -> order status combo changed
function orderStatusChanged(currentServerDate) {
	if ($('order_status').options[$('order_status').selectedIndex].value == 2) {
		$('shipment_date').value = currentServerDate;
	}
}

// account -> update order details -> update order clicked
function updateOrder(order_id) {
	$('updated_info').update('Zapisywanie...');
	new Ajax.Request("/account/update-order/", {
			method: 'post',
			parameters: { order_id: order_id, order_status: $F('order_status'), package_number: $F('package_number'), invoice_number: $F('invoice_number'), shipment_date: $F('shipment_date'), payment_status: ($('payment_status') && $F('payment_status')) || -1 },
			onSuccess: function(transport) {
				$('updated_info').update('Zapisano.');
				window.setTimeout(function() { $('updated_info').update(''); }, 1000);
				window.location.reload();
			},
			onFailure: function(transport) {
				$('updated_info').update('');			
				alert("Błąd: " + transport.responseText);
			}
		}
	);
}

function updateOrderFeedback(originalRequest) {
	if (originalRequest.responseText == "ok") {
		$('updatedInfo').show();
		updateOrderList();
		window.setTimeout(function() { $('updatedInfo').hide(); }, 1000);
	}
	else
		alert("Błąd: " + originalRequest.responseText);
}


/** Cart */
function addToCart(product_id, prefix) {
	var quantity = $F(prefix + product_id);
	var module = '';
	if (prefix == 'bulk') module = '/' + BULK_PREFIX;
	new Ajax.Updater('cart', module + '/cart/add-to-cart/', { method: 'post', parameters : { product_id : product_id, quantity : quantity } } );
}

/** Cart */
function removeFromCart(product_id, forward) {
	new Ajax.Updater('cart', '/cart/remove-from-cart/', { method: 'post', parameters : { product_id : product_id, forward : forward } } );
}

/** Cart */
function setQuantity(product_id, prefix) {
	var quantity = $F('qty' + product_id);
	var module = '';
	if (prefix == 'bulk') module = '/' + BULK_PREFIX;
	new Ajax.Updater('cart', module + '/cart/set-quantity/', { method: 'post', parameters : { product_id : product_id, quantity: quantity } } );
}

// account -> get user orders
function getUserOrders(user_id) {
	$('user_orders').removeClassName('hidden');
	$('user_orders').update(spinnerString);
	new Ajax.Updater("user_orders", "/account/get-user-orders/",
		{ method: 'get', parameters: { user_id: user_id }, evalScripts: true }
	);
}

//account -> customers
function getUserInfo(user_id) {
	$('user_info').removeClassName('hidden');
	$('user_info').update(spinnerString);
	$('user_orders').update('');
	new Ajax.Updater("user_info", "/account/user-info/",
		{ method: 'get', parameters: { user_id: user_id }, evalScripts: true }
	);
}

//account -> products
function getProductInfo(product_id) {
	$('product_info').removeClassName('hidden');
	$('product_info').update(spinnerString);
	new Ajax.Updater("product_info", "/account/product-info/",
		{ method: 'get', parameters: { product_id: product_id }, evalScripts: true }
	);
}

function triggerDelayedPayment(user_id) {
	new Ajax.Request("/account/trigger-delayed-payment/", { method: 'post',
		parameters: { user_id: user_id },
		onSuccess: function(transport) { new Ajax.Updater("user_info", "/account/user-info/", { method: 'get', parameters: { user_id: user_id }, evalScripts: true }); }
	});
}

function triggerPromoPrice(user_id) {
	new Ajax.Request("/account/trigger-promo-price/", { method: 'post',
		parameters: { user_id: user_id },
		onSuccess: function(transport) { new Ajax.Updater("user_info", "/account/user-info/", { method: 'get', parameters: { user_id: user_id }, evalScripts: true }); }
	});
}

function triggerRecommendedProduct(product_id, type) {
	new Ajax.Request("/account/trigger-recommended-product/", { method: 'post',
		parameters: { product_id: product_id, type: type },
		onSuccess: function(transport) { new Ajax.Updater("product_info", "/account/product-info/", { method: 'get', parameters: { product_id: product_id }, evalScripts: true });}
	});
}

function triggerAlwaysVisibleProduct(product_id, type) {
	new Ajax.Request("/account/trigger-always-visible-product/", { method: 'post',
		parameters: { product_id: product_id, type: type },
		onSuccess: function(transport) { new Ajax.Updater("product_info", "/account/product-info/", { method: 'get', parameters: { product_id: product_id }, evalScripts: true });}
	});
}

// product page, clicking on main picture
function popupPicture(sPicURL, name) { 
	window.open("/popup.html?" + sPicURL + "?" + name, "", "resizable = 1, height = 200, width = 200"); 
}

// product page, clicking on a thumbnail picture
function showPicture(url, name) {
	$('main_picture').src = url;
	$('main_picture').alt = name;
	url = url.replace("large/l_", "");
	$('main_picture').onclick = function() { popupPicture(url, name) };	
}

// registration form
function useDifferentPostage() {
	if ($('postage_data').hasClassName('hidden')) $('postage_data').removeClassName('hidden');
	else $('postage_data').addClassName('hidden');
}

function switchInvoiceType(type, postage) {
	var prefix = postage ? "p_" : "";
	
	var companyField = $(prefix + "company");
	var nipField = $(prefix + "nip");
	var tmp = $(prefix + "tmp");
	
	if (type == 1) { // osoba prywatna
		companyField.disabled = true;
		if (!postage) nipField.disabled = false;
		tmp.value = companyField.value;
		companyField.value = "";
		$(prefix + "company_star").innerHTML = "";
		if (!prefix) $(prefix + "nip_star").innerHTML = "";
	}
	else {
		companyField.disabled = false;
		if (!postage) nipField.disabled = false;
		companyField.value = tmp.value;
		$(prefix + "company_star").innerHTML = "*";
		if (!prefix) $(prefix + "nip_star").innerHTML = "*";
	}
}

function triggerShipmentCombobox(shipment_id) {
	$('payment_method').update(spinnerString);
	new Ajax.Updater('payment_method', '/cart/trigger-shipment-combobox/', { method: 'post', parameters: { shipment_id : shipment_id, weight : $('total_weight').innerHTML } } );
	$('shipping_method_name').update('<span class="red bold">Wybierz sposób płatności...</span>');
	$('payment_method_name').update("");
	$('shipping_cost').update("");
	$('total_cost').update(parseFloat($('total_brutto').innerHTML).toFixed(2));
	$('platnosci_pl_method').update("");
}

function triggerPaymentCombobox(shipment_id) {
	new Ajax.Updater('platnosci_pl_method', '/cart/trigger-payment-combobox/', { method: 'post', parameters: { shipment_id: shipment_id } } );
}

function updatePlatnosciPlType(type) {
	$('platnosci_pl_type').value = type;
}

function calculateShipping(shipment_id) {
	new Ajax.Request('/cart/calculate-shipping/', {
		onComplete: function(originalRequest) {
			var tmp = originalRequest.responseText.evalJSON();
			$('shipping_method_name').innerHTML = tmp.name;
			$('payment_method_name').innerHTML = tmp.payment;
			$('shipping_cost').innerHTML = parseFloat(tmp.cost).toFixed(2) + " zł";
			$('total_cost').innerHTML = (parseFloat($('total_brutto').innerHTML) + parseFloat(tmp.cost)).toFixed(2);
		},
		method: 'post',
		parameters: { shipment_id : shipment_id } 
	});
}

function appendFileField() {
	fileFieldNumber++;
	var d = document.createElement("div");
	d.setAttribute("id", "dfile" + fileFieldNumber);
	$('fileInputs').appendChild(d);
	$('dfile' + fileFieldNumber).innerHTML += "<input type='file' name='file" + fileFieldNumber + "' />";
}


/*** CATEGORY TREE ***/
/*
	czTree v0.1
	copyleft Łukasz Adamczak 25.07.2007
	www.czak.net
*/

function czTree(rootid) {
	this.rootid = rootid;
	this.openlist = ".";
	this.parseCookie();
	this.initialize(document.getElementById(rootid), 0, "");
}

function getInternetExplorerVersion() {
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null)
            rv = parseFloat(RegExp.$1);
    }
    return rv;
}

//Funkcja pomocnicza - tworzenie elementu img
czTree.prototype.getImg = function(name) {
	var img = document.createElement("span");
	if (navigator.appName == "Microsoft Internet Explorer" && getInternetExplorerVersion() < 8.0) { img.setAttribute("className", "block sprite-" + name); } else { img.setAttribute("class", "block sprite-" + name); }
	return img;
}

//Pobranie cookiesa z otwartymi węzłami
czTree.prototype.parseCookie = function() {
	var s = document.cookie;
	var i = s.indexOf("czon=");
	if (i == -1) return;
	var ie = s.indexOf(";", i);
	this.openlist = ie===-1 ? s.substr(i+5) : s.substring(i+5, ie);
}

//Funkcja obsługująca klikanie w plusy i minusy
czTree.prototype.click = function(img, depth) {
	var li = img.parentNode;
	var src = navigator.appName == "Microsoft Internet Explorer" && getInternetExplorerVersion() < 8.0 ? img.getAttribute("className") : img.getAttribute("class");
	var imgid = img.id.substr(3)+".";

	// Podmiana obrazków, zapisanie do listy otwartych lub usunięcie z niej
	if (li.className == "") {
		li.className = "open";
		li.lastChild.style.display = "block";
		if (navigator.appName == "Microsoft Internet Explorer" && getInternetExplorerVersion() < 8.0) { img.setAttribute("className", src.replace("sprite-plus", "sprite-minus")); } else { img.setAttribute("class", src.replace("sprite-plus", "sprite-minus")); }
		this.openlist = this.openlist + imgid;
	}
	else {
		li.className = "";
		li.lastChild.style.display = "none";
		if (navigator.appName == "Microsoft Internet Explorer" && getInternetExplorerVersion() < 8.0) { img.setAttribute("className", src.replace("sprite-minus", "sprite-plus")); } else { img.setAttribute("class", src.replace("sprite-minus", "sprite-plus")); }
		this.openlist = this.openlist.replace(imgid, "");
	}
	
	// Zapisanie do cookiesa
	document.cookie = "czon=" + this.openlist + "; path=/";
}

//Konfiguracja drzewka
czTree.prototype.initialize = function(rootul, depth, rootid, rootbottom) {
	var _this = this;
	var nodes = rootul.childNodes;
	for (var i=nodes.length-1,sup="bottom", nid=1; i>=0; i--) {
		if (nodes[i].nodeName.toLowerCase() === "li") {
			var li = nodes[i];
			
			// Czy jest poziom niżej pod tym itemem?
			var uls = li.getElementsByTagName("ul"), exp = false;
			if (uls.length != 0) {
				this.initialize(uls[0], depth+1, rootid+"_"+nid, sup);
				var exp = true;
			}
			
			var a = li.firstChild;
			
			for (var j=0; j<depth; j++) {
				if (rootbottom && j > 0) li.insertBefore(this.getImg("empty"), a);
				else li.insertBefore(this.getImg("line"), a);
			}
			
			// Sprawdź czy ten węzeł jest otwarty czy zamknięty
			var isopen = this.openlist.search(new RegExp("\\b"+rootid+"_"+nid+"\\b")) != -1;
			
			// Wstawienie ikonek
			if (exp) {
				if (isopen) {
					var img = this.getImg("minus"+sup);
					li.className = "open";
					li.lastChild.style.display = "block";
				}
				else { var img = this.getImg("plus"+sup); }
				img.onclick = function() { _this.click(this, depth); };
				img.style.cursor = "pointer";
				img.id = "czp"+rootid+"_"+nid++;
				li.insertBefore(img, a);
				li.insertBefore(this.getImg("folder"), a);
			}
			else {
				li.insertBefore(this.getImg("join"+sup), a);
				li.insertBefore(this.getImg("page"), a);
			}
			// dopisek tylko dla ostatniego
			sup = "";
		}
	}
	if (depth == 0) rootul.style.display = "block";
}
/*** END OF CATEGORY TREE ***/

