/**
 * Pod1 SagePay extension
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/osl-3.0.php
 *
 *
 * @category   Pod1
 * @package    Pod1_SagePay
 * @copyright  Copyright (c) 2010 Pod1 (http://www.pod1.com)
 * @license    http://opensource.org/licenses/osl-3.0.php  Open Software License (OSL 3.0)
 */

if(typeof SagePay == 'undefined') {
    var SagePay = {};
}

/**************************** SAGEPAY SERVER ********************************/
SagePay.Server = Class.create();
SagePay.Server.prototype = {

	initialize: function(config, code, section, singleMethod, virtual){
		this.config 		= config;
		this.code			= code;
		this.section 		= section;
		this.singleMethod 	= singleMethod;
		this.virtual 		= virtual;
		this.step			= $('opc-'+section);
		this.content		= $('opc-'+section).down('.step');
		this.getConfig('review').onSave = this.reviewSave.bindAsEventListener(this);
		if(true === singleMethod && this.enableSingleMethod()){
			var step 	= (true === virtual) ? 'billing' : 'shippingMethod';
			var section = (true === virtual) ? 'billing' : 'shipping-method';
			this.getConfig(step).onSave 	 = this.paymentUpdate.bindAsEventListener(this, step);
			this.getConfig(step).onComplete  = this.paymentAutoSave.bindAsEventListener(this, section);
		} else {
			this.getConfig('payment').onSave = this.paymentSave.bindAsEventListener(this);
		}
		var paymentSubmit = this.getPaymentSubmit();
		if(paymentSubmit) {
			 paymentSubmit.observe('click', this.setPaymentMethod.bindAsEventListener(this));
		}
	},
	
	evalTransport: function(transport){
		try { response = eval('('+transport.responseText+')') } catch(e) { response = {} }
		return response;
	},
	
	getConfig: function(instance){ 
		return this.config[instance]; 
	},
	
	getSections: function(){ 
		return this.getConfig('accordion').sections;
	},
	
	getSection: function(section) { 
		var sections = this.getSections();
		for(var i=0; i<sections.length; i++) {
  			if('opc-'+section === sections[i].id) {
  				return sections[i];
  			}
  		}
  		return false;
	},
	
	updateSection: function(name, content){
		$('checkout-'+name+'-load').update(content);
        content.evalScripts();
	},
	
	enableSingleMethod: function(){
		var payment = this.getSection('payment');
		if(!payment) {
			return false;
		}
		payment.hide();
		this.step.show();
		this.resetStepCount();
		this.paymentMethod = this.code;
		return true;
	},
	
	resetStepCount: function(){
		var sections = this.getSections();
		var count	 = 1;
		for(var i=0; i<sections.length; i++) {
			var section = sections[i];
			var element	= section.select('span.step-count', 'span.number')[0];
  			if(!element || !section.visible()) {
  				continue;
  			}
			element.update(count++);
  		}
  		var section = this.step.select('span.step-count', 'span.number')[0];
  		if(section) {
  			section.update(count);
  		}
  		jQuery('#opc-sagepay .step-title').html('<h2>Step 6. Card Details</h2>');
	},
	
	disableAccordion: function(){ 
		var sections = this.getSections();
	 	for(var i=0; i<sections.length; i++) {
  			Element.removeClassName(sections[i], 'allow');
  		}
	},
	
	getPaymentSubmit: function(){
		var section	 	= this.getSection('payment');
		var elements 	= $$("#"+section.id+" [onclick]");
		 for(var i=0; i<elements.length; i++) {
		 	// IE problems with readAttribute/getAttribute returning invalid results
		 	var attrubutes = [elements[i].readAttribute('onclick'), elements[i].getAttribute('onclick')];
		 	for(var j=0; j<attrubutes.length; j++) {
		 		if(Object.isString(attrubutes[j]) && -1 !== attrubutes[j].search(/payment\.save/)) {
					return elements[i];
				}
		 	}
        }
        return false;
	},
	
	setPaymentMethod: function(){
		this.paymentMethod = this.getPaymentMethod();
	},
	
	getPaymentMethod: function(){
		var form	 	= this.getConfig('payment').form;
		var elements 	= $$("#"+form+" [name='payment[method]']");
        for(var i=0; i<elements.length; i++) {
			if(elements[i].checked) {
				return elements[i].value;
			}
        }
        return this.code;
	},
		
	isPaymentMethod: function(){
		return (this.paymentMethod === this.code);
	},
	
	paymentUpdate: function(transport, step){
		var response = this.evalTransport(transport);
		if(response.error) {
			this.getConfig(step).nextStep(transport);
			return;
		}
		if(response.update_section) { 
			this.updateSection(response.update_section.name, response.update_section.html);
		}
		this.getConfig('checkout').reloadProgressBlock();
	},
	
	paymentAutoSave: function(event, section){
		this.getConfig('checkout').setLoadWaiting(false);
		this.getConfig('payment').save();
		this.getConfig('checkout').setLoadWaiting(section);
	},
	
	paymentSave: function(transport){
		this.transport = transport;
		if(!this.isPaymentMethod() && this.step.visible()) {
			var event = Effect.SlideUp(this.step, { duration: 0.8, afterFinish: this.paymentFinish.bindAsEventListener(this) });
			return;
		}
		if(this.isPaymentMethod() && !this.step.visible()) {
			var event = Effect.SlideDown(this.step, { duration: 0.8, afterFinish: this.paymentFinish.bindAsEventListener(this) });
			this.resetStepCount();
			return;
		}
		this.getConfig('payment').nextStep(this.transport);
	},
	
	paymentFinish: function(event){ 
		this.getConfig('payment').nextStep(this.transport);
	},

	reviewSave: function(transport){
		var response = this.evalTransport(transport);
		if(!response.redirect || !response.success || !this.isPaymentMethod()) { 
			this.getConfig('review').nextStep(transport);
			return;
		}
		this.content.insert(new Element('iframe', { 'id': 'sagepay-iframe', 'src': response.redirect, 'frameborder': '0', 'allowTransparency': 'true', 'height': '550px'}));
		this.getConfig('checkout').gotoSection(this.section);
		this.disableAccordion();
	}
}
