//control type = 1 - dropdown, 2 - radiobutton, 3 - checkbox, 4 - multiple select

//see Versacor.Shop.Library.Constants.Options.cs class for Names compatibility
var fStop = '&path=';
var lStop = '&w=';
var sepName = ',';
var imPart = 'images/'; //this is the main assumptiona that all pictures stored in the "images" folder 
var addon = '_addon'

var price = '_price';

var current = '_curr';
var percent = '_Percent';
var amount = '_Amount';
var hidden = '_hidden';

var origPrice = '_origPrice';
var priceAddon = '_add:'; //using for options where option price is addon to the product price(PriceType = true)
var priceExact = '_exact:'; //using for options where option price is replacing product price(PriceType = false)
var priceZero = '_zero:'; //any type of option price (Pricetype = any) if current price for this option is zero

var optionGroup = '_optionGroup';
var formName = 'aspnetForm';
    
//string prototypes
String.prototype.startsWith = function(str) 
{return (this.match("^"+str)==str)} 
//end of string prototypes

function trim(str)
{
    if(!str || typeof str != 'string')
        return null;

    return str.replace(/^[\s]+/,'').replace(/[\s]+$/,'').replace(/[\s]{2,}/,' ');
}
    
//full cycle function - to change picture and price - complete
function setClickableOption(obj, isSelectControl)
{ 

    //debugger;  
    var optionID;
    var controlType;
    if (!isSelectControl)
    {
         optionID = obj.id;
         controlType = 2;
    }
    else
    {
         optionID = (obj[obj.selectedIndex].id);  
         controlType = 1;      
    } 
       
    var priceIndex = optionID.lastIndexOf(price);
    var ind = obj.name.lastIndexOf(sepName);
    
    //option data
    var optionPicture = optionID.substring(0, priceIndex);        
    var optionPrice = optionID.substring(priceIndex + price.length);
    var optionName = obj.name.substring(ind + 1);
    //end of option data
    
    setImageStuff(optionName, optionPicture);
    setPriceStuff(optionID, optionName, optionPrice, obj, controlType);      
}

//short cycle function - to change price only - complete
function setClickableControl(obj, controlType)
{
//debugger;
    var optionID;
    var controlType;
    if (controlType == 1)
    {
         optionID = (obj[obj.selectedIndex].id);           
    }
    else if (controlType == 2)
    {
         optionID = obj.id;         
    }
    else if (controlType == 3)
    {
        optionID = obj.id;
    }
    else if (controlType == 4)
    {
        optionID = obj.id;
    } 
    var priceIndex = optionID.lastIndexOf(price);
    var ind = obj.name.lastIndexOf(sepName);
    
    //option data
    var optionPrice = optionID.substring(priceIndex + price.length);
    var optionName = obj.name.substring(ind + 1);
    //end of option data
    
    setPriceStuff(optionID, optionName, optionPrice, obj, controlType);  
}

//function to set up image for the item selected - complete
function setImageStuff(optionName, optionPicture)
{
    //image data
    var image = document.getElementById(optionName);
    var imagePath = image.src;
    var indPicNameStart = imagePath.lastIndexOf(fStop);
    var indPicNameEnd = imagePath.lastIndexOf(lStop);
    var picName = imagePath.substring(indPicNameStart + fStop.length, indPicNameEnd);
    image.src = imagePath.replace(picName, imPart + optionPicture);    
    //end of image data
    
    //addon for additional image(view larger)
    var link = document.getElementById(optionName + addon);
    if (link != null)
    {
        imagePath = link.href;
        indPicNameStart = imagePath.lastIndexOf(fStop);
        indPicNameEnd = imagePath.lastIndexOf(lStop);
        picName = imagePath.substring(indPicNameStart + fStop.length, indPicNameEnd);
        link.href = imagePath.replace(picName, imPart + optionPicture);
    }
}

function FormatMoney(c)
{
    var t = this;
    if(c == undefined)
        c = 2;
    var p, d = (t = t.split("."))[1].substr(0, c);
    for(p = (t = t[0]).length; (p -= 3) >= 1;)
        t = t.substr(0, p) + "." + t.substr(p);
    return t + "," + d + Array(c + 1 - d.length).join(0);
}

function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + '$' + dblValue + '.' + strCents);
}


