﻿// _imageFrameId : The <image> tag Id
// var _imageFrameId_ = null;
// var _imageData_ = null;

//var _enumImageTypeNormal_ = 0;
//var _enumImageTypeMatrix_ = 1;

//var _imageViewTypeMedium_ = 0;
//var _imageViewTypeLarge = 1;

var _viewTypeMedium_ = 1;
var _viewTypeLarge_= 2;
var _viewTypeSwatch_ = 4;

var _currentViewType_ = _viewTypeMedium_;

var _selectedSwatchId_ = 1; // initial value would be 1
var _currentImageNumber_ = 0;

function showPicture(id, type, number, isSwatch, swatchId) {
    //var img = $(id);
    /*
    var p = 'Id : ' +  id + '\n';
    p += 'type: ' +  type + '\n';
    p += 'number : ' +  number + '\n';
    alert(p);
    */
    var imgFrame = $(_imageFrameId_);
    
    if(imgFrame == null) {
        alert('ERROR: Picture frame not found!');
        return;
    }
    
    if(_imageData_ == null) {
        alert('ERROR: Image Data not found!');
        return;
    }
    
    // array that will look specify which image collection to find the image number
    var imgCol = null;
    
    // Find the composite image
    var imgComposite;
    if(isSwatch || ((type & _viewTypeSwatch_) == _viewTypeSwatch_) ) {
        _imageData_.swatches.each(
            function(swatch, index) {
                if(swatch.id == (swatchId?swatchId:_selectedSwatchId_)) {
                    imgComposite = swatch;                    
                }
            }
        );
    }
    else {
        imgComposite = _imageData_;
    }
    
    if(imgComposite == null) {
        alert('ERROR: Unable to to find composite image!');
        return;
    }
    
    var imgCol;
    if((type & _viewTypeMedium_) == _viewTypeMedium_)
    {
        imgCol = imgComposite.mediumImages;
    }
    else
    {
        imgCol = imgComposite.largeImages;
    }
    
    //  we can be sure that the image collection will always be 10
    //  but to be safe, we must test
    if(imgCol.length >= number || number == 0) {
        var img = null;
        if(number > 0) {
            img = imgCol[number-1];
        }
        
        if((type & _viewTypeLarge_) == _viewTypeLarge_) {
            if(img == null && number == 0) {
                img = _imageData_.large;
            }
            //alert('Width: ' + img.size.width);
            //alert('Height: ' + img.size.height);
            //alert('Resizable:' + img.resizable);
            var url = 'popup.aspx?psrc='+ img.src;
            var name = 'LargeImage';
            var resizable = img.resizable?'yes':'no';
            var params = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=' + resizable + ',resizable=' + resizable + ',copyhistory=no,width=' + img.size.width + ',height=' + img.size.height + 'left=0,top=0';
            //alert(url);
            //alert(params);
            window.open(url, name, params);
        }
        else {
            imgFrame.src = img.src;
        }
    }
    else {
        alert('ERROR: Image index out of range');
        return;
    }
    
    _currentImageNumber_ = number;
    
    return;
}

function swatchOver(elem) {
    elem.className = 'swatchOver';
}

function swatchOut(elem) {
    elem.className = 'swatchOut';
}

function getSelectedPriceforUnitMeasure()
{      
        _UnitMeasurePriceArray.pricelist.each(function(sitem,sindex){
         if($('UnitMeasureCode').value == sitem.unitmeasurecode) 
         {             
           window.$('variantprice').innerHTML= _variantPriceCaption + '&nbsp;' + sitem.totalpriceqty;       
           
         }
         })         
}


// This function assumes that :
//  1. The individual attribute options are already selected
function verifyHasMatrixItemOptionSelected(prompt) {    
    var umxitems = new Array(); // will hold the attributes that are not selected
    var matrixSelected = false; // flag to indicate whether we have a matrix item selected on the combobox
    
    // check each combobox if they have any items selected
    // other than the first option
    matrixSelected = 
        _optionIds.any(
            function(sitem, sindex) {
                if($(sitem).selectedIndex == 0 ) {
                    umxitems.push(sitem);
                    return false;
                }
            }
        );
    
    if(!matrixSelected && umxitems.length > 0) {
        if(prompt) alert('Please select ' + umxitems);
        return false;
    }
    
    return true;
}

