/* $Id: products.js 205 2010-01-12 14:05:41Z edin.coralic $ */

var ProductLogin =
{
	login_content_id: 22,

	run: function()
	{
		ProductLogin.link = $('product_login_link');
		if (ProductLogin.link) {
			Event.observe(ProductLogin.link, 'click', ProductLogin.clickListener);
			ProductLogin.createContainer();
		}
		var errors = $$('.login p.error');
		if (errors.length > 0) {
		  ProductLogin.showLogin();
		}
	},

	createContainer: function()
	{
    ProductLogin.container = document.createElement('div');
    ProductLogin.container.className = 'login';
  	var form_parent = ProductLogin.link.up('form').parentNode;
		form_parent.appendChild(ProductLogin.container);
	},

	clickListener: function(e)
	{
	  ProductLogin.showLogin();
	  Event.stop(e);
	},

	showLogin: function()
	{
		new Ajax.Updater(
			ProductLogin.container,
			ProductLogin.getUrl(),
			{ method: 'get' }
		);
		Element.scrollTo(ProductLogin.container);
	},

	getUrl: function()
	{
	  var url = location.href;
	  var hash_pos = url.indexOf('#');
	  if (hash_pos > 0) {
	    url = url.substring(0, hash_pos);
	  }
	  if (url.indexOf('content=') == -1) {
	    var delimiter = '?';
		  if (url.indexOf('?') > 0) {
		    delimiter = '&';
		  }
      url += delimiter + 'content=' + ProductLogin.login_content_id;
	  }
		return url;
	}
}

var ProductAttributes =
{
	run: function()
	{
	  ProductAttributes.selects = $$('.products .attributes ul li select');
	  ProductAttributes.price = $$('.products .price em strong').first();
	  ProductAttributes.price_old = $$('.products .price em s').first();
	  ProductAttributes.per_item = $$('.products .price_per_item em strong').first();
	  ProductAttributes.per_item_old = $$('.products .price_per_item em s').first();

	  if (ProductAttributes.selects && ProductAttributes.price) {
	  	ProductAttributes.original = ProductAttributes.price.firstChild.nodeValue;
  		if (ProductAttributes.price_old) {
  			ProductAttributes.original_old = ProductAttributes.price_old.firstChild.nodeValue;
  		}
	    ProductAttributes.selects.each(ProductAttributes.attachListener);
	  }
	},

	attachListener: function(item)
	{
		Event.observe(item, 'change', ProductAttributes.changeListener.bindAsEventListener(item));
	},

	fetchPrices: function()
	{
		var price = null;
		var price_old = null;
		for (var i = 0; i < ProductAttributes.selects.length; i++) {
		    var select = ProductAttributes.selects[i];
		    var title = select.options[select.selectedIndex].title;
			var title_old = select.options[select.selectedIndex].getAttribute('title_old');
		    if (
				(title.length > 0) && (
					(price == null) ||
					(ProductAttributes.getPrice(price) < ProductAttributes.getPrice(title))
				)
			) {
				price = title;
				price_old = title_old;
		    }
		}
		if (price == null) {
			price = ProductAttributes.original;
			if (ProductAttributes.price_old) {
				price_old = ProductAttributes.original_old;
			}
		}

		if (ProductAttributes.price) {
			ProductAttributes.price.firstChild.nodeValue = price;
		}
		if (ProductAttributes.price_old) {
			ProductAttributes.price_old.firstChild.nodeValue = price_old;
		}
		var price_per_item = '';
    	var price_per_item5 = '';
		if (ProductAttributes.per_item && package_items) {

			price_per_item = ProductAttributes.formatPrice(ProductAttributes.getPrice(price) / package_items);
			price_per_item5 = ProductAttributes.formatPrice5(ProductAttributes.getPrice(price) / package_items);
			ProductAttributes.per_item.firstChild.nodeValue = price_per_item;
			if (ProductAttributes.per_item_old) {
				ProductAttributes.per_item_old.firstChild.nodeValue = ProductAttributes.formatPrice(ProductAttributes.getPrice(price_old) / package_items);
			}
		}

		if (!price) {
			return 0;
		}
		var send_price = price.replace('.', '');
		send_price = send_price.replace(',', '.');
		send_price = parseFloat(send_price);
		var send_per_item = price_per_item.replace('.', '');
		send_per_item = send_per_item.replace(',', '.');
		send_per_item = parseFloat(send_per_item);

		var send_per_item5 = price_per_item5.replace('.', '');
		send_per_item5 = send_per_item5.replace(',', '.');
		send_per_item5 = parseFloat(send_per_item5);

		var r = new Object;
		r.price = send_price;
		r.price_per_item = send_per_item;
		r.price_per_item5 = send_per_item5;
		return r;
	},

	changeListener: function()
	{
		var r =ProductAttributes.fetchPrices();
		/*alert(r.price);
		alert(r.price_per_item);*/
		new Ajax.Request(location.href, {
			method: 'get',
			parameters: {
				price: r.price,
				price_per_item: r.price_per_item5
			},
			onSuccess: function(transport) {
				var json = transport.responseText.evalJSON();
				var i;
				for (i in json) {
					var tr = $$('.products table.scale tr.scale_'+ i).first();
         			 var prices = json[i].split('|');
					if (tr) {
						var td = tr.down('td.price');
						if (td) {
							td.innerHTML = prices[0];
						}
						var td = tr.down('td.price_per_item');
						if (td) {
							td.innerHTML = prices[1];
						}
					}
				}

				ProductAmountChange.update();
			}
		});
	},

	getPrice: function(string)
	{
		string = string.replace('.', '');
		string = string.replace(',', '.')
		return parseFloat(string);
	},

	formatPrice: function(number)
	{
    var decimals = 2;
    var dec_point = ',';
    var thousands_sep = '.';

    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "") + ' €';
	},

	formatPrice5: function(number)
	{
    var decimals = 15;
    var dec_point = ',';
    var thousands_sep = '.';

    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

	return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "") + ' €';
	}
}