//function to set up price for the item selected
function setPriceStuff(optionID, optionName, optionPrice, obj, controlType)
{
   
    var priceControl = document.getElementById(optionName + price);
    if (priceControl != null)
    {
        //define priceType of new added option
        var newPriceType = definePriceType(optionPrice, false);
        if (newPriceType >= 0)
        {
            //define original price for the current session
            var origPriceControl = document.getElementById(optionName + origPrice);
            if (origPriceControl != null)
            {
             //debugger;
                var origPriceValue = origPriceControl.value.substring(1).replace(",","");//parseFloat(origPriceControl.value.substring(1));
                            
                //amount of selected "exact options" for current item.
                var exactItems = 0;
                //define priceType of current price set                         
                if (priceControl.exactCounter != null)
                {
                    exactItems = parseInt(priceControl.exactCounter);
                }
                else
                {
                    exactItems = parseInt(priceControl.getAttribute('exactCounter'));    
                }      
                //put updated version to the attribute later
                
                if (newPriceType == 0)
                {
                    optionPrice = optionPrice.substring(priceZero.length);
                }
                else if (newPriceType == 1)
                {
                    optionPrice = optionPrice.substring(priceAddon.length);
                }
                else if (newPriceType == 2)
                {
                    optionPrice = optionPrice.substring(priceExact.length);
                }
                
                var currPriceControl = trim(priceControl.innerHTML);
                var moneySign = currPriceControl.substring(0, 1);
                var currPrice = 0.00;
              //  debugger;
                currPrice = parseFloat(currPriceControl.substring(1).replace(",","")); 
                //currPrice=formatCurrency(currPrice);                    
                
                var isLast = (document.getElementById(optionName + price + 0) == null);
                currPrice = getPriceWithOption(controlType, origPriceValue, obj, optionPrice, exactItems, currPrice, priceControl, newPriceType, isLast);
                
//                if (newPriceType == 1)
//                {
//                   currPrice = getPriceWithOption(controlType, origPriceValue, obj, optionPrice, exactItems, currPrice, priceControl, newPriceType, isLast);// optionPrice = optionPrice.substring(priceAddon.length);
//                }
//                else if (newPriceType == 2)
//                {
//                    currPrice = optionPrice/1;
//                }
                
                if(currPrice == null)
                {
                    return;
                }      
                //total price calculation
                //currPrice = Math.round(currPrice * 100)/10;
                currPrice = currPrice.toFixed(2);
                priceControl.innerHTML = formatCurrency((moneySign + currPrice));
                //priceControl.exactCounter = exactItems;               
                //end of total price
                
                //new price (considering user specific price)
                var specificPriceControl = document.getElementById(optionName + price + current);
                if (specificPriceControl != null)
                {
                    var percent = document.getElementById("_Percent").value;
                    var amount = document.getElementById("_Amount").value;
                    
                    var specificPrice = currPrice * percent / 100 + parseFloat(amount);
                    specificPriceControl.innerHTML = formatCurrency((moneySign + specificPrice.toFixed(2)));
                }
                
                //Wholesale by order Amount and Volume prices update
                for(k = 0; k < 1000; k++)
                {
                    var priceByAmountHidden = document.getElementById(optionName + price + k + hidden);
                    var priceByAmountControl = document.getElementById(optionName + price + k);
                    if(priceByAmountControl != null)
                    {
                        var priceByAmount = parseFloat(trim(priceByAmountHidden.value));
                        var controlPriceByAmount = trim(priceByAmountControl.innerHTML);
                        var moneySign = currPriceControl.substring(0, 1);
                        var currPriceByAmount = 0.00;
                        currPriceByAmount = parseFloat(controlPriceByAmount.substring(1));     
                        var next = k + 1;
                        var isLast = false; 
                        if(document.getElementById(optionName + price + next) == null)
                        {
                            isLast = true;
                        }
                        amountPrice = getPriceWithOption(controlType, priceByAmount, obj, optionPrice, exactItems, currPriceByAmount, priceByAmountControl, newPriceType, isLast);
                        
                        priceByAmountControl.innerHTML = formatCurrency((moneySign + amountPrice.toFixed(2)));
                        
                        //new price (considering user specific price)
                        var specificPriceByAmountControl = document.getElementById(optionName + price + k + current);
                        if (specificPriceByAmountControl != null)
                        {
                            var percent = document.getElementById("_Percent").value;
                            var amount = document.getElementById("_Amount").value;
                            
                            var specificPriceByAmount = amountPrice * percent / 100 + parseFloat(amount);
                            specificPriceByAmountControl.innerHTML = formatCurrency((moneySign + specificPriceByAmount.toFixed(2)));
                        }   
                    }
                    else
                    {
                        break;
                    }
                }
            }    
        }
    }
}

