/**
 *
 * Below code added for Promotion Code changes to viewOrder and payment pages
 * @author Krishna Huliyar
 *
 */

/**
* Call back handler object and methods
*/

function Callback() {
	this.handleError = handleError;
	this.handleSuccess = handleSuccess;
	this.handleFailure = handleFailure;                      
	function handleError(msg) {
	}

	function handleSuccess(response) {
		var error;
		var proceed = true;
		var valChanged = false;
	
		if(proceed) {
			var discountDataElement = response.getElementsByTagName("discountData");
			var packageId = discountDataElement[0].getElementsByTagName("packageid")[0].firstChild.nodeValue;
			var result = discountDataElement[0].getElementsByTagName("result")[0].firstChild.nodeValue;
			var total = discountDataElement[0].getElementsByTagName("total")[0].firstChild.nodeValue;
			if(result == 'success') {
				var discount = discountDataElement[0].getElementsByTagName("discount")[0].firstChild.nodeValue;
				//alert("Result ["+result+"] Discount ["+discount/100+"]");
				ret = discount;
				valChanged = true;
				//return (discount/100);
			} else {
				ret = total;
			}
		} else {
			ret = "0.00";
		}
		
		if($$('div.promotionhead')[0].hasClass('hidden')) {
			//make the heading div with 'Your price' visible
			$$('div.promotionhead')[0].removeClass('hidden');
			$$('div.promotionhead')[0].addClass('visible');
		}
		
		if($('discount-' + packageId).getParent().hasClass('hidden')) {
			$('discount-' + packageId).getParent().removeClass('hidden');
			$('discount-' + packageId).getParent().addClass('visible');
		}
		if(valChanged) {
			if($('discount-' + packageId).getParent().hasClass('error')) {
				$('discount-' + packageId).getParent().removeClass('error');
			}
		} else {
			$('discount-' + packageId).getParent().addClass('error');
		}
		$('discount-' + packageId).set('html', ret);
	}
	function handleFailure() {
	}
}

var callback = new Callback();

//Call the WS to calculate the discount for package

function getDiscountByProduct(packageId, promotionCode, product, myAccountName, channel, currency, operation, orderId, total) {
	var proceed = true;
	if(proceed) {
		var results_wait = document.getElementById('results_wait');
		//results_wait.style.display = "inline";
		queryString = "promotionCode="+promotionCode+"&product="+product+"&myAccountName="+myAccountName+"&channel="+channel+"&currency="+currency+"&operation="+operation + "&packageId=" + packageId + "&orderId=" + orderId + "&total=" + total;
		//queryString = "promotionCode=test_51&packageId=123456&product=17076&myAccountName=jptest70&channel=RETAIL&currency=AUD&operation=New&packageRRPAmount=20455&packageId=185452";
		XMLHttpPost('/cc/soap/calculateDiscountForProduct', "?"+queryString, callback);
	} else {
		return 0;
	}
}

/* 
 * sets cookie with name = oid and value = currency. 
 * also used to alert customer of currency changes on payment confirmation page
 */ 
function currencyCookie() {
	var oid = Cookie.read("oid");
	var initial = Cookie.read(oid);
	var region = (Cookie.read("butternut_snap") == 'au') ? "AUD" : "USD";	
	if($('oidCurrency')) var oidCurrency = $('oidCurrency').innerHTML;
	if($('callcenter')) var contactNumber = $('callcenter').innerHTML;	
	if (!initial && !oidCurrency) 
	{
		Cookie.write(oid, region, { duration : 0, path : '/' });
	} 
	else if (contactNumber && initial && oidCurrency) 
	{	    
	   if (initial != oidCurrency) {
		   var alertMessage = '';
           if (oidCurrency == 'USD') alertMessage = 'Your order currency has changed to US dollars (USD) to reflect your MyAccount details.<br />Please call us on +61 3 8624 2300 if you have any concerns.';
           else alertMessage = 'Your order currency has changed to Australian dollars (AUD) to reflect your MyAccount details. GST is applicable for Australian residents.<br />Please call us on 1300 769 784 if you have any concerns.';		
		   var currencyAlert = new Element('div', { 'id': 'currencyAlert' }).inject('paymentFormSection')
		   var message = new Element('p', { 'html' : alertMessage }).inject(currencyAlert);
		   var iconBlock = new Element('div', { 'id' : 'iconBlock' }).inject(currencyAlert, 'top');
		   var notice = new Element('strong', { 'html' : 'NOTICE:' }).inject(iconBlock, 'top');
		   var alertIcon = new Element('img', { 'src' : '/gfx/icons/icon_alert2.gif' }).inject(iconBlock, 'top'); 
	   }   
	}
}


if(window.addEvent != null) {
    window.addEvent('domready', function() {
			
		currencyCookie();			
		
        if($('addPromotion')) { //addPromotion form exists
            
			var txt = 'Enter your promotion code here';
            if($('promotionCode').value == null || $('promotionCode').value == 'null') {
                $('promotionCode').set('value', txt);
            }
            $('promotionCode').addEvent('focus', function() {
                if(this.get('value') == txt) {
                    this.set('value', '');
                }
            });
            
            $('promotionCode').addEvent('blur', function() {
                if(this.get('value') == '') {
                    this.set('value', txt);
                }
            });
            
            $('addPromotion').addEvent('submit', function() {
                if($('promotionCode').get('value') == txt) {
                    $('promotionCode').set('value') == '';
                }
                
                oldPromo = $('oldPromotionCode').get('value');
                newPromo = $('promotionCode').get('value');
                
                if(oldPromo != 'null' && newPromo == '') {
                    ret = confirm("Do you want to remove the promotion code " + oldPromo);
                } else if(oldPromo == newPromo) {
                    ret = false;
                } else {
                    ret = true;
                }
                return ret;
            });
            
            var val = '';
            $$('select.calculateDiscount').each(function(sel) {
                sel.addEvent('change', function() {
                    id = sel.id.split('|')[1];
                    paramArray = sel.getSelected()[0].id.split('|');
                    val = sel.getSelected()[0].value; 
                    /**
                     * 0 - package id
                     * 1 - promotion code
                     * 2 - product
                     * 3 - myaccount username
                     * 4 - channel
                     * 5 - currency
                     * 6 - operation
                     * 7 - orderId
                     * 8 - total
                     */
                    if(val != "" && paramArray[1] != null) {
                        getDiscountByProduct(paramArray[0], paramArray[1], paramArray[2], paramArray[3], paramArray[4], paramArray[5], paramArray[6], paramArray[7], paramArray[8]);
                    } else {
                        $('discount-' + id).set('html', "0.00");
                        $('discount-' + id).getParent().addClass('error');
                    }
                });
            });
            
            if($$('span.discount.visible').length == 0) {
                $$('div.promotionhead')[0].addClass('hidden');
            } else {
                $$('div.promotionhead')[0].addClass('visible');
            }
            
            /*if(Browser.Engine.trident) {            	
                $('viewOrderSubmitWrapper').setStyle("top", $('promotionSubmit').getCoordinates().top - 5);
            } else {
                $('viewOrderSubmitWrapper').setStyle("bottom", 0);
            }*/ 
        }
        
        if($('discountContainer')) {
            //this is to add '()' around the discount price in payment page.
            //discountCotainer exists, ie. payment page.
            signSpan = $$('div#discountContainer span.sign')[0];
            signSpan.set('html', '(' + signSpan.get('html'));
            
            priceSpan = $$('div#discountContainer span.price')[0];
            priceSpan.set('html', priceSpan.get('html') + ')');
        } 
        
    });
}