﻿function UpdateTotals()
{
    var total = 0;
    //set accessory price
    if ($get('ProductAccessorySubtotal') != null)
    {
       total =  ConvertStringToFloat($get('ProductAccessorySubtotal').innerHTML);
    }
    //product price
    if ($get('ProductPrice') != null)
    {
        total = total + ConvertStringToFloat($get('ProductPrice').innerHTML);
    }
    
    //set total
    if ($get('ProductTotalPrice') != null)
    {
        $get('ProductTotalPrice').innerHTML = GetPriceString(total);
    }
    
}

function UpdateAccessoryTotal()
{
    var accessoryTotal = 0;
    
    //main accessories
    if (AccessoryMain)
    {
        if (AccessoryMain > 0)
        {
            accessoryTotal += CalculateAccessoryTotal('Main',AccessoryMain);
        }
    }

    //extra accessories
    if (AccessoryExtra)
    {
        if (AccessoryExtra > 0)
        {
            accessoryTotal += CalculateAccessoryTotal('Extra', AccessoryExtra);
        }
    }
    //set accessory price
    if ($get('ProductAccessorySubtotal') != null)
    {
        $get('ProductAccessorySubtotal').innerHTML = GetPriceString(accessoryTotal);
    }
    
    UpdateTotals();
}

function GetPriceString(Amount)
{
    //get dec
    var DecimalSeparator = Number("1.2").toLocaleString().substr(1,1); 
     
    var AmountWithCommas = Amount.toLocaleString(); 
    var arParts = String(AmountWithCommas).split(DecimalSeparator); 
    var intPart = arParts[0]; 
    var decPart = (arParts.length > 1 ? arParts[1] : ''); 
    decPart = (decPart + '00').substr(0,2); 
     
    return '&pound;' + intPart + DecimalSeparator + decPart; 
}

function ConvertStringToFloat(val)
{
    if (val)
    {
        return parseFloat(val.replace(/,/g,'').replace('£','').replace('&pound;', ''));
    }
    else
    {
        return 0;
    }    
}

function CalculateAccessoryTotal(type, count)
{
    var result = 0;
    
    if (isInteger(count))
    {
        for(var i=1;i<=count;i++)
        {
            var name = 'Accessory' + type + 'TextBox' + i;
            if ($get(eval(name)) != null)
            {
                var ddl = $get(eval(name));
                if (ddl.value != '')
                {
                    var SelValue = ddl.value
                    if (SelValue > 0)
                    {   
                        //get price
                        var pricename = 'Accessory' + type + 'Price' + i;
                        if ($get(eval(pricename)) != null)
                        {
                            var price = ConvertStringToFloat($get(eval(pricename)).innerHTML);
                            
                            result += SelValue * price;
                        }
                    }
                }
            }
            
        }
    }
    
    return result;
}

 function updateQty(clientID, method) {
    var target = document.getElementById(clientID)
    var qty = parseInt(target.value);
    if (method == 'update')
    {
        if (target.value =='')
        {
            qty = '';
        }
        else if (isInteger(target.value))
        {
            //ignore
        }
        else
        {
            target.value = '0'
        }
    }
    else if(method == 'plus') {
        qty += 1;
        target.value = qty.toString();
    } 
    else 
    {
        if(qty > 0) 
        {
            qty -= 1;
        }
        target.value = qty.toString();
    }

    UpdateAccessoryTotal();
 }
 
//called from check box for installation
function InstallationChecked(target)
{
    if (target.checked == true)
    {
        //installation selected
        ShowInstallationText(true);
        if ($get('installationUnitPrice') != null)
        {
            var Amount = ConvertStringToFloat($get('installationUnitPrice').innerHTML);
            SetInstallationPrice(Amount);
        }
        else
        {
            SetInstallationPrice(0);
        }
        
    }
    else
    {
        //installation deselected
        ShowInstallationText(false);
        SetInstallationPrice(0);
    }
    //set product price
    SetProductPrice()
    //update totals
    UpdateTotals();
}

function SetProductPrice()
{
    var unitPrice = 0;
    var installationPrice = 0;
    var qty = 0;
    
    if ($get(QuantityTextBoxID) != null)
    {
        if ($get(QuantityTextBoxID).value != '')
        { 
            qty = $get(QuantityTextBoxID).value; 
        }
    }
    

    if ($get(UnitPriceSpan) != null)
    {
        unitPrice = $get(UnitPriceSpan).innerHTML - 0;
    }
    
    if (MultiBanding == 'true')
    {
        //override unit price with price banding one
        var tmp =GetMultiBandUnitPrice(qty);
        if (tmp >0)
        {
            unitPrice = tmp;
        }
    }
    
    if ($get(installationSpan) != null)
    {
        installationPrice = $get(installationSpan).innerHTML - 0;
    }
    
    var total = (unitPrice + installationPrice) * qty;
    
    if ($get('ProductPrice') != null)
    {
        $get('ProductPrice').innerHTML = GetPriceString(total);
    }
}