//function to get option price for the option
function getOptionPrice(currObj, controlType)
{
    var optionID;
    if (controlType == 1)
    {
         optionID = currObj.id;           
    } 
    else if (controlType == 2)
    {
         optionID = currObj.id;         
    }
    else if (controlType == 4)
    {   
        optionID = currObj.id;
    }
    
    var priceIndex = optionID.lastIndexOf(price);
    var optionPrice = optionID.substring(priceIndex + price.length);
    if (optionPrice.startsWith(priceZero))
    {
        optionPrice = optionPrice.substring(priceZero.length);
    }
    else if (optionPrice.startsWith(priceAddon))
    {
        optionPrice = optionPrice.substring(priceAddon.length);
    }
    else if (optionPrice.startsWith(priceExact))
    {
        optionPrice = optionPrice.substring(priceExact.length);
    }           
    return optionPrice;
}

//function to define what type of price we're going to implement now
function definePriceType(data, isID)
{
    if (data.length == 0)
    {
        return 0;
    }
    else
    {
        if (isID)
        {
            var priceIndex = data.lastIndexOf(price);
            data = data.substring(priceIndex + price.length);
        }        
        if (data.startsWith(priceZero))
        {
            //no action will be taken. Simply return from the code execution 
            return 0;
        }
        else if (data.startsWith(priceAddon))
        {
            //add this option value to the current price value
            return 1;
        }
        else if (data.startsWith(priceExact))
        {
            //item should set to null product price (if wasn't set before)
            return 2;
        }        
    }    
}

