// [MODULE-HEADER]
// *************************************************************************************************
//
// Name:				ShoWareFrontEndBasket.js
//
// Created:			13.05.2003 VisionOne Worldwide lbo
// Modified:		07.07.2011 VisionOne AG, St. Gallen fbe	: MMH Promotions
// Modified:		27/04/2010 VisionOne AG, St. Gallen NKU	: WI-2393- Fix for javascript error
// Modified:		06/06/2008 VisionOne AG, St. Gallen lbo	: SCR 364 - ' ' for some cultures in the group separator.
// Modified:		31/07/2007 VisionOne AG, St. Gallen lbo	: Handling payment method percentage fee.
// Modified:		11/03/2005 VisionOne AG, St Gallen fbe	: Fix to cultures that use unusual separators (' CH for instance)
// Modified:		27/02/2005 VisionOne AG, St Gallen fbe	: Changes in the formatting of currency values
// Modified:		13.05.2003 VisionOne Worldwide lbo	: Creation
//
// *************************************************************************************************

$(document).ready(function() {
	$('.GiftCertificateInfo').click(function(){
		showPopUp(NAVIGATIONHELPER_ShoWareFrontEndProGiftCertificateInfo, '', 
			'state=0,menubar=no,scrollbars=yes,resizable=yes,channelmode=0,dependent=0,directories=0', 
			'popupDialog',700,500,-1,-1); 
		return false;
	});
});

var B_Type = new crossBrowserType();
function crossBrowserType() {
	this.IE = false;
	this.NS4 = false;
	this.NS6 = false;
	this.id = "";

	if (document.all) {this.IE = true; this.id = "IE";}
	else if (document.getElementById) {this.NS6 = true; this.id = "NS6";}
	else if (document.layers) {this.NS4 = true; this.id = "NS4";}
}
function crossGetObject(id) {
	var obj = null;
	if (B_Type.IE) obj=document.all[id];
	else if (B_Type.NS6) obj=document.getElementById(id);
	else if (B_Type.NS4) obj=document.layers[id];
	return obj;
}

var previousDiv = null;;

/* 27.08.2008, Ari, visionone, São Paulo
   Changes to Implement Discount Box coming Expanded By Default (using a system setting)
   */
function ShowDivByDefault(divName){

	var objDiv = crossGetObject(divName);

	if (objDiv)
		objDiv.style.display = "block";
}


function ShowDivWithoutHidePreviousOne(divName){

	var objDiv = crossGetObject(divName);

	if (objDiv)
		if (objDiv.style.display == "block")
			objDiv.style.display = "none";
		else
			objDiv.style.display = "block";
}
/***/

function ShowDiv(divName){
	var objDiv = crossGetObject(divName);
	
	if (previousDiv)
		if (previousDiv == divName)
		{
			HideDiv(previousDiv);
			return;
		}
		else
			HideDiv(previousDiv);
	
	previousDiv = divName;
	
	if (objDiv)
	{
		objDiv.style.display = "block";
/*		if (B_Type.IE)
			objDiv.style.visibility = "display";
		else if (B_Type.NS6)
			objDiv.visibility = "display";
		else if (B_Type.NS4)
			objDiv.visibility = "display";*/
	}
}
function HideDiv(divName){
	var objDiv = crossGetObject(divName);
	previousDiv = null;
	
	if (objDiv)
	{
		objDiv.style.display = "none";
/*		if (B_Type.IE)
			objDiv.style.visibility = "hidden";
		else if (B_Type.NS6)
			objDiv.visibility = "hide";
		else if (B_Type.NS4)
			objDiv.visibility = "hide";*/
	}
}

