// identyfikatory walut
var currenciesTextId = new Array();
currenciesTextId[1] = "PLN";
currenciesTextId[2] = "EUR";
currenciesTextId[3] = "USD";
currenciesTextId[4] = "GBP";

var currenciesValues = new Array();
var pricePoster = 0;
var idPoster;
var urlShCart = '../shopping-cart/?action=add';

$(document).ready(function()
{

	var addrRegx = new RegExp("^.+\/([A-Za-z0-9\_]+)\.html$", "g");
	var arr = addrRegx.exec(document.location.href);
	if (arr) {
		var id = arr[1];
		idPoster = id;
		
		getNdSetData(id);
		
	} else {
		alert("Error: invalid address. Please contact with administrator.")
		return false;
	}
	
	
});

function setButtonShCart(textId, currency)
{
	var oncl = 'redirectToShopCart(\'' +textId+ '\',\'' +currency+ '\');';
	var shAdd = '<input type="button" onclick="' +oncl+ '" value="Add to shopping cart" id="addToShoppingCart">';
	$("#shAdd").html(shAdd);
}

function redirectToShopCart(id, curr)
{
	
	var addrRegx = new RegExp("^(.+)posters\/([A-Za-z0-9\_]+)\.html$", "g");
	var arr = addrRegx.exec(document.location.href);
	if (arr) {
		addr = arr[1] + 'shopping-cart/?add=' +id+ '&currency=' +curr+ '';
		//window.location.replace(addr)
		document.location.href=addr;
	} else {
		alert("Niepoprawny adres WWW");
	}
		
	//var addr = '../shopping-cart/?add=' +id+ '&currency=' +curr+ '';
	//window.location.replace(addr)
	//document.location.href=addr;

}

function getNdSetData(id)
{

	$.post("../shopping-cart/get-data.php", 
		{textId: id},
		function(data){
			jsonData = eval("("+data+")");
			setData(jsonData);
	});
	
}

function setData(data)
{
	currenciesValues[1] = data.PLN;
	currenciesValues[2] = data.EUR;
	currenciesValues[3] = data.USD;
	currenciesValues[4] = data.GBP;

	pricePoster = data.price;
	
	var aval = parseInt(data.availability);
	
	$("#shoppingCartBox").html(data.shoppingCartBox);
	$("#shAvailabilityText").html("");
	$("#shAvailabilityValue").html(aval ? "" : "Please contact for availability.</div>");

	if (aval) 
	{
		setButtonShCart(idPoster, 'PLN');
		
		var shText = "Price";
		$("#shText").html(shText);
		
		
		var shForm = '<span id="price"></span>&nbsp;\
			<select id="currencyPosters" onchange="setPrice();">';
		for (var i=1; i<5; i++) {
			var sel = (i == data.curr) ? ' selected="selected"' : '';
			shForm += '<option value="' +i+ '"' +sel+ '>' +currenciesTextId[i]+ '&nbsp;</option>';
		}
		shForm += '</select><br />';
		$("#shForm").html(shForm);
		
		setPrice();
	} 
	else
	{
		
	}


}

function setPrice() 
{
	var cuPo = document.getElementById("currencyPosters");
	var cuPoVal = cuPo.options[cuPo.selectedIndex].value;

	var price = (pricePoster / (currenciesValues[cuPoVal]/100) )/100;

	document.getElementById("price").innerHTML = parseInt(price);
	
	setButtonShCart(idPoster, currenciesTextId[cuPoVal]);
	
}