Element.addMethods({
	lock : function(el) {
		el = $(el);
		if (!el.visible()) {
			return;
		}	
		var id = $(el).identify();
		var overlay = $('loading-overlay' + id);
		var indicator = $('loading-overlay-indicator' + id);
		if (!overlay) {
			overlay = new Element('div', {
				id: 'loading-overlay' + id,
				style:'position:absolute;z-index:1000;background:#FFF'		
			}).setOpacity(0.75);			
			indicator = new Element('img', {
				id : 'loading-overlay-indicator' + id,
				src : '/Content/skins/default/img/indicator.gif',	
				width:'10px',
				height:'10px',
				style:'position:absolute;z-index:1001;left:-10px;top:-10px;'
			});
			var body = document.getElementsByTagName('body')[0];
			body.appendChild(overlay);
			body.appendChild(indicator);
		}

		var elPos = el.cumulativeOffset();
		var elScrollPos = el.cumulativeScrollOffset();
		var elSize = el.getDimensions();
		var posX = elPos[0] - elScrollPos[0];
		var posY = elPos[1] - elScrollPos[1];
		
		overlay.setStyle({
			width : elSize.width + 'px',
			height : elSize.height + 'px',
			top : posY + 'px',
			left : posX + 'px'
		});	
		indicator.setStyle({
			top : (posY - 5 + elSize.height/2) + 'px',
			left : (posX - 5 + elSize.width/2) + 'px'
		});
		
		window.setTimeout(function(){
			overlay.show();	
			indicator.show();				
		},1);
	},
	unlock : function(element) {
		var id = $(element).identify();
		window.setTimeout(function(){
			if ($('loading-overlay' + id)) {
				$('loading-overlay' + id).remove();
				$('loading-overlay-indicator' + id).remove();
			}
		}, 1);
	}
});
var Application = {
	initPopups : function() {		
        var popupArea = $('popup-area');
        var popupToggles = $('header-nav').select('.popup-toggle');
        var popupAreas = popupArea.select('.area-frame');
        var popupAnimation = null;
        
        var clearAnimation = function() {
        	popupAnimation = null;
        };
        
        var hidePopup = function(frame) {
        	popupAnimation = new Effect.SlideUp(frame, {
                duration:0.4,
                afterFinish: function() {
                    popupArea.hide();
                    clearAnimation();
                }
            });
        };
                
		$('toggle-close').observe('click', function(e) {
	    	e.stop();
	    	this.blur();
	    	hidePopup('search-frame');
		});
		$('close-cart-popup').observe('click', function(e) {
	    	e.stop();
	    	this.blur();
	    	hidePopup('cart-frame');
		});
		
		var togglePopup = function(btn, forceOpen) {		
	            if (popupAnimation) {
	            	return;
	            }
	            var id = btn.id.replace('-toggle', '');
	            var frame = $(id + '-frame');
	            
	            if (id == 'cart' && $('checkout-page')) 
	            {
	                window.location.href = '/checkout/gostep.shop?step=1';
	                return;
	            }
	            
	            if (frame.visible() && !forceOpen) {
	            	hidePopup(frame);
	            	return;
	            }
	            if (forceOpen) {
	            	popupAreas.each(function(area){
	            		if (area.id == frame.id || !area.visible())
	            			return;
	            		new Effect.SlideUp(area, {duration:0.4});
	            	});
	            	popupArea.show();
	            	if (frame.visible())
	                    return;
	            }
	            else if (popupArea.visible()) {
	            	popupAreas.each(function(area){
	            		if (area.id == frame.id)
	            			return;
	            		new Effect.SlideUp(area, {duration:0.4});
	            	});
	            } else {
	                popupArea.toggle();
	            }
				popupAnimation = new Effect.SlideDown(frame, {duration:0.4, afterFinish: clearAnimation});
		};

        if ($('recent-searches-area')) {
            var links = $A($('recent-searches-area').getElementsByTagName('a'));
            links.each(function(link) {
                link.observe('click', function(e) {
                    e.stop();
                    $('search-text').value = this.innerHTML;
	                $('search-toggle').fire('custom:open');
                });
            });
        }
        
        popupToggles.each(function(btn){
	        btn.observe('click', function(e) {
	            e.stop();
	            this.blur();
	            togglePopup(btn)
	        });
	        btn.observe('custom:open', function(e) {
	            togglePopup(btn, true)
	        });
        });
	},
	initSearch : function() {
    	var searchButton = $('search-btn');
    	var text = $('search-text');
    	
    	var triggerSearch = function(query, page) {
    		if (!query) {
    			query = $F('search-text').strip();
    		}
    		if (!query)
    			return;
    		text.value = query;
    		text.disabled = true;
    		
    		if (!page)
    			page = 0;
    		
    		searchButton.lock();
        	ProductService.FindProducts(query, {Page : page, PageSize: 10}, updateSearchResults);
    	};
    	
    	text.observe('keypress', function(e) {
    		if (e.keyCode == Event.KEY_RETURN) {
    			e.stop();
    			triggerSearch();
    		}
    	});
    	
    	var updateSearchResults = function(result) {
    		text.disabled = false;
    		$('search-btn').unlock();
    		if (!result.Items.length){
    			$('search-results').update(Templates.SearchResultsNone.interpolate({query:text.value}));
    			return;
    		}
    		$('search-results').update(Templates.SearchResultsFound.interpolate(result));
    		var format = Templates.SearchRow;
    		$A(result.Items).each(function(item){
    			var row = new Element('li', {className: 'row'}).update(format.interpolate(item));
    			row.observe('mouseover', function(){
    				row.addClassName('hover');
    			});
    			row.observe('mouseout', function(){
    				row.removeClassName('hover');
    			});
    			row.observe('click', function(){
    			    window.location.href='/prodotto/#{ProductNumber}/#{Title}'.interpolate(
    			    {
    			        ProductNumber: item.ProductNumber,
    			        Title : encodeURIComponent(item.Title.replace(/[^a-zA-Z0-9]+/gi, '-'))
    			    });
    			});
    			$('search-results').insert(row);
    		});
    		
    		// Add Navigation Links
    		var secondary = $('search-results').select('.secondary');
			secondary.each(function(cell){
				var link = new Element('a', {href:'#'}).update('indietro');
				link.observe('click', function(e){
					e.stop();
					this.blur();
					triggerSearch(result.Query, result.Page - 1);
				});
	    		if (result.PageStart == 1) {
	    			link = new Element('span').update('indietro');
	    		}
	    		cell.insert(link);
	    		cell.insert(' / ');
	    		link = new Element('a', {href:'#'}).update('avanti');
	    		link.observe('click', function(e){
					e.stop();
					this.blur();
					triggerSearch(result.Query, result.Page + 1);
				});
	    		if (result.ResultCount <= result.PageEnd) {
	    			link = new Element('span').update('avanti');
	    		}
	    		cell.insert(link);
			});
    	};
    	searchButton.observe('click', function(e) {
    		e.stop();
    		this.blur();
    		triggerSearch();
    	});
	},
    init : function() {
    	Application.initPopups();
    	Application.initSearch();
    	var links = $('side-bar-links').select('a.toggleable');
    	var updateSidebar = function(result, el) {
    		el.update(result)
    	};
    	
    	if ($('toggle-change-password')) {
    	    $('toggle-change-password').observe('click', function(e) {
    	        e.stop();
    	        $$('tr.change-password').invoke('toggle');
    	    });
    	}
    	$$('input.checkout-option').each(function(item) {
    	    item.observe('click', function() {
    	        $('cart-total-checkout').update($F(item.id + '-value'));
    	    });
    	    if (item.checked) {
    	        $('cart-total-checkout').update($F(item.id + '-value'));
    	    }
    	});
    	if ($('step3-form')) {
    	    $('step3-form').observe('submit', function(e) {
    	        if ($('option-3').checked && parseInt($F('Store')) == 0) {
    	            e.stop();
    	            alert("Devi selezionare il punto vendita da cui ritirare la merce");
    	        }
    	        
    	    });
    	}
    	if ($('privato') && $('newUser_businessName')) {
    	    var showBusiness = function(show) {
    	        $('newUser_businessName').disabled = !show;
    	        $('newUser_vatNumber').disabled = !show;
    	        $('newUser_codiceFiscale').disabled = show;
    	        
    	        var businessName = $('newUser_businessName').up().up().getElementsByTagName('label')[0];
    	        var vatNumber = $('newUser_vatNumber').up().up().getElementsByTagName('label')[0];
    	        var codiceFiscale = $('newUser_codiceFiscale').up().up().getElementsByTagName('label')[0];
    	        
    	        if (show) {
    	            businessName.removeClassName('disabled');
    	            vatNumber.removeClassName('disabled');
    	            codiceFiscale.addClassName('disabled');
    	            $('newUser_businessName').removeClassName('disabled');
    	            $('newUser_vatNumber').removeClassName('disabled');
    	            $('newUser_codiceFiscale').addClassName('disabled');
    	        } else {
    	            businessName.addClassName('disabled');
    	            vatNumber.addClassName('disabled');
    	            codiceFiscale.removeClassName('disabled');
    	            $('newUser_businessName').addClassName('disabled');
    	            $('newUser_vatNumber').addClassName('disabled');
    	            $('newUser_codiceFiscale').removeClassName('disabled');
    	        }
    	    };
    	    $('privato').observe('click', function() {
    	        showBusiness(false);
    	    });
    	    $('azienda').observe('click', function() {
    	        showBusiness(true);
    	    });
    	    showBusiness($('azienda').checked); 
    	}
    	
    	links.each(function(link){
    		link.observe('click', function(e){
    			e.stop();
    			this.blur();
    			
    			var detail = this.next();
    			detail.toggle();
    			if (detail.visible()) {
    				this.addClassName('is-open');
    			} else {
    				this.removeClassName('is-open');
    			}
    		});
    	});
    }
};
document.observe('dom:loaded', Application.init);