function SWFrontEndBasket_ChangeDeliveryMethodValue(selectedDeliveryMethodID)
{
	var paymentMethodForDeliveryMethod = eval("SWBasket_payment4Delivery_" + selectedDeliveryMethodID);

	var changeSelectedPaymentMethod = false;
	var firstAvailablePaymentMethod = null;
	var currentlySelectedPaymentMethod = null;
	var optPaymentMethods = document.getElementsByName("optPaymentMethod");
	for (i=0; i < optPaymentMethods.length; ++i)
	{
		if (optPaymentMethods[i].tagName.toUpperCase() == 'INPUT' ) 
		{
			var shouldBeVisible = false;
			for (j=0; j < paymentMethodForDeliveryMethod.length; ++j)
			{
				if (paymentMethodForDeliveryMethod[j] == optPaymentMethods[i].value)
				{
					shouldBeVisible = true;
					if (firstAvailablePaymentMethod == null)
						firstAvailablePaymentMethod = optPaymentMethods[i];
					break;
				}
			}
			
			var parent = optPaymentMethods[i].parentNode;
			parent.style.display = shouldBeVisible ? 'inline' : 'none';
			if (optPaymentMethods[i].checked)
				if (!shouldBeVisible)
				{
					optPaymentMethods[i].checked = false;
					changeSelectedPaymentMethod = true; 
				}
				else
				{
					currentlySelectedPaymentMethod = optPaymentMethods[i];
				}
		}	
	}
		
	SWFrontEndBasket_UpdateFee(SWBasketFooter_lblShippingFee, eval("SWBasket_deliveryFee" + selectedDeliveryMethodID), false, 0, 0);
	
	if (changeSelectedPaymentMethod)
	{
		if (firstAvailablePaymentMethod)
		{
			firstAvailablePaymentMethod.checked = true;
			SWFrontEndBasket_UpdateFee(SWBasketFooter_lblPaymentFee, eval("SWBasket_paymentFee" + firstAvailablePaymentMethod.value), eval("SWBasket_paymentFeePercentage" + firstAvailablePaymentMethod.value), SWBasket_roundPrecisionForPaymentMethodFees, SWBasket_roundTypeForPaymentMethodFees);
		}
		else
		{
			SWFrontEndBasket_UpdateFee(SWBasketFooter_lblPaymentFee, 0, false, 0, 0);
		}
	}
	else
	{
		if (currentlySelectedPaymentMethod)
		{
			SWFrontEndBasket_UpdateFee(SWBasketFooter_lblPaymentFee, eval("SWBasket_paymentFee" + currentlySelectedPaymentMethod.value), eval("SWBasket_paymentFeePercentage" + currentlySelectedPaymentMethod.value), SWBasket_roundPrecisionForPaymentMethodFees, SWBasket_roundTypeForPaymentMethodFees);
		}
		else
		{
		}
	}
	
	// check the will call
	var isWillCall = false;
	for (i=0; i < SWBasket_willCalls.length; ++i)
	{
		if (SWBasket_willCalls[i] == selectedDeliveryMethodID)
		{
			isWillCall = true;
			break;
		}
	}
			
	var tablePickupLocation = document.getElementById("tablePickupLocation");	
	if (tablePickupLocation)
	{		
		var tableWillCallPickupLocations = document.getElementById("tableWillCallPickupLocations");
		
		if (!isWillCall)
		{
			if (SWBasket_hasWillCallOnly)
			{
				tableWillCallPickupLocations.style.display = "none";
			}
			else
			{
				tablePickupLocation.style.display = "none";			
			}
		}
		else
		{
			tableWillCallPickupLocations.style.display = "";
			tablePickupLocation.style.display = "";
		}
	}

  return;
}

function SWFrontEndBasket_ChangeDeliveryMethod(cboDeliveryMethod)
{
	var selectedDeliveryMethodID = cboDeliveryMethod.options[cboDeliveryMethod.options.selectedIndex].value;
	
	SWFrontEndBasket_ChangeDeliveryMethodValue(selectedDeliveryMethodID);
	
	// 20/04/2005 VisionOne AG, St Gallen fbe
	// Display the delivery method description
	if (SWBasket_deliveryMethodDisplayDescription)
		SWFrontEndBasket_DisplayDeliveryMethodDescription(cboDeliveryMethod.options.selectedIndex);
}

// Displays the delivery method description
function SWFrontEndBasket_DisplayDeliveryMethodDescription(deliveryMethodSelectedIndex)
{	
	SWFrontEndBasket_GetElementByName("deliveryMethodDescription").innerHTML = SWBasket_deliveryMethodDescriptions[deliveryMethodSelectedIndex];
}

function SWFrontEndBasket_PaymentMethodChanged(selectedPaymentMethodID)
{
	SWFrontEndBasket_UpdateFee(SWBasketFooter_lblPaymentFee, eval("SWBasket_paymentFee" + selectedPaymentMethodID), eval("SWBasket_paymentFeePercentage" + selectedPaymentMethodID), SWBasket_roundPrecisionForPaymentMethodFees, SWBasket_roundTypeForPaymentMethodFees);
	var needsCreditCard = false;
	try
	{
		if (selectedPaymentMethodID > 0)
			needsCreditCard = eval("SWBasket_paymentMethodNeedsCreditcard" + selectedPaymentMethodID);
	}
	catch(err){}
	
	var creditCardFields = crossGetObject("creditCardFields");
	if (creditCardFields)
	{
		creditCardFields.style.display = needsCreditCard ? "block" : "none";
	}
}