function getPriceWithOption(controlType, origPriceValue, obj, optionPrice, exactItems, 

currPrice, priceControl, newPriceType, isLast)
{
var oldPrice = currPrice;
    if (controlType == 1) 
    {
        var j = obj.options.length;
        for (i = 0; i < j; i++)
        {
            var arrItem = obj.options[i];
            if(arrItem.previousState == 1)
            {
                var oldValue = arrItem.value;
                var newValue = obj[obj.selectedIndex].value;
                if (oldValue == newValue)
                {
                    //this is the same item - do nothing
                    //return;
                }
                else
                {
                    var oldPrice = getOptionPrice(arrItem, controlType);
                    //remove cost of this option from the currPrice;
                    currPrice = currPrice - parseFloat(oldPrice);	
                    if (exactItems > 0)
                    {
                        //check - if this item belongs to the exact ones
                        var oldPriceType = definePriceType(arrItem.id, true);
                        if (oldPriceType == 2)
                        {
                            exactItems = parseInt(exactItems - 1);
                            if (exactItems == 0)
                            {
                                currPrice = currPrice + parseFloat(origPriceValue);	  

               
                            }		                            
                        }
                    }	                               		            
                    if(isLast)
                    arrItem.previousState = 0;
                    continue;		            
                }		        		        	       
            }
            else
            {
                //check if this is new item and we can append price for it
                if (arrItem.value == obj[obj.selectedIndex].value)
                {
                    var newPriceType = definePriceType(arrItem.id, true);
                    currPrice = currPrice + parseFloat(optionPrice);
                    //currPrice = parseFloat(optionPrice);
		    if (newPriceType == 2)
                    {
                        exactItems = parseInt(exactItems + 1);
                        if (exactItems == 1)
                        {
                            currPrice = currPrice - parseFloat(origPriceValue);
                        }		                        
                    }
                    if(isLast)
                    arrItem.previousState = 1;		                    
                }
            }   
        }
    }
    else if (controlType == 2)
    {
        var j = document.getElementsByName(obj.name).length;
        var objArray = document.getElementsByName(obj.name);
        for (i = 0; i < j; i++)
        {
            if(objArray[i].previousState == 1)
            {
                var oldValue = objArray[i].value;
                var newValue = obj.value;
                if (oldValue == newValue)
                {
                    //this is the same item - do nothing
                    //return;
                }
                else
                {
                    var oldPrice = getOptionPrice(objArray[i], controlType);
                    //remove cost of this option from the currPrice;
                    currPrice = currPrice - parseFloat(oldPrice)		          

  		            
                    if (exactItems > 0)
                    {
                        //check - if this item belongs to the exact ones
                        var oldPriceType = definePriceType(objArray[i].id, true);
                        if (oldPriceType == 2)
                        {
                            exactItems = parseInt(exactItems - 1);
                            if (exactItems == 0)
                            {
                                currPrice = currPrice + parseFloat(origPriceValue);	  

               
                            }		                            
                        }
                    }
                    if(isLast)
                    objArray[i].previousState = 0;
                    continue;           
                }		        		        	       
            }
            else
            {
                //check if this is new item and we can append price for it
                if (objArray[i].value == obj.value)
                {
                    currPrice = currPrice + parseFloat(optionPrice);
                    var newPriceType = definePriceType(objArray[i].id, true);
                    if (newPriceType == 2)
                    {
                        exactItems = parseInt(exactItems + 1);
                        if (exactItems == 1)
                        {
                            currPrice = currPrice - parseFloat(origPriceValue);
                        }		                        
                    }
                    if(isLast)
                    objArray[i].previousState = 1;
                }
            }
        }
    }
    else if (controlType == 3)
    {
        //recalculate price - because it's include of optionGroup as well
        var ind = optionPrice.lastIndexOf(optionGroup);
        //define group number for this type
        var optionGroupValue =  optionPrice.substring(ind + optionGroup.length);
        optionPrice = optionPrice.substring(0, ind);
        var netForm = document.forms[0];
        for(var ctr = 0 ; ctr < netForm.length; ctr++)
        {
            if(netForm[ctr].type == 'checkbox')
            {
                var item = netForm[ctr];
                //define if it has groupValue
                var currInd = item.id.lastIndexOf(optionGroup);
                if (currInd < 0)
                {
                    continue;
                }
                var currOptionGroupValue = item.id.substring(currInd + 

optionGroup.length);
                if ((item.name.lastIndexOf(optionName) >= 0) 
                    && (item.name.length == item.name.lastIndexOf(optionName) + 

optionName.length )
                    && optionGroupValue == currOptionGroupValue)
                {
                    if (item.value == obj.value)
                    {
                        //same item - process it
                        var currPriceType = definePriceType(item.id, true);
                        if (item.checked)
                        {
                            //add its price
                            currPrice = currPrice + parseFloat(optionPrice);
                            if (currPriceType == 2)
                            {
                                exactItems = parseInt(exactItems + 1);
                                if (exactItems == 1)
                                {
                                    currPrice = currPrice - parseFloat(origPriceValue);
                                }		                          
                            }
                        }
                        else
                        {
                            //substract its price
                            currPrice = currPrice - parseFloat(optionPrice);
                            if (exactItems > 0)
                            {
                                if (currPriceType == 2)
                                {
                                    exactItems = parseInt(exactItems - 1);
                                    if (exactItems == 0)
                                    {
                                        currPrice = currPrice + 

parseFloat(origPriceValue);	                 
                                    }   
                                }
                            }
                        }
                        break;                        
                    }                    
                }
                else
                {
                    continue;
                }  
            }            
        }        
    }
    else if (controlType == 4)
    {
        //multiple control
        var j = obj.options.length;
        for (i = 0; i < j; i++)
        {
            var arrItem = obj.options[i];
            if(arrItem.previousState == 1)
            {
                if (arrItem.selected)
                {
                    //do nothing - nothing changed
                    continue;   
                }
                else
                {
                    //substract its value
                    var oldPrice = getOptionPrice(arrItem, controlType);
                    currPrice = currPrice - parseFloat(oldPrice);
                    if (exactItems > 0)
                    {
                        //check - if this item belongs to the exact ones
                        var oldPriceType = definePriceType(arrItem.id, true);
                        if (oldPriceType == 2)
                        {
                            exactItems = parseInt(exactItems - 1);
                            if (exactItems == 0)
                            {
                                currPrice = currPrice + parseFloat(origPriceValue);	  

               
                            }		                            
                        }
                    }
                    if(isLast)		            		            
                    arrItem.previousState = 0;		                
                }
            }
            else if (arrItem.previousState == 0 || arrItem.previousState == null)
            {
                if (arrItem.selected)
                {
                    //add its price to the total price
                    var oldPrice = getOptionPrice(arrItem, controlType);
                    currPrice = currPrice + parseFloat(oldPrice);
                    var newPriceType = definePriceType(arrItem.id, true);
                    if (newPriceType == 2)
                    {
                        exactItems = parseInt(exactItems + 1);
                        if (exactItems == 1)
                        {
                            currPrice = currPrice - parseFloat(origPriceValue);
                        }		                        
                    }
                    if(isLast)		            		            
                    arrItem.previousState = 1;		                
                }
                else
                {
                    //do nothing
                    continue;
                }		        
            }		       
        }
    }
    priceControl.exactCounter = exactItems; 

    return currPrice;
}