var ProductValidation =
{
	run: function()
	{
	  ProductValidation.button = $$('.products .add_cart input.cart_add').first();
	  ProductValidation.amount = $$('.products .add_cart input.amount').first();
	  if (ProductValidation.button && ProductValidation.amount) {
	  	ProductValidation.min_amount = ProductValidation.amount.value;
		Event.observe(ProductValidation.button, 'click', ProductValidation.clickListener);
	  }
	},

	clickListener: function(e)
	{
	  if (parseInt(ProductValidation.amount.value) < parseInt(ProductValidation.min_amount)) {
	    alert(ProductValidation.amountError.replace('\[min\]', ProductValidation.min_amount));
	    Event.stop(e);
	  }
	}
}

var ProductAttributeLinks =
{
	run: function()
	{
		$$('.products .attributes select').each(function(select) {
			Event.observe(select, 'change', ProductAttributeLinks.changeListener.bindAsEventListener(select));
			select.next('a').setAttribute('params', 'lightwindow_type=page');
		});
	},
	changeListener: function(e)
	{
		var option = this.options[this.selectedIndex];
		var href = option.getAttribute('href');
		var link = this.next('a');
		if (href) {
			link.href = href;
			link.style.visibility = 'visible';
		} else {
			link.style.visibility = 'hidden';
		}
	}
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName])
  {
      return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName];
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

function getFlashIdentifier(id)
{
	var result = id.match(/^flash_identifier_(.+)$/);
	if (result && result[1]) {
		return result[1];
	}
}

function onSwfLoad()
{
	var selects = $$("#product_attributes select");
	for(x=0; x<selects.length; x++) {
		var rel = getFlashIdentifier( selects[x].readAttribute("id") );
		if (rel) {
			selects[x].observe('change', function(event) {
				candleSetInit();
			});
		}
	}
	candleSetInit();
}
function candleSet(flicker, symbol, x, y, x2, y2){
	var obj = getFlashMovieObject("flash_overlay");
	//obj.candleSet(flicker, symbol, x, y, x2, y2);
	//alert(flicker+","+symbol+","+x+","+y+","+x2+","+y2);
	obj.SetVariable("setVar", flicker+","+symbol+","+x+","+y+","+x2+","+y2);
}
function candleSetInit(){
	var flicker = "none";
	var symbol = "none";
	var x=0;
	var y=0;
	var x2=0;
	var y2=0;
	var selects = $$("#product_attributes select");
		for(x=0; x<selects.length; x++){
			var val = selects[x].value;
			var rel = getFlashIdentifier( selects[x].readAttribute("id") );
			if(rel){
				if(rel=="FlickerType" || rel=="Addition"){
					var options = selects[x].getElementsBySelector("option");
					for(var i=0; i<options.length; i++){
						if(options[i].value==val){
							var oRel = options[i].readAttribute("atributek");
							if(oRel){
								oRel = oRel.split(",");
								if(oRel.length==3 && oRel[0]){
									if(rel=="FlickerType"){
										flicker = oRel[0];
										x = oRel[1];
										y = oRel[2];
									}else{
										symbol = oRel[0];
										x2 = oRel[1];
										y2 = oRel[2];
									}
								}
							}
						}

					}
				}
			}



	}
	candleSet(flicker, symbol, x, y, x2, y2);
}


var ProductCartAdd = {

	run: function() {
		var submit1 = $$('.products form .cart_add').first();
		ProductCartAdd.submit(submit1);

		var submit2 = $$('.products form .favorite_add').first();
		ProductCartAdd.submit(submit2);
	},
	submit: function(submit) {
		if (submit) {
			submit.observe('click', function(e){
				var selected_size = 0;
				var selects = $$('.products .attributes select');
				if (selects.size()) {
					selects.each(function(select){
						if (select.selectedIndex > 0) {
							selected_size += 1;
						}
					});
				}

				if (selected_size != selects.size()) {
					Event.stop(e);
					var error = $$('.products form div.cart_add_error').first();
					if (error) {
						alert(error.innerHTML);
					}
				}
			});
		}
	}

}


var ProductAmountChange =
{
	run: function()
	{
		var input = $$('.products .add_cart input[name="amount"]').first();
		if (input) {
			Event.observe(input, 'keyup', ProductAmountChange.onChangeListener.bindAsEventListener(input));
		}
	},
	onChangeListener: function(e)
	{
		if (this.value == '') {
			return;
		}
		ProductAmountChange.update();
	},
	update: function()
	{
		var input = $$('.products .add_cart input[name="amount"]').first();
		if (!input) {
			return;
		}

		var amount = Number(input.value.replace(/[^0-9]+/g,''));
		amount = amount > 1 ? amount : 1;
		input.value = amount;

		var r = ProductAttributes.fetchPrices();

		new Ajax.Request(location.href, {
			method: 'get',
			parameters: {
				what: 'fetchPerItemText',
				price: r.price,
				price_per_item: r.price_per_item5,
				amount: amount,
				content: 0
			},
			onSuccess: function(transport) {
				var container = $$('.products .add_cart .per_item').first();
				if (container) {
					container.innerHTML = transport.responseText;
				}
			}
		});
	}
}

new StartUp(ProductValidation);
new StartUp(ProductLogin);
new StartUp(ProductAttributes);
new StartUp(ProductAttributeLinks);
new StartUp(ProductCartAdd);
new StartUp(ProductAmountChange);
