var MAX_IMG_SIZE = 80; // max width/height in px
$(document).ready(function(){
						   
   $('.attrib select').each(function(i) {
		$(this)
			.after('<div id="selected_attrib_'+$(this).attr('name')+i+'"></div>')
			.change(function() {
				  var c = $(this).attr('name')+i;
				  var option = $(this).find(":selected").text();
				  if ($('#img_'+c).length > 0)   $('#img_'+c).fadeOut();
				  if ($('#img_'+c).length > 0)   $('#img_'+c).remove();
				  $.ajax({
					  url: '/product_alt_ajax.php',
					  //dataType: 'json',
					  data: {what:'attribval_images',val_ids:$('option:selected', this).val()},
					  cache: false,
					  contentType: "application/json",
					  success: function(msg){
					  	// clean up old json style
							msg = msg.replace(/'/g,'"');
							msg = msg.replace(/{/g,'{"');
							msg = msg.replace(/:/g,'":');
							msg = msg.replace(/,/g,',"');
							msg = msg.replace(/\n/g,"");
							var json = "";//= $.parseJSON(msg);	
							try
							{
							json = jQuery.parseJSON( msg );
							}
							catch(e)
							{
							// We report an error, and show the erronous JSON string (we replace all " by ', to prevent another error)
							//alert(msg);
							} 
							
							 				   
						    for (id in json) {
								var img = json[id];
								var h = img['h'];
								var w = img['w'];
								// scale down images if they are > MAX_IMG_SIZE tall or wide;
								if (w > MAX_IMG_SIZE) {
									h *= MAX_IMG_SIZE/w;
									w = MAX_IMG_SIZE;
								} else if (h > MAX_IMG_SIZE) {
									w *= MAX_IMG_SIZE/h;
									h = MAX_IMG_SIZE;
								}
							   var img_html = '<a href="'+img['src']+'" target="_blank" rel="lightbox" title="'+option+'"><img src="'+img['src']+'" id="img_'+c+'" width="'+w+'px" height="'+h+'px" /></a>';
							   $('#selected_attrib_'+c).append(img_html).fadeIn();   
							   jQuery("#selected_attrib_"+c+" a[rel='lightbox']").slimbox();
						   }
						},
					 	error : function(obj,err,text) {
							alert(obj+err+text);
						}
				});
		   });
 	});
});