function GetMultiBandUnitPrice(quantity)
{
    var count = 1;
    var gotRows = true;
    var result = 0;
    while (gotRows && count < 30)
    {
        var rowName = 'PromotionBand' + count;
        if ($get(rowName) != null)
        {
            var text = $get(rowName).value;
            if (text != "")
            {
                var splitString = text.split("|");
                var min  = splitString[0] - 0;
                var max = splitString[1] - 0;
                var amount = splitString[2] - 0;
                
                if (quantity >= min)
                {
                    if (max >= 1000 || quantity <= max)
                    {
                        result = amount;
                        gotRows = false;
                    }
                }
                
                count ++;
            }
            else
            {
                gotRows = false;
            }
        }
        else
        {
            gotRows = false;
        }
    }
    
    return result;
    
}

function SetInstallationPrice(Amount)
{
    if ($get(installationSpan) != null)
    {
        $get(installationSpan).innerHTML = Amount;
    }
}

function ShowInstallationText(show)
{
    if ($get('divInstallation') != null)
    {
        if (show == true)
        {
            $get('divInstallation').className = 'InstallationLine';
        }
        else
        {
            $get('divInstallation').className = 'InstallationLine Hidden';
        }
    }
}
//called from key up event on qty box
function CalculateTotals(target)
{
    var i = 1;
    if (target.value =='')
    {
    }
    else if (isInteger(target.value))
    {
        i = target.value;
    }
    else
    {
        target.value = 1;
    }
    
    SetProductPrice();
    UpdateTotals();
    
}

//Model Functions

    var emailPopup;
    var addToBasketPopup;
    var upgradePopup;
    
	function OpenModal(targetName) {
	    switch (targetName)
	    {
	       case 'EmailAFriend':
		        emailPopup = ModalPopup(document.getElementById(targetName), null, null);
		        emailPopup.Open();
	           break;
	       case 'AddToBasket':
		        addToBasketPopup = ModalPopup(document.getElementById(targetName), null, null);
		        addToBasketPopup.Open();
		        break;
		     case 'UpgradePopup':
		        upgradePopup = ModalPopup(document.getElementById(targetName), null, null);
		        upgradePopup.Open();
		        break; 
	    }
	}

	function CloseModal(targetName) {
	    switch (targetName)
	    {
	       case 'EmailAFriend':
		        emailPopup.Close();
		        emailPopup = null;
	           break;
	       case 'AddToBasket':
		        addToBasketPopup.Close();
		        addToBasketPopup = null;
		        break;
		     case 'UpgradePopup':
		        upgradePopup.Close();
		        upgradePopup = null;
		        break;  
	    }
	}

	//add to basket functions
	var redirectToBasket = false;
	
	function AddToBasket() {
        var qty = $get(QuantityTextBoxID).value;
        if (qty != '') {
            var code = $get(codeSpan).innerHTML;
            var price = $get('ProductPrice').innerHTML;
            price = ConvertStringToFloat(price) / qty;
            AddToBasketMethod(code, 'True', price);
        }
    }

    function AddToBasketFromUpgrade() {
        var qty = $get(QuantityTextBoxID).value;
        if (qty != '') {
            var code = $get(codeSpan).innerHTML;
            var upgradeCode = $get('spanUpgradeCode').innerHTML;
            ProductWebservice.CreateProductUpgradeReport(code, upgradeCode, qty, "No");
            AddToBasket();
        }
    }

    function AddUpgradeToBasket() {
	    var code = $get('spanUpgradeCode').innerHTML;
	    var qty = $get(QuantityTextBoxID).value;
	    var oldCode = $get(codeSpan).innerHTML;
	    var addAccessories = $get('spanAddAccessories').innerHTML;
	    var price = $get('UpgradeProductPrice').innerHTML;
	    price = ConvertStringToFloat(price);
	    ProductWebservice.CreateProductUpgradeReport(oldCode, code, qty, "Yes");
	    AddToBasketMethod(code, addAccessories, price);
	}

	function AddToBasketAndRedirect() {
	    redirectToBasket = true;
	    var qty = $get(QuantityTextBoxID).value;
	    if (qty != '') {
	        var code = $get(codeSpan).innerHTML;
	        var upgradeCode = $get('spanUpgradeCode').innerHTML;
	        var price = $get('ProductPrice').innerHTML;
	        ProductWebservice.CreateProductUpgradeReport(code, upgradeCode, qty, "No");
	        price = ConvertStringToFloat(price) / qty;
	        AddToBasketMethod(code, 'True', price);
	    }
	}

	function AddUpgradeToBasketAndRedirect() {
	    redirectToBasket = true;
	    var code = $get('spanUpgradeCode').innerHTML;
	    var addAccessories = $get('spanAddAccessories').innerHTML;
	    var qty = $get(QuantityTextBoxID).value;
	    var oldCode = $get(codeSpan).innerHTML;
	    var price = $get('UpgradeProductPrice').innerHTML;
	    price = ConvertStringToFloat(price);
	    ProductWebservice.CreateProductUpgradeReport(oldCode, code, qty, "Yes");
	    AddToBasketMethod(code, addAccessories, price);
	}
	
