/*
 * Product Manager
 * @author Stefano Aurilio <stefano.aurilio@triboo.it>
 */

function ProductManager(){
               
    var _mainProductId            = -1;
    var _mainProductAttributesMap = [];
    var _productsByAttributeMap   = [];
    var _productsPriceMap         = [];
    var _productsImageMap         = [];
    var _productsQtyMap           = [];
    var _priceStyleIdPrefix       = 'product-price-';
    var _priceAreaStyleId         = null;
    var _productIdHidden          = 'productId';
    var _cheaperProductId         = 0;
    
    /* --- PRIVATE SCOPE --- */
   
    function _init(config){
		_mainProductId            = config.fatherProductId;
		_mainProductAttributesMap = config.fatherAttributeIds;
		_productsByAttributeMap   = config.productsByAttribute;
		_productsPriceMap         = config.productsPrice;
		_productsImageMap         = config.productsImage;
		_productsQtyMap           = config.productsQty;
		_cheaperProductId         = config.cheaperProductId;
		_priceAreaStyleId         = _priceStyleIdPrefix + _mainProductId;	
    }//End of method
   
    function _arrayIn(findme, array){
        var foundIt = false;
        for(var i=0; i<array.length; i++){        	
			if(array[i] == findme){
				foundIt = true;
            	break;
          	}
        }
       
        return foundIt;  
    }//End of method

    function _arrayIntersect(array1, array2){
        var intersect = [];
        for(var i=0; i<array1.length; i++){
			var item = array1[i];
                if(array2!=undefined){
                    for(var j=0; j<array2.length; j++){
                    if(item == array2[j] && !_arrayIn(item, intersect))
                                            intersect.push(item);
                    }
                }
        }
       
        return intersect;
    }//End of method
    
    function _getAllChildIds(){    	
    	var childProductIds = new Array();
    	for(var productId in _productsPriceMap){
    		childProductIds.push(productId);
    	}
    	
    	return childProductIds;
    }//End of method
    
    function _getMinPriceObj(productIds){
    	var minPrice = 0;
    	var priceObj = null;
    	for(var i=0; i<productIds.length; i++){    		
    		var productId  = productIds[i];
			var mapValue   = _productsPriceMap[productId];
			var priceValue = parseFloat(mapValue['priceValue']);
			if(i==0){
				minPrice = parseFloat(priceValue);
				priceObj = mapValue;
			}else{
				if (priceValue < minPrice){
					minPrice = priceValue;
					priceObj = mapValue;
				}
			}
    	}
    	
    	return priceObj;
    }//End of method
    
    function _getCheaperProducts(productIds){
    	var products = new Array();    	    	    	    
    	var minPrice = parseFloat( _getMinPriceObj( productIds ).priceValue );    	   
		for(var productId in _productsPriceMap){
			if(_arrayIn(productId,productIds)){
				var priceValue = parseFloat( _productsPriceMap[productId].priceValue );
				if(priceValue == minPrice){
					products.push(productId);
				}				
			}
		}
		
		return products;
    }//End of method

    function _replacePrice(priceObj){                
        var priceArea   = document.getElementById(_priceAreaStyleId);
        if(typeof(priceArea) == 'undefined')
            return;
        if(priceObj.specialPriceValue > 0){
            priceArea.innerHTML = priceObj.priceLabel + " " +priceObj.specialPriceLabel;
        }
        else
        {
            priceArea.innerHTML = priceObj.priceLabel;
        }
        var specialStyle = jQuery('#p-detail-dx .regular-price span')
        if(specialStyle.length==1){jQuery(specialStyle[0]).css('text-decoration','none')}
        if(specialStyle.length==2){jQuery(specialStyle[0]).css('text-decoration','line-through');jQuery(specialStyle[0]).css('color','#000');
        var currentFontSize = jQuery(specialStyle[0]).css('font-size');
        var currentFontSizeNum = parseFloat(currentFontSize, 10);
        var newFontSize = currentFontSizeNum*0.8;
        jQuery(specialStyle[0]).css('font-size', newFontSize);
        jQuery(specialStyle[0]).css('padding-top','5px')

}

        if(jQuery('.quick-shop')) {
            var quickspecialStyle = jQuery('.quick-shop .regular-price span')
        if(quickspecialStyle.length==1){jQuery(quickspecialStyle[0]).css('text-decoration','none')}
        if(quickspecialStyle.length==2){jQuery(quickspecialStyle[0]).css('text-decoration','line-through');jQuery(quickspecialStyle[0]).css('float','left')}
        }

    }//End of method

    function _setProductId(productId){
        
    	var productIdField = document.getElementById(_productIdHidden);
        if(productIdField.value!=productId)
          productIdField.value = productId;
                        
    }//End of method

    function _setAvailable (quantity){
        if(quantity==0){
            $('no').show();
            $('yes').hide();
        }
        else{
            $('no').hide();
            $('yes').show();
        }
    }//End of method

    function _setProductFormAction(productId){
    	var productForm = document.forms['product_addtocart_form'];
    	if(typeof(productForm) == 'undefined')
        	return;
        	                
    	var currentFormAction = productForm.action;
		var re = new RegExp('/product/[0-9]+/', "g");
		if(currentFormAction.match(re)){
			var replacement    = '/product/' + productId + '/'; 
			var newFormAction  = currentFormAction.replace(re, replacement);
			productForm.action = newFormAction;
		}
    }//End of method  
       
    /* --- PUBLIC SCOPE --- */
    return {
        
        setConfig: function(config){
            _init(config);
        },//End of method

        updateProductPanel: function(attributeId, attributeValue){
    		var selectedProduct = 0;
    		var selectedPrice   = 0;
    		var matchedProducts = new Array();
        	for(var i=0; i<_mainProductAttributesMap.length; i++){
            	var currentAttributeId = _mainProductAttributesMap[i];
        		var dropdown = document.getElementById('attribute' + currentAttributeId);
        		if(dropdown.selectedIndex > 0){
					var selectedValue = dropdown.options[dropdown.selectedIndex].value;
					var mapKey = currentAttributeId + '#' + selectedValue;
					var associatedProducts = _productsByAttributeMap[mapKey];
					if(i == 0){
						matchedProducts = associatedProducts;
    				}else{
    					matchedProducts = _arrayIntersect(matchedProducts, associatedProducts);
					}        					
        		}else{
        			break;
        		}
        	}
        	
        	if(matchedProducts.length > 0){
                    var priceObj = _getMinPriceObj(matchedProducts);
                    _replacePrice( priceObj );
        	
                    if(matchedProducts.length == 1){
                        var productId = matchedProducts[0];
                        _setProductId( productId );
                        
                        
                        _setProductFormAction( productId );
                        Event.observe(window, 'load', function() {
                            _setAvailable( priceObj.productQty );
                        });                       
                    }
                }
        },//End of method
        
        getFilteredCombination: function(filters){
        	
        	var allCombinations = {};
        	var allProducts    = _getAllChildIds();
        	
        	for(var i=0; i<allProducts.length; i++){
        		
        		var combination = [];
        		
        		var productId = allProducts[i];
        		for(var j=0; j<_mainProductAttributesMap.length; j++){
        			var attributeId = _mainProductAttributesMap[j];
        			for(var itemKey in _productsByAttributeMap){
        				var findme = attributeId + '#';
        				if(itemKey.search(findme) != -1){
        					var products = _productsByAttributeMap[itemKey];
        					if(_arrayIn(productId, products)){
        						var re = new RegExp(findme, "g");
        						attributeValue = itemKey.replace(re, "");
        						baseImage  = _productsImageMap[itemKey];        						
        						combination.push( {
        							'attributeId'    : attributeId,
        							'attributeValue' : attributeValue,
        							'baseImage'      : baseImage
        						} );
        					}
        				}
        			}
        		}
        		
        		allCombinations[productId] = combination;
        	}
        	
        	var matchedProductIds = new Array();
        	var matchedCombinationStack = {};
        	for(productId in allCombinations){
        		var matchedCount = 0;
        		var combinationStack = allCombinations[productId];
        		for(var k=0; k<combinationStack.length; k++){
        			var combination = combinationStack[k];
        			for(var i=0; i<filters.length; i++){
            			var filter = filters[i];
            			if(filter['attributeId'] == combination['attributeId'] && combination['attributeValue'] == filter['attributeValue'])
            				matchedCount++;
            		}
        		}
        		
        		if(matchedCount == filters.length){
        			matchedCombinationStack[productId] = combinationStack;
        			matchedProductIds.push(productId);
        		}
        	}
        	
        	var cheaperProducts = _getCheaperProducts(matchedProductIds);
        	var resultCombinationStack = null;
        	if(cheaperProducts.length > 0){
        		var cheaperProductId = cheaperProducts[0];
        		resultCombinationStack = matchedCombinationStack[cheaperProductId];
        	}
        	
        	return resultCombinationStack;
        	
        },//End of method
        
        getInitialCheaperCombination : function(){
    		
    		var combinationStack = new Array();   		
    		
    		var cheaperProducts  = _getCheaperProducts(_getAllChildIds());
    		for(var k=0; k<_mainProductAttributesMap.length; k++){
    			var attributeId = _mainProductAttributesMap[k];
    			var attributeValue  = null;
    			var baseImage       = null;
        		for(var itemKey in _productsByAttributeMap){
        			var findme = attributeId + '#';
        			if(itemKey.search(findme) != -1){
        				var products = _productsByAttributeMap[itemKey];
        				for(var i=0; i<cheaperProducts.length; i++){
        					if( _arrayIn(cheaperProducts[i], products) ){
            					var re = new RegExp(findme, "g");
            					attributeValue = itemKey.replace(re, "");
            					baseImage  = _productsImageMap[itemKey];            					
            					break;
            				}
        				}
        			}
        			
        			if(attributeValue != null)
        				break;
        		}
        		
        		var combination = {
    				'attributeId'    : attributeId,
    				'attributeValue' : attributeValue,
    				'baseImage'      : baseImage
        		};
        		
        		combinationStack.push(combination);
    		}
    		
    		return combinationStack;
    		
       }//End of method      
  }
   
}//EOF class
