//Filling SELECTs
$(function()
{
	build_promotion_products(promote_products, affiliate_pageID);

	build_selects(product_selects, product_data);
});

function get_list_params(list_params)
{
	var output = new Object();
	output.productID = new Object();

	for (var key in list_params)
	{
		output['productID'][key] = list_params[key]['productID'];
	}

	return $.param(output);
}

function build_promotion_products(promote_products, affiliate_pageID)
{
       $('.fproduct').each(function(i){
		$(this).bind('click', function() {
			window.location = basedomain + promote_products[i].link.replace(/{refID}/gi, affiliate_pageID);
		}); // make box clickable
		$(this).find('.fn').text(promote_products[i].display_name);
		$(this).find('a.url').attr('href',basedomain + promote_products[i].link.replace(/{refID}/gi, affiliate_pageID));
		$(this).find('.currency').text('$');
		$(this).find('.price .primary').text(promote_products[i].data.price[0]);
		$(this).find('.price .decimal').text(promote_products[i].data.price[1]);
		$(this).find('.photo').attr('src', product_images + promote_products[i].data.homepage_banner_img_src);
		$(this).find('.photo').attr('alt', promote_products[i].display_name);
       });
}

function build_selects(list_data, product_data)
{
	var product_key = null;
	var qty_key = null;
	var product;
	var qty;
	var listId;
	var affiliate_pageID_param = '';
	var quantityID;

	for (product_key in list_data)
	{
		listId = list_data[product_key]['elm_id'];
		product = product_data[list_data[product_key]['productID']];

		if (product)
		{
			//Removing previous options.
			$('#' + list_data[product_key]['elm_id']).children('option').remove();
			//Activating select's button.
			$('.btn_' + listId).bind("click", { listId: listId, Param2: 2 }, function(event){
				quantityID = $('#' + event.data.listId).val();
				if (affiliate_pageID && parseInt(affiliate_pageID) != NaN) affiliate_pageID_param = '&affiliate_pageID=' + affiliate_pageID;
				else affiliate_pageID = '';
				window.location = cart_url + '?quantityID=' + quantityID + affiliate_pageID_param;
			});

			var count = 0;
			for (qty_key in product['qty']) {
			       count++;
			}
			middle = Math.round(count/2);
			var index = 0
			for (qty_key in product['qty'])
			{
				index++;
				qty = product['qty'][qty_key];
				if (qty)
				{
					//Adding options from fetched data.
					$('<option value="' + qty.quantityID  + '" '+ (index == middle ? 'selected="selected"' : '') +'>' + qty.text  + '</option>').appendTo($('#' + listId));
				}
			}
			//seting price per pill
			$('.ppp_' + listId).text('$'+qty.price_pp);
		}
	}
}

