/**
 * Magento
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE_AFL.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magentocommerce.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magentocommerce.com for more information.
 *
 * @copyright  Copyright (c) 2008 Irubin Consulting Inc. DBA Varien (http://www.varien.com)
 * @license    http://opensource.org/licenses/afl-3.0.php  Academic Free License (AFL 3.0)
 */

var Subscription = Class.create();
Subscription.prototype = {
    initialize: function(cartContainer, urls, nbOffer, isResubscription, currentProduct){
        this.cartContainer = cartContainer;
        this.nbOffer = nbOffer;
        this.isResubscription = isResubscription;
        this.currentProduct = currentProduct;
        this.tempProduct = null;
        this.saveUrl = urls.save;
        this.addAjaxUrl = urls.addAjaxUrl;
        this.removeAjaxUrl = urls.removeAjaxUrl;
        this.onSave = this.addReaboToCart.bindAsEventListener(this);
        this.onComplete = this.resetLoadWaiting.bindAsEventListener(this);
        this.loadWaiting = false;
        this.selectedProductId = '';
        this.selectedShippingArray = new Array('');
    },

    ajaxFailure: function(){
    	$('ajaxFailed').value = 1;
    },

    saveShipping: function(){
	
    	var oRadio = $$('.shipping_method');
        this.selectedShippingArray = new Array('');
    	if(oRadio){
			for(var i = 0; i < oRadio.length; i++) {
				if(oRadio[i].checked) {
					this.selectedShippingArray.push(oRadio[i].id);
				}
			}
    	}
    },

    restoreShipping: function(){
    	if(this.selectedShippingArray && this.selectedShippingArray.length>0){
			for(var i = 0; i < this.selectedShippingArray.length; i++) {
		    	if(this.selectedShippingArray[i] != '' && $(this.selectedShippingArray[i])){
		    		$(this.selectedShippingArray[i]).checked=true;
		    	}
			}
			this.changePriceTotal();
    	}
    },
    
    changePriceTotal : function(){
		var oRadio = $$('.shipping_method');
		var shippingvalue = 0;
		for(var i = 0; i < oRadio.length; i++) {
			if(oRadio[i].checked) {
				name = oRadio[i].value+'_price';
				shippingvalue = shippingvalue + parseFloat($(name).value);
			}
		}
		var newSubtotal = $('subtotal').value;
		var discount = $('discount').value;
		var newShipping = '';
		newSubtotal = parseFloat(newSubtotal) + parseFloat(shippingvalue) + parseFloat(discount);
		var num = new Number(newSubtotal);
		var shippingNum = new Number(parseFloat(shippingvalue));
		newSubtotal = 'Total : <strong>'+num.toFixed(2)+'&nbsp;&#x20AC;</strong>'
		newShipping = 'Frais de port : <strong>'+shippingNum.toFixed(2)+'&nbsp;&#x20AC;</strong>'
		$('tunnel_total_value').innerHTML = newSubtotal;
		$('tunnel_shipping_value').innerHTML = newShipping;
		this.toggleValidCart(true);
		//this.saveShipping();
	},


    toggleValidCart: function(enable){
    	if(!enable){
			document.getElementById("reaboStep2Basket2" ).innerHTML  = '<div id="reaboStep2Basket"><p class="tunnelValidBasket">Panier validé</p></div>';
			var oA = document.getElementById('reaboStep2');
			oA.className = 'reaboStep2Valid';
    	}else{
			document.getElementById("reaboStep2Basket2" ).innerHTML  = '<div onclick="validCart()" id="reaboStep2Basket"><a href="javascript:return false;">Je valide mon panier</a></div>';
			var oA = document.getElementById('reaboStep2');
			oA.className = 'reaboStep2';
    	}
    },
    
    isChecked: function(productId){
		if (productId == $('selectedProductId').value)
			return true;
		else 
			return false;
    },
	
    setSelectedProductId: function(productId) {
    	if($('inputOffer_'+productId)){
    		if(this.currentProduct == null){
    			this.currentProduct = productId;
    		}else{
        		$('inputOffer_'+this.currentProduct).checked=false;
    			this.currentProduct = productId;
    		}
    		$('inputOffer_'+this.currentProduct).checked=true;
    	}
	},
	
    unsetSelectedProductId: function(productId) {
    	if($('inputOffer_'+productId)){
    		$('inputOffer_'+productId).checked=false;
    		$('inputOffer_'+productId).blur();
    	}
	},

    
    getSelectedProductId: function(url){
    	new Ajax.Request(url, { 
    		method:'post',
    		asynchronous: false,
    		onSuccess: function(req) {	
    			var json = req.responseText.evalJSON();
    			if (json.getSelectedProductId) {
    				$('selectedProductId').value = json.getSelectedProductId;
    			}
    		}
    	});
    },
    
    
		
    setSelectedMagReabo: function(subscriptionForm) {
    	var validator = new Validation(subscriptionForm); 
    	if (validator.validate()) { 
			this.addReaboToCart(subscriptionForm);
		}
	
	tunnel.changePriceTotal();
	},

    addReaboToCart: function(subscriptionForm){
    	this.saveShipping();
    	this.form = subscriptionForm; 

	   if (this.loadWaiting!=false) return;
	   this.setLoadWaiting('tunnel');
		
			
	    var request = new Ajax.Request(
	        		this.addAjaxUrl,
	                {
			    asynchronous:false,
	                    method:'post',
	                    onComplete: this.onComplete,
	                    onSuccess: this.updateCart.bindAsEventListener(this),
	                    onFailure: this.ajaxFailure.bind(this),
	                    parameters: Form.serialize(this.form) 
	                }
	    );
    },

    addProductToCart: function(url,productForm){
    	this.submitUrl = url; 
    	this.form = productForm;
	   if (this.loadWaiting!=false) return;
	   this.setLoadWaiting('tunnel');
		
			
	    var request = new Ajax.Request(
	    			this.submitUrl,
	                {
	                    method:'post',
	                    onComplete: this.onComplete,
	                    onSuccess: this.updateCart.bindAsEventListener(this),
	                    onFailure: this.ajaxFailure.bind(this),
	                    parameters: Form.serialize(this.form) 
	                }
	    );
   
    },

    addProductToCartCB: function(url,productForm){
    	this.submitUrl = url; 

			
	    var request = new Ajax.Request(
	    			this.submitUrl,
	                {
	                    method:'post',
	                    onComplete: this.onComplete,
	                    onSuccess: this.updateCart.bindAsEventListener(this),
	                    onFailure: this.ajaxFailure.bind(this)
	                }
	    );
	    parent.J($.fn).colorbox.close();
   
    },

    removeProduct: function(productId){
    	this.saveShipping();
        if (this.loadWaiting!=false) return;
		this.setLoadWaiting('tunnel');
		urlToUse = this.removeAjaxUrl+'item_to_remove/'+productId;		
        var request = new Ajax.Request(
        		urlToUse,
                {
                    method:'post',
                    onComplete: this.onComplete,
                    onSuccess: this.updateCart.bindAsEventListener(this),
                    onFailure: this.ajaxFailure.bind(this)
                }
        );
    },
   
    checkCoupon: function(checkCouponUrl){
    	this.saveShipping();
    	this.checkCouponUrl = checkCouponUrl;
    	new Ajax.Request(this.checkCouponUrl + (this.checkCouponUrl.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true' ), {
    	    parameters : {
    	    	coupon_code: $F('coupon_code'),
    	    	customer: $F('customerId')
    	    },
    	    method     : 'post',
            onComplete: this.onComplete,
            onSuccess: this.updateCart.bindAsEventListener(this),
            onFailure: this.ajaxFailure.bind(this)
    	});
    },
   
    removeCoupon: function(checkCouponUrl){
    	this.saveShipping();
    	this.checkCouponUrl = checkCouponUrl;
    	new Ajax.Request(this.checkCouponUrl + (this.checkCouponUrl.match(new RegExp('\\?')) ? '&isAjax=true' : '?isAjax=true' ), {
    	    parameters : {
    	    	remove: '1'
    	    },
    	    method     : 'post',
            onComplete: this.onComplete,
            onSuccess: this.updateCart.bindAsEventListener(this),
            onFailure: this.ajaxFailure.bind(this)
    	});
    },
    
    updateCart: function(transport){
        if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
        }
        /*
        * if there is an error in payment, need to show error message
        */
        if (response.error) {
            this.unsetSelectedProductId(response.last_product);
            alert(response.message);
            return;
        }
        if (response.success) {
        	$('tunnel_cart').innerHTML = response.html;
        	if (response.message) {
               // $('promoCodeMessage').innerHTML = response.message;
            }

            $$('.shipping_method').each(function(e) {
                if(e.checked) {
                    e.checked = false;
                }
            });

        	if($('nbItems') && response.nbItem){
        		$('nbItems').innerHTML = response.nbItem;
        	}
            $('selectedProductId').value = response.addedproduct;
            if(response.last_product && response.last_product != ''){
            	this.unsetSelectedProductId(response.last_product);
            }
            this.setSelectedProductId(response.addedproduct);
            this.toggleValidCart(true);
            if(response.containadi){
            	this.displayCheckmo(false);
            }else{
            	this.displayCheckmo(true);
            }
            this.restoreShipping();
        }
    },
   
    _disableEnableAll: function(element, isDisabled) {
        var descendants = element.descendants();
        for (var k in descendants) {
            descendants[k].disabled = isDisabled;
        }
        element.disabled = isDisabled;
    },

    setLoadWaiting: function(step, keepDisabled) {
//        if (step) {
//            if (this.loadWaiting) {
//                this.setLoadWaiting(false);
//            }
//            var container = $(step+'-buttons-container');
//            container.setStyle({opacity:.5});
//            this._disableEnableAll(container, true);
//            Element.show(step+'-please-wait');
//        } else {
//            if (this.loadWaiting) {
//                var container = $(this.loadWaiting+'-buttons-container');
//                var isDisabled = (keepDisabled ? true : false);
//                if (!isDisabled) {
//                    container.setStyle({opacity:1});
//                }
//                this._disableEnableAll(container, isDisabled);
//                Element.hide(this.loadWaiting+'-please-wait');
//            }
//        }
        this.loadWaiting = step;
    },

    resetLoadWaiting: function(){
        this.setLoadWaiting(false, this.isSuccess);
    },
    
    displayCheckmo: function(display){
    	if (display) {
			var elOptNew = document.createElement('option');
	        elOptNew.text = 'Par chèque'
	        elOptNew.value = 'checkmo';
	        elOptNew.id = 'checkmo';
	        if (!$('checkmo')) {
			    try {
	                $('payment_methods').add(elOptNew, $('payment_methods').options[2]); // standards compliant; doesn't work in IE
	            }
	            catch(ex) {
	                $('payment_methods').add(elOptNew, 2); // IE only
	            }
	            $('atossips_cb').value = 'atossips_direct';
	            $('atossips_cb').text = 'Par carte bancaire';
	        }
		} else {
			if ($('checkmo')) $('payment_methods').remove(2);
			$('atossips_cb').value = 'atossips_ccimprint';
            $('atossips_cb').text = 'Par carte bancaire (PayId)';
		}
	    $('payment_methods').selectedIndex = 0;
	    if (!$('payment_form_atossips_direct') && $('payment_form_atossips_ccimprint'))
            $('payment_form_atossips_ccimprint').id = 'payment_form_atossips_direct'
		$('payment_form_atossips_direct').hide();
    },
    
    isSuccess: true
}