// This function assumes that :
//  1. The individual attribute options are already selected
function getSelectedMatrixItem() {
    //alert('gago!');
    
    var selectedMatrixItem = null;
    
     _matrixGroup.items.each(        
        function(mxitem, mxindex) {
            var match = 0;
            _optionIds.each(
                function(sitem, sindex) {
                    mxitem.attributes.each(
                        function(mxaitem, mxaindex) {
                            if(mxaitem.code == sitem) {
                                if($(sitem).options[$(sitem).selectedIndex].value == mxaitem.values[0].value)
                                    match +=1;
                            }
                        }
                    );
                }
            );

            if(match == mxitem.attributes.length) {
                selectedMatrixItem = mxitem;
            }
        }
    );
    
    return selectedMatrixItem;
}

// This function assumes that :
//  1. The individual attribute options are already selected
function setSelectedMatrixItem() {
    var selectedMatrixItem = getSelectedMatrixItem();
        
    // NOTE : Mark 
    //  change image code will go here...
    //  on the new swatch image implementation
    
    if(selectedMatrixItem != null) {
    
        //alert(selectedMatrixItem.code);
        //alert(selectedMatrixItem.price);
        
        $('MatrixItem').value = selectedMatrixItem.code;
          
        var elemStockHint = $('imgStockHint');
        if(null != elemStockHint) {
            if(selectedMatrixItem.unitsInStock > 0) 
            {
            
                elemStockHint.src ='images/instock.gif';
            }
            else 
            {
                elemStockHint.src = 'images/outofstock.gif';
            }
        }
        updateMatrixPrice(
            selectedMatrixItem.onSale, 
            selectedMatrixItem.price, 
            selectedMatrixItem.promoPrice
        );
    }
    else {
        
        // we didn't find any matching matrix item
        // invalidate the product...
        $('ProductID').value = '';
        $('MatrixItem').value = '';
    }
}

// This function assumes that :
//  1. The individual attribute options are already selected
//  2. The matrix item is already selected
//  3. IgnoreStockLevel = true
function verifySelectedMatrixItemQuantityGreaterThanProposedQuantity(proposedQuantity, initialMessage) {
    var selectedMatrixItem = getSelectedMatrixItem();
    
    //*************************************
    
    //alert('Units in Stock :' + selectedMatrixItem.unitsInStock);
    
    //*************************************
    
    if(selectedMatrixItem.unitsInStock < proposedQuantity) {
        //alert('gagong siraulo');
        alert(initialMessage + selectedMatrixItem.unitsInStock);
        return false;
    }
    
    // +ok
    return true;
}

function selectMatrixItem() {
    selectMatrixItem(false);
}
function selectMatrixItem(skip, selectedQuantity, ignoreStockLevels) {
    //var umxitems = new Array();
    var matrixSelected = false;
    
    if(verifyHasMatrixItemOptionSelected(true)) {
        var selectedMatrixItem = getSelectedMatrixItem();
        
        // NOTE : Mark 
        //  change image code will go here...
        //  on the new swatch image implementation
        
        alert(selectedMatrixItem.code);
        
        $('MatrixItem').value = selectedMatrixItem.code;
        
        alert(selectedQuantity);
        updateMatrixPrice(selectedMatrixItem.onSale, selectedMatrixItem.price, selectedMatrixItem.promoPrice);
    }
    
    return false; 
}

function updateMatrixPrice(onsale, price, promoPrice) {
    if(onsale) {
        if(window.$('RegularPrice') && window._regPriceCaption) {
            $('RegularPrice').innerHTML = _regPriceCaption + '&nbsp;' + formatPrice(price);
            $('RegularPrice').style.textDecoration = 'line-through';
        }
        if(window.$('PromotionalPrice') && window._promoPriceCaption) {
            $('PromotionalPrice').innerHTML = _promoPriceCaption + '&nbsp;' + formatPrice(promoPrice);
            $('PromotionalPrice').style.visibility = 'visible';
        }
    }
    else {
        if(window.$('RegularPrice') && window._variantPriceCaption) {
            $('RegularPrice').innerHTML = _variantPriceCaption + '&nbsp;' + formatPrice(price);
            $('RegularPrice').style.textDecoration = 'none';
        }
        if(window.$('PromotionalPrice')) {
            $('PromotionalPrice').style.visibility = 'hidden';
        }
    }
}