function SWFrontEndBasket_UpdateFee(feeElementName, newFeeValue, newFeePercentage, roundPrecision, roundType)
{	
	var curFeeValue = 0;
	var curFeeValueText = SWFrontEndBasket_GetText(feeElementName);
	curFeeValue = SWFrontEndBasket_ToFloat(curFeeValueText);				
			
	// updates the ui
	if (newFeePercentage)
	{
		var curTotalValue = 0;
		var curTotalValueText = SWFrontEndBasket_GetText(SWBasketFooter_lblOrderTotal);
		curTotalValue = SWFrontEndBasket_ToFloat(curTotalValueText);
		curTotalValue -= curFeeValue;
		newFeeValue = ((curTotalValue / (1 - (newFeeValue / 100))) - curTotalValue);
		newFeeValue = ShoWarePageBase_Round(newFeeValue, roundPrecision, roundType)
		//alert(feeElementName + ", " + newFeeValue + ", " + newFeePercentage + "\r\n" + curTotalValueText + " / " + curTotalValue);
	}
	SWFrontEndBasket_GetElementByName(feeElementName).innerHTML = SWFrontEndBasket_FormatDecimal(newFeeValue);	
	
	SWFrontEndBasket_UpdateOrderTotal(newFeeValue - curFeeValue);
}

function SWFrontEndBasket_UpdateOrderTotal(difference)
{
    var curTotalValue = 0;
    var curTotalValueText = SWFrontEndBasket_GetText(SWBasketFooter_lblOrderTotal);
    curTotalValue = SWFrontEndBasket_ToFloat(curTotalValueText);

    var newOrderTotal = curTotalValue + (difference);
    SWFrontEndBasket_GetElementByName(SWBasketFooter_lblOrderTotal).innerHTML = SWFrontEndBasket_FormatDecimal(newOrderTotal);
    //alert('SWFrontEndBasket_UpdateOrderTotal = ' + newOrderTotal + ' (difference = ' + difference + ')' + "\r\n" + curTotalValueText);

    // if there is gift certificates, update them too
    if (window.SWFrontEndGiftCertificate_UpdateOrderTotal)
    {
        SWFrontEndGiftCertificate_UpdateOrderTotal(newOrderTotal);
    }


    if (window.SWBasketFooter_lblTotalLeftToPay)
    {
        var curTotalToPayValue = 0;
        var curTotalToPayValueText = SWFrontEndBasket_GetText(SWBasketFooter_lblTotalLeftToPay);
        curTotalToPayValue = SWFrontEndBasket_ToFloat(curTotalToPayValueText);

        curTotalToPayValue += difference;
        SWFrontEndBasket_GetElementByName(SWBasketFooter_lblTotalLeftToPay).innerHTML = SWFrontEndBasket_FormatDecimal(curTotalToPayValue);

        if (curTotalToPayValue > 0)
        {
            $('.PaymentMethods_Area').show();
        }
        else
        {
            $('.PaymentMethods_Area').hide();
        }
    }
    else
    {
        if (newOrderTotal > 0)
        {
            $('.PaymentMethods_Area').show();
        }
        else
        {
            $('.PaymentMethods_Area').hide();
        }
    }

}

function SWFrontEndBasket_GetElementByName(elementName)
{
	if (document.getElementById)
		return document.getElementById(elementName);
		
	return null;
}


function SWFrontEndBasket_StringInsert(value, index, valueToInsert)
{
	var result = value.substring(0, index);
	result += valueToInsert;
	
	if (index < value.length)
		result += value.substring(index, value.length);
		
	return result;
}


function SWFrontEndBasket_ToFloat(value)
{
	var result = 0;
	if (value && value != "undefined")
	{
		var newValue = "";		
		for (i=0; i < value.length; ++i)
		{
			if (value.charAt(i) != '.' 
				&& value.charAt(i) != ','
				&& value.charAt(i) != ' '
				&& value.charAt(i) != "'"
				&& value.charAt(i) != clientFormatThousandSeparator
				&& value.charAt(i) != clientFormatDecimalPoint)
			{
				newValue += value.charAt(i);
			}
		}
		
		if (!isNaN(newValue))
		{
			result = parseFloat(newValue) / 100.0;
		}
	}
	
	return result;	
}

