/**
 * 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 Checkout = Class.create();
Checkout.prototype = {
	initialize: function(accordion, urls, sections){
		this.progressUrl = urls.progress;
		this.reviewUrl = urls.review; //laatste URL voor opslaan order
		this.saveMethodUrl = urls.saveMethod;
		this.failureUrl = urls.failure;
		this.billingForm = false;
		this.shippingForm = false;
		this.syncBillingShipping = false;
		this.method = '';
		this.payment = '';
		this.loadWaiting = false;
		this.sections = sections;
		this.accordion = accordion;
		this.accordion.disallowAccessToNextSections = true;
		this.currentSection;
		
		this.retries = 0;
		this.setGuest();
		
		this.showStep(0); //eerste sectie openen
	},
	
	setGuest: function(){
		this.retries++;
		if (this.retries>6) return false;
		new Ajax.Request(
	        this.saveMethodUrl,
	        {method: 'post', onFailure: this.setGuest.bind(this), parameters: {method:'guest'}}
	    );
	},
	
	ajaxFailure: function(request){
		//location.href = this.failureUrl;
	},
	
    reloadProgressBlock: function(){
		$('review').show();
        var updater = new Ajax.Updater($$('.op-progress')[0], this.progressUrl, {method: 'get',
		onFailure: function(response)
		{
			ajaxErrorLog(response, 'Checkout.reloadProgressBlock');
		}
		});
    },
	
	showStep: function (step)
	{
		section = $(this.sections[step]);
        section.addClassName('allow');
        this.accordion.openSection(section);
		
		//vorige secties toestaan
		
		for (i = 0; i < step; i++)
		{
			this.section = $(this.sections[i])
			this.section.addClassName('allow');
		}
		this.currentSection = step;
	}
}

var Shipping = Class.create();
Shipping.prototype = {
    initialize: function(form, saveUrl){
		this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
		this.sameAsBilling = true;
        this.saveUrl = saveUrl;
		this.onSave = this.nextStep.bindAsEventListener(this);
    },
	
	setSameAsBilling: function(value){
		this.sameAsBilling = value;
		billing.setUseForShipping(value);
	},
	
	save: function(){
		var validator = new Validation(this.form);
        if (validator.validate()) {
			billing.setEmail($('shipping:email').value)
			var request = new Ajax.Request(
	            this.saveUrl,
	            {
	                method:'post',
	                onSuccess: this.onSave,
					onFailure: function(response)
					{
						ajaxErrorLog(response, 'Shipping.save');
					},
	                parameters: Form.serialize(this.form)
	            }
	        );
		}
	},
	
	nextStep: function(transport){
		if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                errorLog('response', 'lege of onjuiste response', 'shipping.nextStep');
				return false;
            }
        }
		
        if (response.error) {
			errorLog('response', 'fout: ' + response.message, 'shipping.nextStep');
			if (response.message != undefined)
            	alert(response.message);
            return false;
        }

        if (response.update_section) {
            $('shipping_selector').update(response.update_section.html);
            response.update_section.html.evalScripts();
        }
		
		if (this.sameAsBilling){
			billing.syncWithShipping();
			billing.save(true); //gaat ook naar volgende stap
		}
		else
		{
			checkout.showStep(1); //volgende stap
		}
		//checkout.reloadProgressBlock();
	}	
}

var Billing = Class.create();
Billing.prototype = {
	initialize: function(form, saveUrl){
		this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }		
		this.emailadres = "";
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.saveUrl = saveUrl;
	},
	
	setUseForShipping: function(value){
		if (value){
			this.syncWithShipping();
		}
		else{
			$(this.form).enable();
		}
		shipping.sameAsBilling = value;
        $('shipping:same_as_billing').checked = value;
        $('billing:use_for_shipping').checked = value;
	},
	
	setEmail: function(value){
		this.emailadres = value;
	},
		
    syncWithShipping: function () {
		//$(this.form).disable();
        arrElements = Form.getElements(this.form);
        for (var elemIndex in arrElements) {
            if (arrElements[elemIndex].id) {
                var sourceField = $(arrElements[elemIndex].id.replace(/^billing:/, 'shipping:'));
                if (sourceField){
                    arrElements[elemIndex].value = sourceField.value;
                }
            }
        }
    },
	
	save: function(hide){
		if (hide) succes = function(){};
		var validator = new Validation(this.form);
        if (validator.validate()) {
			var request = new Ajax.Request(
	            this.saveUrl,
	            {
	                method:'post',
	                onSuccess: this.onSave,
					onFailure: function(response)
					{
						ajaxErrorLog(response, 'Billing.save');
					},
	                parameters: Form.serialize(this.form) + "&billing[email]=" + this.emailadres
	            }
	        );
		}
	},
	
	nextStep: function(transport){
		if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                errorLog('response', 'lege of onjuiste response', 'billing.nextStep');
				return false;
            }
        }
		if (response.goto_section == 'shipping') 
			checkout.showStep(2); //volgende stap
		else 
		{
			errorLog('response', 'fout: ' + response.message, 'billing.nextStep');
			if (response.message != undefined)
            	alert(response.message);
		}
	}
}


var ShippingMethod = Class.create();
ShippingMethod.prototype = {
	initialize: function(form, saveUrl){
		this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.saveUrl = saveUrl;
		
		this.selectedShipMethod;
		this.setShipMethod();
	},
	
	save: function(){
		this.setShipMethod(); //extra check
		
		var validator = new Validation(this.form);
	        if (validator.validate()) {
				var request = new Ajax.Request(
	            this.saveUrl,
	            {
	                method:'post',
	                onSuccess: this.onSave,
					onFailure: function(response)
					{
						ajaxErrorLog(response, 'ShippingMethod.save');
					},
	                parameters: "&shipping_method=" + this.selectedShipMethod
	            }
	        );
		}
	},
	
	setShipMethod: function(){
		this.selectedShipMethod = getCheckedValue($(this.form).shipping_method);
		if (this.selectedShipMethod!="tablerate_bestway" && this.selectedShipMethod!="freeshipping_freeshipping")
		{
			if ($('payment_method:cashondelivery'))
			{
				$('payment_method:cashondelivery').disable();
				$('payment_method:cashondelivery').checked = false;
			}
			if ($('payment_method:checkmo')) $('payment_method:checkmo').enable();
		}
		else
		{
			if ($('payment_method:cashondelivery')) $('payment_method:cashondelivery').enable();
			if ($('payment_method:checkmo'))
			{
				$('payment_method:checkmo').disable();
				$('payment_method:checkmo').checked = false;
			}
		}
	},
	
	nextStep: function(transport){
		if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
				errorLog('response', 'lege of onjuiste response', 'ShippingMethod.nextStep');
				return false;
            }
        }
		
        if (response.error) {
			errorLog('response', 'fout: ' + response.message, 'ShippingMethod.nextStep');
			if (response.message != undefined)
            	alert(response.message);
            return false;
        }

        if (response.update_section) {
            $('payment').update(response.update_section.html);
            response.update_section.html.evalScripts();
        }
		
		checkout.showStep(3); //volgende stap
		//checkout.reloadProgressBlock();
	}
}

var PaymentMethod = Class.create();
PaymentMethod.prototype = {
	initialize: function(form, saveUrl){
		this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
		this.onSave = this.nextStep.bindAsEventListener(this);
		this.saveUrl = saveUrl;
		
		this.selectedPayMethod;
		this.setPayMethod();
	},
	
	getPaymentParams: function(){
		return "&payment[method]=" + this.selectedPayMethod;
	},
	
	save: function(){
		this.setPayMethod(); //extra check
		var validator = new Validation(this.form);
        if (validator.validate()) {
			var request = new Ajax.Request(
	            this.saveUrl,
	            {
	                method:'post',
	                onSuccess: this.onSave,
					onFailure: function(response)
					{
						ajaxErrorLog(response, 'PaymentMethod.save');
					},
	                parameters: this.getPaymentParams()
	            }
	        );
		}
	},
	
	nextStep: function(){
		checkout.showStep(4); //volgende stap
		checkout.reloadProgressBlock();
	},
	
	setPayMethod: function(){
		this.selectedPayMethod = getCheckedValue($(this.form).payment_method);
	}
}

var Review = Class.create();
Review.prototype = {
    initialize: function(saveUrl, successUrl, form){
		this.debug = false;
        this.saveUrl = saveUrl;
        this.successUrl = successUrl;
        this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        this.onSave = this.nextStep.bindAsEventListener(this);
    },

    save: function(){
		$('onepage_submit').disable();
		var validator = new Validation(this.form);
        if (validator.validate()) {
	        var params = paymentMethod.getPaymentParams();			
	        if (this.form) {
	            params += '&'+Form.serialize(this.form);
	        }
	        params.save = true;
	        var request = new Ajax.Request(
	            this.saveUrl,
	            {
	                method:'post',
	                parameters:params,
	                //onComplete: this.onComplete,
	                onSuccess: this.onSave,
	                onFailure: function(response){
						ajaxErrorLog(response, 'Review.save');
						$('onepage_submit').enable();
					}
	            }
	        );
		}
		else
		{
			$('onepage_submit').enable();
		}
    },

    nextStep: function(transport){
        if (transport && transport.responseText) {
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
				errorLog('response', 'lege of onjuiste response', 'Review.nextStep');
				return false;
            }
            if (response.redirect) {
				this.inschrijven();
                location.href = response.redirect;
                return;
            }
            if (response.success) {
                this.isSuccess = true;
				this.inschrijven();
                window.location=this.successUrl;
            }
            else{
                var msg = response.error_messages;
                if (typeof(msg)=='object') {
                    msg = msg.join(" - ");
                }
				errorLog('response', 'Kon de order niet plaatsen: ' + msg, 'Review.nextStep');
                alert('Uw bestelling kon niet worden geplaatst, onze excuses voor het ongemak. Probeer het aub later nogmaals.');
				$('onepage_submit').enable();
            }
        }
		else
		{
			$('onepage_submit').enable();
		}
    },
	
	inschrijven: function()
	{
		if ($("co-nieuwsbrief").checked) //inschrijven nieuwsbrief
		{
			var request = new Ajax.Request(
	            "/newsletter/subscriber/new/",
	            {
					asynchronous: false, //laat script wachten op request
	                method:'post',
	                parameters:"&email=" + billing.emailadres,
					onFailure: function(response){
						ajaxErrorLog(response, 'Review.inschrijven');
						$('onepage_submit').enable();
					}
	            }
	        );
		}
	},

    isSuccess: false
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked == true) {
			return radioObj[i].value;
		}
	}
	return "";
}

function ajaxErrorLog(response, scope) {
	try 
	{
		if (scope == undefined || scope == '') 
			scope = 'global';
		new Ajax.Request('/ajaxlog.php', {
			method: 'get',
			parameters: '&log[status]=' + response.status +
			'&log[HTTPresp]=' +
			response.statusText +
			'&log[resp]=' +
			response.responseText +
			'&log[resp]=' +
			response.responseText +
			'&log[scope]=' +
			scope
		});
	}
	catch (e){}
}

function errorLog(type, message, scope) {
	try 
	{
		if (scope == undefined || scope == '') 
			scope = 'global';
		new Ajax.Request('/ajaxlog.php', {
			method: 'get',
			parameters: '&log[type]=' + type + '&log[error]=' + encodeURI(message) + '&log[scope]=' + scope
		});
	} 
	catch (e) 
	{
	}
}

window.onerror = function(errorMsg, url, lineNumber)
{
	try
	{
		errorLog('jserror', errorMsg + ' (' + url + ':' + lineNumber + ')', 'window');		
	}
	catch(e)
	{
		
	}
}
