PageRenderTime 58ms CodeModel.GetById 2ms app.highlight 47ms RepoModel.GetById 1ms app.codeStats 1ms

/skin/frontend/ultimo/default/onestepcheckout/js/sagePaySuite_Checkout.js

https://gitlab.com/Tung/magento
JavaScript | 993 lines | 834 code | 139 blank | 20 comment | 285 complexity | 0546a4213dd836fb40710d5c6977d5c0 MD5 | raw file
  1notifyThreedError = function(msg){
  2	Control.Window.windows.each(function(w){
  3		if(w.container.visible()){
  4			w.close();
  5		}
  6	});
  7	// if((typeof checkout.accordion == 'object')){
  8		// checkout.accordion.openSection('opc-payment');
  9	// }
 10	alert(msg);
 11	var loading_osc = $$('div#onestepcheckout-place-order-loading');
 12	if(loading_osc.length){
 13		$('onestepcheckout-button-place-order').removeClassName('place-order-loader').addClassName('btn-checkout');
 14		$('onestepcheckout-button-place-order').removeAttribute('disabled');
 15		loading_osc.invoke('hide');
 16		already_placing_order = false;
 17	}
 18}
 19
 20restoreOscLoad = function(){
 21		//Hide loading indicator on OSC//
 22			var loading_osc = $$('div.onestepcheckout-place-order-loading');
 23			if(loading_osc.length){
 24				$('onestepcheckout-place-order').removeClassName('grey').addClassName('orange');
 25				$('onestepcheckout-place-order').removeAttribute('disabled');
 26				loading_osc.invoke('hide');
 27				already_placing_order = false;
 28			}else{
 29				var loading_osc = $$('div#onestepcheckout-place-order-loading');
 30				if(loading_osc.length){
 31					$('onestepcheckout-button-place-order').removeClassName('place-order-loader').addClassName('btn-checkout');
 32					$('onestepcheckout-button-place-order').removeAttribute('disabled');
 33					loading_osc.invoke('hide');
 34					already_placing_order = false;
 35				}
 36			}
 37}
 38
 39if(typeof EbizmartsSagePaySuite == 'undefined') {
 40    var EbizmartsSagePaySuite = {};
 41}
 42EbizmartsSagePaySuite.Checkout = Class.create();
 43EbizmartsSagePaySuite.Checkout.prototype = {
 44
 45	initialize: function(config){
 46		this.config 		= config;
 47		this.servercode			= 'sagepayserver';
 48		this.directcode			= 'sagepaydirectpro';
 49		this.paypalcode			= 'sagepaypaypal';
 50		this.formcode			= 'sagepayform';
 51		this.code               = '';
 52		this.oldUrl             = '';
 53
 54		if(this.getConfig('review')){
 55			this.oldUrl = this.getConfig('review').saveUrl;
 56			this.getConfig('review').saveUrl = SuiteConfig.getConfig('global', 'sgps_saveorder_url');
 57			this.getConfig('review').onSave = this.reviewSave.bindAsEventListener(this);
 58		}else if(this.getConfig('osc')){
 59
 60		Event.stopObserving($('onestepcheckout-form'));
 61		$('onestepcheckout-form')._submit = $('onestepcheckout-form').submit;
 62		$('onestepcheckout-form').submit = function(){ this.reviewSave(); }.bind(this);
 63
 64		}else if(this.getConfig('magestore')){
 65			Event.stopObserving($('one-step-checkout-form'));
 66			$('one-step-checkout-form')._submit = $('one-step-checkout-form').submit;
 67			$('one-step-checkout-form').submit = function(){ this.reviewSave(); }.bind(this);
 68		}else if(this.getConfig('msform')){
 69			this.getConfig('msform').observe('submit', function(evmsc){Event.stop(evmsc);this.reviewSave(evmsc);}.bind(this));
 70		}
 71
 72		var blFormMAC = $('multishipping-billing-form');
 73		if(blFormMAC){
 74			blFormMAC.observe('submit', function(_event_){ Event.stop(_event_); this.setPaymentMethod(); }.bind(this));
 75		}
 76
 77		var paymentSubmit = this.getPaymentSubmit();
 78		if(paymentSubmit) {
 79
 80			 if(this.getCurrentCheckoutStep() == 'opc-review'){//Magento 1.5.x+
 81			 	this.setPaymentMethod(true);
 82			 }else{
 83			 	paymentSubmit.observe('click', this.setPaymentMethod.bindAsEventListener(this));
 84			 }
 85
 86		}
 87
 88	},
 89	evalTransport: function(transport){
 90		try { response = eval('('+transport.responseText+')') } catch(e) { response = {} }
 91                return response;
 92	},
 93	getConfig: function(instance){
 94		return (this.config[instance] != 'undefined' ? this.config[instance] : false);
 95	},
 96	getCurrentCheckoutStep: function(){
 97		return this.getConfig('checkout').accordion.currentSection;
 98	},
 99	getPaymentSubmit: function(){
100		var elements 	= $$("#opc-payment [onclick]");
101		 for(var i=0; i<elements.length; i++) {
102		 	// IE problems with readAttribute/getAttribute returning invalid results
103		 	var attrubutes = [elements[i].readAttribute('onclick'), elements[i].getAttribute('onclick')];
104		 	for(var j=0; j<attrubutes.length; j++) {
105		 		if(Object.isString(attrubutes[j]) && -1 !== attrubutes[j].search(/payment\.save/)) {
106					return elements[i];
107				}
108		 	}
109        }
110        return false;
111	},
112	getShippingMethodSubmit: function(){
113		var elements 	= $$("#opc-shipping_method [onclick]");
114		 for(var i=0; i<elements.length; i++) {
115		 	var attrubutes = [elements[i].readAttribute('onclick'), elements[i].getAttribute('onclick')];
116		 	for(var j=0; j<attrubutes.length; j++) {
117		 		if(Object.isString(attrubutes[j]) && -1 !== attrubutes[j].search(/shippingMethod\.save/)) {
118					return elements[i];
119				}
120		 	}
121        }
122        return false;
123	},
124	getPaymentMethod: function(){
125
126		var form = null;
127
128		if($('multishipping-billing-form')){
129			form = $('multishipping-billing-form');
130		}else if(this.getConfig('osc')){
131			form = this.getConfig('oscFrm');
132		}else if(this.getConfig('magestore')){
133			form = this.getConfig('magestoreFrm');
134		}else if((typeof this.getConfig('payment')) != 'undefined'){
135			form = $(this.getConfig('payment').form);
136		}
137
138		if(form === null){
139			return this.code;
140		}
141
142		var checkedPayment = null
143
144		form.getInputs('radio', 'payment[method]').each(function(el){
145			if(el.checked){
146				checkedPayment = el.value;
147				throw $break;
148			}
149		});
150
151		if(checkedPayment != null){
152			return checkedPayment;
153		}
154
155        return this.code;
156	},
157	isFormPaymentMethod: function(){
158		return (this.getPaymentMethod() === this.formcode);
159	},
160	isServerPaymentMethod: function(){
161		return (this.getPaymentMethod() === this.servercode || ($('suite_ms_payment_method') && $('suite_ms_payment_method').getValue()==this.servercode));
162	},
163	isDirectPaymentMethod: function(){
164		return (this.getPaymentMethod() === this.directcode);
165	},
166	isSagePay: function(){
167		var isSagePay = false;
168		if( (this.getPaymentMethod() === this.formcode) || (this.getPaymentMethod() === this.directcode) ||
169   		    (this.getPaymentMethod() === this.servercode) || (this.getPaymentMethod() === this.paypalcode) ) {
170   		    isSagePay = true;
171   		}
172
173   		return isSagePay;
174	},
175	growlError: function(msg){
176		alert(msg);
177		return;
178		try{
179			var ng = new k.Growler({location:"tc"});
180			ng.error(msg, {life:10});
181		}catch(grwlerror){
182			alert(msg);
183		}
184	},
185	growlWarn: function(msg){
186		alert(msg);
187		return;
188		try{
189			var ng = new k.Growler({location:"tc"});
190			ng.warn(msg, {life:10});
191		}catch(grwlerror){
192			alert(msg);
193		}
194	},
195	isDirectTokenTransaction: function(){
196		var tokenRadios = $$('div#payment_form_sagepaydirectpro ul.tokensage li.tokencard-radio input');
197		if(tokenRadios.length){
198			if(tokenRadios[0].disabled === false){
199				return true;
200			}
201		}
202		return false;
203	},
204	isServerTokenTransaction: function(){
205		var tokenRadios = $$('div#payment_form_sagepayserver ul.tokensage li.tokencard-radio input');
206		if(tokenRadios.length){
207			if(tokenRadios[0].disabled === false){
208				return true;
209			}
210		}
211		return false;
212	},
213	getServerSecuredImage: function(){
214		return new Element('img', {'src':SuiteConfig.getConfig('server', 'secured_by_image'), 'style':'margin-bottom:5px'});
215	},
216	setShippingMethod: function(){
217		try{
218				if($('sagepaydirectpro_cc_type')){
219					$('sagepaydirectpro_cc_type').selectedIndex = 0;
220				}
221		}catch(ser){
222			alert(ser);
223		}
224	},
225	setPaymentMethod: function(modcompat){
226
227		if(this.getConfig('review')){
228			if(!this.isSagePay()) {
229				this.getConfig('review').saveUrl = this.oldUrl;
230			}
231			else{
232				this.getConfig('review').saveUrl = SuiteConfig.getConfig('global', 'sgps_saveorder_url');
233			}
234		}
235
236		// Remove Server InCheckout iFrame if exists
237		if($('sagepaysuite-server-incheckout-iframe')){
238			$('checkout-review-submit').show();
239			$('sagepaysuite-server-incheckout-iframe').remove();
240		}
241
242		if(this.isServerPaymentMethod()){
243
244			if( parseInt(SuiteConfig.getConfig('global','token_enabled')) === 1 && ($('remembertoken-sagepayserver').checked === true) ){
245
246			$('sagepayserver-dummy-link').writeAttribute('href', SuiteConfig.getConfig('server','new_token_url'));
247				if(this.isServerTokenTransaction()){
248
249					if($('multishipping-billing-form')){
250						$('multishipping-billing-form').submit();
251					}
252
253					return;
254				}
255				 var lcontwmt = new Element('div',{className: 'lcontainer'});
256				 var heit = parseInt(SuiteConfig.getConfig('server','token_iframe_height'))+80;
257				 lcontwmt.setStyle({'height':heit.toString() + 'px'});
258
259				 var wmt = new Control.Modal('sagepayserver-dummy-link',{
260						     className: 'modal',
261						     iframe: true,
262						     closeOnClick: false,
263						     insertRemoteContentAt: lcontwmt,
264						     height: SuiteConfig.getConfig('server','token_iframe_height'),
265						     width: SuiteConfig.getConfig('server','token_iframe_width'),
266						     fade: true,
267						     afterClose: function(){
268						     	this.getTokensHtml();
269				 			 }.bind(this)
270				 })
271				wmt.container.insert(lcontwmt);
272
273				wmt.container.down().insert(this.getServerSecuredImage());
274				wmt.container.setStyle({'height':heit.toString() + 'px'});
275			 	wmt.open();
276
277				if(this.getConfig('checkout') && (modcompat == undefined)){
278					this.getConfig('checkout').accordion.openSection('opc-payment');
279				}
280				return;
281			}
282
283		}else if(this.isDirectPaymentMethod() && parseInt(SuiteConfig.getConfig('global','token_enabled')) === 1 && ($('remembertoken-sagepaydirectpro').checked === true)){
284
285			if(this.isDirectTokenTransaction()){
286				return;
287			}
288
289			try{
290	            if(new Validation(this.getConfig('payment').form).validate() === false){
291	                return;
292	            }
293            }catch(one){}
294
295			if(this.getConfig('osc')){
296				var valOsc = new VarienForm('onestepcheckout-form').validator.validate();
297				if(!valOsc){
298					return;
299				}
300			}else if(this.getConfig('magestore')){
301				var valOsc = new VarienForm('one-step-checkout-form').validator.validate();
302				if(!valOsc){
303					return;
304				}
305			}
306
307			var pmntForm = (this.getConfig('osc') ? this.getConfig('oscFrm') : $('co-payment-form'));
308			if(this.getConfig('magestore')){
309				pmntForm = this.getConfig('magestoreFrm');
310			}
311			new Ajax.Request(SuiteConfig.getConfig('direct','sgps_registerdtoken_url'),{
312					method:"post",
313					parameters: Form.serialize(pmntForm),
314					onSuccess:function(f){
315
316						try{
317							this.getTokensHtml();
318
319							var d=f.responseText.evalJSON();
320
321							if(d.response_status=="INVALID"||d.response_status=="MALFORMED"||d.response_status=="ERROR"||d.response_status=="FAIL"){
322								if(this.getConfig('checkout')){
323									this.getConfig('checkout').accordion.openSection('opc-payment');
324								}
325								this.growlWarn("An error ocurred with Sage Pay Direct:\n" + d.response_status_detail.toString());
326
327								if(this.getConfig('osc')){
328									$('onestepcheckout-place-order').removeClassName('grey').addClassName('orange');
329									$$('div.onestepcheckout-place-order-loading').invoke('remove');
330									return;
331								}else if(this.getConfig('magestore')){
332									$('onestepcheckout-button-place-order').addClassName('btn-checkout');
333									$('onestepcheckout-button-place-order').removeClassName('place-order-loader');
334								}
335
336							}else if(d.response_status == 'threed'){
337								$('sagepaydirectpro-dummy-link').writeAttribute('href', d.url);
338							}
339
340							if(this.getConfig('osc')){
341								this.reviewSave({'tokenSuccess':true});
342								return;
343							}else if(this.getConfig('magestore')){
344								this.reviewSave({'tokenSuccess':true});
345								return;
346							}
347
348						}catch(alfaEr){
349
350							if(this.getConfig('checkout')){
351								this.getConfig('checkout').accordion.openSection('opc-payment');
352							}
353							this.growlError(f.responseText.toString());
354						}
355
356					}.bind(this)
357			});
358
359		}
360
361	},
362	getTokensHtml: function(){
363
364		new Ajax.Updater(('tokencards-payment-' + this.getPaymentMethod()), SuiteConfig.getConfig('global', 'html_paymentmethods_url'), {
365						 parameters: { payment_method: this.getPaymentMethod() },
366						 onComplete:function(){
367                                               if($$('a.addnew').length > 1){
368                                                   $$('a.addnew').each(function(el){
369                                                      if(!el.visible()){
370                                                          el.remove();
371                                                      }
372                                                   })
373                                               }
374                                               toggleNewCard(2);
375
376										     	if($('onestepcheckout-form') && this.isServerPaymentMethod()){
377											     	toggleNewCard(1);
378
379											     	var tokens = $$('div#payment_form_sagepayserver ul li.tokencard-radio input');
380											     	if(tokens.length){
381												     	tokens.each(function(radiob){
382															radiob.disabled = true;
383															radiob.removeAttribute('checked');
384														});
385														tokens.first().writeAttribute('checked', 'checked');
386														tokens.first().disabled = false;
387														$('onestepcheckout-form').submit();
388													}else{
389														this.resetOscLoading();
390													}
391
392										     	}
393						 }.bind(this)
394		});
395
396	},
397	resetOscLoading: function(){
398		restoreOscLoad();
399	},
400	reviewSave: function(transport){
401			if((typeof transport) == 'undefined'){
402				var transport = {};
403			}
404
405			//OSC\\
406			
407			if((typeof transport.responseText) == 'undefined' && ($('onestepcheckout-form')||$('one-step-checkout-form'))){
408				if(!this.isSagePay()){
409					if(this.getConfig('osc')){
410						$('onestepcheckout-form')._submit();
411					}else if(this.getConfig('magestore')){
412						$('one-step-checkout-form')._submit();
413					}
414					return;
415				}
416				if(this.getConfig('osc')){
417					if(this.isFormPaymentMethod()){
418						new Ajax.Request(SuiteConfig.getConfig('global', 'sgps_saveorder_url'),{
419								method:"post",
420								parameters: Form.serialize($('onestepcheckout-form')),
421								onSuccess:function(f){
422									var d = f.responseText.evalJSON();
423									if(d.response_status == 'ERROR'){
424										alert(d.response_status_detail);
425										this.resetOscLoading();
426										return;
427									}
428
429									setLocation(SuiteConfig.getConfig('form','url'));
430								}
431						});
432						return;
433					}
434				}else if(this.getConfig('magestore')){
435					if(this.isFormPaymentMethod()){
436						disable_payment();
437						new Ajax.Request(SuiteConfig.getConfig('global', 'sgps_saveorder_url'),{
438								method:"post",
439								parameters: Form.serialize($('one-step-checkout-form')),
440								onSuccess:function(f){
441									var d = f.responseText.evalJSON();
442									if(d.response_status == 'ERROR'){
443										alert(d.response_status_detail);
444										this.resetOscLoading();
445										return;
446									}
447
448									setLocation(SuiteConfig.getConfig('form','url'));
449								}
450						});
451						return;
452					}
453
454				}
455				if((this.isDirectPaymentMethod() || this.isServerPaymentMethod()) && parseInt(SuiteConfig.getConfig('global','token_enabled')) === 1){
456					if((typeof transport.tokenSuccess) == 'undefined'){
457						this.setPaymentMethod();
458
459						if(!this.isDirectTokenTransaction() && !this.isServerTokenTransaction() && (($('remembertoken-sagepaydirectpro') && $('remembertoken-sagepaydirectpro').checked === true) || ($('remembertoken-sagepayserver') && $('remembertoken-sagepayserver').checked === true))){
460							return;
461						}
462					}
463				}
464				
465				if(this.getConfig('osc')){
466					if(parseInt($$('div.onestepcheckout-place-order-loading').length) || (typeof transport.tokenSuccess != 'undefined' && true === transport.tokenSuccess)){
467
468						if(Ajax.activeRequestCount > 1 && (typeof transport.tokenSuccess) == 'undefined'){
469							return;
470						}
471						var slPayM = this.getPaymentMethod();
472
473
474						if(slPayM == this.servercode || slPayM == this.directcode){
475							new Ajax.Request(SuiteConfig.getConfig('global', 'sgps_saveorder_url'),{
476									method:"post",
477									parameters: Form.serialize($('onestepcheckout-form')),
478									onSuccess:function(f){
479										this.reviewSave(f);
480										transport.element().removeClassName('grey').addClassName('orange');
481										$$('div.onestepcheckout-place-order-loading').invoke('hide');
482									}.bind(this)
483							});
484							return;
485						}else{
486						   $('onestepcheckout-form')._submit();
487						   return;
488						}
489
490					  }else{
491						return;
492					  }
493					}else if(this.getConfig('magestore')){
494						if(parseInt($$('div#onestepcheckout-place-order-loading').length) || (typeof transport.tokenSuccess != 'undefined' && true === transport.tokenSuccess)){
495
496						if(Ajax.activeRequestCount > 1 && (typeof transport.tokenSuccess) == 'undefined'){
497							return;
498						}
499						var slPayM = this.getPaymentMethod();
500
501
502						if(slPayM == this.servercode || slPayM == this.directcode){
503							disable_payment();
504							new Ajax.Request(SuiteConfig.getConfig('global', 'sgps_saveorder_url'),{
505									method:"post",
506									parameters: Form.serialize($('one-step-checkout-form')),
507									onSuccess:function(f){
508										this.reviewSave(f);
509										transport.element().removeClassName('place-order-loader').addClassName('btn-checkout');
510										$$('div#onestepcheckout-place-order-loading').invoke('hide');
511									}.bind(this)
512							});
513							return;
514						}else{
515						   $('one-step-checkout-form')._submit();
516						   return;
517						}
518
519					  }else{
520						return;
521					  }
522					}
523			//OSC\\
524			
525			}else if((typeof transport.responseText) == 'undefined' && this.getConfig('msform')){
526					var ps = $H({'payment[method]': 'sagepayserver'});
527
528					if($('sagepay_server_token_cc_id')){
529						ps.set('payment[sagepay_token_cc_id]', $('sagepay_server_token_cc_id').getValue());
530					}
531
532					new Ajax.Request(SuiteConfig.getConfig('global', 'sgps_saveorder_url'),{
533							method:"post",
534							parameters: ps,
535							onSuccess:function(f){
536								this.reviewSave(f);
537							}.bind(this)
538					});
539					return;
540		}else{
541			try{
542				var response = this.evalTransport(transport);
543			}catch(notv){
544				suiteLogError(notv);
545			}
546		}
547
548		if((typeof response.response_status != 'undefined') && response.response_status != 'OK' && response.response_status != 'threed' && response.response_status != 'paypal_redirect'){
549
550			this.resetOscLoading();
551
552			this.growlWarn("An error ocurred with Sage Pay:\n" + response.response_status_detail.toString());
553			return;
554		}
555
556		if(response.response_status == 'paypal_redirect'){
557			setLocation(response.redirect);
558			return;
559		}
560
561		if(this.getConfig('osc') && response.success && response.response_status == 'OK' && (typeof response.next_url == 'undefined')){
562			setLocation(SuiteConfig.getConfig('global','onepage_success_url'));
563			return;
564		}else if(this.getConfig('magestore') && response.success && response.response_status == 'OK' && (typeof response.next_url == 'undefined')){
565			setLocation(SuiteConfig.getConfig('global','onepage_success_url'));
566			return;
567		}
568
569		if(!response.redirect || !response.success) {
570			this.getConfig('review').nextStep(transport);
571			return;
572		}
573
574		if(this.isServerPaymentMethod()){
575
576			$('sagepayserver-dummy-link').writeAttribute('href', response.redirect);
577
578			 var rbButtons = $('review-buttons-container');
579
580			 var lcont = new Element('div',{className: 'lcontainer'});
581			 var heit = parseInt(SuiteConfig.getConfig('server','iframe_height'));
582			 if(Prototype.Browser.IE){
583			 	heit = heit-65;
584			 }
585
586			var wtype = SuiteConfig.getConfig('server','payment_iframe_position').toString();
587			if(wtype == 'modal'){
588
589				 var wm = new Control.Modal('sagepayserver-dummy-link',{
590						     className: 'modal',
591						     iframe: true,
592						     closeOnClick: false,
593						     insertRemoteContentAt: lcont,
594						     height: SuiteConfig.getConfig('server','iframe_height'),
595						     width: SuiteConfig.getConfig('server','iframe_width'),
596						     fade: true,
597						     afterOpen: function(){
598								if(rbButtons){
599									rbButtons.addClassName('disabled');
600								}
601				 			 },
602						     afterClose: function(){
603						     	if(rbButtons){
604						     		rbButtons.removeClassName('disabled');
605						     	}
606				 			 }
607				 });
608			 	wm.container.insert(lcont);
609				wm.container.down().setStyle({'height':heit.toString() + 'px'});
610				wm.container.down().insert(this.getServerSecuredImage());
611				wm.open();
612
613			}else if(wtype == 'incheckout'){
614
615				var iframeId = 'sagepaysuite-server-incheckout-iframe';
616				var paymentIframe = new Element('iframe', {'src': response.redirect, 'id': iframeId});
617
618				if(this.getConfig('osc')){
619					var placeBtn = $('onestepcheckout-place-order');
620
621					placeBtn.hide();
622
623					$('onestepcheckout-form').insert( { after:paymentIframe } );
624					$(iframeId).scrollTo();
625
626				}else if(this.getConfig('magestore')){
627					var placeBtn = $('onestepcheckout-button-place-order');
628
629					placeBtn.hide();
630
631					$('one-step-checkout-form').insert( { after:paymentIframe } );
632					$(iframeId).scrollTo();
633				}else{
634
635					if( (typeof $('checkout-review-submit')) == 'undefined' ){
636						var btnsHtml  = $$('div.content.button-set').first();
637					}else{
638						var btnsHtml  = $('checkout-review-submit');
639					}
640
641					btnsHtml.hide();
642					btnsHtml.insert( { after:paymentIframe } );
643
644				}
645
646			}
647
648		}else if(this.isDirectPaymentMethod() && (typeof response.response_status != 'undefined') && response.response_status == 'threed'){
649
650			 $('sagepaydirectpro-dummy-link').writeAttribute('href', response.redirect);
651
652			 var lcontdtd = new Element('div',{className: 'lcontainer'});
653			 var dtd = new Control.Modal('sagepaydirectpro-dummy-link',{
654			     className: 'modal sagepaymodal',
655                 closeOnClick: false,
656                 insertRemoteContentAt: lcontdtd,
657			     iframe: true,
658			     height: SuiteConfig.getConfig('direct','threed_iframe_height'),
659			     width: SuiteConfig.getConfig('direct','threed_iframe_width'),
660			     fade: true,
661			     afterOpen: function(){
662
663				     if(true === Prototype.Browser.IE){
664				     	var ie_version = parseFloat(navigator.appVersion.split("MSIE")[1]);
665						if(ie_version<8){
666							return;
667						}
668				     }
669
670				     try{
671				     	var daiv = this.container;
672
673				     	if($$('.sagepaymodal').length > 1){
674				     		$$('.sagepaymodal').each(function(elem){
675				     			if(elem.visible()){
676				     				daiv = elem;
677				     				throw $break;
678				     			}
679				     		});
680				     	}
681
682						daiv.down().down('iframe').insert({before:new Element('div', {'id':'sage-pay-direct-ddada','style':'background:#FFF'}).update(
683							SuiteConfig.getConfig('direct','threed_after').toString() + SuiteConfig.getConfig('direct','threed_before').toString())});
684
685						}catch(er){}
686
687						if(false === Prototype.Browser.IE){
688							daiv.down().down('iframe').setStyle({'height':(parseInt(daiv.down().getHeight())-60)+'px'});
689							daiv.setStyle({'height':(parseInt(daiv.down().getHeight())+57)+'px'});
690						}else{
691							daiv.down().down('iframe').setStyle({'height':(parseInt(daiv.down().getHeight())+116)+'px'});
692						}
693
694	 			 },
695			     afterClose: function(){
696                     if($('sage-pay-direct-ddada')){
697                     	$('sage-pay-direct-ddada').remove();
698                     }
699					$('sagepaydirectpro-dummy-link').writeAttribute('href', '');
700	 			 }
701			 });
702			 dtd.container.insert(lcontdtd);
703			 dtd.open();
704
705		}else if(this.isDirectPaymentMethod()){
706			new Ajax.Request(SuiteConfig.getConfig('direct','sgps_registertrn_url'),{
707					onSuccess:function(f){
708
709						try{
710
711							var d=f.responseText.evalJSON();
712
713							if(d.response_status=="INVALID"||d.response_status=="MALFORMED"||d.response_status=="ERROR"||d.response_status=="FAIL"){
714								this.getConfig('checkout').accordion.openSection('opc-payment');
715								this.growlWarn("An error ocurred with Sage Pay Direct:\n" + d.response_status_detail.toString());
716							}else if(d.response_status == 'threed'){
717								$('sagepaydirectpro-dummy-link').writeAttribute('href', d.url);
718							}
719
720						}catch(alfaEr){
721							this.growlError(f.responseText.toString());
722						}
723
724					}.bind(this)
725			});
726		}
727		else{
728			this.getConfig('review').nextStep(transport);
729			return;
730		}
731	}
732}
733
734try{
735	Event.observe(window,"load",function(){
736	var options = document.getElementsByName('payment[method]');
737	var checkSagepay = false;
738	for(var i=0;i<options.length;i++){
739		if(options[i].id.contains('sagepay')){
740			checkSagepay = true;
741			break;
742		}
743	
744	}	
745	if(!checkSagepay || checkSagepay==false){
746		return;
747	}
748	$(document.body).insert(new Element('a', { 'id': 'sagepayserver-dummy-link', 'href': '#', 'style':'display:none' }).update('&nbsp;'));
749	$(document.body).insert(new Element('a', { 'id': 'sagepaydirectpro-dummy-link', 'href': '#', 'style':'display:none' }).update('&nbsp;'));
750
751	var msCont = $('suite_ms_payment_method');
752
753		if( !msCont && (SuiteConfig.getConfig('global', 'ajax_review') == '2') && ((typeof window.review) != 'undefined') ){
754	        var SageServer = new EbizmartsSagePaySuite.Checkout(
755	                {
756	                        'checkout':             window.checkout,
757	                        'review':               window.review,
758	                        'payment':              window.payment,
759	                        'billing':              window.billing,
760	                        'accordion':            window.accordion
761	                }
762	        );
763        }else if(!msCont && ($$('div.shopping-cart-totals').length != 1) && $('onestepcheckout-form')){
764	        var SageServer = new EbizmartsSagePaySuite.Checkout(
765	                {
766	                        'osc': $('onestepcheckout-place-order'),
767	                        'oscFrm': $('onestepcheckout-form')
768	                }
769	        );
770
771        }else if($('one-step-checkout-form')){
772			var SageServer = new EbizmartsSagePaySuite.Checkout(
773	                {
774	                        'magestore': $('onestepcheckout-button-place-order'),
775	                        'magestoreFrm': $('one-step-checkout-form')
776	                }
777	        );
778		}else if(msCont && (msCont.getValue() == 'sagepayserver')){
779	        var SageServer = new EbizmartsSagePaySuite.Checkout(
780	                {
781	                	'msform': $$('div.multiple-checkout')[0].down(2)
782	                }
783	        );
784        }
785
786		if(parseInt(SuiteConfig.getConfig('global','valid')) === 0){
787			if(SuiteConfig.getConfig('direct','mode') == "live" || SuiteConfig.getConfig('server','mode') == "live"){
788				new PeriodicalExecuter(function(){ alert(SuiteConfig.getConfig('global','not_valid_message')); }, 10);
789			}else{
790				var invalidG = new k.Growler({location:"bl"}).error('<strong>'+SuiteConfig.getConfig('global','not_valid_message')+'</strong>', {life:14400});
791			}
792		}
793	})
794}catch(er){ suiteLogError(er); }
795
796
797    addValidationClass = function(obj){
798        if(obj.hasClassName('validation-passed')){
799            obj.removeClassName('validation-passed');
800        }
801        obj.addClassName('validate-issue-number');
802    }
803    paypalClean = function(reverse){
804    	var ccTypeContainer = $('sagepaydirectpro_cc_type');
805       	var sf = 'div#payment_form_sagepaydirectpro';
806       	var sfls = $$(sf+' input, '+sf+' select, '+sf+' radio, '+sf+' checkbox');
807
808       	if(reverse){
809	       	//sfls.invoke('enable');
810	       	//Just hide items wose parent is visible, these prevents enabling hiden token card elements
811	       	sfls.each(function(item){
812	       		if(item.up().visible() === true){
813	       			item.enable();
814	       		}
815	       	});
816
817	       	sfls.invoke('show');
818
819	       	$$(sf+' label, '+sf+' a[class!="addnew"]').invoke('show');
820
821	       	//ccTypeContainer.show();
822	       	//ccTypeContainer.disabled = false;
823	       	ccTypeContainer.addClassName('validate-ccsgpdp-type-select');
824       	}else{
825	       	sfls.invoke('disable');
826	       	sfls.invoke('hide');
827
828	       	$$(sf+' label, '+sf+' a').invoke('hide');
829
830	       	ccTypeContainer.show();
831	       	ccTypeContainer.disabled = false;
832	       	ccTypeContainer.removeClassName('validate-ccsgpdp-type-select');
833       	}
834
835    }
836    changecsvclass = function(obj) {
837        var ccTypeContainer = $('sagepaydirectpro_cc_type');
838        var ccCVNContainer = $('sagepaydirectpro_cc_cid');
839
840        fillSagePayTestData();
841
842        if(ccTypeContainer.value == 'PAYPAL'){//PayPal MARK integration
843        	paypalClean(false);
844        }else{
845        	paypalClean(true);
846        }
847
848        if(ccTypeContainer)
849        {
850            if(ccTypeContainer.value == 'LASER' && ccCVNContainer.hasClassName('required-entry'))
851            {
852                if(ccCVNContainer) {
853                    ccCVNContainer.removeClassName('required-entry');
854                }
855            }
856            if(ccTypeContainer.value != 'LASER' && !ccCVNContainer.hasClassName('required-entry'))
857            {
858                if(ccCVNContainer) {
859                    ccCVNContainer.addClassName('required-entry');
860                }
861            }
862        }
863    }
864
865    Validation.addAllThese([
866        ['validate-ccsgpdp-number', 'Please enter a valid credit card number.', function(v, elm) {
867                // remove non-numerics
868			try{
869           var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_number')) + '_cc_type');
870                if (ccTypeContainer && typeof Validation.creditCartTypes.get(ccTypeContainer.value) != 'undefined'
871                        && Validation.creditCartTypes.get(ccTypeContainer.value)[2] == false) {
872                    if (!Validation.get('IsEmpty').test(v) && Validation.get('validate-digits').test(v)) {
873                        return true;
874                    } else {
875                        return false;
876                    }
877                }
878
879                if (ccTypeContainer.value == 'OT' ||  ccTypeContainer.value == 'UKE' || ccTypeContainer.value == 'DELTA' || ccTypeContainer.value == 'MAESTRO' || ccTypeContainer.value == 'SOLO' || ccTypeContainer.value == 'SWITCH' || ccTypeContainer.value == 'LASER' || ccTypeContainer.value == 'JCB' || ccTypeContainer.value == 'DC') {
880                     return true;
881                }
882
883                return validateCreditCard(v);
884                }catch(_error){return true;}
885            }],
886        ['validate-ccsgpdp-cvn', 'Please enter a valid credit card verification number.', function(v, elm) {
887        		try{
888                var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_cid')) + '_cc_type');
889                var ccCVNContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_cid')) + '_cc_cid');
890                if(ccTypeContainer)
891                {
892                    if(ccTypeContainer.value == 'LASER' && ccCVNContainer.hasClassName('required-entry'))
893                    {
894                        if(ccCVNContainer) {
895                            ccCVNContainer.removeClassName('required-entry');
896                        }
897                    }
898                    if(ccTypeContainer.value != 'LASER' && !ccCVNContainer.hasClassName('required-entry'))
899                    {
900                        if(ccCVNContainer) {
901                            ccCVNContainer.addClassName('required-entry');
902                        }
903                    }
904                }
905                else
906                {
907                    return true;
908                }
909                if (!ccTypeContainer && ccTypeContainer.value != 'LASER') {
910                    return true;
911                }
912                var ccType = ccTypeContainer.value;
913
914                switch (ccType) {
915                    case 'VISA' :
916                    case 'MC' :
917                        re = new RegExp('^[0-9]{3}$');
918                        break;
919                    //case 'AMEX' :
920                    //    re = new RegExp('^[0-9]{4}$');
921                    //    break;
922                    case 'MAESTRO':
923                    case 'SOLO':
924                    case 'SWITCH':
925                        re = new RegExp('^([0-9]{1}|^[0-9]{2}|^[0-9]{3})?$');
926                        break;
927                    default:
928                        re = new RegExp('^([0-9]{3}|[0-9]{4})?$');
929                        break;
930                }
931
932                if (v.match(re) || ccType == 'LASER') {
933                    return true;
934                }
935
936                return false;
937                                }catch(_error){return true;}
938            }],
939            ['validate-ccsgpdp-type', 'Credit card number doesn\'t match credit card type', function(v, elm) {
940            try{
941                    // remove credit card number delimiters such as "-" and space
942                    elm.value = removeDelimiters(elm.value);
943                    v         = removeDelimiters(v);
944
945                    var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_number')) + '_cc_type');
946                    if (!ccTypeContainer) {
947                        return true;
948                    }
949                    var ccType = ccTypeContainer.value;
950
951                    // Other card type or switch or solo card
952                    if (ccType == 'OT' ||  ccType == 'UKE' || ccType == 'DELTA' || ccType == 'MAESTRO' || ccType == 'SOLO' || ccType == 'SWITCH' || ccType == 'LASER' || ccType == 'JCB' || ccType == 'DC') {
953                        return true;
954                    }
955                    // Credit card type detecting regexp
956                    var ccTypeRegExp = {
957                        'VISA': new RegExp('^4[0-9]{12}([0-9]{3})?$'),
958                        'MC': new RegExp('^5[1-5][0-9]{14}$'),
959                        'AMEX': new RegExp('^3[47][0-9]{13}$')
960                    };
961
962                    // Matched credit card type
963                    var ccMatchedType = '';
964                    $H(ccTypeRegExp).each(function (pair) {
965                        if (v.match(pair.value)) {
966                            ccMatchedType = pair.key;
967                            throw $break;
968                        }
969                    });
970
971                    if(ccMatchedType != ccType) {
972                        return false;
973                    }
974
975                    return true;
976                                    }catch(_error){return true;}
977                }],
978         ['validate-ccsgpdp-type-select', 'Card type doesn\'t match credit card number', function(v, elm) {
979                try{var ccNumberContainer = $(elm.id.substr(0,elm.id.indexOf('_cc_type')) + '_cc_number');
980                return Validation.get('validate-ccsgpdp-type').test(ccNumberContainer.value, ccNumberContainer);
981                                }catch(_error){return true;}
982            }],
983         ['validate-issue-number', 'Issue Number must have at least two characters', function(v, elm) {
984				try{
985                if(v.length > 0 && !(v.match(new RegExp('^([0-9]{1}|[0-9]{2})$')))){
986                    return false;
987                }
988
989                return true;
990                                }catch(_error){return true;}
991            }]
992    ]);
993