//function selectMatrixItem(selectIds) {
//    var umxitems = new Array();
//    var matrixSelected = false;
//    
//    matrixSelected = 
//        selectIds.any(
//            function(sitem, sindex) {
//                if($(sitem).selectedIndex == 0 ) {
//                    umxitems.push(sitem);
//                    return false;
//                }
//                    
//            }
//        );
//        
//    if(!matrixSelected && umxitems.length >0){
//        alert('Please select ' + umxitems);    
//        return false;
//    } 
//    
//    _matrixItems.each(        
//        function(mxitem, mxindex) {
//            var match = 0;
//            selectIds.each(
//                function(sitem, sindex) {
//                    mxitem.attributes.each(
//                        function(mxaitem, mxaindex) {
//                            if(mxaitem.code == sitem) {
//                                if($(sitem).options[$(sitem).selectedIndex].value == mxaitem.value)
//                                    match +=1;
//                            }
//                        }
//                    );
//                }
//            );

//            if(match == mxitem.attributes.length) {
//                $('MatrixItem').value = mxitem.code;
//                matrixSelected = true;
//            }
//        }
//    );
//        
//    return matrixSelected;
//}

function selectKitItem(grpCode, itemCode, itemId, chk) {
//    if( _kitItem != null ) {
//        _kitItem.groups.each(
//            function(gitem, gindex) {
//                if(gitem.code == grpCode) {
//                    switch(gitem.type)
//                    {
//                        case "Multi-Select":
//                            break;
//                            
//                        case "Required":
//                            break;
//                        case "Optional":
//                            if( $(itemId).checked ) {
//                                $(itemId).checked = false;
//                            }
//                            else {
//                                $(itemId).checked = true;
//                            }
//                            break;
//                    }
//                }
//            }
//        );
//    }
    
    //alert(allow);
    
    //return allow;
    updateKitPrice();
}

function updateKitPrice() {
    var total = 0;    
    if(_kitItem != null) {
        var kitDetails = new Array();
        
        _kitItem.selectedItems = new Array();
        _kitItem.groups.each(
            function(gitem, gindex) {
            
                var groupDefault = null;
                
                gitem.items.each(
                    
                    function(item, index){
                    
                        //alert(gitem.type + ':' + item.code + ' Checked: ' + $(item.id).checked + ' Price: ' + item.price);
                        
                        if($(item.id).checked){
                            groupDefault = item;
                            //defaultprice = item.price;
                            total += item.price;
                            _kitItem.selectedItems.push(gitem.code+'+'+item.code);
                            
                            kitDetails.push(item.description);
                        } 
                    }
                );  
                            
                gitem.items.each(
                    
                    function(item, index){
                    
                        
                    
                        //alert(gitem.type + ':' + item.code + ' Checked: ' + $(item.id).checked + ' Price: ' + item.price);
                        
                        if($(item.id).checked){
                            //alert(item.code);
                            //alert(item.price);
                            if (_captionIncluded != undefined && _captionIncluded != null){ 
                                $('PriceOf_' + item.id).innerHTML = _captionIncluded;
                                //_kitItem.selectedItems.push('('+'['+gitem.code+']'+'+'+'['+item.code+']'+')');
                            }
                        } 
                        else
                        {
                            if (gitem.type == 'Required' || gitem.type == 'Optional'){
                                var priceDifference = 0;
                                
                                if (!groupDefault){
                                         if (_captionAdd != undefined && _captionAdd != null){ 
                                            $('PriceOf_' + item.id).innerHTML = _captionAdd + '&nbsp;' + formatPrice(item.price);
                                        }                                
                                }
                                else
                                {                                
                                    if (item.price >= groupDefault.price){
                                        if (_captionAdd != undefined && _captionAdd != null){ 
                                            priceDifference = item.price - groupDefault.price;
                                            $('PriceOf_' + item.id).innerHTML = _captionAdd + '&nbsp;' + formatPrice(priceDifference);
                                        }
                                    }
                                    else
                                    {
                                        if (_captionLess != undefined && _captionLess != null){ 
                                            priceDifference = groupDefault.price - item.price;
                                            $('PriceOf_' + item.id).innerHTML = _captionLess + '&nbsp;' + formatPrice(Math.abs(priceDifference));
                                        }                                
                                    }  
                                }  
                            }
                            else
                            {
                                        if (_captionAdd != undefined && _captionAdd != null){ 
                                            $('PriceOf_' + item.id).innerHTML = _captionAdd + '&nbsp;' + formatPrice(item.price);
                                        }                             
                            }
                        }
                    }
                );
            }
        );
    }
    
    var priceElems = document.getElementsByClassName('KitPrice');
    priceElems.each(
        function(elem, idx) {
            elem.innerHTML = formatPrice(total);
        }
    );

//    if(window.$('KitPrice')) {
//        $('KitPrice').innerHTML = formatPrice(total); //(_curSymbol != null)? _curSymbol + ' ' + total : total;
//    }
    
    
    var items = document.getElementsByClassName('KitItems');
    items.each(
        function(elem, idx) {
            elem.value = _kitItem.selectedItems;
        }
    );
    
    //$('KitItems').value = _kitItem.selectedItems;
    //alert($('KitItems').value);
    
    // populate the selected item display    
    
    var divDetails = $('KitAddToCartFormDetails');
    if(divDetails) {
        divDetails.innerHTML = '';
        
        var ul = document.createElement('ul');
        
        kitDetails.each(
            function(item, idx) {
                var li = document.createElement('li');
                li.innerHTML = item;
                
                ul.appendChild(li);
            }
        );
        
        divDetails.appendChild(ul);
    }
}

