/*
 * Blade Search
 *
 * Interfaccia di ricerca web per Blade - Giorgio Tesi Vivai
 *
 * Autore: Alfonso Tatarelli
 * ©2009 Rigel Engineering Srl 
 *
 */
 
var jBlade_Connect = {
	// declare callback functions   
	onStart: function(event) {
		jQuery('#'+jBlade_Connect.waiting_id).show();
		jBlade_Connect.logEvent(event);
	},
	onStop: function(event) {
		jQuery('#'+jBlade_Connect.waiting_id).hide();
		jBlade_Connect.logEvent(event);
	},
	onSend: function(event, xhr, settings) {
		jBlade_Connect.logEvent(event, xhr, settings);
	},
	onComplete: function(event, xhr, settings) {
		jBlade_Connect.logEvent(event, xhr, settings);
	},
	onSuccess: function(event, xhr, settings) {
		jBlade_Connect.logEvent(event, xhr, settings);
	},
	onError: function(event, xhr, settings, err) {
		jBlade_Connect.logEvent(event, xhr, settings, err);
	},
	   
	// create function to log the event info   
	logEvent: function(event, xhr, settings, err) {
		var s = 'event: ' + event.type;
		
		// don't access the xhr's 'status' prop too soon (some browsers will generate errors)
		if (xhr && xhr.readyState > 1)
			s += ';  statusCode: ' + xhr.status;
	
		// access our settings object
		if (settings)
			s += ';  url: ' + settings.url;
			
		// log error message if there is one
		if (err)
			s += ';  error: ' + err;
			
		// add new div to log element
		jQuery('#log').prepend('<div>'+s+'</div>');
	},
	
	blade_url: 'http://www.giorgiotesivivai.it/catalogo/index.php/api/',
	theme_url: '',

	selected:  [],

	accessKey: '4629y2Z8RJ9K767k',
	logged: 0,
	userLevel: 0,

	language: 'it_IT', // default it_IT [en_US, ...]
	
	sendok: false,
	total_items: 0,
		
	currTableName: 'catalogo',
	countItems: 0,
	currPage: 0,
	pagelimit: 10,

	search_value: '_',
	fullsearch_value: '_',
	
	anni_id: 'year',
	tecnica_id: 'tecnica',
	titolo_id: 'titolo',
	
	waiting_id: 'blade-waiting',
	search_box_id: 'blade-header',
	header_id: '-title',
	results_id: 'blade-results',
	scheda_id: 'card-container',
	title_results: 'title-results',
	title_card: 'title-card',
	cart_id: 'blade-cart-content',
	cart_message: 'blade-cart-message',
	cart_form_id: 'cart-form',
	
	cart_form_content: 'blade-cart-form-content',
	cart_form_title: 'send',
	cart_form_header: 'blade-cart-header',
	
	cart_is_info_opened: false,
	cart_show_all: 'blade-cart-show-all',

	catalog_is_info_opened: false,
	
	main_container: 'container',
	blade_container: 'blade-container',
	blade_pagination: 'blade-pagination',
	
	fullsearch_id: 'fullsearch',
	
	updateList: true,
	
	init: function() {

		// bind global ajax event handlers
		jQuery().ajaxStart(jBlade_Connect.onStart)
			.ajaxStop(jBlade_Connect.onStop)
			.ajaxSend(jBlade_Connect.onSend)
			.ajaxComplete(jBlade_Connect.onComplete)
			.ajaxSuccess(jBlade_Connect.onSuccess)
			.ajaxError(jBlade_Connect.onError);		

		// jQuery('#blade-cart-content').addClass('loading');

		jQuery('.bar-title').hover(
			function(){ 
				jQuery('#'+this.id).addClass('hover'); 
			},
			function(){ 
				jQuery('#'+this.id).removeClass('hover'); 
			}
		).click(function(e){
			switch(this.id) {
				case 'reset':
					jBlade_Connect.resetCart();
					break;
				case 'send':
					if(jBlade_Connect.isValidCart()) {
						jQuery('.'+jBlade_Connect.cart_form_content).slideToggle('normal', function(){
							var display = jQuery('.'+jBlade_Connect.cart_form_content).css('display');
							if((display=='block'))
								jQuery.scrollTo(jQuery('#'+jBlade_Connect.cart_form_title), 800 );
							else
								jQuery.scrollTo(jQuery('.'+jBlade_Connect.main_container), 800 );
						});
					} else {
						jQuery('.'+jBlade_Connect.cart_form_content).slideUp();
					}
					break;
			}
			e.stopPropagation();
		});

		jQuery('.button-bar > input').each(function (elem) {
			jQuery(this).click(function(e) {
				switch(this.id) {
					case 'sendmail':
						// jBlade_Connect.sendCart();
						jQuery('#'+jBlade_Connect.cart_form_id).submit();
						break;
					case 'cancelmail':
						jQuery('.'+jBlade_Connect.cart_form_content).slideToggle();
						jQuery.scrollTo(jQuery('.'+jBlade_Connect.main_container), 800 );
						break;
					case 'sendsearch':
						jBlade_Connect.fullSearch()
						break;
				}
				e.stopPropagation();
			});
		});

		jQuery('#sendsearch').click(function(e) {
			jBlade_Connect.fullSearch();
			e.stopPropagation();
		});
		
		jQuery('#'+jBlade_Connect.fullsearch_id).keydown(function(e) {
			// track last key pressed
			// lastKeyPressCode = e.keyCode;
			switch(e.keyCode) {
				case 9:  // tab
				case 13: // return
					jBlade_Connect.fullSearch();
					e.preventDefault();
					break;
				default:
					if(jBlade_Connect.fullsearch_value != jQuery(this).val()) {
						jQuery('#sendsearch').show();
						jQuery('#clearsearch').hide();
					}
					break;
			}
		}).keyup(function(e){
			switch(e.keyCode) {
				case 9:  // tab
				case 13: // return
					// jBlade_Connect.fullSearch();
					// e.preventDefault();
					break;
				default:
					if(jBlade_Connect.fullsearch_value != jQuery(this).val()) {
						jQuery('#sendsearch').show();
						jQuery('#clearsearch').hide();
					}
					break;
			}
		});

		jQuery('#clearsearch').click(function(e) {
			jQuery('#'+jBlade_Connect.fullsearch_id).val('');
			jBlade_Connect.clearData();
			jBlade_Connect.updateCatalogoList();
			e.stopPropagation();
		});

/*
		jQuery('#button-search').click(function(e) {
			jQuery('#blade-search').slideToggle();
			e.stopPropagation();
		});
*/
		jQuery('#blade-search').hide();

		jQuery('.alphabetic-search > span').each(function (elem) {
			jQuery(this).click(function(e) {
				var selected = jQuery(this).hasClass('selected');
				// jQuery('.alphabetic-search > span').removeClass('selected');
				jQuery('#'+jBlade_Connect.fullsearch_id).val('');
				jBlade_Connect.clearData();
				if(selected) {
				} else {
					jQuery(this).addClass('selected');
					jBlade_Connect.search_value = this.id;
				}
				jBlade_Connect.updateCatalogoList();
				e.stopPropagation();
			});
		});
		
		jQuery('#'+this.cart_form_id).formValidation({
			err_class : "invalidInput"
		,	callback : jBlade_Connect.sendCart
		,	err_message : "Please fill all required fields! (Marked with red background colour)\n"
		,	display_alert : false
		});
		
		jQuery('#'+this.cart_show_all).click(function(e) {
			jQuery('.other-info').each(function (elem) {
				if(this.cart_is_info_opened)
					jQuery(this).hide();
				else
					jQuery(this).show();
				this.cart_is_info_opened = !this.cart_is_info_opened;
			});
			e.stopPropagation();
		}).css({'cursor':'pointer'});

	/* bubbleInfo */
        jQuery('.bubbleInfo').each(function () {
            var distance = 10;
            var time = 250;
            var hideDelay = 500;

            var hideDelayTimer = null;

            var beingShown = false;
            var shown = false;
            var trigger = jQuery('.popup-trigger', this);
            var info = jQuery('.help-popup', this).css('opacity', 0);
            
            jQuery([trigger.get(0), info.get(0)]).mouseover(function () {
				var position = jQuery(this).position();
				var width1 = jQuery(this).width();
				var height1 = jQuery(this).height();
				var width = jQuery('.bubbleInfo').width();
				var height = (jQuery('.bubbleInfo').height()==0)?143:jQuery('.bubbleInfo').height();

				var top =  position.top - ((height/2) - (height1/2));
				var left =  position.left - ((width/2) - (width1/2));

                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (beingShown || shown) {
                    // don't trigger the animation again
                    return;
                } else {
                    // reset position of info box
                    beingShown = true;

                    info.css({
                        top: top - (height/2),
                        left: left,
                        display: 'block'
                    }).animate({
                        top: '-=' + distance + 'px',
                        opacity: 1
                    }, time, 'swing', function() {
                        beingShown = false;
                        shown = true;
                    });
                }

                return false;
            }).mouseout(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                hideDelayTimer = setTimeout(function () {
                    hideDelayTimer = null;
                    info.animate({
                        top: '-=' + distance + 'px',
                        opacity: 0
                    }, time, 'swing', function () {
                        shown = false;
                        info.css('display', 'none');
                    });

                }, hideDelay);

                return false;
            });
        });
	/**/
	
		this.clearData();
		// this.updateCatalogoList();
	},
	
	bindLayout: function() {
		jQuery('.c-item').each(function (elem) {
			jQuery(this).click(function(e) {
				jQuery('#c-item-info-edit-'+this.id.split("-")[1]).hide();
				jQuery('#'+this.id+' > .c-item-info').slideToggle();
				jQuery('#'+this.id).toggleClass('opened');
				e.stopPropagation();
			});
		if(false) {
			jQuery(this).hover(
				function(){ 
					jQuery('#'+this.id).addClass('hover');
					jQuery('#'+this.id+' > .info-trigger').show();
				},
				function(){ 
					jQuery('#'+this.id).removeClass('hover'); 
					jQuery('#'+this.id+' > .info-trigger').hide();
				}
			);
		}
		});

		jQuery('.box-description').jTruncate({  
			/* length: 200, */  
			/* minTrail: 0, */  
			moreText: "[more]",  
			lessText: "[less]",  
			ellipsisText: "&#8230;",  
			moreAni: "normal",  
			lessAni: "normal"  
		}); 
		
		jQuery('.cmd-link').each(function (elem) {
			jQuery(this).click(function(e) {
				jBlade_Connect.handleCommand(this);
				e.stopPropagation();
			});
		});

		jBlade_Connect.catalog_is_info_opened = false;
		jQuery('#show-all-info').click(function(e) {
			jQuery('.c-item').each(function (elem) {
				// jQuery('#c-item-info-edit-'+this.id.split("-")[1]).hide();
				// jQuery('#'+this.id+' > .c-item-info').slideToggle();
				// jQuery('#'+this.id).toggleClass('opened');
				jQuery('#c-item-info-edit-'+this.id.split("-")[1]).hide();
				if(jBlade_Connect.catalog_is_info_opened) {
					jQuery('#'+this.id+' > .c-item-info').show();
					jQuery('#'+this.id).addClass('opened');
				} else {
					jQuery('#'+this.id+' > .c-item-info').hide();
					jQuery('#'+this.id).removeClass('opened');
				}
			});
			jBlade_Connect.catalog_is_info_opened = !jBlade_Connect.catalog_is_info_opened;
			e.stopPropagation();
		}).css({'cursor':'pointer'});

/*
		jQuery('.box-image > img').each(function (elem) {
			jQuery(this).click(function(e) {
				// alert(this.id);
				e.stopPropagation();
			});
		});
*/

/*
		jQuery('a.thickbox').thickbox({
			macFFBgHack: jBlade_Connect.theme_url+'images/macFFBgHack.png',
			loadingImage: jBlade_Connect.theme_url+'images/thickbox-loading.gif'
		});
*/
		// lightbox activation
		if (jQuery.facebox) 
			jQuery('a[rel*=facebox]').facebox({
				loadingImage : jBlade_Connect.theme_url+'css/facebox/loading.gif',
				closeImage   : jBlade_Connect.theme_url+'css/facebox/closelabel.gif',
				next_image    : jBlade_Connect.theme_url+'css/facebox/icons/small/fast_forward.png',
				play_image    : jBlade_Connect.theme_url+'css/facebox/icons/small/play.png',
				pause_image   : jBlade_Connect.theme_url+'css/facebox/icons/small/pause.png',
				prev_image    : jBlade_Connect.theme_url+'css/facebox/icons/small/rewind.png'
			}) 
	},
	
	handleCommand: function(elem) {
		var e_split = elem.id.split("-");
		var action = e_split[0];
		var id = e_split[1];
		
		switch(action) {
			case 'edit':
				jBlade_Connect.edit(id);
				// jQuery('#c-item-info-no-' + elem.id).slideToggle();
				// jQuery('#c-item-info-' + elem.id).slideToggle();
				break;
				
			case 'remove':
				if(confirm('[Comando non abilitato] Rimuovo elemento ' + id)) {
					
				};
				break;
				
			case 'add':
				jBlade_Connect.addCart(id);
				break;
				
			case 'removeimage':
				if(confirm('Vuoi veramente elimiare questa immagine?')) {
					var filename = id;
					
					jQuery('#browser-image').block({ message: null });
					var url = jBlade_Connect.blade_url+'catalogo/remove_image/'+jBlade_Connect.serializeSearch(true);
					var serialize = {id: jQuery("#id").val(), filename: filename};
					jQuery.post(url, serialize,
						function(data){
							if(data.status == 'ok') {
								var api = jQuery("#chained").scrollable(); 
								api.getItems().filter("[id*="+filename+"]").remove(); 
								api.reload();
							}						
							jQuery('#browser-image').unblock();
						}, "json");
	
				}
				break;

			case 'currentimage':
				jQuery('#browser-image').block({ message: null });
				var cid = jQuery("#id").val();
				var url = jBlade_Connect.blade_url+'catalogo/set_current_image/'+jBlade_Connect.serializeSearch(true);
				var serialize = {id: cid, genere_cod: jQuery("#genere_cod").val(), varieta_cod: jQuery("#varieta_cod").val(), filename: id};
				jQuery.post(url, serialize,
					function(data){
						if(data.status == 'ok') {
							if(data.url!='') jQuery('#cimage-'+cid).attr('src', data.url);
						}						
						jQuery('#browser-image').unblock();
					}, "json");
				break;
		}
	},
	
	clearData: function() {
		jQuery('.alphabetic-search > span').removeClass('selected');
		this.search_value = '_';
		this.fullsearch_value = '_';
		this.countItems = 0;
		this.currPage = 0;
		this.total_items = 0;
		this.selected = [];
		jQuery('#sendsearch').show();
		jQuery('#clearsearch').hide();
	},
	
	showhideAllInfo: function(show) {
		jQuery('.c-item-info-no').each(function (elem) {
			if(show) {
				jQuery(this).show();
			} else {
				jQuery(this).hide();
			}
		});		
	},
	
	showhideEditInfo: function(id, show) {
		if(show) {
			jQuery('#c-item-info-no-'+id).hide();
			jQuery('#c-item-info-edit-'+id).show();
		} else {
			jQuery('#c-item-info-no-'+id).show();
			jQuery('#c-item-info-edit-'+id).hide();
		}
		jQuery.Event.stopPropagation();
	},
	
	serializeSearch: function(segment) {
		var result;
		if(segment) {
			result = this.accessKey + '/' + this.logged + '/' + this.userLevel + '/' + this.currPage + '/' + this.pagelimit + '/' + this.search_value + '/' + this.fullsearch_value + '/' + this.language;
;
		} else {
			result = 'key=' + this.accessKey + '&logged=' + this.logged + '&userlevel=' + this.userLevel + '&page=' + this.currPage + '&limit=' + this.pagelimit + '&searchvalue=' + this.search_value + '&fullsearchvalue' + this.fullsearch_value + '&language' + this.language;
		}
		return escape(result);
	},
	
	showSearch: function() {
		
	},
		
	fullSearch: function() {
		var fieldValue = jQuery('#'+this.fullsearch_id).val();
		this.clearData();
		this.fullsearch_value = fieldValue;
		if(this.fullsearch_value!='') {
			jQuery('#sendsearch').hide();
			jQuery('#clearsearch').show();
		} else {
			this.fullsearch_value = '_';
		}
		this.updateCatalogoList();
	},
	
	updateCatalogoList: function(search) {
		if((search) && (search=='new')) this.currPage = 0;
		
		var url = this.blade_url+'catalogo/search/'+this.serializeSearch(true)+'/'+this.results_id;
		if(search) {url += '/'+search;} else {url += '/new';}
		var params = this.serializeSearch()+'&elem='+this.results_id;
		if(search) {params += '&search='+search;} else {params += '&search=new';}

		jQuery('#'+this.results_id).load(url, jBlade_Connect.bindLayout);
	},
	
	showPage: function(page, count) {
		this.currPage = page;
		this.updateCatalogoList('page');
	},
	
	addCart: function(id) {
		if (this.selected.indexOf(id) == -1) {
			var url = this.blade_url+'catalogo/addcart/'+this.serializeSearch(true);
			jQuery('.basket').addClass('loading');
			jQuery.post(url, { elem_id: id },
				function(data){
					jBlade_Connect.processJSON_cart(data);
					jQuery('.basket').removeClass('loading');
				}, "json");
		} else {
			this.alert('duplicate');
			jQuery('#cart-item_'+id).effect("pulsate", { times:2 }, 500);
		}
	},

	delCart: function(id) {
		var url = this.blade_url+'catalogo/delcart/'+this.serializeSearch(true);
		jQuery('.basket').addClass('loading');
		jQuery.post(url, { elem_id: id },
			function(data){
				// jBlade_Connect.processJSON_cart(data);
				jQuery('#cart-item_'+id).remove();
				jQuery('.basket').removeClass('loading');
			}, "json");
	},
	
	updateCartAmount: function() {
		var url = this.blade_url+'catalogo/updatecartamount/'+this.serializeSearch(true);
		jQuery('.basket').addClass('loading');
		var serialize = jQuery('#'+jBlade_Connect.cart_form_id).serializeArray();
		jQuery.post(url, serialize,
			function(data){
				jQuery('#'+jBlade_Connect.cart_message).html('');
				// jBlade_Connect.processJSON_cart(data);
				jQuery('.basket').removeClass('loading');
			}, "json");
	},

	updateCart: function() {
		var url = this.blade_url+'catalogo/updatecart/'+this.serializeSearch(true);
		jQuery('.basket').addClass('loading');
		jQuery.post(url, { elem_id: 0 },
			function(data){
				jBlade_Connect.processJSON_cart(data);
				jQuery('.basket').removeClass('loading');
			}, "json");
	},
	
	resetCart: function() {
		var url = this.blade_url+'catalogo/resetcart/'+this.serializeSearch(true);
		jQuery('.basket').addClass('loading');
		jQuery.post(url, { elem_id: 0 },
			function(data){
				jBlade_Connect.selected = [];
				jBlade_Connect.total_items = 0;
				jQuery('#'+jBlade_Connect.cart_form_header).hide();
				jQuery('#'+jBlade_Connect.cart_id).hide();
				jQuery('#'+jBlade_Connect.cart_message).html(Blade_Language.getTxt('cart.default_message', jBlade_Connect.language));
				jQuery('#'+jBlade_Connect.cart_id).html('');
				jQuery('.basket').removeClass('loading');
				jQuery.scrollTo(jQuery('.'+jBlade_Connect.main_container), 800 );
			}, "json");
	},
	
	isValidCart: function() {
		var valid = true;
		
		jQuery('input[name*=qta]').each(function (elem) {
			if((jQuery(this).val()=='0') || jQuery(this).val()=='') valid = false;
		});
		
		if(valid) {
			if(jBlade_Connect.total_items == 0) {
				valid = false;
				jQuery('#'+jBlade_Connect.cart_message).html(Blade_Language.getTxt('cart.empty', jBlade_Connect.language));
				jQuery.scrollTo(jQuery('.'+jBlade_Connect.main_container), 800 );
			}
		} else {
			jQuery('#'+jBlade_Connect.cart_message).html(Blade_Language.getTxt('cart.no_quantita', jBlade_Connect.language));
			jQuery.scrollTo(jQuery('.'+jBlade_Connect.main_container), 800 );
		}
		
		return valid;
	},
	
	sendCart: function() {
		if(jBlade_Connect.isValidCart()) {
			jQuery('div.'+jBlade_Connect.cart_form_content).block({ message: null });
			var url = this.blade_url+'catalogo/sendcart/'+this.serializeSearch(true);
			jQuery('.basket').addClass('loading');
			var serialize = jQuery('#'+jBlade_Connect.cart_form_id).serializeArray();
			jQuery.post(url, serialize,
				function(data){
					jQuery('div.'+jBlade_Connect.cart_form_content).unblock();
					jBlade_Connect.selected = [];
					jBlade_Connect.total_items = 0;
					jQuery('#'+jBlade_Connect.cart_message).html(Blade_Language.getTxt('cart.success', jBlade_Connect.language));
					jQuery('#'+jBlade_Connect.cart_id).hide();
					jQuery('#'+jBlade_Connect.cart_id).html('');
					jQuery('.'+jBlade_Connect.cart_form_content).slideToggle();
					jQuery('.basket').removeClass('loading');
				}, "json");
		} else {
			jQuery('.'+jBlade_Connect.cart_form_content).slideUp();
		}
	},
	

	processJSON_cart: function(data) {
		if(data.status == 'ok') {
			var t = jQuery.template('<div id="cart-item_${id}" class="cart-item success"><span id="cart-descr_${id}" class="description left">[${id}] ${genere}-${varieta}</span><span class="qta right"><input type="hidden" name="id[]" value="${id}" /><input id="qta_${id}" type="text" name="qta[]" required="true" mask="numeric" value="0" class="text right" style="width: 40px;text-align: right;" /></span></div><div class="clear"></div><div id="info-cart-descr_${id}" class="other-info" style="display: none;"><div class="span-1">${condizionamento}</div><div class="span-1">${contenitore}</div><div class="span-1">&nbsp;${altezza_cod}</div><div class="span-1">&nbsp;${circonferenza_cod}</div><div class="span-2 text-right">${euro}</div></div><div class="clear"></div>');

			if(data.total == 1) {
				if(jBlade_Connect.total_items == 0) {
					jQuery('#'+jBlade_Connect.cart_form_header).show();
					jQuery('#'+jBlade_Connect.cart_id).show();
				}
				jBlade_Connect.selected.push(data.id);	
				jBlade_Connect.total_items++;
				jQuery('#'+jBlade_Connect.cart_message).html('');
				jQuery('#'+jBlade_Connect.cart_id).append(t, {
					id: data.id,
					varieta: data.varieta,
					varieta_cod: data.varieta_cod,
					genere: data.genere,
					genere_cod: data.genere_cod,
					varieta: data.varieta,
					varieta_cod: data.varieta_cod,
					condizionamento: data.condizionamento,
					condizionamento_cod: data.condizionamento_cod,
					contenitore: data.contenitore,
					contenitore_cod: data.contenitore_cod,
					circonferenza: data.circonferenza,
					circonferenza_cod: data.circonferenza_cod,
					altezza: data.altezza,
					altezza_cod: data.altezza_cod,
					euro: data.euro
				});
				
				jQuery("#cart-descr_"+data.id).click(function(){jQuery('#info-'+this.id).slideToggle();});
				jQuery("#qta_"+data.id).change(function(){jBlade_Connect.updateCartAmount();});
			} else { // updateCart
				if(data.total == 0) {
					if(jBlade_Connect.total_items == 0) {
						jQuery('#'+jBlade_Connect.cart_form_header).hide();
						jQuery('#'+jBlade_Connect.cart_id).hide();
					}
					jQuery('#'+jBlade_Connect.cart_message).html(Blade_Language.getTxt('cart.default_message', jBlade_Connect.language));
				} else {
					if(jBlade_Connect.total_items == 0) {
						jQuery('#'+jBlade_Connect.cart_form_header).show();
						jQuery('#'+jBlade_Connect.cart_id).show();
					}
					jBlade_Connect.selected = [];
					jBlade_Connect.total_items = 0;
					jQuery('#'+jBlade_Connect.cart_message).html('');
					jQuery('#'+jBlade_Connect.cart_id).html('');
					for(var i=0;i<data.total;i++) {
						jBlade_Connect.selected.push(data.elems[i].id);	
						jBlade_Connect.total_items++;
						jQuery('#'+jBlade_Connect.cart_id).append(t, {
							id: data.elems[i].id,
							varieta: data.elems[i].varieta,
							varieta_cod: data.elems[i].varieta_cod,
							genere: data.elems[i].genere,
							genere_cod: data.elems[i].genere_cod,
							varieta: data.elems[i].varieta,
							varieta_cod: data.elems[i].varieta_cod,
							condizionamento: data.elems[i].condizionamento,
							condizionamento_cod: data.elems[i].condizionamento_cod,
							contenitore: data.elems[i].contenitore,
							contenitore_cod: data.elems[i].contenitore_cod,
							circonferenza: data.elems[i].circonferenza,
							circonferenza_cod: data.elems[i].circonferenza_cod,
							altezza: data.elems[i].altezza,
							altezza_cod: data.elems[i].altezza_cod,
							euro: data.elems[i].euro
						});
						jQuery("#cart-descr_"+data.elems[i].id).click(function(){jQuery('#info-'+this.id).slideToggle();});
						jQuery("#qta_"+data.elems[i].id).change(function(){jBlade_Connect.updateCartAmount();});
					}
				}
			}
		} else {
			jQuery('#'+jBlade_Connect.cart_message).html('<p class="error">ERRORE</p>').fadeOut(8000, jBlade_Connect.showMessage);
		}
	},
	
	showMessage: function() {
		jQuery('#'+jBlade_Connect.cart_message).html('').fadeIn();
	},
	
	showOpera: function(codice) {
		if ((codice != '')) {
			var url = this.blade_url+'api/opere/get_opera/'+this.accessKey+'/'+codice+'/'+this.scheda_id;
			var params = 'api='+this.accessKey+'&id='+codice+'&elem='+this.scheda_id;
			new Ajax.Request(url, {
				crossSite: true,
				evalScripts: true, 
				method: 'get',
				parameters: params,
				onSuccess: function(request) {
					Effect.BlindUp(this.search_box_id, {duration: 0.5});
					$('master-hide').hide();
					$('master-show').show();
					$(this.results_id+'-title').hide();
					$(this.scheda_id+'-title').show();
					$(this.scheda_id+'-back').show();
					new Effect.Appear(this.scheda_id, {});
					new Effect.Fade(this.results_id, {});
					// this.hideWaiting();
					new Effect.ScrollTo(this.scheda_id,{});
				}.bind(this)
			});
		}
	},
	
	showCatalogoList: function() {
		this.updateCatalogoList();
		jQuery('.post').fadeOut();
		jQuery('#'+this.blade_container).fadeIn();
		jQuery('#'+this.blade_pagination).fadeIn();
		jQuery('#blade-search').fadeIn();
	},
	hideCatalogoList: function() {
		jQuery('.post').fadeIn();
		jQuery('#'+this.blade_container).fadeOut();
		jQuery('#'+this.blade_pagination).fadeOut();
		jQuery('#blade-search').fadeOut();
	},
	
	edit: function(id) {
		var url = this.blade_url+'catalogo/show_edit/'+this.serializeSearch(true)+'/'+id;
		jQuery.facebox({ ajax: url });
	},

	save: function() {
		jQuery('#edit-form').block({ message: null });
		var url = this.blade_url+'catalogo/save_detail/'+this.serializeSearch(true);
		var serialize = jQuery('#edit-form').serializeArray();
		jQuery.post(url, serialize,
			function(data){
				jQuery('#edit-form').unblock();
			}, "json");
	},
	
	upload: function() {
		jQuery('#uploadify').uploadifySettings('scriptData', {
						'id' : jQuery("#id").val(),
						'update_famiglia' : jQuery("#update_famiglia").is(':checked'),
						'update_only_famiglia' : jQuery("#update_only_famiglia").is(':checked')
					});

		jQuery('#uploadify').uploadifyUpload();
	},
	
/*
 * Utilities
 *
 */
 
	alert: function(s, msg) {
		if(msg==undefined) msg='';
		jQuery.facebox(Blade_Language.getTxt(s, jBlade_Connect.language)+msg);
	},
	
	serializeCartElements: function(c) {
		var result = new Array();
		var elements = jQuery('.cart-item');
		jQuery.each(elements, function(){
		  result.push(this.id.split("_")[1]);
		});
		if(c!='') {
			return result.join(c);
		} else {
			return result;
		}
	},
	
	getSelected: function() {
		var sel = this.selected;
		if (sel.length==0) {
		  this.nothingSelected = true;
		  return [];
		}
		this.nothingSelected = false;
		return sel;
	}
	
};