function SWFrontEndBasket_FormatDecimal(value)
{
	value = Math.round(value * 100) / 100;
	
	var DECIMAL_COUNT = 2;
	var currDecimal = 0;
	var result = new String(value);
	var separator = clientFormatDecimalPoint;

	if(!isNaN(value))
	{
		var indexDecimalSeparator = Math.max(result.lastIndexOf("."), result.lastIndexOf(","));
		indexDecimalSeparator = Math.max(indexDecimalSeparator, result.lastIndexOf(clientFormatThousandSeparator));
		indexDecimalSeparator = Math.max(indexDecimalSeparator, result.lastIndexOf(clientFormatDecimalPoint));		
		
		if (indexDecimalSeparator != -1)
		{
			currDecimal = result.length - (indexDecimalSeparator + 1);
			
			var tempResult = "";
			for (i=0; i < result.length; ++i)
			{
				if (result.charAt(i) != ',' 
					&& result.charAt(i) != '.' 
					&& result.charAt(i) != ' ' 
					&& result.charAt(i) != "'"
					&& result.charAt(i) != clientFormatThousandSeparator
					&& result.charAt(i) != clientFormatDecimalPoint)
				{
					tempResult += result.charAt(i);
				}
			}												
			
			result = tempResult;
		}				
		
		// add the '0's in the end
		for (; currDecimal < DECIMAL_COUNT; ++currDecimal)
			result += '0';
			
		result = SWFrontEndBasket_StringInsert(result, result.length - 2, clientFormatDecimalPoint);	
		
		// add the thousand separators
		var thousandSeparatorsCount = Math.floor(((result.length - (2 + DECIMAL_COUNT)) / 3));
		if (thousandSeparatorsCount > 0)
		{
			var indexToAddSeparator = result.length - (DECIMAL_COUNT + 4);
			for (; thousandSeparatorsCount > 0; --thousandSeparatorsCount)
			{
				result = SWFrontEndBasket_StringInsert(result, indexToAddSeparator, clientFormatThousandSeparator);
				indexToAddSeparator -= 3;
			}
		}
	}

	return result;			
}

function SWFrontEndBasket_GetText(elementName)
{
	var element = SWFrontEndBasket_GetElementByName(elementName);
	if (element)
		// cross browser solution
		return element.innerText || element.textContent;
	return '';
}

function SWFrontEndBasket_ShowPromotionRedemptionTutorial(message) {
/*    $("input[type=text].promocodetextbox").first().qtip({
        style: { border: { width: 2, radius: 8} },
        content: { text: message },
        show: { ready: true }
    });

    setTimeout(function() { $("input[type=text].promocodetextbox").first().qtip("destroy"); }, 5000);    */
}

$(document).ready(function () {

    // setup tooltips
    $(".promocodetextbox").each(function () {
        var $imageHint = $(this).parent().find(".ItemPromotion_Hint");
        var promotions = $imageHint.attr("promotions");

        $imageHint.qtip({
            position: { corner: { tooltip: 'leftMiddle'} },
            show: { solo: true },
            style: { width: 300, height: 250, tip: true },
            content: { url: '../Basket/ShoWarePromotionTooltipInfo.aspx', data: { ID: promotions} }
        });

        $(this).focus(function (e) {
            e.stopPropagation();
            var $imageHint = $(this).parent().find(".ItemPromotion_Hint");
            $imageHint.qtip("show");
        });

        $(this).blur(function (e) {
            e.stopPropagation();
            var $imageHint = $(this).parent().find(".ItemPromotion_Hint");
            $imageHint.qtip("hide");
        });

        $(this).keydown(function (e) {
            if (e.keyCode == 13) {
                e.stopPropagation();
                e.preventDefault();
                $(this).parent().find(".ApplyPromotion").first().click();
            }
        });

    });

    $(".RedeemPromotion_Hint").each(function () {
        $(this).qtip({
            position: { corner: { tooltip: 'leftMiddle'} },
            show: { solo: true },
            content: '<span class="FormDefaultLabel">'+message_redeempromotion_hint+'</span>'
        });
    });
});