function formatPrice(price) {
    //alert(_curSymbol);
    //alert(_curDecimalDigits);
    
    var num = new NumberFormat();
    num.setInputDecimal('.');
    num.setNumber(price);
    num.setPlaces(_curDecimalDigits, false);
    num.setCurrencyValue(_curSymbol);
    num.setCurrency(true);
    num.setCurrencyPosition(num.LEFT_OUTSIDE);
    num.setNegativeFormat(num.LEFT_DASH);
    num.setNegativeRed(false);
    num.setSeparators(true, ',', ',');
    //alert(num.toFormatted());
    
    return num.toFormatted();
}

var InventoryItem = Class.create();
InventoryItem.prototype = {

    initialize : function (id, code, type, unitMeasure){
        this.id = id;
        this.code = code;
        this.type = type;
        this.unitMeasure = unitMeasure;
    },
    
    setUnitMeasure : function(unitMeasure) {
        this.unitMeasure = unitMeasure;
    },
    
    setQuantity : function(quantity) {
        this.quantity = quantity;
    },
    
    setIgnoreStockLevel : function(ignoreStockLevel) {
        this.ignoreStockLevel = ignoreStockLevel;
    }
    
}

var InventoryManager = {
    
    setAvailableStockPerUnitMeasure : function(availableStockPerUnitMeasure) {
        // JSON formatted {unit measure code(string), free stock(decimal)}
        this.availableStockPerUnitMeasure = availableStockPerUnitMeasure;
    },
    
    setupAndVerify : function(item) {
        this.setup(item);
        return this.verify(item);
    },
    
    setup : function(item) {
        if('undefined' != $('Quantity') && null != $('Quantity')) {
            item.quantity = $('Quantity').value;
        }
        
        if('undefined' != $('UnitMeasureCode') && null != $('UnitMeasureCode')) {
            item.unitMeasure = $('UnitMeasureCode').value;
        }
    },
    
    verify : function(item) {
        if(item.quantity === 'undefined' || item.quantity === null) {
            alert('Quantity not set!');
            return false;
        }
        
        if(!item.ignoreStockLevel) {
            
            if(item.type === 'Matrix Group') {
                // verify that a matrix has been selected from the ui
                if(!verifyHasMatrixItemOptionSelected(true)) return false;              

                // free stock computation verify
                // NOTE : Mark
                //  Comment the lines below to allow adding items below allowable free stock
                // Start Comment ------------------------------------------------>
                
                //if(!verifySelectedMatrixItemQuantityGreaterThanProposedQuantity(item.quantity, 'Quantity ordered is greater than available')) return false;
                
                // <---------------------- End Comment 
                
                setSelectedMatrixItem();
            }
            else {
                // iterate through the unit measure free stock table
                // and check if we went over the free stock for the item
                
                // NOTE : Mark
                //  Comment the lines below to allow adding items below allowable free stock
                // Start Comment ------------------------------------------------>
                
                /*
                for(var ctr=0; ctr<this.availableStockPerUnitMeasure.length; ctr++) {
                    var stockByUM = this.availableStockPerUnitMeasure[ctr];
                    if(stockByUM.unitMeasureCode === item.unitMeasure) {
                        if(item.quantity > stockByUM.freeStock) {
                            alert('Available stock : ' + stockByUM.freeStock);
                            return false;
                        }
                    }
                }
                */
                
                // <---------------------- End Comment 
            }
        }
        
        if(item.type === 'Kit') {
            updateKitPrice();
        }
      
        //alert('sdgdasgas');
          
        return true;
    }
}

function preloadImages() {
   if (document.images) {
      var args = preloadImages.arguments;
      for (var ctr = 0; ctr < args.length; ctr++) {
         var img = new Image();
         img.src = args[ctr];
         img = null;
      }
   }
}

function changeImage(imgSrc)
{
       if (document.images) {
	      document.ProductPic.src=imgSrc;
	   }
}