function AddToBasketMethod(code, addAccessories, price)
{
    var qty = $get(QuantityTextBoxID).value;
    if (qty != '')
    {
        if (qty > 0)
        {
            if ($get(InstallationCheckBox) != null)
            {
                var includeInstallation = $get(InstallationCheckBox).checked;
            }
            var MyArray = new Array(1)
            
            MyArray[1]  = code + ':' + qty + ':' + price + ':' + includeInstallation;

            if (addAccessories == 'True') {
                //main accessories
                if (typeof (AccessoryMain) != 'undefined') {
                    if (AccessoryMain > 0) {
                        AddChosenAccessory('Main', AccessoryMain, MyArray);
                    }
                }

                //extra accessories
                if (typeof (AccessoryExtra) != 'undefined') {
                    if (AccessoryExtra > 0) {
                        AddChosenAccessory('Extra', AccessoryExtra, MyArray);
                    }
                }
            }          
            ProductWebservice.AddItemsToBasket(MyArray, AddToBasketResponse);
        }
    }

}

function AddToBasketResponse(result) {
    if (redirectToBasket == false) {
        $get('spanAddToBasketHeader').innerHTML = result[0];
        $get('spanAddToBasketPanel').innerHTML = result[1];
        $get('BasketSummaryTotal').innerHTML = result[2];
        $get('spanErrorMessage').innerHTML = result[3];
        if (result[3] == '') {
            $get('spanErrorMessage').style.display = 'none';
        }
        else {
            $get('spanErrorMessage').style.display = '';
        }
        OpenModal('AddToBasket');
    }
    else {
        window.location ='../Basket';
    } 
}

function AddChosenAccessory(type, count, refArray)
{
    var result = 0;
    
    if (isInteger(count))
    {
        for(var i=1;i<=count;i++)
        {
            var name = 'Accessory' + type + 'TextBox' + i;
            if ($get(eval(name)) != null)
            {
                var ddl = $get(eval(name));
                if (ddl.value != '')
                {
                    var SelValue = ddl.value
                    if (SelValue > 0)
                    {   
                        //get code
                        var codename = 'Accessory' + type + 'Code' + i;
                        var code ='';
                        if ($get(eval(codename)) != null)
                        {
                            code = $get(eval(codename)).innerHTML;
                        }
                        
                        //get price
                        var pricename = 'Accessory' + type + 'Price' + i;
                        var price = 0.00;
                        if ($get(eval(pricename)) != null)
                        {
                            price = ConvertStringToFloat($get(eval(pricename)).innerHTML);
                        }
                             
                             
                        refArray.push(code + ':' + SelValue + ':' + price);
                   }
                }
            }
            
        }
    }
    
    return result;
}

//product comments
function ReviewKeyPress(element)
{
    var NewLength = 255 - element.value.length;
    if (NewLength <= 0)
    {
        NewLength = 0;
        element.value = element.value.substr(0,255);
    }
    document.getElementById('ReviewTextCounter').innerHTML = NewLength;
}

//common functions
   function isInteger (s)
   {
      var i;

      if (isEmpty(s))
      if (isInteger.arguments.length == 1) return 0;
      else return (isInteger.arguments[1] == true);

      for (i = 0; i < s.length; i++)
      {
         var c = s.charAt(i);

         if (!isDigit(c)) return false;
      }

      return true;
   }

   function isEmpty(s)
   {
      return ((s == null) || (s.length == 0))
   }

   function isDigit (c)
   {
      return ((c >= '0') && (c <= '9'))
   }
